source: protocols/skype/skyped.py @ 7e5b4bd

Last change on this file since 7e5b4bd was 7e5b4bd, checked in by Miklos Vajna <vmiklos@…>, at 2013-02-11T12:56:03Z

skype: add --dont-start-skype option

For cases when case skype start/stop/restart is being handled externally.
Skype4Py seem to be able to handle client going on/off.

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