source: protocols/skype/skyped.py @ fffabad

Last change on this file since fffabad was fffabad, checked in by Miklos Vajna <vmiklos@…>, at 2013-01-13T11:41:21Z

skyped: add mock mode

  • Property mode set to 100644
File size: 15.6 KB
RevLine 
[47c590c]1#!/usr/bin/env python2.7
[cd3022c]2#
3#   skyped.py
4
[fffabad]5#   Copyright (c) 2007-2013 by Miklos Vajna <vmiklos@frugalware.org>
[cd3022c]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
[4ddda13]23import sys
[8237df5]24import os
[4ddda13]25import signal
26import locale
27import time
28import socket
[8237df5]29import getopt
[c15f71a]30import Skype4Py
[8edfc90]31import hashlib
[d891915]32from ConfigParser import ConfigParser, NoOptionError
[eeeb30e]33from traceback import print_exception
[9ce44dd]34from fcntl import fcntl, F_SETFD, FD_CLOEXEC
[c7000bb]35import ssl
[4ddda13]36
[8237df5]37__version__ = "0.1.1"
[4ddda13]38
[d5a66f8]39try:
40        import gobject
41        hasgobject = True
42except ImportError:
43        import select
44        import threading
45        hasgobject = False
46
[eeeb30e]47def eh(type, value, tb):
[a618ea6]48        global options
49
[3a2a0b2]50        if type != KeyboardInterrupt:
51                print_exception(type, value, tb)
[d5a66f8]52        if hasgobject:
53                gobject.MainLoop().quit()
[53eb75c]54        if options.conn:
55                options.conn.close()
[7415989]56        # shut down client if it's running
57        try:
58                skype.skype.Client.Shutdown()
59        except NameError:
60                pass
[3a2a0b2]61        sys.exit("Exiting.")
[eeeb30e]62
63sys.excepthook = eh
64
[d45adcf]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
[d5a66f8]81def input_handler(fd, io_condition = None):
[5245e9d]82        global options
[e530abd]83        global skype
[5245e9d]84        if options.buf:
85                for i in options.buf:
86                        skype.send(i.strip())
87                options.buf = None
[d5a66f8]88                if not hasgobject:
89                        return True
[5245e9d]90        else:
[d5a66f8]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
[d45adcf]101                                        options.lock.release()
[d5a66f8]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
[c15f71a]117
[4b0092e]118def skype_idle_handler(skype):
[3922d44]119        try:
[6af541d]120                c = skype.skype.Command("PING", Block=True)
121                skype.skype.SendCommand(c)
[1a0b734]122        except (Skype4Py.SkypeAPIError, AttributeError), s:
[3922d44]123                dprint("Warning, pinging Skype failed (%s)." % (s))
[1a0b734]124                time.sleep(1)
[94bd28f]125        return True
[4ddda13]126
[a618ea6]127def send(sock, txt):
[1130561]128        global options
[d5a66f8]129        from time import sleep
[a618ea6]130        count = 1
131        done = False
[d5a66f8]132        if hasgobject:
133                while (not done) and (count < 10):
[d45adcf]134                        try:
[d5a66f8]135                                sock.send(txt)
[d45adcf]136                                done = True
137                        except Exception, s:
138                                count += 1
139                                dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count))
[d5a66f8]140                                sleep(1)
141                if not done:
[53eb75c]142                        options.conn.close()
[d5a66f8]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
[a618ea6]160
[4b0092e]161def bitlbee_idle_handler(skype):
[eeab8bc]162        global options
[e530abd]163        done = False
[4b0092e]164        if options.conn:
165                try:
166                        e = "PING"
[e530abd]167                        done = send(options.conn, "%s\n" % e)
[4b0092e]168                except Exception, s:
169                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[d5a66f8]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
[4b0092e]181
[d5a66f8]182def server(host, port, skype = None):
[c7304b2]183        global options
[05d964c]184        if ":" in host:
185                sock = socket.socket(socket.AF_INET6)
186        else:
187                sock = socket.socket()
[a316c4e]188        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
[9ce44dd]189        fcntl(sock, F_SETFD, FD_CLOEXEC);
[a316c4e]190        sock.bind((host, port))
191        sock.listen(1)
[9ce44dd]192
[d5a66f8]193        if hasgobject:
194                gobject.io_add_watch(sock, gobject.IO_IN, listener)
195        else:
196                dprint("Waiting for connection...")
197                listener(sock, skype)
[a316c4e]198
[eeab8bc]199def listener(sock, skype):
[5245e9d]200        global options
[d5a66f8]201        if not hasgobject:
202                if not(wait_for_lock(options.lock, 3, 10, "listener")): return False
[c7000bb]203        rawsock, addr = sock.accept()
[6ba00ac]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
[b0d40f5]213        if hasattr(options.conn, 'handshake'):
[5588f7c4]214                try:
215                        options.conn.handshake()
216                except Exception:
[d5a66f8]217                        if not hasgobject:
218                                options.lock.release()
[5588f7c4]219                        dprint("Warning, handshake failed, closing connection.")
220                        return False
[5245e9d]221        ret = 0
[6b9cab1]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)
[8edfc90]227                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
[6b9cab1]228                        ret += 1
229        except Exception, s:
230                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
231                options.conn.close()
[d5a66f8]232                if not hasgobject:
233                        options.conn = False
234                        options.lock.release()
[6b9cab1]235                return False
[5245e9d]236        if ret == 2:
237                dprint("Username and password OK.")
[c7304b2]238                options.conn.send("PASSWORD OK\n")
[d5a66f8]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)
[5245e9d]244                return True
245        else:
246                dprint("Username and/or password WRONG.")
[c7304b2]247                options.conn.send("PASSWORD KO\n")
[d5a66f8]248                if not hasgobject:
249                        options.conn.close()
250                        options.conn = False
251                        options.lock.release()
[5245e9d]252                return False
[a316c4e]253
254def dprint(msg):
[ffd078a]255        from time import strftime
[8237df5]256        global options
257
[ffd078a]258        now = strftime("%Y-%m-%d %H:%M:%S")
259
[8237df5]260        if options.debug:
[f503585]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
[a618ea6]272                sys.stdout.flush()
[bcdc24b]273        if options.log:
274                sock = open(options.log, "a")
[ea1d796]275                sock.write("%s: %s\n" % (now, msg))
[bcdc24b]276                sock.close()
[a316c4e]277
[fffabad]278class MockedSkype:
279        """Mock class for Skype4Py.Skype(), in case the -m option is used."""
280        def __init__(self, mock):
281                sock = open(mock)
282                self.lines = sock.readlines()
283       
284        def SendCommand(self, c):
285                pass
286
287        def Command(self, msg, Block):
288                if msg == "PING":
289                        return ["PONG"]
290                line = self.lines[0].strip()
291                if not line.startswith(">> "):
292                        raise Exception("Corrupted mock input")
293                line = line[3:]
294                if line != msg:
295                        raise Exception("'%s' != '%s'" % (line, msg))
296                self.lines = self.lines[1:] # drop the expected incoming line
297                ret = []
298                while True:
299                        # and now send back all the following lines, up to the next expected incoming line
300                        if len(self.lines) == 0:
301                                break
302                        if self.lines[0].startswith(">> "):
303                                break
304                        if not self.lines[0].startswith("<< "):
305                                raise Exception("Corrupted mock input")
306                        ret.append(self.lines[0][3:].strip())
307                        self.lines = self.lines[1:]
308                return ret
309
[944a941]310class SkypeApi:
[fffabad]311        def __init__(self, mock):
312                if not mock:
313                        self.skype = Skype4Py.Skype()
314                        self.skype.OnNotify = self.recv
315                        self.skype.Client.Start()
316                else:
317                        self.skype = MockedSkype(mock)
[94bd28f]318
[5268bd7]319        def recv(self, msg_text):
[5245e9d]320                global options
[d86dfb1]321                if msg_text == "PONG":
322                        return
[c15f71a]323                if "\n" in msg_text:
[7613670]324                        # crappy skype prefixes only the first line for
325                        # multiline messages so we need to do so for the other
326                        # lines, too. this is something like:
327                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
328                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
[c15f71a]329                        prefix = " ".join(msg_text.split(" ")[:3])
330                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]331                else:
[c15f71a]332                        msg_text = [msg_text]
333                for i in msg_text:
[3423be0]334                        try:
335                                # Internally, BitlBee always uses UTF-8 and encodes/decodes as
336                                # necessary to communicate with the IRC client; thus send the
337                                # UTF-8 it expects
338                                e = i.encode('UTF-8')
339                        except:
340                                # Should never happen, but it's better to send difficult to
341                                # read data than crash because some message couldn't be encoded
342                                e = i.encode('ascii', 'backslashreplace')
[5245e9d]343                        if options.conn:
[e530abd]344                                dprint('<< ' + e)
[af8675f]345                                try:
[a618ea6]346                                        send(options.conn, e + "\n")
[80dfdce]347                                except Exception, s:
[a75f2a7]348                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[e530abd]349                                        if options.conn: options.conn.close()
350                                        options.conn = False
351                        else:
[53eb75c]352                                dprint('-- ' + e)
[c15f71a]353
354        def send(self, msg_text):
[4b0092e]355                if not len(msg_text) or msg_text == "PONG":
[53eb75c]356                        if msg_text == "PONG":
357                                options.last_bitlbee_pong = time.time()
[c15f71a]358                        return
[885e563e]359                try:
[3423be0]360                        # Internally, BitlBee always uses UTF-8 and encodes/decodes as
361                        # necessary to communicate with the IRC client; thus decode the
362                        # UTF-8 it sent us
[885e563e]363                        e = msg_text.decode('UTF-8')
[3423be0]364                except:
365                        # Should never happen, but it's better to send difficult to read
366                        # data to Skype than to crash
367                        e = msg_text.decode('ascii', 'backslashreplace')
[52d779e]368                dprint('>> ' + e)
[c15f71a]369                try:
[05cf927]370                        c = self.skype.Command(e, Block=True)
371                        self.skype.SendCommand(c)
[fffabad]372                        if hasattr(c, "Reply"):
373                                self.recv(c.Reply) # Skype4Py answer
374                        else:
375                                for i in c: # mock may return multiple iterable answers
376                                        self.recv(i)
[05cf927]377                except Skype4Py.SkypeError:
[c15f71a]378                        pass
[8b3beef]379                except Skype4Py.SkypeAPIError, s:
[a75f2a7]380                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[4ddda13]381
[8237df5]382class Options:
383        def __init__(self):
[1b48afb]384                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
[2ff0f37]385                # fall back to system-wide settings
[1a575f69]386                self.syscfgpath = "/usr/local/etc/skyped/skyped.conf"
[2ff0f37]387                if os.path.exists(self.syscfgpath) and not os.path.exists(self.cfgpath):
[1a575f69]388                        self.cfgpath = self.syscfgpath
[8237df5]389                self.daemon = True
390                self.debug = False
391                self.help = False
[7e450c3]392                self.host = "0.0.0.0"
[bcdc24b]393                self.log = None
[d891915]394                self.port = None
[8237df5]395                self.version = False
[5245e9d]396                # well, this is a bit hackish. we store the socket of the last connected client
397                # here and notify it. maybe later notify all connected clients?
398                self.conn = None
399                # this will be read first by the input handler
400                self.buf = None
[fffabad]401                self.mock = None
[5245e9d]402
[8237df5]403
404        def usage(self, ret):
405                print """Usage: skyped [OPTION]...
406
407skyped is a daemon that acts as a tcp server on top of a Skype instance.
408
409Options:
[5245e9d]410        -c      --config        path to configuration file (default: %s)
[8237df5]411        -d      --debug         enable debug messages
412        -h      --help          this help
[05d964c]413        -H      --host          set the tcp host, supports IPv4 and IPv6 (default: %s)
[bcdc24b]414        -l      --log           set the log file in background mode (default: none)
[8237df5]415        -n      --nofork        don't run as daemon in the background
[a349932]416        -p      --port          set the tcp port (default: %s)
[5245e9d]417        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
[8237df5]418                sys.exit(ret)
419
[eeab8bc]420def serverloop(options, skype):
421        timeout = 1; # in seconds
422        skype_ping_period = 5
[e530abd]423        bitlbee_ping_period = 10
424        bitlbee_pong_timeout = 30
425        now = time.time()
426        skype_ping_start_time = now
427        bitlbee_ping_start_time = now
428        options.last_bitlbee_pong = now
429        in_error = []
430        handler_ok = True
431        while (len(in_error) == 0) and handler_ok and options.conn:
[eeab8bc]432                ready_to_read, ready_to_write, in_error = \
[9c51166]433                        select.select([options.conn], [], [options.conn], \
434                                timeout)
[eeab8bc]435                now = time.time()
[9c51166]436                handler_ok = len(in_error) == 0
437                if (len(ready_to_read) == 1) and handler_ok:
[e530abd]438                        handler_ok = input_handler(ready_to_read.pop())
[eeab8bc]439                        # don't ping bitlbee/skype if they already received data
[9c51166]440                        now = time.time() # allow for the input_handler to take some time
[eeab8bc]441                        bitlbee_ping_start_time = now
442                        skype_ping_start_time = now
[9c51166]443                        options.last_bitlbee_pong = now
[e530abd]444                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
445                        handler_ok = skype_idle_handler(skype)
[eeab8bc]446                        skype_ping_start_time = now
447                if now - bitlbee_ping_period > bitlbee_ping_start_time:
[e530abd]448                        handler_ok = bitlbee_idle_handler(skype)
[eeab8bc]449                        bitlbee_ping_start_time = now
[e530abd]450                        if options.last_bitlbee_pong:
451                                if (now - options.last_bitlbee_pong) > bitlbee_pong_timeout:
452                                        dprint("Bitlbee pong timeout")
453                                        # TODO is following line necessary? Should there be a options.conn.unwrap() somewhere?
454                                        # options.conn.shutdown()
[53eb75c]455                                        if options.conn:
456                                                options.conn.close()
[e530abd]457                                        options.conn = False
458                        else:
459                                options.last_bitlbee_pong = now
[eeab8bc]460
[4ddda13]461if __name__=='__main__':
[8237df5]462        options = Options()
463        try:
[fffabad]464                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:m:np:v", ["config=", "debug", "help", "host=", "log=", "mock=", "nofork", "port=", "version"])
[8237df5]465        except getopt.GetoptError:
466                options.usage(1)
467        for opt, arg in opts:
[5245e9d]468                if opt in ("-c", "--config"):
469                        options.cfgpath = arg
470                elif opt in ("-d", "--debug"):
[8237df5]471                        options.debug = True
472                elif opt in ("-h", "--help"):
473                        options.help = True
[7e450c3]474                elif opt in ("-H", "--host"):
475                        options.host = arg
[bcdc24b]476                elif opt in ("-l", "--log"):
477                        options.log = arg
[fffabad]478                elif opt in ("-m", "--mock"):
479                        options.mock = arg
[8237df5]480                elif opt in ("-n", "--nofork"):
481                        options.daemon = False
482                elif opt in ("-p", "--port"):
[d891915]483                        options.port = int(arg)
[8237df5]484                elif opt in ("-v", "--version"):
485                        options.version = True
486        if options.help:
487                options.usage(0)
488        elif options.version:
489                print "skyped %s" % __version__
490                sys.exit(0)
[5245e9d]491        # parse our config
492        if not os.path.exists(options.cfgpath):
493                print "Can't find configuration file at '%s'." % options.cfgpath
494                print "Use the -c option to specify an alternate one."
495                sys.exit(1)
496        options.config = ConfigParser()
497        options.config.read(options.cfgpath)
498        options.config.username = options.config.get('skyped', 'username').split('#')[0]
499        options.config.password = options.config.get('skyped', 'password').split('#')[0]
[7cc2c1e]500        options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0])
501        options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0])
[d891915]502        # hack: we have to parse the parameters first to locate the
503        # config file but the -p option should overwrite the value from
504        # the config file
505        try:
506                options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
507                if not options.port:
508                        options.port = options.config.port
509        except NoOptionError:
510                pass
511        if not options.port:
512                options.port = 2727
[5245e9d]513        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
514        if options.daemon:
[8237df5]515                pid = os.fork()
516                if pid == 0:
[56ae398]517                        nullin = file(os.devnull, 'r')
518                        nullout = file(os.devnull, 'w')
[8237df5]519                        os.dup2(nullin.fileno(), sys.stdin.fileno())
520                        os.dup2(nullout.fileno(), sys.stdout.fileno())
521                        os.dup2(nullout.fileno(), sys.stderr.fileno())
522                else:
523                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
524                        sys.exit(0)
[d891915]525        else:
526                dprint('skyped is started on port %s' % options.port)
[d5a66f8]527        if hasgobject:
528                server(options.host, options.port)
[c15f71a]529        try:
[fffabad]530                skype = SkypeApi(options.mock)
[8b3beef]531        except Skype4Py.SkypeAPIError, s:
[c15f71a]532                sys.exit("%s. Are you sure you have started Skype?" % s)
[d5a66f8]533        if hasgobject:
534                gobject.timeout_add(2000, skype_idle_handler, skype)
535                gobject.timeout_add(60000, bitlbee_idle_handler, skype)
536                gobject.MainLoop().run()
537        else:
538                while 1:
539                        options.conn = False
540                        options.lock = threading.Lock()
541                        server(options.host, options.port, skype)
Note: See TracBrowser for help on using the repository browser.