1 | #!/usr/bin/env python2.7 |
---|
2 | # |
---|
3 | # skyped.py |
---|
4 | # |
---|
5 | # Copyright (c) 2007, 2008, 2009, 2010 by Miklos Vajna <vmiklos@frugalware.org> |
---|
6 | # |
---|
7 | # This program is free software; you can redistribute it and/or modify |
---|
8 | # it under the terms of the GNU General Public License as published by |
---|
9 | # the Free Software Foundation; either version 2 of the License, or |
---|
10 | # (at your option) any later version. |
---|
11 | # |
---|
12 | # This program is distributed in the hope that it will be useful, |
---|
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
15 | # GNU General Public License for more details. |
---|
16 | # |
---|
17 | # You should have received a copy of the GNU General Public License |
---|
18 | # along with this program; if not, write to the Free Software |
---|
19 | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
---|
20 | # USA. |
---|
21 | # |
---|
22 | |
---|
23 | import sys |
---|
24 | import os |
---|
25 | import signal |
---|
26 | import locale |
---|
27 | import time |
---|
28 | import socket |
---|
29 | import getopt |
---|
30 | import Skype4Py |
---|
31 | import hashlib |
---|
32 | from ConfigParser import ConfigParser, NoOptionError |
---|
33 | from traceback import print_exception |
---|
34 | import ssl |
---|
35 | import select |
---|
36 | import threading |
---|
37 | |
---|
38 | __version__ = "0.1.1" |
---|
39 | |
---|
40 | def eh(type, value, tb): |
---|
41 | global options |
---|
42 | |
---|
43 | if type != KeyboardInterrupt: |
---|
44 | print_exception(type, value, tb) |
---|
45 | if options.conn: |
---|
46 | options.conn.close() |
---|
47 | # shut down client if it's running |
---|
48 | try: |
---|
49 | skype.skype.Client.Shutdown() |
---|
50 | except NameError: |
---|
51 | pass |
---|
52 | sys.exit("Exiting.") |
---|
53 | |
---|
54 | sys.excepthook = eh |
---|
55 | |
---|
56 | def wait_for_lock(lock, timeout_to_print, timeout, msg): |
---|
57 | start = time.time() |
---|
58 | locked = lock.acquire(0) |
---|
59 | while not(locked): |
---|
60 | time.sleep(0.5) |
---|
61 | if timeout_to_print and (time.time() - timeout_to_print > start): |
---|
62 | dprint("%s: Waited %f seconds" % \ |
---|
63 | (msg, time.time() - start)) |
---|
64 | timeout_to_print = False |
---|
65 | if timeout and (time.time() - timeout > start): |
---|
66 | dprint("%s: Waited %f seconds, giving up" % \ |
---|
67 | (msg, time.time() - start)) |
---|
68 | return False |
---|
69 | locked = lock.acquire(0) |
---|
70 | return True |
---|
71 | |
---|
72 | def input_handler(fd): |
---|
73 | global options |
---|
74 | global skype |
---|
75 | if options.buf: |
---|
76 | for i in options.buf: |
---|
77 | skype.send(i.strip()) |
---|
78 | options.buf = None |
---|
79 | return True |
---|
80 | else: |
---|
81 | close_socket = False |
---|
82 | if wait_for_lock(options.lock, 3, 10, "input_handler"): |
---|
83 | try: |
---|
84 | input = fd.recv(1024) |
---|
85 | options.lock.release() |
---|
86 | except Exception, s: |
---|
87 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
88 | fd.close() |
---|
89 | options.conn = False |
---|
90 | options.lock.release() |
---|
91 | return False |
---|
92 | for i in input.split("\n"): |
---|
93 | if i.strip() == "SET USERSTATUS OFFLINE": |
---|
94 | close_socket = True |
---|
95 | skype.send(i.strip()) |
---|
96 | return not(close_socket) |
---|
97 | |
---|
98 | def skype_idle_handler(skype): |
---|
99 | try: |
---|
100 | c = skype.skype.Command("PING", Block=True) |
---|
101 | skype.skype.SendCommand(c) |
---|
102 | except Skype4Py.SkypeAPIError, s: |
---|
103 | dprint("Warning, pinging Skype failed (%s)." % (s)) |
---|
104 | return True |
---|
105 | |
---|
106 | def send(sock, txt): |
---|
107 | global options |
---|
108 | count = 1 |
---|
109 | done = False |
---|
110 | while (not done) and (count < 10) and options.conn: |
---|
111 | if wait_for_lock(options.lock, 3, 10, "socket send"): |
---|
112 | try: |
---|
113 | if options.conn: sock.send(txt) |
---|
114 | options.lock.release() |
---|
115 | done = True |
---|
116 | except Exception, s: |
---|
117 | options.lock.release() |
---|
118 | count += 1 |
---|
119 | dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count)) |
---|
120 | time.sleep(1) |
---|
121 | if not done: |
---|
122 | if options.conn: |
---|
123 | options.conn.close() |
---|
124 | options.conn = False |
---|
125 | return done |
---|
126 | |
---|
127 | def bitlbee_idle_handler(skype): |
---|
128 | global options |
---|
129 | done = False |
---|
130 | if options.conn: |
---|
131 | try: |
---|
132 | e = "PING" |
---|
133 | done = send(options.conn, "%s\n" % e) |
---|
134 | except Exception, s: |
---|
135 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
136 | if options.conn: options.conn.close() |
---|
137 | options.conn = False |
---|
138 | done = False |
---|
139 | return done |
---|
140 | |
---|
141 | def server(host, port, skype): |
---|
142 | global options |
---|
143 | sock = socket.socket() |
---|
144 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
145 | sock.bind((host, port)) |
---|
146 | sock.listen(1) |
---|
147 | dprint("Waiting for connection...") |
---|
148 | listener(sock, skype) |
---|
149 | |
---|
150 | def listener(sock, skype): |
---|
151 | global options |
---|
152 | if not(wait_for_lock(options.lock, 3, 10, "listener")): return False |
---|
153 | rawsock, addr = sock.accept() |
---|
154 | options.conn = ssl.wrap_socket(rawsock, |
---|
155 | server_side=True, |
---|
156 | certfile=options.config.sslcert, |
---|
157 | keyfile=options.config.sslkey, |
---|
158 | ssl_version=ssl.PROTOCOL_TLSv1) |
---|
159 | if hasattr(options.conn, 'handshake'): |
---|
160 | try: |
---|
161 | options.conn.handshake() |
---|
162 | except Exception: |
---|
163 | options.lock.release() |
---|
164 | dprint("Warning, handshake failed, closing connection.") |
---|
165 | return False |
---|
166 | ret = 0 |
---|
167 | try: |
---|
168 | line = options.conn.recv(1024) |
---|
169 | if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username: |
---|
170 | ret += 1 |
---|
171 | line = options.conn.recv(1024) |
---|
172 | if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password: |
---|
173 | ret += 1 |
---|
174 | except Exception, s: |
---|
175 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
176 | options.conn.close() |
---|
177 | options.conn = False |
---|
178 | options.lock.release() |
---|
179 | return False |
---|
180 | if ret == 2: |
---|
181 | dprint("Username and password OK.") |
---|
182 | options.conn.send("PASSWORD OK\n") |
---|
183 | options.lock.release() |
---|
184 | serverloop(options, skype) |
---|
185 | return True |
---|
186 | else: |
---|
187 | dprint("Username and/or password WRONG.") |
---|
188 | options.conn.send("PASSWORD KO\n") |
---|
189 | options.conn.close() |
---|
190 | options.conn = False |
---|
191 | options.lock.release() |
---|
192 | return False |
---|
193 | |
---|
194 | def dprint(msg): |
---|
195 | from time import strftime |
---|
196 | global options |
---|
197 | |
---|
198 | now = strftime("%Y-%m-%d %H:%M:%S") |
---|
199 | |
---|
200 | if options.debug: |
---|
201 | try: |
---|
202 | print now + ": " + msg |
---|
203 | except Exception, s: |
---|
204 | try: |
---|
205 | sanitized = msg.encode("ascii", "backslashreplace") |
---|
206 | except Error, s: |
---|
207 | try: |
---|
208 | sanitized = "hex [" + msg.encode("hex") + "]" |
---|
209 | except Error, s: |
---|
210 | sanitized = "[unable to print debug message]" |
---|
211 | print now + "~=" + sanitized |
---|
212 | sys.stdout.flush() |
---|
213 | if options.log: |
---|
214 | sock = open(options.log, "a") |
---|
215 | sock.write("%s: %s\n" % (now, msg)) |
---|
216 | sock.close() |
---|
217 | |
---|
218 | class SkypeApi: |
---|
219 | def __init__(self): |
---|
220 | self.skype = Skype4Py.Skype() |
---|
221 | self.skype.OnNotify = self.recv |
---|
222 | self.skype.Client.Start() |
---|
223 | |
---|
224 | def recv(self, msg_text): |
---|
225 | global options |
---|
226 | if msg_text == "PONG": |
---|
227 | return |
---|
228 | if "\n" in msg_text: |
---|
229 | # crappy skype prefixes only the first line for |
---|
230 | # multiline messages so we need to do so for the other |
---|
231 | # lines, too. this is something like: |
---|
232 | # 'CHATMESSAGE id BODY first line\nsecond line' -> |
---|
233 | # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line' |
---|
234 | prefix = " ".join(msg_text.split(" ")[:3]) |
---|
235 | msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")] |
---|
236 | else: |
---|
237 | msg_text = [msg_text] |
---|
238 | for i in msg_text: |
---|
239 | try: |
---|
240 | # Internally, BitlBee always uses UTF-8 and encodes/decodes as |
---|
241 | # necessary to communicate with the IRC client; thus send the |
---|
242 | # UTF-8 it expects |
---|
243 | e = i.encode('UTF-8') |
---|
244 | except: |
---|
245 | # Should never happen, but it's better to send difficult to |
---|
246 | # read data than crash because some message couldn't be encoded |
---|
247 | e = i.encode('ascii', 'backslashreplace') |
---|
248 | if options.conn: |
---|
249 | dprint('<< ' + e) |
---|
250 | try: |
---|
251 | send(options.conn, e + "\n") |
---|
252 | except Exception, s: |
---|
253 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
254 | if options.conn: options.conn.close() |
---|
255 | options.conn = False |
---|
256 | else: |
---|
257 | dprint('-- ' + e) |
---|
258 | |
---|
259 | def send(self, msg_text): |
---|
260 | if not len(msg_text) or msg_text == "PONG": |
---|
261 | if msg_text == "PONG": |
---|
262 | options.last_bitlbee_pong = time.time() |
---|
263 | return |
---|
264 | try: |
---|
265 | # Internally, BitlBee always uses UTF-8 and encodes/decodes as |
---|
266 | # necessary to communicate with the IRC client; thus decode the |
---|
267 | # UTF-8 it sent us |
---|
268 | e = msg_text.decode('UTF-8') |
---|
269 | except: |
---|
270 | # Should never happen, but it's better to send difficult to read |
---|
271 | # data to Skype than to crash |
---|
272 | e = msg_text.decode('ascii', 'backslashreplace') |
---|
273 | dprint('>> ' + e) |
---|
274 | try: |
---|
275 | c = self.skype.Command(e, Block=True) |
---|
276 | self.skype.SendCommand(c) |
---|
277 | self.recv(c.Reply) |
---|
278 | except Skype4Py.SkypeError: |
---|
279 | pass |
---|
280 | except Skype4Py.SkypeAPIError, s: |
---|
281 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
282 | |
---|
283 | class Options: |
---|
284 | def __init__(self): |
---|
285 | self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf") |
---|
286 | # for backwards compatibility |
---|
287 | self.syscfgpath = "/usr/local/etc/skyped/skyped.conf" |
---|
288 | if os.path.exists(self.syscfgpath): |
---|
289 | self.cfgpath = self.syscfgpath |
---|
290 | self.daemon = True |
---|
291 | self.debug = False |
---|
292 | self.help = False |
---|
293 | self.host = "0.0.0.0" |
---|
294 | self.log = None |
---|
295 | self.port = None |
---|
296 | self.version = False |
---|
297 | # well, this is a bit hackish. we store the socket of the last connected client |
---|
298 | # here and notify it. maybe later notify all connected clients? |
---|
299 | self.conn = None |
---|
300 | # this will be read first by the input handler |
---|
301 | self.buf = None |
---|
302 | |
---|
303 | |
---|
304 | def usage(self, ret): |
---|
305 | print """Usage: skyped [OPTION]... |
---|
306 | |
---|
307 | skyped is a daemon that acts as a tcp server on top of a Skype instance. |
---|
308 | |
---|
309 | Options: |
---|
310 | -c --config path to configuration file (default: %s) |
---|
311 | -d --debug enable debug messages |
---|
312 | -h --help this help |
---|
313 | -H --host set the tcp host (default: %s) |
---|
314 | -l --log set the log file in background mode (default: none) |
---|
315 | -n --nofork don't run as daemon in the background |
---|
316 | -p --port set the tcp port (default: %s) |
---|
317 | -v --version display version information""" % (self.cfgpath, self.host, self.port) |
---|
318 | sys.exit(ret) |
---|
319 | |
---|
320 | def serverloop(options, skype): |
---|
321 | timeout = 1; # in seconds |
---|
322 | skype_ping_period = 5 |
---|
323 | bitlbee_ping_period = 10 |
---|
324 | bitlbee_pong_timeout = 30 |
---|
325 | now = time.time() |
---|
326 | skype_ping_start_time = now |
---|
327 | bitlbee_ping_start_time = now |
---|
328 | options.last_bitlbee_pong = now |
---|
329 | in_error = [] |
---|
330 | handler_ok = True |
---|
331 | while (len(in_error) == 0) and handler_ok and options.conn: |
---|
332 | ready_to_read, ready_to_write, in_error = \ |
---|
333 | select.select([options.conn], [], [options.conn], \ |
---|
334 | timeout) |
---|
335 | now = time.time() |
---|
336 | handler_ok = len(in_error) == 0 |
---|
337 | if (len(ready_to_read) == 1) and handler_ok: |
---|
338 | handler_ok = input_handler(ready_to_read.pop()) |
---|
339 | # don't ping bitlbee/skype if they already received data |
---|
340 | now = time.time() # allow for the input_handler to take some time |
---|
341 | bitlbee_ping_start_time = now |
---|
342 | skype_ping_start_time = now |
---|
343 | options.last_bitlbee_pong = now |
---|
344 | if (now - skype_ping_period > skype_ping_start_time) and handler_ok: |
---|
345 | handler_ok = skype_idle_handler(skype) |
---|
346 | skype_ping_start_time = now |
---|
347 | if now - bitlbee_ping_period > bitlbee_ping_start_time: |
---|
348 | handler_ok = bitlbee_idle_handler(skype) |
---|
349 | bitlbee_ping_start_time = now |
---|
350 | if options.last_bitlbee_pong: |
---|
351 | if (now - options.last_bitlbee_pong) > bitlbee_pong_timeout: |
---|
352 | dprint("Bitlbee pong timeout") |
---|
353 | # TODO is following line necessary? Should there be a options.conn.unwrap() somewhere? |
---|
354 | # options.conn.shutdown() |
---|
355 | if options.conn: |
---|
356 | options.conn.close() |
---|
357 | options.conn = False |
---|
358 | else: |
---|
359 | options.last_bitlbee_pong = now |
---|
360 | |
---|
361 | if __name__=='__main__': |
---|
362 | options = Options() |
---|
363 | try: |
---|
364 | opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"]) |
---|
365 | except getopt.GetoptError: |
---|
366 | options.usage(1) |
---|
367 | for opt, arg in opts: |
---|
368 | if opt in ("-c", "--config"): |
---|
369 | options.cfgpath = arg |
---|
370 | elif opt in ("-d", "--debug"): |
---|
371 | options.debug = True |
---|
372 | elif opt in ("-h", "--help"): |
---|
373 | options.help = True |
---|
374 | elif opt in ("-H", "--host"): |
---|
375 | options.host = arg |
---|
376 | elif opt in ("-l", "--log"): |
---|
377 | options.log = arg |
---|
378 | elif opt in ("-n", "--nofork"): |
---|
379 | options.daemon = False |
---|
380 | elif opt in ("-p", "--port"): |
---|
381 | options.port = int(arg) |
---|
382 | elif opt in ("-v", "--version"): |
---|
383 | options.version = True |
---|
384 | if options.help: |
---|
385 | options.usage(0) |
---|
386 | elif options.version: |
---|
387 | print "skyped %s" % __version__ |
---|
388 | sys.exit(0) |
---|
389 | # parse our config |
---|
390 | if not os.path.exists(options.cfgpath): |
---|
391 | print "Can't find configuration file at '%s'." % options.cfgpath |
---|
392 | print "Use the -c option to specify an alternate one." |
---|
393 | sys.exit(1) |
---|
394 | options.config = ConfigParser() |
---|
395 | options.config.read(options.cfgpath) |
---|
396 | options.config.username = options.config.get('skyped', 'username').split('#')[0] |
---|
397 | options.config.password = options.config.get('skyped', 'password').split('#')[0] |
---|
398 | options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0]) |
---|
399 | options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0]) |
---|
400 | # hack: we have to parse the parameters first to locate the |
---|
401 | # config file but the -p option should overwrite the value from |
---|
402 | # the config file |
---|
403 | try: |
---|
404 | options.config.port = int(options.config.get('skyped', 'port').split('#')[0]) |
---|
405 | if not options.port: |
---|
406 | options.port = options.config.port |
---|
407 | except NoOptionError: |
---|
408 | pass |
---|
409 | if not options.port: |
---|
410 | options.port = 2727 |
---|
411 | dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username)) |
---|
412 | if options.daemon: |
---|
413 | pid = os.fork() |
---|
414 | if pid == 0: |
---|
415 | nullin = file(os.devnull, 'r') |
---|
416 | nullout = file(os.devnull, 'w') |
---|
417 | os.dup2(nullin.fileno(), sys.stdin.fileno()) |
---|
418 | os.dup2(nullout.fileno(), sys.stdout.fileno()) |
---|
419 | os.dup2(nullout.fileno(), sys.stderr.fileno()) |
---|
420 | else: |
---|
421 | print 'skyped is started on port %s, pid: %d' % (options.port, pid) |
---|
422 | sys.exit(0) |
---|
423 | else: |
---|
424 | dprint('skyped is started on port %s' % options.port) |
---|
425 | try: |
---|
426 | skype = SkypeApi() |
---|
427 | except Skype4Py.SkypeAPIError, s: |
---|
428 | sys.exit("%s. Are you sure you have started Skype?" % s) |
---|
429 | while 1: |
---|
430 | options.conn = False |
---|
431 | options.lock = threading.Lock() |
---|
432 | server(options.host, options.port, skype) |
---|