source: skype/skyped.py @ d45adcf

Last change on this file since d45adcf was d45adcf, checked in by unknown <pcfeb0009@…>, at 2010-12-24T12:21:16Z

Add locking to ensure only one thread accesses the socket

The Skype API calls the OnNotify callback in a separate thread: see
http://skype4py.sourceforge.net/doc/html/Skype4Py.utils.EventHandlingBase-class.html

Tested informally (chatting with another person for > 15 min)

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