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
Line 
1#!/usr/bin/env python2.7
2#
3#   skyped.py
4
5#   Copyright (c) 2007, 2008, 2009, 2010 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
35import select
36
37__version__ = "0.1.1"
38
39def eh(type, value, tb):
40        global options
41
42        if type != KeyboardInterrupt:
43                print_exception(type, value, tb)
44        if options.conn: options.conn.close()
45        # shut down client if it's running
46        try:
47                skype.skype.Client.Shutdown()
48        except NameError:
49                pass
50        sys.exit("Exiting.")
51
52sys.excepthook = eh
53
54def input_handler(fd):
55        global options
56        global skype
57        if options.buf:
58                for i in options.buf:
59                        skype.send(i.strip())
60                options.buf = None
61                return True
62        else:
63                try:
64                        input = fd.recv(1024)
65                except Exception, s:
66                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
67                        fd.close()
68                        options.conn = False
69                        return False
70                for i in input.split("\n"):
71                        skype.send(i.strip())
72                return True
73
74def skype_idle_handler(skype):
75        try:
76                c = skype.skype.Command("PING", Block=True)
77                skype.skype.SendCommand(c)
78                dprint("... skype pinged")
79        except Skype4Py.SkypeAPIError, s:
80                dprint("Warning, pinging Skype failed (%s)." % (s))
81        return True
82
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))
93                        time.sleep(1)
94        if not done:
95                if options.conn: options.conn.close()
96                options.conn = False
97        return done
98
99def bitlbee_idle_handler(skype):
100        global options
101        done = False
102        if options.conn:
103                try:
104                        e = "PING"
105                        done = send(options.conn, "%s\n" % e)
106                        dprint("... pinged Bitlbee")
107                except Exception, s:
108                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
109                        if options.conn: options.conn.close()
110                        options.conn = False
111                        done = False
112        return done
113
114def server(host, port, skype):
115        global options
116        sock = socket.socket()
117        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
118        sock.bind((host, port))
119        sock.listen(1)
120        dprint("Waiting for connection...")
121        listener(sock, skype)
122
123def listener(sock, skype):
124        global options
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)
131        if hasattr(options.conn, 'handshake'):
132                try:
133                        options.conn.handshake()
134                except Exception:
135                        dprint("Warning, handshake failed, closing connection.")
136                        return False
137        ret = 0
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)
143                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
144                        ret += 1
145        except Exception, s:
146                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
147                options.conn.close()
148                options.conn = False
149                return False
150        if ret == 2:
151                dprint("Username and password OK.")
152                options.conn.send("PASSWORD OK\n")
153                serverloop(options, skype)
154                return True
155        else:
156                dprint("Username and/or password WRONG.")
157                options.conn.send("PASSWORD KO\n")
158                options.conn.close()
159                options.conn = False
160                return False
161
162def dprint(msg):
163        from time import strftime
164        global options
165
166        now = strftime("%Y-%m-%d %H:%M:%S")
167
168        if options.debug:
169                print now + ": " + msg
170                sys.stdout.flush()
171        if options.log:
172                sock = open(options.log, "a")
173                sock.write("%s: %s\n" % (now, msg))
174                sock.close()
175
176class SkypeApi:
177        def __init__(self):
178                self.skype = Skype4Py.Skype()
179                self.skype.OnNotify = self.recv
180                self.skype.Client.Start()
181
182        def recv(self, msg_text):
183                global options
184                if msg_text == "PONG":
185                        return
186                if "\n" in msg_text:
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'
192                        prefix = " ".join(msg_text.split(" ")[:3])
193                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
194                else:
195                        msg_text = [msg_text]
196                for i in msg_text:
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')
203                        if options.conn:
204                                dprint('<< ' + e)
205                                try:
206                                        # I called the send function really_send
207                                        send(options.conn, e + "\n")
208                                except Exception, s:
209                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
210                                        if options.conn: options.conn.close()
211                                        options.conn = False
212                        else:
213                                dprint('---' + e)
214
215        def send(self, msg_text):
216                if not len(msg_text) or msg_text == "PONG":
217                        if msg_text == "PONG": options.last_bitlbee_pong = time.time()
218                        return
219                try:
220                        encoding = locale.getdefaultlocale()[1]
221                        if not encoding:
222                                raise ValueError
223                        e = msg_text.decode(encoding)
224                except ValueError:
225                        e = msg_text.decode('UTF-8')
226                dprint('>> ' + e)
227                try:
228                        c = self.skype.Command(e, Block=True)
229                        self.skype.SendCommand(c)
230                        self.recv(c.Reply)
231                except Skype4Py.SkypeError:
232                        pass
233                except Skype4Py.SkypeAPIError, s:
234                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
235
236class Options:
237        def __init__(self):
238                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
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
243                self.daemon = True
244                self.debug = False
245                self.help = False
246                self.host = "0.0.0.0"
247                self.log = None
248                self.port = None
249                self.version = False
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
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:
263        -c      --config        path to configuration file (default: %s)
264        -d      --debug         enable debug messages
265        -h      --help          this help
266        -H      --host          set the tcp host (default: %s)
267        -l      --log           set the log file in background mode (default: none)
268        -n      --nofork        don't run as daemon in the background
269        -p      --port          set the tcp port (default: %s)
270        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
271                sys.exit(ret)
272
273def serverloop(options, skype):
274        timeout = 1; # in seconds
275        skype_ping_period = 5
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:
285                ready_to_read, ready_to_write, in_error = \
286                        select.select([options.conn], [], [], timeout)
287                now = time.time()
288                handler_ok = True
289                if len(ready_to_read) == 1:
290                        handler_ok = input_handler(ready_to_read.pop())
291                        # don't ping bitlbee/skype if they already received data
292                        bitlbee_ping_start_time = now
293                        skype_ping_start_time = now
294                if (now - skype_ping_period > skype_ping_start_time) and handler_ok:
295                        handler_ok = skype_idle_handler(skype)
296                        skype_ping_start_time = now
297                if now - bitlbee_ping_period > bitlbee_ping_start_time:
298                        handler_ok = bitlbee_idle_handler(skype)
299                        bitlbee_ping_start_time = now
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")
312
313if __name__=='__main__':
314        options = Options()
315        try:
316                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"])
317        except getopt.GetoptError:
318                options.usage(1)
319        for opt, arg in opts:
320                if opt in ("-c", "--config"):
321                        options.cfgpath = arg
322                elif opt in ("-d", "--debug"):
323                        options.debug = True
324                elif opt in ("-h", "--help"):
325                        options.help = True
326                elif opt in ("-H", "--host"):
327                        options.host = arg
328                elif opt in ("-l", "--log"):
329                        options.log = arg
330                elif opt in ("-n", "--nofork"):
331                        options.daemon = False
332                elif opt in ("-p", "--port"):
333                        options.port = int(arg)
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)
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]
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])
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
363        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
364        if options.daemon:
365                pid = os.fork()
366                if pid == 0:
367                        nullin = file(os.devnull, 'r')
368                        nullout = file(os.devnull, 'w')
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)
375        else:
376                dprint('skyped is started on port %s' % options.port)
377        try:
378                skype = SkypeApi()
379        except Skype4Py.SkypeAPIError, s:
380                sys.exit("%s. Are you sure you have started Skype?" % s)
381        while 1:
382                options.conn = False
383                server(options.host, options.port, skype)
Note: See TracBrowser for help on using the repository browser.