git » msnlib » master » tree

[master] / msnlib.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
import sys
import string
import socket
import urllib

"""
MSN Messenger Client Library
by Alberto Bertogli (albertito@blitiri.com.ar)
"""

# constants
VERSION = 0x0308
LOGIN_HOST = 'messenger.hotmail.com'
LOGIN_PORT = 1863

status_table = {
	'online':       'NLN',
	'away':         'AWY',
	'busy':         'BSY',
	'brb':          'BRB',
	'phone':        'PHN',
	'lunch':        'LUN',
	'invisible':    'HDN',
	'idle':         'IDL',
	'offline':      'FLN',
}

reverse_status = {
	'NLN':		'online',
	'AWY':		'away',
	'BSY':		'busy',
	'BRB':		'brb',
	'PHN':		'phone',
	'LUN':		'lunch',
	'HDN':		'invisible',
	'IDL':		'idle',
	'FLN':		'offline',
}


# Possible exceptions
class SocketError (Exception):
	pass

class VersionError (Exception):
	pass

class NSError (Exception):
	pass

class AuthError (Exception):
	pass



def debug(s):
	sys.stderr.write('\r' + str(s) + '\n')
	sys.stderr.flush()

def nickquote(nick):
	"""Quotes a nick the way the server likes it: replacing spaces with
	'%20' but leaving extender characters alone, as they get sent UTF-8
	encoded."""
	nick = nick.replace(' ', '%20')
	return nick

class user:
	"""User class, used to store your 'friends'"""
	def __init__(self, email = '', nick = '', gid = None):
		self.email = email
		self.nick = nick
		self.realnick = ''
		self.status = 'FLN'
		self.online = 0
		self.gid = gid
		self.homep = None
		self.workp = None
		self.mobilep = None
		self.sbd = None
		self.priv = {}
		self.lists = []

	def __repr__(self):
		return '<user email:%s nick:"%s" gid:%s>' % (self.email,
				self.nick, self.gid)


class sbd:
	"""SwitchBoard Descriptor
	Used as a pseudo-fd to store per-switchboard connection information.
	The state is either one of (too many):

	[answer]
	cp	connect pending (just came from rng)
	re	ready (just came from connect)
	an	waiting for answer reply

	[invite]
	xf	waiting for xfr response (not even connected yet)
	us	waiting for usr response
	ca	waiting for cal response
	jo	waiting for a join response

	es	established (waiting in boredom)

	You will find more information in the doc directory.
	"""

	def __init__(self):
		self.fd = None		# connection fd
		self.state = None	# connection's state (see doc above)
		self.emails = []	# emails we talk to through
		self.msgqueue = []	# outgoing message queue
		self.hash = None	# server-sent hash
		self.session_id = None	# server-sent sid
		self.endpoint = ()	# remote end (ip, port)
		self.type = None	# either 'answer' or 'invite'
		self.tid = 1		# the transaction id, it needs to be
					# unique for consistency
		self.block = 1		# blocking state
		self.orig_tid = None	# tid of the original XFR

	def __repr__(self):
		return '<sbd: emails:%s state:%s fd:%d endpoint:%s>' % \
			(str(self.emails), self.state, \
			self.fileno(), self.endpoint)

	def fileno(self):
		return self.fd.fileno()

	def get_tid(self):
		"Returns a valid tid as string"
		self.tid = self.tid + 1
		return str(self.tid - 1)



class msnd:
	"""MSN Descriptor
	This is the main and most important class; it represents a msn
	instance.

	It's, afaik, nonblocking (not through setblocking() but mainly because
	it forces a select() i/o model (which you would probably have used
	anyway, unless you think async/signal io worths the mess for a stupid
	messenger protocol, or you are a thread freak)), then the reads should
	always succed. Note that we sanely assume that writes do not block.

	Yes yes, you can use poll() too =)

	The only blocking call is the login() which is in charge of doing the
	initial connection and setup, all the rest are cpu bound.

	Once you have created an instance you should assign an email and a
	password at least, then do the login and i recommend you to call sync
	after that (and everyonce in a while doesn't hurt either). Finally you
	change your status and you're ready to idle.

	Oh, and don't forget to set the callbacks: they are the most important
	part, they are the ones which allow you to control the protocol and
	make this useful.

	They are completely asyncronous, are driven by the read method, and
	never block. A special care should be taken if you use threads (which
	you shouldn't need, that was the whole idea behind this), because
	there is not a single lock on these lines, and it will remain that way.

	There is an example (a very bad one, but you'll see how it would work)
	that should have come with this file; also the callback file has good
	working code.
	"""

	def __init__(self):
		self.fd = None			# socket fd
		self.sb_fds = []		# switchboard fds
		self.tid = 1			# transaction id

		self.email = None		# login email
		self.pwd = None			# login pwd
		self.nick = None		# nick

		self.homep = None		# home phone
		self.workp = None		# work phone
		self.mobilep = None		# mobile phone

		self.status = 'FLN'		# status
		self.encoding = 'iso-8859-1'	# local encoding

		self.lhost = LOGIN_HOST
		self.lport = LOGIN_PORT
		self.ns = (None, None)		# notification server
		self.hash = None		# hash used to authenticate

		self.syn_lver = 0		# user list version
		self.syn_total = 10000		# qty. of users from SYN
		self.syn_ngroups = 0		# qty. of groups from SYN

		self.lst_total = 0		# qty. of LSTs got

		self.cb = None			# callbacks

		self.users = {}			# forward user list
		self.reverse = {}		# reverse user list
		self.groups = {}		# group list


	def __repr__(self):
		return '<msnd object, fd:%s, email:%s, tid:%s>' % (self.fd,
			self.email, self.tid)

	def fileno(self):
		"Useful for select()"
		return self.fd.fileno()

	def encode(self, s):
		"Encodes a string from local encoding to utf8"
		try:
			return s.decode(self.encoding).encode('utf-8')
		except:
			return s

	def decode(self, s):
		"Decodes a string from utf8 to local encoding"
		try:
			return s.decode('utf-8').encode(self.encoding)
		except:
			return s


	def pollable(self):
		"""Return a pair of lists of poll()/select()ables network
		descriptors (ie. they are not fds, but actually classes that
		implement fileno() methods, like this one and the sbd). We do
		it this way because then it's simpler to read().

		The reason behind the tuple is that for connect-pending fds we
		need to wait for writing readiness, so we must tell the
		userspace so. Notice that it still goes with the read() path.

		Yes, it is a mess but i couldn't find anything better yet. It
		works, it's efficient; let's pretend it's correct =)

		It includes the main file descriptor, and all the switchboards
		connections; then you call self.read(fd) on what this returns,
		and magic happens."""

		iwtd = []
		owtd = []
		iwtd.append(self)
		for nd in self.sb_fds:
			if nd.state == 'cp':	# connect is pending
				owtd.append(nd)
			elif nd.state == 'xf':	# skip this case because it's
						# not connected yet
				pass
			else:			# readable!
				iwtd.append(nd)
		return (iwtd, owtd)


	def get_tid(self):
		"Returns a valid tid as string"
		self.tid = self.tid + 1
		return str(self.tid - 1)


	def _send(self, cmd, params = '', nd = None, raw = 0):
		"""Sends a command to the server, building it first as a
		string; uses, if specified, the pseudo fd (it can be either
		msnd or sbd)."""
		if not nd:
			nd = self
		tid = nd.get_tid()
		fd = nd.fd
		c = cmd + ' ' + tid
		if params: c = c + ' ' + params
		debug(str(fd.fileno()) + ' >>> ' + c)
		if not raw:
			c = c + '\r\n'
		c = self.encode(c)
		return fd.send(c)


	def _recv(self, fd = None):
		"Reads a command from the server, returns (cmd, tid, params)"
		if not fd:
			fd = self.fd
		# cheap and dirty readline, FIXME
		buf = ''
		c = fd.recv(1)
		while c != '\n' and c != '':
			buf = buf + c
			c = fd.recv(1)

		if c == '':
			raise SocketError

		buf = buf.strip()
		pbuf = buf.split(' ')

		cmd = pbuf[0]

		# it's possible that we don't have any params (errors being
		# the most common) so we cover our backs
		if len(pbuf) >= 3:
			tid = pbuf[1]
			params = self.decode(string.join(pbuf[2:]))
		elif len(pbuf) == 2:
			tid = pbuf[1]
			params = ''
		else:
			tid = '0'
			params = ''

		debug(str(fd.fileno()) + ' <<< ' + buf)
		return (cmd, tid, params)


	def _recvmsg(self, msglen, fd = None):
		"Read a message from the server, returns it"
		if not fd:
			fd = self.fd
		left = msglen
		buf = ''
		while len(buf) != msglen:
			c = fd.recv(left)
			#debug(str(fd.fileno()) + ' <<< ' + buf)
			buf = buf + c
			left = left - len(c)

		return self.decode(buf)


	def submit_sbd(self, sbd):
		"""Submits a switchboard descriptor to add to our list; it is
		also put on our global list.

		Note that if there is no such user, we create it in order to
		be able to do operations on users that are not in our server
		list."""

		self.sb_fds.append(sbd)
		email = sbd.emails[0]
		if email not in self.users.keys():
			self.users[email] = user(email)
		if self.users[email].sbd and self.users[email].sbd != sbd:
			# override the sbd, but keep the message queue
			sbd.msgqueue = self.users[email].sbd.msgqueue[:]
			self.close(self.users[email].sbd)
		self.users[email].sbd = sbd
		return


	def change_status(self, st):
		"""Changes the current status to: online, away, busy, brb,
		phone, lunch, invisible, idle, offline"""
		if not status_table.has_key(st): return 0
		self.status = status_table[st]
		self._send('CHG', self.status)
		return 1


	def privacy(self, public = 1, auth = 0):
		"""Sets our privacy state. First parameter define if you get
		messages from everybody or only from people on your list; the
		second defines if you want users to ask for authorization or
		let everybody add you"""
		if public:	self._send('BLP', 'AL') # be social
		else:		self._send('BLP', 'BL') # live in a cave

		if auth:	self._send('GTC', 'A')	# ask for auth
		else:		self._send('GTC', 'N')	# let them add you

		return 1


	def change_nick(self, nick):
		"Changes our nick"
		nick = nickquote(nick)
		self._send('REA', self.email + ' ' + nick)
		return 1


	def sync(self):
		"Syncronizes the tables"
		self._send('SYN', '0')
		return 1


	def useradd(self, email, nick = None, gid = '0'):
		"Adds a user"
		if not nick: nick = email
		nick = nickquote(nick)
		self._send('ADD', 'AL ' + email + ' ' + nick)
		self._send('ADD', 'FL ' + email + ' ' + nick + ' ' + gid)
		return 1


	def userdel(self, email):
		"Removes a user"
		self._send('REM', 'AL ' + email)
		self._send('REM', 'FL ' + email)
		return 1

	def userren(self, email, newnick):
		"Renames a user"
		newnick = nickquote(newnick)
		self._send('REA', email + ' ' + newnick)
		return 1

	def userblock(self, email):
		self._send('REM', 'AL ' + email)
		self._send('ADD', 'BL ' + email + ' ' + email)
		if 'B' not in self.users[email].lists:
			self.users[email].lists.append('B')

	def userunblock(self, email):
		self._send('REM', 'BL ' + email)
		self._send('ADD', 'AL ' + email + ' ' + email)
		if 'B' in self.users[email].lists:
			self.users[email].lists.remove('B')

	def groupadd(self, name):
		"Adds a group"
		name = nickquote(name)
		self._send('ADG', name + ' 0')
		return 1

	def groupdel(self, gid):
		"Removes a group"
		self._send('RMG', gid)
		return 1

	def groupren(self, gid, newname):
		newname = nickquote(newname)
		self._send('REG', gid + ' ' + newname)
		return 1

	def disconnect(self):
		"Disconnect from the server"
		self.fd.send('OUT\r\n')
		self.fd.close()


	def close(self, sb):
		"Closes a given sbd"
		self.sb_fds.remove(sb)
		self.users[sb.emails[0]].sbd = None
		try:
			self._send('BYE', self.email, nd = sb)
			sb.fd.close()
		except:
			pass
		del(sb)

	def ping(self):
		"Sends a ping to the server"
		try:
			self.fd.send('PNG\r\n')
			debug(str(self.fd.fileno()) + ' >>> PNG')
		except:
			pass

	def invite(self, email, sbd):
		"Invites a user into an existing sbd"
		self._send('CAL', email, nd = sbd)

	def login(self):
		"Logins to the server, really boring"

		# open socket
		self.fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.fd.connect((self.lhost, self.lport))

		# version information
		self._send('VER', 'MSNP8 CVR0')

		r = self._recv()
		if r[0] != 'VER' and r[2][0:4] != 'MSNP8':
			raise VersionError, r

		# lie the version, just in case
		self._send('CVR', '0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS ' + self.email)
		self._recv()	# we just don't care what we get

		# ask for notification server
		self._send('USR', 'TWN I ' + self.email)

		r = self._recv()
		if r[0] != 'XFR' and r[2][0:2] != 'NS':
			raise NSError, r

		# parse the notification server ip and port (as int)
		ns = string.split(r[2])[1]
		self.ns = ns.split(':')
		self.ns[1] = int(self.ns[1])
		self.ns = tuple(self.ns)

		# close the fd and reopen it on the ns
		self.fd.close()
		self.fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.fd.connect(self.ns)

		# version, same as before
		self._send('VER', 'MSNP8 CVR0')
		r = self._recv()
		if r[0] != 'VER' and r[2][0:4] != 'MSNP8':
			raise VersionError, r

		# lie the version, just in case
		self._send('CVR', '0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS	' + self.email)
		self._recv()	# we just don't care what we get

		# auth: send user, get hash
		self._send('USR', 'TWN I ' + self.email)

		r = self._recv()
		if r[0] != 'USR':
			raise AuthError, r
		hash = string.split(r[2])[2]

		# get and use the passport id
		passportid = self.passport_auth(hash)
		self._send('USR', 'TWN S ' + passportid)

		r = self._recv()
		if r[0] != 'USR' and r[2][0:2] != 'OK':
			raise AuthError, r
		self.nick = string.split(r[2])[2]
		self.nick = urllib.unquote(self.nick)

		return 1


	def passport_auth(self, hash):
		"""Logins into passport and obtains an ID used for
		authorization; it's a helper function for login"""
		import urllib
		import httplib

		# initial connection
		debug('PASSPORT begin')
		nexus = urllib.urlopen('https://nexus.passport.com/rdr/pprdr.asp')
		h = nexus.headers
		purl = h['PassportURLs']

		# parse the info
		d = {}
		for i in purl.split(','):
		        key, val = i.split('=', 1)
			d[key] = val

		# get the login server
		login_server = 'https://' + d['DALogin']
		login_host = d['DALogin'].split('/')[0]

		# build the authentication headers
		ahead =  'Passport1.4 OrgVerb=GET'
		ahead += ',OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom'
		ahead += ',sign-in=' + urllib.quote(self.email)
		ahead += ',pwd=' + urllib.quote(self.pwd)
		ahead += ',lc=1033,id=507,tw=40,fs=1,'
		ahead += 'ru=http%3A%2F%2Fmessenger%2Emsn%2Ecom,ct=0,'
		ahead += 'kpp=1,kv=5,ver=2.1.0173.1,'
		ahead += hash
		headers = { 'Authorization': ahead }

		# connect to the given server
		debug('SSL Connect to %s' % login_server)
		ls = httplib.HTTPSConnection(login_host)

		# make the request
		debug('SSL GET')
		ls.request('GET', login_server, '', headers)
		resp = ls.getresponse()

		# loop if we get redirects until we get a definitive answer
		debug('SSL Response %d' % resp.status)
		while resp.status == 302:
			login_server = resp.getheader('Location')
			login_host = login_server.split('/')[2]
			debug('SSL Redirect to %s' % login_server)
			ls = httplib.HTTPSConnection(login_host)
			headers = { 'Authorization': ahead }
			ls.request('GET', login_server, '', headers)
			resp = ls.getresponse()
			debug('SSL Response %d' % resp.status)

		# now we have a definitive answer, if it's not 200 (success)
		# just raise AuthError
		if resp.status != 200:
			# for now we raise 911, which means authentication
			# failed; but maybe we can get more detailed
			# information
			raise AuthError, (911, 'SSL Auth failed')

		# and parse the headers to get the passport id
		try:
			ainfo = resp.getheader('Authentication-Info')
		except:
			ainfo = resp.getheader('WWW-Authenticate')

		d = {}
		for i in ainfo.split(','):
			key, val = i.split('=', 1)
			d[key] = val

		passportid = d['from-PP']
		passportid = passportid[1:-1]		# remove the "'"
		return passportid


	def read(self, nd = None):
		"""Reads from the specified nd and run the callback. The nd
		can be either a msnd or a sbd (that's why it's called 'nd'
		from 'network descriptor').
		"""
		if not nd:
			nd = self

		# handle different stages of switchboard initialization
		if nd in self.sb_fds:
			# connect pending
			if nd.state == 'cp':
				# see if the connect went well
				r = nd.fd.getsockopt(socket.SOL_SOCKET,
					socket.SO_ERROR)
				if r != 0:
					raise SocketError, 'Connect failed'
				nd.fd.setblocking(1)
				nd.block = 1
				nd.state = 're'

			# need to send the answer to the remote invitation
			if nd.type == 'answer' and nd.state == 're':
				params = self.email + ' ' + nd.hash + ' ' + \
					nd.session_id
				self._send('ANS', params, nd)
				nd.state = 'an'
				return
			if nd.type == 'invite' and nd.state == 're':
				params = self.email + ' ' + nd.hash
				self._send('USR', params, nd)
				nd.state = 'us'
				return



		r = self._recv(nd.fd)
		type = r[0]
		tid = r[1]
		params = string.strip(r[2])

		if   type == 'CHL': self.cb.chl(self, type, tid, params)
		elif type == 'QRY': self.cb.qry(self, type, tid, params)
		elif type == 'ILN': self.cb.iln(self, type, tid, params)
		elif type == 'CHG': self.cb.chg(self, type, tid, params)
		elif type == 'OUT': self.cb.out(self, type, tid, params)
		elif type == 'FLN': self.cb.fln(self, type, tid, params)
		elif type == 'NLN': self.cb.nln(self, type, tid, params)
		elif type == 'BLP': self.cb.blp(self, type, tid, params)
		elif type == 'LST': self.cb.lst(self, type, tid, params)
		elif type == 'GTC': self.cb.gtc(self, type, tid, params)
		elif type == 'SYN': self.cb.syn(self, type, tid, params)
		elif type == 'PRP': self.cb.prp(self, type, tid, params)
		elif type == 'LSG': self.cb.lsg(self, type, tid, params)
		elif type == 'BPR': self.cb.bpr(self, type, tid, params)
		elif type == 'ADD': self.cb.add(self, type, tid, params)
		elif type == 'REA': self.cb.rea(self, type, tid, params)
		elif type == 'REM': self.cb.rem(self, type, tid, params)
		elif type == 'ADG': self.cb.adg(self, type, tid, params)
		elif type == 'RMG': self.cb.rmg(self, type, tid, params)
		elif type == 'REG': self.cb.reg(self, type, tid, params)
		elif type == 'RNG': self.cb.rng(self, type, tid, params)

		elif type == 'IRO': self.cb.iro(self, type, tid, params, nd)
		elif type == 'ANS': self.cb.ans(self, type, tid, params, nd)
		elif type == 'XFR': self.cb.xfr(self, type, tid, params)
		elif type == 'USR': self.cb.usr(self, type, tid, params, nd)
		elif type == 'CAL': self.cb.cal(self, type, tid, params, nd)
		elif type == 'JOI': self.cb.joi(self, type, tid, params, nd)

		elif type == 'ACK': self.cb.ack(self, type, tid, params, nd)
		elif type == 'NAK': self.cb.nak(self, type, tid, params, nd)
		elif type == 'BYE': self.cb.bye(self, type, tid, params, nd)

		elif type == 'QNG': self.cb.qng(self, type, tid, params)

		elif type == 'MSG':
			params = tid + ' ' + params
			mlen = int(r[2].split()[-1])
			msg = self._recvmsg(mlen, nd.fd)
			self.cb.msg(self, type, params, msg, nd)

		elif type == 'NOT':
			mlen = int(tid)
			msg = self._recvmsg(mlen, nd.fd)
			self.cb.notice(self, type, "", msg, nd)

		else:
			# catch server errors - always numeric type
			try:
				errno = int(type)
			except:
				errno = None

			if errno:
				self.cb.err(self, errno, \
					str(tid) + ' ' + str(params))
			else:
				# if we got this far, we have no idea
				self.cb.unk(self, type, tid, params)
		return


	def sendmsg(self, email, msg = '', sb = None):
		"""Sends a message to the user identified by 'email', either
		the one specified or flush the queue.
		Returns:
		1	message queued for delivery
		2	queue flushed
		-2	the message is too big

		To verify the message delivery, use the ack callbacks.
		Message sending order is guaranteed within a sbd; but not the
		acknowledge; that's what the ACK/NAK callbacks are for.
		"""

		if email and email not in self.users.keys():
			self.users[email] = user(email)

		if len(msg) > 1500:
			return -2

		if not sb:
			sb = self.users[email].sbd

		# we don't have a connection
		if not sb:
			sb = sbd()
			sb.state = 'xf'
			sb.type = 'invite'
			sb.emails.append(email)
			sb.msgqueue.append(msg)

			self.submit_sbd(sb)	# no need to connect it yet
			# we set the orig_tid of the sbd to the next tid (that
			# is, the tid the XFR is going to have), in order to
			# be able to identify it later, in cb.cb_xfr()
			sb.orig_tid = str(self.tid)
			self._send('XFR', 'SB')
			return 1

		# it's not ready yet
		elif sb.state != 'es':
			sb.msgqueue.append(msg)
			return 1

		# no more excuses, send it
		else:
			# we make a list with all the messages to send
			pend = sb.msgqueue
			if msg:
				pend.append(msg)
			while len(pend):
				m = pend[0]
				header = "MIME-Version: 1.0\r\n" + \
					"Content-Type: text/plain; " + \
					"charset=UTF-8\r\n\r\n"
				m = header + m
				msize = len(self.encode(m))
				params = 'A ' + str(msize) + '\r\n' + m
				self._send('MSG', params, sb, raw = 1)
				del(pend[0])

			return 2