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
Line 
1#!/usr/bin/env python2.7
2#
3#   skyped.py
4#
5#   Copyright (c) 2007-2013 by Miklos Vajna <vmiklos@vmiklos.hu>
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 time
27import socket
28import Skype4Py
29import hashlib
30from ConfigParser import ConfigParser, NoOptionError
31from traceback import print_exception
32from fcntl import fcntl, F_SETFD, FD_CLOEXEC
33import ssl
34
35__version__ = "0.1.1"
36
37try:
38        import gobject
39        hasgobject = True
40except ImportError:
41        import select
42        import threading
43        hasgobject = False
44
45def eh(type, value, tb):
46        global options
47
48        if type != KeyboardInterrupt:
49                print_exception(type, value, tb)
50        if hasgobject:
51                gobject.MainLoop().quit()
52        if options.conn:
53                options.conn.close()
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
60        sys.exit("Exiting.")
61
62sys.excepthook = eh
63
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
80def input_handler(fd, io_condition = None):
81        global options
82        global skype
83        if options.buf:
84                for i in options.buf:
85                        skype.send(i.strip())
86                options.buf = None
87                if not hasgobject:
88                        return True
89        else:
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
100                                        options.lock.release()
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
116
117def skype_idle_handler(skype):
118        try:
119                c = skype.skype.Command("PING", Block=True)
120                skype.skype.SendCommand(c)
121        except (Skype4Py.SkypeAPIError, AttributeError), s:
122                dprint("Warning, pinging Skype failed (%s)." % (s))
123                time.sleep(1)
124        return True
125
126def send(sock, txt):
127        global options
128        from time import sleep
129        count = 1
130        done = False
131        if hasgobject:
132                while (not done) and (count < 10):
133                        try:
134                                sock.send(txt)
135                                done = True
136                        except Exception, s:
137                                count += 1
138                                dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count))
139                                sleep(1)
140                if not done:
141                        options.conn.close()
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
159
160def bitlbee_idle_handler(skype):
161        global options
162        done = False
163        if options.conn:
164                try:
165                        e = "PING"
166                        done = send(options.conn, "%s\n" % e)
167                except Exception, s:
168                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
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
180
181def server(host, port, skype = None):
182        global options
183        if ":" in host:
184                sock = socket.socket(socket.AF_INET6)
185        else:
186                sock = socket.socket()
187        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
188        fcntl(sock, F_SETFD, FD_CLOEXEC);
189        sock.bind((host, port))
190        sock.listen(1)
191
192        if hasgobject:
193                gobject.io_add_watch(sock, gobject.IO_IN, listener)
194        else:
195                dprint("Waiting for connection...")
196                listener(sock, skype)
197
198def listener(sock, skype):
199        global options
200        if not hasgobject:
201                if not(wait_for_lock(options.lock, 3, 10, "listener")): return False
202        rawsock, addr = sock.accept()
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
212        if hasattr(options.conn, 'handshake'):
213                try:
214                        options.conn.handshake()
215                except Exception:
216                        if not hasgobject:
217                                options.lock.release()
218                        dprint("Warning, handshake failed, closing connection.")
219                        return False
220        ret = 0
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)
226                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
227                        ret += 1
228        except Exception, s:
229                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
230                options.conn.close()
231                if not hasgobject:
232                        options.conn = False
233                        options.lock.release()
234                return False
235        if ret == 2:
236                dprint("Username and password OK.")
237                options.conn.send("PASSWORD OK\n")
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)
243                return True
244        else:
245                dprint("Username and/or password WRONG.")
246                options.conn.send("PASSWORD KO\n")
247                if not hasgobject:
248                        options.conn.close()
249                        options.conn = False
250                        options.lock.release()
251                return False
252
253def dprint(msg):
254        from time import strftime
255        global options
256
257        now = strftime("%Y-%m-%d %H:%M:%S")
258
259        if options.debug:
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
271                sys.stdout.flush()
272        if options.log:
273                sock = open(options.log, "a")
274                sock.write("%s: %s\n" % (now, msg))
275                sock.close()
276
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()
282
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
309class SkypeApi:
310        def __init__(self, mock):
311                global options
312                if not mock:
313                        self.skype = Skype4Py.Skype()
314                        self.skype.OnNotify = self.recv
315                        if not options.dont_start_skype:
316                                self.skype.Client.Start()
317                else:
318                        self.skype = MockedSkype(mock)
319
320        def recv(self, msg_text):
321                global options
322                if msg_text == "PONG":
323                        return
324                if "\n" in msg_text:
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'
330                        prefix = " ".join(msg_text.split(" ")[:3])
331                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
332                else:
333                        msg_text = [msg_text]
334                for i in msg_text:
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')
344                        if options.conn:
345                                dprint('<< ' + e)
346                                try:
347                                        send(options.conn, e + "\n")
348                                except Exception, s:
349                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
350                                        if options.conn: options.conn.close()
351                                        options.conn = False
352                        else:
353                                dprint('-- ' + e)
354
355        def send(self, msg_text):
356                if not len(msg_text) or msg_text == "PONG":
357                        if msg_text == "PONG":
358                                options.last_bitlbee_pong = time.time()
359                        return
360                try:
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
364                        e = msg_text.decode('UTF-8')
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')
369                dprint('>> ' + e)
370                try:
371                        c = self.skype.Command(e, Block=True)
372                        self.skype.SendCommand(c)
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)
378                except Skype4Py.SkypeError:
379                        pass
380                except Skype4Py.SkypeAPIError, s:
381                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
382
383
384def serverloop(options, skype):
385        timeout = 1; # in seconds
386        skype_ping_period = 5
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:
396                ready_to_read, ready_to_write, in_error = \
397                        select.select([options.conn], [], [options.conn], \
398                                timeout)
399                now = time.time()
400                handler_ok = len(in_error) == 0
401                if (len(ready_to_read) == 1) and handler_ok:
402                        handler_ok = input_handler(ready_to_read.pop())
403                        # don't ping bitlbee/skype if they already received data
404                        now = time.time() # allow for the input_handler to take some time
405                        bitlbee_ping_start_time = now
406                        skype_ping_start_time = now
407                        options.last_bitlbee_pong = now
408                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
409                        handler_ok = skype_idle_handler(skype)
410                        skype_ping_start_time = now
411                if now - bitlbee_ping_period > bitlbee_ping_start_time:
412                        handler_ok = bitlbee_idle_handler(skype)
413                        bitlbee_ping_start_time = now
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()
419                                        if options.conn:
420                                                options.conn.close()
421                                        options.conn = False
422                        else:
423                                options.last_bitlbee_pong = now
424
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")
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")
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:
457                print "skyped %s" % __version__
458                sys.exit(0)
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
471        options.config = ConfigParser()
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
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:
482                options.config.port = int(options.config.get('skyped', 'port').split('#', 1)[0])
483                if not options.port:
484                        options.port = options.config.port
485        except NoOptionError:
486                pass
487        if not options.port:
488                options.port = port
489        dprint("Parsing config file '%s' done, username is '%s'." % (options.config, options.config.username))
490        if not options.nofork:
491                pid = os.fork()
492                if pid == 0:
493                        nullin = file(os.devnull, 'r')
494                        nullout = file(os.devnull, 'w')
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)
501        else:
502                dprint('skyped is started on port %s' % options.port)
503        if hasgobject:
504                server(options.host, options.port)
505        try:
506                skype = SkypeApi(options.mock)
507        except Skype4Py.SkypeAPIError, s:
508                sys.exit("%s. Are you sure you have started Skype?" % s)
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)
518
519
520if __name__ == '__main__': main()
Note: See TracBrowser for help on using the repository browser.