source: protocols/skype/skyped.py @ b56c76c

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

skype: use argparse instead of getopt for CLI in skyped

  • Property mode set to 100644
File size: 15.0 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        # shut down client if it's running
55        try:
56                skype.skype.Client.Shutdown()
57        except NameError:
58                pass
59        sys.exit("Exiting.")
60
61sys.excepthook = eh
62
63def wait_for_lock(lock, timeout_to_print, timeout, msg):
64        start = time.time()
65        locked = lock.acquire(0)
66        while not(locked):
67                time.sleep(0.5)
68                if timeout_to_print and (time.time() - timeout_to_print > start):
69                        dprint("%s: Waited %f seconds" % \
70                                        (msg, time.time() - start))
71                        timeout_to_print = False
72                if timeout and (time.time() - timeout > start):
73                        dprint("%s: Waited %f seconds, giving up" % \
74                                        (msg, time.time() - start))
75                        return False
76                locked = lock.acquire(0)
77        return True
78
79def input_handler(fd, io_condition = None):
80        global options
81        global skype
82        if options.buf:
83                for i in options.buf:
84                        skype.send(i.strip())
85                options.buf = None
86                if not hasgobject:
87                        return True
88        else:
89                if not hasgobject:
90                        close_socket = False
91                        if wait_for_lock(options.lock, 3, 10, "input_handler"):
92                                try:
93                                                input = fd.recv(1024)
94                                                options.lock.release()
95                                except Exception, s:
96                                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
97                                        fd.close()
98                                        options.conn = False
99                                        options.lock.release()
100                                        return False
101                                for i in input.split("\n"):
102                                        if i.strip() == "SET USERSTATUS OFFLINE":
103                                                close_socket = True
104                                        skype.send(i.strip())
105                        return not(close_socket)
106                try:
107                        input = fd.recv(1024)
108                except Exception, s:
109                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
110                        fd.close()
111                        return False
112                for i in input.split("\n"):
113                        skype.send(i.strip())
114                return True
115
116def skype_idle_handler(skype):
117        try:
118                c = skype.skype.Command("PING", Block=True)
119                skype.skype.SendCommand(c)
120        except (Skype4Py.SkypeAPIError, AttributeError), s:
121                dprint("Warning, pinging Skype failed (%s)." % (s))
122                time.sleep(1)
123        return True
124
125def send(sock, txt):
126        global options
127        from time import sleep
128        count = 1
129        done = False
130        if hasgobject:
131                while (not done) and (count < 10):
132                        try:
133                                sock.send(txt)
134                                done = True
135                        except Exception, s:
136                                count += 1
137                                dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count))
138                                sleep(1)
139                if not done:
140                        options.conn.close()
141        else:
142                while (not done) and (count < 10) and options.conn:
143                        if wait_for_lock(options.lock, 3, 10, "socket send"):
144                                try:
145                                         if options.conn: sock.send(txt)
146                                         options.lock.release()
147                                         done = True
148                                except Exception, s:
149                                        options.lock.release()
150                                        count += 1
151                                        dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count))
152                                        sleep(1)
153                if not done:
154                        if options.conn:
155                                options.conn.close()
156                        options.conn = False
157                return done
158
159def bitlbee_idle_handler(skype):
160        global options
161        done = False
162        if options.conn:
163                try:
164                        e = "PING"
165                        done = send(options.conn, "%s\n" % e)
166                except Exception, s:
167                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
168                        if hasgobject:
169                                options.conn.close()
170                        else:
171                                if options.conn: options.conn.close()
172                                options.conn = False
173                                done = False
174        if hasgobject:
175                return True
176        else:
177                return done
178        return True
179
180def server(host, port, skype = None):
181        global options
182        if ":" in host:
183                sock = socket.socket(socket.AF_INET6)
184        else:
185                sock = socket.socket()
186        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
187        fcntl(sock, F_SETFD, FD_CLOEXEC);
188        sock.bind((host, port))
189        sock.listen(1)
190
191        if hasgobject:
192                gobject.io_add_watch(sock, gobject.IO_IN, listener)
193        else:
194                dprint("Waiting for connection...")
195                listener(sock, skype)
196
197def listener(sock, skype):
198        global options
199        if not hasgobject:
200                if not(wait_for_lock(options.lock, 3, 10, "listener")): return False
201        rawsock, addr = sock.accept()
202        try:
203                options.conn = ssl.wrap_socket(rawsock,
204                        server_side=True,
205                        certfile=options.config.sslcert,
206                        keyfile=options.config.sslkey,
207                        ssl_version=ssl.PROTOCOL_TLSv1)
208        except ssl.SSLError:
209                dprint("Warning, SSL init failed, did you create your certificate?")
210                return False
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        now = strftime("%Y-%m-%d %H:%M:%S")
257
258        if options.debug:
259                try:
260                        print now + ": " + msg
261                except Exception, s:
262                        try:
263                                sanitized = msg.encode("ascii", "backslashreplace")
264                        except Error, s:
265                                try:
266                                        sanitized = "hex [" + msg.encode("hex") + "]"
267                                except Error, s:
268                                        sanitized = "[unable to print debug message]"
269                        print now + "~=" + sanitized
270                sys.stdout.flush()
271        if options.log:
272                sock = open(options.log, "a")
273                sock.write("%s: %s\n" % (now, msg))
274                sock.close()
275
276class MockedSkype:
277        """Mock class for Skype4Py.Skype(), in case the -m option is used."""
278        def __init__(self, mock):
279                sock = open(mock)
280                self.lines = sock.readlines()
281
282        def SendCommand(self, c):
283                pass
284
285        def Command(self, msg, Block):
286                if msg == "PING":
287                        return ["PONG"]
288                line = self.lines[0].strip()
289                if not line.startswith(">> "):
290                        raise Exception("Corrupted mock input")
291                line = line[3:]
292                if line != msg:
293                        raise Exception("'%s' != '%s'" % (line, msg))
294                self.lines = self.lines[1:] # drop the expected incoming line
295                ret = []
296                while True:
297                        # and now send back all the following lines, up to the next expected incoming line
298                        if len(self.lines) == 0:
299                                break
300                        if self.lines[0].startswith(">> "):
301                                break
302                        if not self.lines[0].startswith("<< "):
303                                raise Exception("Corrupted mock input")
304                        ret.append(self.lines[0][3:].strip())
305                        self.lines = self.lines[1:]
306                return ret
307
308class SkypeApi:
309        def __init__(self, mock):
310                if not mock:
311                        self.skype = Skype4Py.Skype()
312                        self.skype.OnNotify = self.recv
313                        self.skype.Client.Start()
314                else:
315                        self.skype = MockedSkype(mock)
316
317        def recv(self, msg_text):
318                global options
319                if msg_text == "PONG":
320                        return
321                if "\n" in msg_text:
322                        # crappy skype prefixes only the first line for
323                        # multiline messages so we need to do so for the other
324                        # lines, too. this is something like:
325                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
326                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
327                        prefix = " ".join(msg_text.split(" ")[:3])
328                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
329                else:
330                        msg_text = [msg_text]
331                for i in msg_text:
332                        try:
333                                # Internally, BitlBee always uses UTF-8 and encodes/decodes as
334                                # necessary to communicate with the IRC client; thus send the
335                                # UTF-8 it expects
336                                e = i.encode('UTF-8')
337                        except:
338                                # Should never happen, but it's better to send difficult to
339                                # read data than crash because some message couldn't be encoded
340                                e = i.encode('ascii', 'backslashreplace')
341                        if options.conn:
342                                dprint('<< ' + e)
343                                try:
344                                        send(options.conn, e + "\n")
345                                except Exception, s:
346                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
347                                        if options.conn: options.conn.close()
348                                        options.conn = False
349                        else:
350                                dprint('-- ' + e)
351
352        def send(self, msg_text):
353                if not len(msg_text) or msg_text == "PONG":
354                        if msg_text == "PONG":
355                                options.last_bitlbee_pong = time.time()
356                        return
357                try:
358                        # Internally, BitlBee always uses UTF-8 and encodes/decodes as
359                        # necessary to communicate with the IRC client; thus decode the
360                        # UTF-8 it sent us
361                        e = msg_text.decode('UTF-8')
362                except:
363                        # Should never happen, but it's better to send difficult to read
364                        # data to Skype than to crash
365                        e = msg_text.decode('ascii', 'backslashreplace')
366                dprint('>> ' + e)
367                try:
368                        c = self.skype.Command(e, Block=True)
369                        self.skype.SendCommand(c)
370                        if hasattr(c, "Reply"):
371                                self.recv(c.Reply) # Skype4Py answer
372                        else:
373                                for i in c: # mock may return multiple iterable answers
374                                        self.recv(i)
375                except Skype4Py.SkypeError:
376                        pass
377                except Skype4Py.SkypeAPIError, s:
378                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
379
380
381def serverloop(options, skype):
382        timeout = 1; # in seconds
383        skype_ping_period = 5
384        bitlbee_ping_period = 10
385        bitlbee_pong_timeout = 30
386        now = time.time()
387        skype_ping_start_time = now
388        bitlbee_ping_start_time = now
389        options.last_bitlbee_pong = now
390        in_error = []
391        handler_ok = True
392        while (len(in_error) == 0) and handler_ok and options.conn:
393                ready_to_read, ready_to_write, in_error = \
394                        select.select([options.conn], [], [options.conn], \
395                                timeout)
396                now = time.time()
397                handler_ok = len(in_error) == 0
398                if (len(ready_to_read) == 1) and handler_ok:
399                        handler_ok = input_handler(ready_to_read.pop())
400                        # don't ping bitlbee/skype if they already received data
401                        now = time.time() # allow for the input_handler to take some time
402                        bitlbee_ping_start_time = now
403                        skype_ping_start_time = now
404                        options.last_bitlbee_pong = now
405                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
406                        handler_ok = skype_idle_handler(skype)
407                        skype_ping_start_time = now
408                if now - bitlbee_ping_period > bitlbee_ping_start_time:
409                        handler_ok = bitlbee_idle_handler(skype)
410                        bitlbee_ping_start_time = now
411                        if options.last_bitlbee_pong:
412                                if (now - options.last_bitlbee_pong) > bitlbee_pong_timeout:
413                                        dprint("Bitlbee pong timeout")
414                                        # TODO is following line necessary? Should there be a options.conn.unwrap() somewhere?
415                                        # options.conn.shutdown()
416                                        if options.conn:
417                                                options.conn.close()
418                                        options.conn = False
419                        else:
420                                options.last_bitlbee_pong = now
421
422
423def main(args=None):
424        global options
425        global skype
426
427        cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
428        syscfgpath = "/usr/local/etc/skyped/skyped.conf"
429        if not os.path.exists(cfgpath) and os.path.exists(syscfgpath):
430                cfgpath = syscfgpath # fall back to system-wide settings
431        port = 2727
432
433        import argparse
434        parser = argparse.ArgumentParser()
435        parser.add_argument('-c', '--config',
436                metavar='path', default=cfgpath,
437                help='path to configuration file (default: %(default)s)')
438        parser.add_argument('-H', '--host', default='0.0.0.0',
439                help='set the tcp host, supports IPv4 and IPv6 (default: %(default)s)')
440        parser.add_argument('-p', '--port', type=int,
441                help='set the tcp port (default: %(default)s)')
442        parser.add_argument('-l', '--log', metavar='path',
443                help='set the log file in background mode (default: none)')
444        parser.add_argument('-v', '--version', action='store_true', help='display version information')
445        parser.add_argument('-n', '--nofork',
446                action='store_true', help="don't run as daemon in the background")
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.