source: skype/skyped.py @ 5a54ec8

Last change on this file since 5a54ec8 was 5a54ec8, checked in by Philippe Crama <pcfeb0009@…>, at 2010-12-19T20:15:14Z

More debugging ouput to make sure the skype daemon is not dead

  • Property mode set to 100644
File size: 10.1 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        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, io_condition):
55        global options
56        if options.buf:
57                for i in options.buf:
58                        skype.send(i.strip())
59                options.buf = None
60        else:
61                try:
62                        input = fd.recv(1024)
63                except Exception, s:
64                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
65                        fd.close()
66                        return False
67                for i in input.split("\n"):
68                        skype.send(i.strip())
69                return True
70
71def skype_idle_handler(skype):
72        try:
73                c = skype.skype.Command("PING", Block=True)
74                skype.skype.SendCommand(c)
75                dprint("... skype pinged")
76        except Skype4Py.SkypeAPIError, s:
77                dprint("Warning, pinging Skype failed (%s)." % (s))
78        return True
79
80def send(sock, txt):
81        from time import sleep
82        count = 1
83        done = False
84        while (not done) and (count < 10):
85                try:
86                        sock.send(txt)
87                        done = True
88                except Exception, s:
89                        count += 1
90                        dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count))
91                        sleep(1)
92        if not done:
93                options.conn.close()
94
95def bitlbee_idle_handler(skype):
96        global options
97        if options.conn:
98                try:
99                        e = "PING"
100                        send(options.conn, "%s\n" % e)
101                        dprint("... pinged Bitlbee")
102                except Exception, s:
103                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
104                        options.conn.close()
105        return True
106
107def server(host, port, skype):
108        global options
109        sock = socket.socket()
110        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
111        sock.bind((host, port))
112        sock.listen(1)
113        dprint("Waiting for connection...")
114        listener(sock, skype)
115
116def listener(sock, skype):
117        global options
118        rawsock, addr = sock.accept()
119        options.conn = ssl.wrap_socket(rawsock,
120                server_side=True,
121                certfile=options.config.sslcert,
122                keyfile=options.config.sslkey,
123                ssl_version=ssl.PROTOCOL_TLSv1)
124        if hasattr(options.conn, 'handshake'):
125                try:
126                        options.conn.handshake()
127                except Exception:
128                        dprint("Warning, handshake failed, closing connection.")
129                        return False
130        ret = 0
131        try:
132                line = options.conn.recv(1024)
133                if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
134                        ret += 1
135                line = options.conn.recv(1024)
136                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
137                        ret += 1
138        except Exception, s:
139                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
140                options.conn.close()
141                return False
142        if ret == 2:
143                dprint("Username and password OK.")
144                options.conn.send("PASSWORD OK\n")
145                serverloop(options, skype)
146                return True
147        else:
148                dprint("Username and/or password WRONG.")
149                options.conn.send("PASSWORD KO\n")
150                return False
151
152def dprint(msg):
153        from time import strftime
154        global options
155
156        now = strftime("%Y-%m-%d %H:%M:%S")
157
158        if options.debug:
159                print now + ": " + msg
160                sys.stdout.flush()
161        if options.log:
162                sock = open(options.log, "a")
163                sock.write("%s: %s\n" % (now, msg))
164                sock.close()
165
166class SkypeApi:
167        def __init__(self):
168                self.skype = Skype4Py.Skype()
169                self.skype.OnNotify = self.recv
170                self.skype.Client.Start()
171
172        def recv(self, msg_text):
173                global options
174                if msg_text == "PONG":
175                        return
176                if "\n" in msg_text:
177                        # crappy skype prefixes only the first line for
178                        # multiline messages so we need to do so for the other
179                        # lines, too. this is something like:
180                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
181                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
182                        prefix = " ".join(msg_text.split(" ")[:3])
183                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
184                else:
185                        msg_text = [msg_text]
186                for i in msg_text:
187                        # use utf-8 here to solve the following problem:
188                        # people use env vars like LC_ALL=en_US (latin1) then
189                        # they complain about why can't they receive latin2
190                        # messages.. so here it is: always use utf-8 then
191                        # everybody will be happy
192                        e = i.encode('UTF-8')
193                        dprint('<< ' + e)
194                        if options.conn:
195                                try:
196                                        # I called the send function really_send
197                                        send(options.conn, e + "\n")
198                                except Exception, s:
199                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
200                                        options.conn.close()
201
202        def send(self, msg_text):
203                if not len(msg_text) or msg_text == "PONG":
204                        return
205                try:
206                        encoding = locale.getdefaultlocale()[1]
207                        if not encoding:
208                                raise ValueError
209                        e = msg_text.decode(encoding)
210                except ValueError:
211                        e = msg_text.decode('UTF-8')
212                dprint('>> ' + e)
213                try:
214                        c = self.skype.Command(e, Block=True)
215                        self.skype.SendCommand(c)
216                        self.recv(c.Reply)
217                except Skype4Py.SkypeError:
218                        pass
219                except Skype4Py.SkypeAPIError, s:
220                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
221
222class Options:
223        def __init__(self):
224                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
225                # for backwards compatibility
226                self.syscfgpath = "/usr/local/etc/skyped/skyped.conf"
227                if os.path.exists(self.syscfgpath):
228                        self.cfgpath = self.syscfgpath
229                self.daemon = True
230                self.debug = False
231                self.help = False
232                self.host = "0.0.0.0"
233                self.log = None
234                self.port = None
235                self.version = False
236                # well, this is a bit hackish. we store the socket of the last connected client
237                # here and notify it. maybe later notify all connected clients?
238                self.conn = None
239                # this will be read first by the input handler
240                self.buf = None
241
242
243        def usage(self, ret):
244                print """Usage: skyped [OPTION]...
245
246skyped is a daemon that acts as a tcp server on top of a Skype instance.
247
248Options:
249        -c      --config        path to configuration file (default: %s)
250        -d      --debug         enable debug messages
251        -h      --help          this help
252        -H      --host          set the tcp host (default: %s)
253        -l      --log           set the log file in background mode (default: none)
254        -n      --nofork        don't run as daemon in the background
255        -p      --port          set the tcp port (default: %s)
256        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
257                sys.exit(ret)
258
259def serverloop(options, skype):
260        timeout = 1; # in seconds
261        skype_ping_period = 5
262        bitlbee_ping_period = 30
263        skype_ping_start_time = time.time()
264        bitlbee_ping_start_time = time.time()
265        while 1:
266                ready_to_read, ready_to_write, in_error = \
267                        select.select([options.conn], [], [], timeout)
268                now = time.time()
269                if len(ready_to_read) == 1:
270                        input_handler(ready_to_read.pop(), options)
271                        # don't ping bitlbee/skype if they already received data
272                        bitlbee_ping_start_time = now
273                        skype_ping_start_time = now
274                if now - skype_ping_period > skype_ping_start_time:
275                        skype_idle_handler(skype)
276                        skype_ping_start_time = now
277                if now - bitlbee_ping_period > bitlbee_ping_start_time:
278                        bitlbee_idle_handler(skype)
279                        bitlbee_ping_start_time = now
280
281if __name__=='__main__':
282        options = Options()
283        try:
284                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"])
285        except getopt.GetoptError:
286                options.usage(1)
287        for opt, arg in opts:
288                if opt in ("-c", "--config"):
289                        options.cfgpath = arg
290                elif opt in ("-d", "--debug"):
291                        options.debug = True
292                elif opt in ("-h", "--help"):
293                        options.help = True
294                elif opt in ("-H", "--host"):
295                        options.host = arg
296                elif opt in ("-l", "--log"):
297                        options.log = arg
298                elif opt in ("-n", "--nofork"):
299                        options.daemon = False
300                elif opt in ("-p", "--port"):
301                        options.port = int(arg)
302                elif opt in ("-v", "--version"):
303                        options.version = True
304        if options.help:
305                options.usage(0)
306        elif options.version:
307                print "skyped %s" % __version__
308                sys.exit(0)
309        # parse our config
310        if not os.path.exists(options.cfgpath):
311                print "Can't find configuration file at '%s'." % options.cfgpath
312                print "Use the -c option to specify an alternate one."
313                sys.exit(1)
314        options.config = ConfigParser()
315        options.config.read(options.cfgpath)
316        options.config.username = options.config.get('skyped', 'username').split('#')[0]
317        options.config.password = options.config.get('skyped', 'password').split('#')[0]
318        options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0])
319        options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0])
320        # hack: we have to parse the parameters first to locate the
321        # config file but the -p option should overwrite the value from
322        # the config file
323        try:
324                options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
325                if not options.port:
326                        options.port = options.config.port
327        except NoOptionError:
328                pass
329        if not options.port:
330                options.port = 2727
331        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
332        if options.daemon:
333                pid = os.fork()
334                if pid == 0:
335                        nullin = file(os.devnull, 'r')
336                        nullout = file(os.devnull, 'w')
337                        os.dup2(nullin.fileno(), sys.stdin.fileno())
338                        os.dup2(nullout.fileno(), sys.stdout.fileno())
339                        os.dup2(nullout.fileno(), sys.stderr.fileno())
340                else:
341                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
342                        sys.exit(0)
343        else:
344                dprint('skyped is started on port %s' % options.port)
345        try:
346                skype = SkypeApi()
347        except Skype4Py.SkypeAPIError, s:
348                sys.exit("%s. Are you sure you have started Skype?" % s)
349        server(options.host, options.port, skype)
Note: See TracBrowser for help on using the repository browser.