git » msnlib » master » tree

[master] / utils / msncd

  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
#!/usr/bin/env python 


import sys
import os
import socket
import select
import string

import msnlib
import msncb


"""
MSN Client Daemon

This is a MSN client that reads commands from a named pipe, using
a little text-only protocol. It's main use is to serve as a 'glue'
to implement clients in other languages.

This is yet experimental because lack of testing, please let me know if you
try it out.
"""


def null(s):
	"Null function, useful to void debug ones"
	pass
		

#
# This are the callback replacements, which only handle the output and then
# call the original callbacks to do the lower level stuff
#

# basic classes
m = msnlib.msnd()
m.cb = msncb.cb()

# status change
def cb_iln(md, type, tid, params):
	t = params.split()
	status = msnlib.reverse_status[t[0]]
	email = t[1]
	equeue.append('STCH %s %s\n' % (email, status))
	msncb.cb_iln(md, type, tid, params)
m.cb.iln = cb_iln

def cb_nln(md, type, tid, params):
	status = msnlib.reverse_status[tid]
	t = string.split(params)
	email = t[0]
	equeue.append('STCH %s %s\n' % (email, status))
	msncb.cb_nln(md, type, tid, params)
m.cb.nln = cb_nln

def cb_fln(md, type, tid, params):
	email = tid
	u = m.users[email]
	discarded = 0
	if u.sbd and u.sbd.msgqueue:
		discarded = len(u.sbd.msgqueue)
	equeue.append('STCH %s offline %d\n' % (email, discarded))
	msncb.cb_fln(md, type, tid, params)
m.cb.fln = cb_fln

# server disconnect
def cb_out(md, type, tid, params):
	equeue.append('ERR SERV_DISC Server sent disconnect\n')
	msncb.cb_out(md, type, tid, params)
m.cb.out = cb_out


# message
def cb_msg(md, type, tid, params, sbd):
	t = string.split(tid)
	email = t[0]
	
	# messages from hotmail are only when we connect, and send things
	# regarding, aparently, hotmail issues. we ignore them (basically
	# because i couldn't care less; however if somebody has intrest in
	# these and provides some debug output i'll be happy to implement
	# parsing).
	if email == 'Hotmail':
		return

	# parse
	lines = string.split(params, '\n')
	headers = {}
	eoh = 1
	for i in lines:
		# end of headers
		if i == '\r':
			break
		tv = string.split(i, ':')
		type = tv[0]
		value = string.join(tv[1:], ':')
		value = string.strip(value)
		headers[type] = value
		eoh += 1
	
	if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol':
		# the typing notices
		equeue.append('TYPING %s\n' % email)
	else:
		# messages
		equeue.append('MSG %d %d %s\n%s\n' % \
			(len(lines), eoh, email, string.join(lines, '\n')) )
	
	msncb.cb_msg(md, type, tid, params, sbd)
m.cb.msg = cb_msg


# join a conversation and send pending messages
def cb_joi(md, type, tid, params, sbd):
	email = tid
	if len(sbd.msgqueue) > 0:
		equeue.append('MFLUSH %s\n' % email)
	msncb.cb_joi(md, type, tid, params, sbd)
m.cb.joi = cb_joi

# server errors
def cb_err(md, errno, params):
	if not msncb.error_table.has_key(errno):
		desc = 'Unknown'
	else:
		desc = msncb.error_table[errno]
	equeue.append('ERR %s %s\n' % (errno, desc))
	msncb.cb_err(md, errno, params)
m.cb.err = cb_err
	
# users add, delete and modify
def cb_add(md, type, tid, params):
	t = params.split()
	type = t[0]
	if type == 'RL' or type == 'FL':
		email = t[2]
	if type == 'RL':
		equeue.append('UADD %s\n' % email)
	elif type == 'FL':
		equeue.append('ADDFL %s\n' % email)
	msncb.cb_add(md, type, tid, params)
m.cb.add = cb_add

def cb_rem(md, type, tid, params):
	t = params.split()
	type = t[0]
	if type == 'RL' or type == 'FL':
		email = t[2]
	if type == 'RL':
		equeue.append('UDEL %s\n' % email)
	elif type == 'FL':
		equeue.append('DELFL %s\n' % email)
	msncb.cb_rem(md, type, tid, params)
m.cb.rem = cb_rem


def login(email, password):
	# login to msn
	printl('Logging in... ', c.green, 1)
	try:
		m.login()
		printl('done\n', c.green, 1)
	except msnlib.AuthError, info:
		errno = int(info[0])
		if not msncb.error_table.has_key(errno):
			desc = 'Unknown'
		else:
			desc = msncb.error_table[errno]
		perror('Error: %s\n' % desc)
		quit(1)
	except KeyboardInterrupt:
		quit()
	except (msnlib.SocketError, socket.error), info:
		perror('Network error: ' + str(info) + '\n')
		quit(1)
	except:
		pexc('Exception logging in\n')
		quit(1)


#
# the pipe read
#

# first, a small send wrapper to avoid repeating 'addr' all over the place
# note that as they are implemented using udp, if more than one client
# connects it can get quite quite messy
addr = ()
def psend(pipe, s):
	print '-->', s,
	return pipe.sendto(s, addr)

# read from the pipe, c being the pipe socket passed from the caller
def pipe_read(c):
	global m
	global addr
	global equeue	
	
	# we don't worry about lines too much in this implementation because
	# we use datagrams. however, when using stream sockets you should
	s, addr = c.recvfrom(4 * 1024)	# input buffer, should be enough
	print '<--', s,
	try:
		s = s.split(' ', 1)
		if len(s) == 2:
			cmd, params = s
		else:
			cmd = s[0]
			params = ''

		cmd = cmd.strip()
		if params:
			params = params.strip()
			params = params.split(' ')
	except:
		psend(c, 'ERR EINVAL\n')
		return

	if cmd == 'LOGIN':
		if len(params) != 2:
			psend(c, 'ERR PARAMS\n')
			return
		try:
			email, pwd = params
			m.email = email
			m.pwd = pwd
			m.login()
			m.sync()
		except msnlib.AuthError, info:
			errno = int(info[0])
			if not msncb.error_table.has_key(errno):
				desc = 'Unknown'
			else:
				desc = msncb.error_table[errno]
			psend(c, 'ERR MSN %d %s\n' % (errno, desc))
			return
		except (msnlib.SocketError, socket.error), info:
			psend(c, 'ERR SOCK %s\n' % str(info))
			return
		psend(c, 'OK\n')
		return
		
	elif cmd == 'LOGOFF':
		m.disconnect()
		psend(c, 'OK\n')
		return
		
	# if we are not connected, the following commands are not available
	if not m.fd:
		psend(c, 'ERR ENOTCONN\n')
		return
	
	
	if cmd == 'STATUS':
		status = string.join(params, ' ')
		if not m.change_status(status):
			psend(c, 'ERR UNK STATUS\n')
		else:
			psend(c, 'OK\n')
		return
		
	if cmd == 'POLL':
		equeue.append('POLLEND\n')
		for evt in equeue:
			psend(c, evt)
		equeue = []
		return
	
	if cmd == 'GETCL':
		psend(c, 'CL %d\n' % len(m.users.keys()) )
		for email in m.users.keys():
			u = m.users[email]
			status = msnlib.reverse_status[u.status]
			psend(c, '%s %s %s\n' % (status, email, u.nick))
		return
	
	if cmd == 'GETRCL':
		psend(c, 'CL %d\n' % len(m.reverse.keys()) )
		for email in m.reverse.keys():
			u = m.reverse[email]
			status = msnlib.reverse_status[u.status]
			psend(c, '%s %s %s\n' % (status, email, u.nick))
		return
	
	if cmd == 'INFO':
		if len(params) != 1:
			psend(c, 'ERR PARAMS\n')
			return
		if not m.users.has_key(email):
			psend(c, 'ERR UNK USER\n')
		u = m.users[email]
		psend(c, 'email = %s\n' % email)
		psend(c, 'nick = %s\n' % u.nick)
		psend(c, 'homep = %s\n' % u.homep)
		psend(c, 'workp = %s\n' % u.workp)
		psend(c, 'mobilep = %s\n' % u.mobilep)
		psend(c, '\n')
		return
	
	if cmd == 'ADD':
		if len(params) != 2:
			psend(c, 'ERR PARAMS\n')
			return
		nick, email = params
		m.useradd(email, nick)
		psend(c, 'OK\n')
		return
	
	if cmd == 'DEL':
		if len(params) != 1:
			psend(c, 'ERR PARAMS\n')
			return
		m.userdel(params)
		psend(c, 'OK\n')
		return
	
	if cmd == 'NICK':
		if len(params) != 1:
			psend(c, 'ERR PARAMS\n')
			return
		m.change_nick(params)
		psend(c, 'OK\n')
		return
	
	if cmd == 'PRIV':
		if len(params) != 2:
			psend(c, 'ERR PARAMS\n')
			return
		try:
			public = int(p[0])
			auth = int(p[1])
			if public not in (0, 1) or auth not in (0, 1):
				raise
		except:
			psend(c, 'ERR EINVAL\n')
			return
		m.privacy(public, auth)
		psend(c, 'OK\n')
		return
	
	if cmd == 'SENDMSG':
		params = string.join(params, ' ')
		params = string.split(params, '\n', 2)
		params, msg = params
		params = string.split(params, ' ')
		if len(params) < 2:
			psend(c, 'ERR PARAMS\n')
			return
		lines = params[0]
		email = params[1]
		msg = msg
		m.sendmsg(email, msg)
		psend(c, 'OK\n')
		return
		
	# if we got here is because the command is unknown		
	psend(c, 'ERR UNK\n')
	return
	
		

#
# now the real thing
#

# void the debug
msnlib.debug = null
msncb.debug = null

# POLL event queue
# We implement it in a very, very efficient way: text =)
# Yes, it's actually a list, but just because .append() is readable
# and allow us to keep track of the number of pending events
equeue = []

# open the socket for local communication
# we use datagram sockets to avoid complex reads and writes for now, but the
# protocol is line-oriented and perfectly capable of working over a stream
# socket.
pipe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
pipe.bind(('127.0.0.1', 3030))


# loop, waiting for connections
while 1:
	infd = outfd = []
	# if we are connected, poll from msn
	if m.fd != None:
		t = m.pollable()
		infd = t[0]
		outfd = t[1]
	infd.append(pipe)

	fds = select.select(infd, outfd, [], 0)
	
	for i in fds[0] + fds[1]:	# see msnlib.msnd.pollable.__doc__
		if i == pipe:
			# read from the pipe
			pipe_read(pipe)
		else:
			try:
				m.read(i)
			except (msnlib.SocketError, socket.error), err:
				if i != m:
					# user closed a connection
					# note that messages can be
					# lost here
					equeue.append('SCLOSE USER %s %d\n' % (i.emails[0], len(i.msgqueue)) )
					m.close(i)
				else:
					# main socket closed
					# report
					equeue.append('SCLOSE MAIN\n')
					quit(1)