source: protocols/skype/skyped.py @ 3d1b06f

Last change on this file since 3d1b06f was a016221, checked in by Miklos Vajna <vmiklos@…>, at 2013-04-21T19:39:39Z

skyped: missing newline in log

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