source: protocols/skype/skyped.py @ 505fdaa

Last change on this file since 505fdaa 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
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                        done = sock.sendall(txt)
132                except socket.error as 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: done = sock.sendall(txt)
142                                         options.lock.release()
143                                except socket.error as 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, 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
211        if hasattr(options.conn, 'handshake'):
212                try:
213                        options.conn.handshake()
214                except Exception:
215                        if not hasgobject:
216                                options.lock.release()
217                        dprint("Warning, handshake failed, closing connection.")
218                        return False
219        ret = 0
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)
225                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
226                        ret += 1
227        except Exception, s:
228                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
229                options.conn.close()
230                if not hasgobject:
231                        options.conn = False
232                        options.lock.release()
233                return False
234        if ret == 2:
235                dprint("Username and password OK.")
236                options.conn.send("PASSWORD OK\n")
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)
242                return True
243        else:
244                dprint("Username and/or password WRONG.")
245                options.conn.send("PASSWORD KO\n")
246                if not hasgobject:
247                        options.conn.close()
248                        options.conn = False
249                        options.lock.release()
250                return False
251
252def dprint(msg):
253        from time import strftime
254        global options
255
256        if options.debug:
257                import inspect
258                prefix = strftime("[%Y-%m-%d %H:%M:%S]") + " %s:%d" % inspect.stack()[1][1:3]
259                sanitized = msg
260
261                try:
262                        print prefix + ": " + msg
263                except Exception, s:
264                        try:
265                                sanitized = msg.encode("ascii", "backslashreplace")
266                        except Error, s:
267                                try:
268                                        sanitized = "hex [" + msg.encode("hex") + "]"
269                                except Error, s:
270                                        sanitized = "[unable to print debug message]"
271                        print prefix + "~=" + sanitized
272
273                if options.log:
274                        sock = open(options.log, "a")
275                        sock.write("%s: %s\n" % (prefix, sanitized))
276                        sock.close()
277
278                sys.stdout.flush()
279
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()
285
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
312class SkypeApi:
313        def __init__(self, mock):
314                global options
315                if not mock:
316                        self.skype = Skype4Py.Skype()
317                        self.skype.OnNotify = self.recv
318                        if not options.dont_start_skype:
319                                self.skype.Client.Start()
320                else:
321                        self.skype = MockedSkype(mock)
322
323        def recv(self, msg_text):
324                global options
325                if msg_text == "PONG":
326                        return
327                if "\n" in msg_text:
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'
333                        prefix = " ".join(msg_text.split(" ")[:3])
334                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
335                else:
336                        msg_text = [msg_text]
337                for i in msg_text:
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')
347                        if options.conn:
348                                dprint('<< ' + e)
349                                try:
350                                        send(options.conn, e + "\n")
351                                except Exception, s:
352                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
353                                        if options.conn: options.conn.close()
354                                        options.conn = False
355                        else:
356                                dprint('-- ' + e)
357
358        def send(self, msg_text):
359                if not len(msg_text) or msg_text == "PONG":
360                        if msg_text == "PONG":
361                                options.last_bitlbee_pong = time.time()
362                        return
363                try:
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
367                        e = msg_text.decode('UTF-8')
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')
372                dprint('>> ' + e)
373                try:
374                        c = self.skype.Command(e, Block=True)
375                        self.skype.SendCommand(c)
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)
381                except Skype4Py.SkypeError:
382                        pass
383                except Skype4Py.SkypeAPIError, s:
384                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
385
386
387def serverloop(options, skype):
388        timeout = 1; # in seconds
389        skype_ping_period = 5
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:
399                ready_to_read, ready_to_write, in_error = \
400                        select.select([options.conn], [], [options.conn], \
401                                timeout)
402                now = time.time()
403                handler_ok = len(in_error) == 0
404                if (len(ready_to_read) == 1) and handler_ok:
405                        handler_ok = input_handler(ready_to_read.pop())
406                        # don't ping bitlbee/skype if they already received data
407                        now = time.time() # allow for the input_handler to take some time
408                        bitlbee_ping_start_time = now
409                        skype_ping_start_time = now
410                        options.last_bitlbee_pong = now
411                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
412                        handler_ok = skype_idle_handler(skype)
413                        skype_ping_start_time = now
414                if now - bitlbee_ping_period > bitlbee_ping_start_time:
415                        handler_ok = bitlbee_idle_handler(skype)
416                        bitlbee_ping_start_time = now
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()
422                                        if options.conn:
423                                                options.conn.close()
424                                        options.conn = False
425                        else:
426                                options.last_bitlbee_pong = now
427
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")
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")
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:
460                print "skyped %s" % __version__
461                sys.exit(0)
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):
470                parser.error(( "Can't find configuration file at '%s'. "
471                        "Use the -c option to specify an alternate one." )% options.config)
472
473        cfgpath = options.config
474        options.config = ConfigParser()
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
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:
485                options.config.port = int(options.config.get('skyped', 'port').split('#', 1)[0])
486                if not options.port:
487                        options.port = options.config.port
488        except NoOptionError:
489                pass
490        if not options.port:
491                options.port = port
492        dprint("Parsing config file '%s' done, username is '%s'." % (cfgpath, options.config.username))
493        if not options.nofork:
494                pid = os.fork()
495                if pid == 0:
496                        nullin = file(os.devnull, 'r')
497                        nullout = file(os.devnull, 'w')
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)
504        else:
505                dprint('skyped is started on port %s' % options.port)
506        if hasgobject:
507                server(options.host, options.port)
508        try:
509                skype = SkypeApi(options.mock)
510        except Skype4Py.SkypeAPIError, s:
511                sys.exit("%s. Are you sure you have started Skype?" % s)
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)
521
522
523if __name__ == '__main__': main()
Note: See TracBrowser for help on using the repository browser.