source: protocols/skype/skyped.py @ 5a4f22e

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

skype: don't do retries on send() on socket errors with gobject

As it's a blocking socket, I imagine there might be only EINTR
errors from signals, which don't seem to be used here.
I think the same tweak can be applied to select() code, but
I don't run it, so no idea if Skype4Py threads might make such loop
necessary there.

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