source: skype/skyped.py @ e530abd

Last change on this file since e530abd was e530abd, checked in by Philippe Crama <pcfeb0009@…>, at 2010-12-20T20:51:49Z

Make skyped restart itself

Now skyped.py detects broken sockets and restarts itself waiting
for a new connection: this sould help with passing the tests
(see branch NetBSD-test-suite)

  • Property mode set to 100644
File size: 11.2 KB
RevLine 
[47c590c]1#!/usr/bin/env python2.7
[cd3022c]2#
3#   skyped.py
4
[7cf146f]5#   Copyright (c) 2007, 2008, 2009, 2010 by Miklos Vajna <vmiklos@frugalware.org>
[cd3022c]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
[4ddda13]23import sys
[8237df5]24import os
[4ddda13]25import signal
26import locale
27import time
28import socket
[8237df5]29import getopt
[c15f71a]30import Skype4Py
[8edfc90]31import hashlib
[d891915]32from ConfigParser import ConfigParser, NoOptionError
[eeeb30e]33from traceback import print_exception
[c7000bb]34import ssl
[eeab8bc]35import select
[4ddda13]36
[8237df5]37__version__ = "0.1.1"
[4ddda13]38
[eeeb30e]39def eh(type, value, tb):
[a618ea6]40        global options
41
[3a2a0b2]42        if type != KeyboardInterrupt:
43                print_exception(type, value, tb)
[e530abd]44        if options.conn: options.conn.close()
[7415989]45        # shut down client if it's running
46        try:
47                skype.skype.Client.Shutdown()
48        except NameError:
49                pass
[3a2a0b2]50        sys.exit("Exiting.")
[eeeb30e]51
52sys.excepthook = eh
53
[e530abd]54def input_handler(fd):
[5245e9d]55        global options
[e530abd]56        global skype
[5245e9d]57        if options.buf:
58                for i in options.buf:
59                        skype.send(i.strip())
60                options.buf = None
[e530abd]61                return True
[5245e9d]62        else:
[2eb4b1f]63                try:
64                        input = fd.recv(1024)
[140ffc8]65                except Exception, s:
66                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
[bd85ec5]67                        fd.close()
[e530abd]68                        options.conn = False
[bd85ec5]69                        return False
[5245e9d]70                for i in input.split("\n"):
71                        skype.send(i.strip())
72                return True
[c15f71a]73
[4b0092e]74def skype_idle_handler(skype):
[3922d44]75        try:
[6af541d]76                c = skype.skype.Command("PING", Block=True)
77                skype.skype.SendCommand(c)
[5a54ec8]78                dprint("... skype pinged")
[3922d44]79        except Skype4Py.SkypeAPIError, s:
80                dprint("Warning, pinging Skype failed (%s)." % (s))
[94bd28f]81        return True
[4ddda13]82
[a618ea6]83def send(sock, txt):
84        count = 1
85        done = False
86        while (not done) and (count < 10):
87                try:
88                        sock.send(txt)
89                        done = True
90                except Exception, s:
91                        count += 1
92                        dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count))
[e530abd]93                        time.sleep(1)
[a618ea6]94        if not done:
[e530abd]95                if options.conn: options.conn.close()
96                options.conn = False
97        return done
[a618ea6]98
[4b0092e]99def bitlbee_idle_handler(skype):
[eeab8bc]100        global options
[e530abd]101        done = False
[4b0092e]102        if options.conn:
103                try:
104                        e = "PING"
[e530abd]105                        done = send(options.conn, "%s\n" % e)
[5a54ec8]106                        dprint("... pinged Bitlbee")
[4b0092e]107                except Exception, s:
108                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[e530abd]109                        if options.conn: options.conn.close()
110                        options.conn = False
111                        done = False
112        return done
[4b0092e]113
[eeab8bc]114def server(host, port, skype):
[c7304b2]115        global options
[c7000bb]116        sock = socket.socket()
[a316c4e]117        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
118        sock.bind((host, port))
119        sock.listen(1)
[eeab8bc]120        dprint("Waiting for connection...")
121        listener(sock, skype)
[a316c4e]122
[eeab8bc]123def listener(sock, skype):
[5245e9d]124        global options
[c7000bb]125        rawsock, addr = sock.accept()
126        options.conn = ssl.wrap_socket(rawsock,
127                server_side=True,
128                certfile=options.config.sslcert,
129                keyfile=options.config.sslkey,
130                ssl_version=ssl.PROTOCOL_TLSv1)
[b0d40f5]131        if hasattr(options.conn, 'handshake'):
[5588f7c4]132                try:
133                        options.conn.handshake()
134                except Exception:
135                        dprint("Warning, handshake failed, closing connection.")
136                        return False
[5245e9d]137        ret = 0
[6b9cab1]138        try:
139                line = options.conn.recv(1024)
140                if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
141                        ret += 1
142                line = options.conn.recv(1024)
[8edfc90]143                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
[6b9cab1]144                        ret += 1
145        except Exception, s:
146                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
147                options.conn.close()
[e530abd]148                options.conn = False
[6b9cab1]149                return False
[5245e9d]150        if ret == 2:
151                dprint("Username and password OK.")
[c7304b2]152                options.conn.send("PASSWORD OK\n")
[eeab8bc]153                serverloop(options, skype)
[5245e9d]154                return True
155        else:
156                dprint("Username and/or password WRONG.")
[c7304b2]157                options.conn.send("PASSWORD KO\n")
[e530abd]158                options.conn.close()
159                options.conn = False
[5245e9d]160                return False
[a316c4e]161
162def dprint(msg):
[ffd078a]163        from time import strftime
[8237df5]164        global options
165
[ffd078a]166        now = strftime("%Y-%m-%d %H:%M:%S")
167
[8237df5]168        if options.debug:
[ffd078a]169                print now + ": " + msg
[a618ea6]170                sys.stdout.flush()
[bcdc24b]171        if options.log:
172                sock = open(options.log, "a")
[ea1d796]173                sock.write("%s: %s\n" % (now, msg))
[bcdc24b]174                sock.close()
[a316c4e]175
[944a941]176class SkypeApi:
[94bd28f]177        def __init__(self):
[c15f71a]178                self.skype = Skype4Py.Skype()
[5268bd7]179                self.skype.OnNotify = self.recv
[6af541d]180                self.skype.Client.Start()
[94bd28f]181
[5268bd7]182        def recv(self, msg_text):
[5245e9d]183                global options
[d86dfb1]184                if msg_text == "PONG":
185                        return
[c15f71a]186                if "\n" in msg_text:
[7613670]187                        # crappy skype prefixes only the first line for
188                        # multiline messages so we need to do so for the other
189                        # lines, too. this is something like:
190                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
191                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
[c15f71a]192                        prefix = " ".join(msg_text.split(" ")[:3])
193                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]194                else:
[c15f71a]195                        msg_text = [msg_text]
196                for i in msg_text:
[a75f2a7]197                        # use utf-8 here to solve the following problem:
198                        # people use env vars like LC_ALL=en_US (latin1) then
199                        # they complain about why can't they receive latin2
200                        # messages.. so here it is: always use utf-8 then
201                        # everybody will be happy
202                        e = i.encode('UTF-8')
[5245e9d]203                        if options.conn:
[e530abd]204                                dprint('<< ' + e)
[af8675f]205                                try:
[eeab8bc]206                                        # I called the send function really_send
[a618ea6]207                                        send(options.conn, e + "\n")
[80dfdce]208                                except Exception, s:
[a75f2a7]209                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[e530abd]210                                        if options.conn: options.conn.close()
211                                        options.conn = False
212                        else:
213                                dprint('---' + e)
[c15f71a]214
215        def send(self, msg_text):
[4b0092e]216                if not len(msg_text) or msg_text == "PONG":
[e530abd]217                        if msg_text == "PONG": options.last_bitlbee_pong = time.time()
[c15f71a]218                        return
[885e563e]219                try:
[072c0fe]220                        encoding = locale.getdefaultlocale()[1]
221                        if not encoding:
222                                raise ValueError
223                        e = msg_text.decode(encoding)
[885e563e]224                except ValueError:
225                        e = msg_text.decode('UTF-8')
[52d779e]226                dprint('>> ' + e)
[c15f71a]227                try:
[05cf927]228                        c = self.skype.Command(e, Block=True)
229                        self.skype.SendCommand(c)
230                        self.recv(c.Reply)
231                except Skype4Py.SkypeError:
[c15f71a]232                        pass
[8b3beef]233                except Skype4Py.SkypeAPIError, s:
[a75f2a7]234                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[4ddda13]235
[8237df5]236class Options:
237        def __init__(self):
[1b48afb]238                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
[1a575f69]239                # for backwards compatibility
240                self.syscfgpath = "/usr/local/etc/skyped/skyped.conf"
241                if os.path.exists(self.syscfgpath):
242                        self.cfgpath = self.syscfgpath
[8237df5]243                self.daemon = True
244                self.debug = False
245                self.help = False
[7e450c3]246                self.host = "0.0.0.0"
[bcdc24b]247                self.log = None
[d891915]248                self.port = None
[8237df5]249                self.version = False
[5245e9d]250                # well, this is a bit hackish. we store the socket of the last connected client
251                # here and notify it. maybe later notify all connected clients?
252                self.conn = None
253                # this will be read first by the input handler
254                self.buf = None
255
[8237df5]256
257        def usage(self, ret):
258                print """Usage: skyped [OPTION]...
259
260skyped is a daemon that acts as a tcp server on top of a Skype instance.
261
262Options:
[5245e9d]263        -c      --config        path to configuration file (default: %s)
[8237df5]264        -d      --debug         enable debug messages
265        -h      --help          this help
[7e450c3]266        -H      --host          set the tcp host (default: %s)
[bcdc24b]267        -l      --log           set the log file in background mode (default: none)
[8237df5]268        -n      --nofork        don't run as daemon in the background
[a349932]269        -p      --port          set the tcp port (default: %s)
[5245e9d]270        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
[8237df5]271                sys.exit(ret)
272
[eeab8bc]273def serverloop(options, skype):
274        timeout = 1; # in seconds
275        skype_ping_period = 5
[e530abd]276        bitlbee_ping_period = 10
277        bitlbee_pong_timeout = 30
278        now = time.time()
279        skype_ping_start_time = now
280        bitlbee_ping_start_time = now
281        options.last_bitlbee_pong = now
282        in_error = []
283        handler_ok = True
284        while (len(in_error) == 0) and handler_ok and options.conn:
[eeab8bc]285                ready_to_read, ready_to_write, in_error = \
286                        select.select([options.conn], [], [], timeout)
287                now = time.time()
[e530abd]288                handler_ok = True
[eeab8bc]289                if len(ready_to_read) == 1:
[e530abd]290                        handler_ok = input_handler(ready_to_read.pop())
[eeab8bc]291                        # don't ping bitlbee/skype if they already received data
292                        bitlbee_ping_start_time = now
293                        skype_ping_start_time = now
[e530abd]294                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
295                        handler_ok = skype_idle_handler(skype)
[eeab8bc]296                        skype_ping_start_time = now
297                if now - bitlbee_ping_period > bitlbee_ping_start_time:
[e530abd]298                        handler_ok = bitlbee_idle_handler(skype)
[eeab8bc]299                        bitlbee_ping_start_time = now
[e530abd]300                        if options.last_bitlbee_pong:
301                                if (now - options.last_bitlbee_pong) > bitlbee_pong_timeout:
302                                        dprint("Bitlbee pong timeout")
303                                        # TODO is following line necessary? Should there be a options.conn.unwrap() somewhere?
304                                        # options.conn.shutdown()
305                                        if options.conn: options.conn.close()
306                                        options.conn = False
307                                else:
308                                        dprint("%f seconds since last PONG" % (now - options.last_bitlbee_pong))
309                        else:
310                                options.last_bitlbee_pong = now
311        dprint("Serverloop done")
[eeab8bc]312
[4ddda13]313if __name__=='__main__':
[8237df5]314        options = Options()
315        try:
[a985369]316                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"])
[8237df5]317        except getopt.GetoptError:
318                options.usage(1)
319        for opt, arg in opts:
[5245e9d]320                if opt in ("-c", "--config"):
321                        options.cfgpath = arg
322                elif opt in ("-d", "--debug"):
[8237df5]323                        options.debug = True
324                elif opt in ("-h", "--help"):
325                        options.help = True
[7e450c3]326                elif opt in ("-H", "--host"):
327                        options.host = arg
[bcdc24b]328                elif opt in ("-l", "--log"):
329                        options.log = arg
[8237df5]330                elif opt in ("-n", "--nofork"):
331                        options.daemon = False
332                elif opt in ("-p", "--port"):
[d891915]333                        options.port = int(arg)
[8237df5]334                elif opt in ("-v", "--version"):
335                        options.version = True
336        if options.help:
337                options.usage(0)
338        elif options.version:
339                print "skyped %s" % __version__
340                sys.exit(0)
[5245e9d]341        # parse our config
342        if not os.path.exists(options.cfgpath):
343                print "Can't find configuration file at '%s'." % options.cfgpath
344                print "Use the -c option to specify an alternate one."
345                sys.exit(1)
346        options.config = ConfigParser()
347        options.config.read(options.cfgpath)
348        options.config.username = options.config.get('skyped', 'username').split('#')[0]
349        options.config.password = options.config.get('skyped', 'password').split('#')[0]
[7cc2c1e]350        options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0])
351        options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0])
[d891915]352        # hack: we have to parse the parameters first to locate the
353        # config file but the -p option should overwrite the value from
354        # the config file
355        try:
356                options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
357                if not options.port:
358                        options.port = options.config.port
359        except NoOptionError:
360                pass
361        if not options.port:
362                options.port = 2727
[5245e9d]363        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
364        if options.daemon:
[8237df5]365                pid = os.fork()
366                if pid == 0:
[56ae398]367                        nullin = file(os.devnull, 'r')
368                        nullout = file(os.devnull, 'w')
[8237df5]369                        os.dup2(nullin.fileno(), sys.stdin.fileno())
370                        os.dup2(nullout.fileno(), sys.stdout.fileno())
371                        os.dup2(nullout.fileno(), sys.stderr.fileno())
372                else:
373                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
374                        sys.exit(0)
[d891915]375        else:
376                dprint('skyped is started on port %s' % options.port)
[c15f71a]377        try:
[3953172]378                skype = SkypeApi()
[8b3beef]379        except Skype4Py.SkypeAPIError, s:
[c15f71a]380                sys.exit("%s. Are you sure you have started Skype?" % s)
[e530abd]381        while 1:
382                options.conn = False
383                server(options.host, options.port, skype)
Note: See TracBrowser for help on using the repository browser.