source: protocols/skype/skyped.py @ 4cb21b7

Last change on this file since 4cb21b7 was 1a0b734, checked in by Miklos Vajna <vmiklos@…>, at 2012-07-20T20:32:53Z

#979 skyped: tolerate errors from skype during startup

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