source: protocols/skype/skyped.py @ e93fa05

Last change on this file since e93fa05 was 6ba00ac, checked in by Miklos Vajna <vmiklos@…>, at 2011-12-11T23:25:40Z

skyped: give reasonable error message when cert is missing

  • Property mode set to 100644
File size: 14.4 KB
Line 
1#!/usr/bin/env python2.7
2#
3#   skyped.py
4
5#   Copyright (c) 2007, 2008, 2009, 2010, 2011 by Miklos Vajna <vmiklos@frugalware.org>
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 locale
27import time
28import socket
29import getopt
30import Skype4Py
31import hashlib
32from ConfigParser import ConfigParser, NoOptionError
33from traceback import print_exception
34import ssl
35
36__version__ = "0.1.1"
37
38try:
39        import gobject
40        hasgobject = True
41except ImportError:
42        import select
43        import threading
44        hasgobject = False
45
46def eh(type, value, tb):
47        global options
48
49        if type != KeyboardInterrupt:
50                print_exception(type, value, tb)
51        if hasgobject:
52                gobject.MainLoop().quit()
53        if options.conn:
54                options.conn.close()
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, s:
122                dprint("Warning, pinging Skype failed (%s)." % (s))
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        sock.bind((host, port))
188        sock.listen(1)
189        if hasgobject:
190                gobject.io_add_watch(sock, gobject.IO_IN, listener)
191        else:
192                dprint("Waiting for connection...")
193                listener(sock, skype)
194
195def listener(sock, skype):
196        global options
197        if not hasgobject:
198                if not(wait_for_lock(options.lock, 3, 10, "listener")): return False
199        rawsock, addr = sock.accept()
200        try:
201                options.conn = ssl.wrap_socket(rawsock,
202                        server_side=True,
203                        certfile=options.config.sslcert,
204                        keyfile=options.config.sslkey,
205                        ssl_version=ssl.PROTOCOL_TLSv1)
206        except ssl.SSLError:
207                dprint("Warning, SSL init failed, did you create your certificate?")
208                return False
209        if hasattr(options.conn, 'handshake'):
210                try:
211                        options.conn.handshake()
212                except Exception:
213                        if not hasgobject:
214                                options.lock.release()
215                        dprint("Warning, handshake failed, closing connection.")
216                        return False
217        ret = 0
218        try:
219                line = options.conn.recv(1024)
220                if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
221                        ret += 1
222                line = options.conn.recv(1024)
223                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
224                        ret += 1
225        except Exception, s:
226                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
227                options.conn.close()
228                if not hasgobject:
229                        options.conn = False
230                        options.lock.release()
231                return False
232        if ret == 2:
233                dprint("Username and password OK.")
234                options.conn.send("PASSWORD OK\n")
235                if hasgobject:
236                        gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
237                else:
238                        options.lock.release()
239                        serverloop(options, skype)
240                return True
241        else:
242                dprint("Username and/or password WRONG.")
243                options.conn.send("PASSWORD KO\n")
244                if not hasgobject:
245                        options.conn.close()
246                        options.conn = False
247                        options.lock.release()
248                return False
249
250def dprint(msg):
251        from time import strftime
252        global options
253
254        now = strftime("%Y-%m-%d %H:%M:%S")
255
256        if options.debug:
257                try:
258                        print now + ": " + msg
259                except Exception, s:
260                        try:
261                                sanitized = msg.encode("ascii", "backslashreplace")
262                        except Error, s:
263                                try:
264                                        sanitized = "hex [" + msg.encode("hex") + "]"
265                                except Error, s:
266                                        sanitized = "[unable to print debug message]"
267                        print now + "~=" + sanitized
268                sys.stdout.flush()
269        if options.log:
270                sock = open(options.log, "a")
271                sock.write("%s: %s\n" % (now, msg))
272                sock.close()
273
274class SkypeApi:
275        def __init__(self):
276                self.skype = Skype4Py.Skype()
277                self.skype.OnNotify = self.recv
278                self.skype.Client.Start()
279
280        def recv(self, msg_text):
281                global options
282                if msg_text == "PONG":
283                        return
284                if "\n" in msg_text:
285                        # crappy skype prefixes only the first line for
286                        # multiline messages so we need to do so for the other
287                        # lines, too. this is something like:
288                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
289                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
290                        prefix = " ".join(msg_text.split(" ")[:3])
291                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
292                else:
293                        msg_text = [msg_text]
294                for i in msg_text:
295                        try:
296                                # Internally, BitlBee always uses UTF-8 and encodes/decodes as
297                                # necessary to communicate with the IRC client; thus send the
298                                # UTF-8 it expects
299                                e = i.encode('UTF-8')
300                        except:
301                                # Should never happen, but it's better to send difficult to
302                                # read data than crash because some message couldn't be encoded
303                                e = i.encode('ascii', 'backslashreplace')
304                        if options.conn:
305                                dprint('<< ' + e)
306                                try:
307                                        send(options.conn, e + "\n")
308                                except Exception, s:
309                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
310                                        if options.conn: options.conn.close()
311                                        options.conn = False
312                        else:
313                                dprint('-- ' + e)
314
315        def send(self, msg_text):
316                if not len(msg_text) or msg_text == "PONG":
317                        if msg_text == "PONG":
318                                options.last_bitlbee_pong = time.time()
319                        return
320                try:
321                        # Internally, BitlBee always uses UTF-8 and encodes/decodes as
322                        # necessary to communicate with the IRC client; thus decode the
323                        # UTF-8 it sent us
324                        e = msg_text.decode('UTF-8')
325                except:
326                        # Should never happen, but it's better to send difficult to read
327                        # data to Skype than to crash
328                        e = msg_text.decode('ascii', 'backslashreplace')
329                dprint('>> ' + e)
330                try:
331                        c = self.skype.Command(e, Block=True)
332                        self.skype.SendCommand(c)
333                        self.recv(c.Reply)
334                except Skype4Py.SkypeError:
335                        pass
336                except Skype4Py.SkypeAPIError, s:
337                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
338
339class Options:
340        def __init__(self):
341                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
342                # fall back to system-wide settings
343                self.syscfgpath = "/usr/local/etc/skyped/skyped.conf"
344                if os.path.exists(self.syscfgpath) and not os.path.exists(self.cfgpath):
345                        self.cfgpath = self.syscfgpath
346                self.daemon = True
347                self.debug = False
348                self.help = False
349                self.host = "0.0.0.0"
350                self.log = None
351                self.port = None
352                self.version = False
353                # well, this is a bit hackish. we store the socket of the last connected client
354                # here and notify it. maybe later notify all connected clients?
355                self.conn = None
356                # this will be read first by the input handler
357                self.buf = None
358
359
360        def usage(self, ret):
361                print """Usage: skyped [OPTION]...
362
363skyped is a daemon that acts as a tcp server on top of a Skype instance.
364
365Options:
366        -c      --config        path to configuration file (default: %s)
367        -d      --debug         enable debug messages
368        -h      --help          this help
369        -H      --host          set the tcp host, supports IPv4 and IPv6 (default: %s)
370        -l      --log           set the log file in background mode (default: none)
371        -n      --nofork        don't run as daemon in the background
372        -p      --port          set the tcp port (default: %s)
373        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
374                sys.exit(ret)
375
376def serverloop(options, skype):
377        timeout = 1; # in seconds
378        skype_ping_period = 5
379        bitlbee_ping_period = 10
380        bitlbee_pong_timeout = 30
381        now = time.time()
382        skype_ping_start_time = now
383        bitlbee_ping_start_time = now
384        options.last_bitlbee_pong = now
385        in_error = []
386        handler_ok = True
387        while (len(in_error) == 0) and handler_ok and options.conn:
388                ready_to_read, ready_to_write, in_error = \
389                        select.select([options.conn], [], [options.conn], \
390                                timeout)
391                now = time.time()
392                handler_ok = len(in_error) == 0
393                if (len(ready_to_read) == 1) and handler_ok:
394                        handler_ok = input_handler(ready_to_read.pop())
395                        # don't ping bitlbee/skype if they already received data
396                        now = time.time() # allow for the input_handler to take some time
397                        bitlbee_ping_start_time = now
398                        skype_ping_start_time = now
399                        options.last_bitlbee_pong = now
400                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
401                        handler_ok = skype_idle_handler(skype)
402                        skype_ping_start_time = now
403                if now - bitlbee_ping_period > bitlbee_ping_start_time:
404                        handler_ok = bitlbee_idle_handler(skype)
405                        bitlbee_ping_start_time = now
406                        if options.last_bitlbee_pong:
407                                if (now - options.last_bitlbee_pong) > bitlbee_pong_timeout:
408                                        dprint("Bitlbee pong timeout")
409                                        # TODO is following line necessary? Should there be a options.conn.unwrap() somewhere?
410                                        # options.conn.shutdown()
411                                        if options.conn:
412                                                options.conn.close()
413                                        options.conn = False
414                        else:
415                                options.last_bitlbee_pong = now
416
417if __name__=='__main__':
418        options = Options()
419        try:
420                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"])
421        except getopt.GetoptError:
422                options.usage(1)
423        for opt, arg in opts:
424                if opt in ("-c", "--config"):
425                        options.cfgpath = arg
426                elif opt in ("-d", "--debug"):
427                        options.debug = True
428                elif opt in ("-h", "--help"):
429                        options.help = True
430                elif opt in ("-H", "--host"):
431                        options.host = arg
432                elif opt in ("-l", "--log"):
433                        options.log = arg
434                elif opt in ("-n", "--nofork"):
435                        options.daemon = False
436                elif opt in ("-p", "--port"):
437                        options.port = int(arg)
438                elif opt in ("-v", "--version"):
439                        options.version = True
440        if options.help:
441                options.usage(0)
442        elif options.version:
443                print "skyped %s" % __version__
444                sys.exit(0)
445        # parse our config
446        if not os.path.exists(options.cfgpath):
447                print "Can't find configuration file at '%s'." % options.cfgpath
448                print "Use the -c option to specify an alternate one."
449                sys.exit(1)
450        options.config = ConfigParser()
451        options.config.read(options.cfgpath)
452        options.config.username = options.config.get('skyped', 'username').split('#')[0]
453        options.config.password = options.config.get('skyped', 'password').split('#')[0]
454        options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0])
455        options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0])
456        # hack: we have to parse the parameters first to locate the
457        # config file but the -p option should overwrite the value from
458        # the config file
459        try:
460                options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
461                if not options.port:
462                        options.port = options.config.port
463        except NoOptionError:
464                pass
465        if not options.port:
466                options.port = 2727
467        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
468        if options.daemon:
469                pid = os.fork()
470                if pid == 0:
471                        nullin = file(os.devnull, 'r')
472                        nullout = file(os.devnull, 'w')
473                        os.dup2(nullin.fileno(), sys.stdin.fileno())
474                        os.dup2(nullout.fileno(), sys.stdout.fileno())
475                        os.dup2(nullout.fileno(), sys.stderr.fileno())
476                else:
477                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
478                        sys.exit(0)
479        else:
480                dprint('skyped is started on port %s' % options.port)
481        if hasgobject:
482                server(options.host, options.port)
483        try:
484                skype = SkypeApi()
485        except Skype4Py.SkypeAPIError, s:
486                sys.exit("%s. Are you sure you have started Skype?" % s)
487        if hasgobject:
488                gobject.timeout_add(2000, skype_idle_handler, skype)
489                gobject.timeout_add(60000, bitlbee_idle_handler, skype)
490                gobject.MainLoop().run()
491        else:
492                while 1:
493                        options.conn = False
494                        options.lock = threading.Lock()
495                        server(options.host, options.port, skype)
Note: See TracBrowser for help on using the repository browser.