source: skype/skyped.py @ ffd078a

Last change on this file since ffd078a was ffd078a, checked in by Miklos Vajna <vmiklos@…>, at 2009-08-18T11:33:57Z

dprint() now timestamps debug messages

it's good to know when exactly a problem occurs.

[ mv: minor rewording of the commit message and filter pointless mode
change ]

  • Property mode set to 100644
File size: 9.5 KB
Line 
1#!/usr/bin/env python
2#
3#   skyped.py
4
5#   Copyright (c) 2007, 2008, 2009 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 gobject
29import socket
30import getopt
31import Skype4Py
32import hashlib
33from ConfigParser import ConfigParser, NoOptionError
34from traceback import print_exception
35
36__version__ = "0.1.1"
37
38SKYPE_SERVICE = 'com.Skype.API'
39
40def eh(type, value, tb):
41        if type != KeyboardInterrupt:
42                print_exception(type, value, tb)
43        gobject.MainLoop().quit()
44        # shut down client if it's running
45        try:
46                skype.skype.Client.Shutdown()
47        except NameError:
48                pass
49        sys.exit("Exiting.")
50
51sys.excepthook = eh
52
53def input_handler(fd, io_condition):
54        global options
55        if options.buf:
56                for i in options.buf:
57                        skype.send(i.strip())
58                options.buf = None
59        else:
60                try:
61                        input = fd.recv(1024)
62                except Exception, s:
63                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
64                        fd.close()
65                        return False
66                for i in input.split("\n"):
67                        skype.send(i.strip())
68                return True
69
70def skype_idle_handler(skype):
71        try:
72                c = skype.skype.Command("PING", Block=True)
73                skype.skype.SendCommand(c)
74        except Skype4Py.SkypeAPIError, s:
75                dprint("Warning, pinging Skype failed (%s)." % (s))
76        return True
77
78def bitlbee_idle_handler(skype):
79        if options.conn:
80                try:
81                        e = "PING"
82                        options.conn.send("%s\n" % e)
83                except Exception, s:
84                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
85                        options.conn.close()
86        return True
87
88def server(host, port):
89        global options
90        try:
91                if "SKYPED_NO_GNUTLS" in os.environ.keys():
92                        dprint("Warning, using OpenSSL instead of gnutls as requested (not recommended).")
93                        raise ImportError
94                from gnutls import crypto, connection
95                cert = crypto.X509Certificate(open(options.config.sslcert).read())
96                key = crypto.X509PrivateKey(open(options.config.sslkey).read())
97                cred = connection.X509Credentials(cert, key)
98                sock = connection.ServerSessionFactory(socket.socket(), cred)
99        except ImportError:
100                from OpenSSL import SSL
101                ctx = SSL.Context(SSL.TLSv1_METHOD)
102                ctx.use_privatekey_file(options.config.sslkey)
103                ctx.use_certificate_file(options.config.sslcert)
104                sock = SSL.Connection(ctx, socket.socket())
105        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
106        sock.bind((host, port))
107        sock.listen(1)
108        gobject.io_add_watch(sock, gobject.IO_IN, listener)
109
110def listener(sock, *args):
111        global options
112        options.conn, addr = sock.accept()
113        if hasattr(options.conn, 'handshake'):
114                try:
115                        options.conn.handshake()
116                except Exception:
117                        dprint("Warning, handshake failed, closing connection.")
118                        return False
119        ret = 0
120        try:
121                line = options.conn.recv(1024)
122                if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
123                        ret += 1
124                line = options.conn.recv(1024)
125                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
126                        ret += 1
127        except Exception, s:
128                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
129                options.conn.close()
130                return False
131        if ret == 2:
132                dprint("Username and password OK.")
133                options.conn.send("PASSWORD OK\n")
134                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
135                return True
136        else:
137                dprint("Username and/or password WRONG.")
138                options.conn.send("PASSWORD KO\n")
139                return False
140
141def dprint(msg):
142        from time import strftime
143        global options
144
145        now = strftime("%Y-%m-%d %H:%M:%S")
146
147        if options.debug:
148                print now + ": " + msg
149        if options.log:
150                sock = open(options.log, "a")
151                sock.write("%s: %s\n" % now, msg)
152                sock.close()
153
154class SkypeApi:
155        def __init__(self):
156                self.skype = Skype4Py.Skype()
157                self.skype.OnNotify = self.recv
158                self.skype.Client.Start()
159
160        def recv(self, msg_text):
161                global options
162                if msg_text == "PONG":
163                        return
164                if "\n" in msg_text:
165                        # crappy skype prefixes only the first line for
166                        # multiline messages so we need to do so for the other
167                        # lines, too. this is something like:
168                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
169                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
170                        prefix = " ".join(msg_text.split(" ")[:3])
171                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
172                else:
173                        msg_text = [msg_text]
174                for i in msg_text:
175                        # use utf-8 here to solve the following problem:
176                        # people use env vars like LC_ALL=en_US (latin1) then
177                        # they complain about why can't they receive latin2
178                        # messages.. so here it is: always use utf-8 then
179                        # everybody will be happy
180                        e = i.encode('UTF-8')
181                        dprint('<< ' + e)
182                        if options.conn:
183                                try:
184                                        options.conn.send(e + "\n")
185                                except Exception, s:
186                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
187                                        options.conn.close()
188
189        def send(self, msg_text):
190                if not len(msg_text) or msg_text == "PONG":
191                        return
192                try:
193                        encoding = locale.getdefaultlocale()[1]
194                        if not encoding:
195                                raise ValueError
196                        e = msg_text.decode(encoding)
197                except ValueError:
198                        e = msg_text.decode('UTF-8')
199                dprint('>> ' + e)
200                try:
201                        c = self.skype.Command(e, Block=True)
202                        self.skype.SendCommand(c)
203                        self.recv(c.Reply)
204                except Skype4Py.SkypeError:
205                        pass
206                except Skype4Py.SkypeAPIError, s:
207                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
208
209class Options:
210        def __init__(self):
211                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
212                if not os.path.exists(self.cfgpath):
213                        self.cfgpath = "/usr/local/etc/skyped/skyped.conf"
214                self.daemon = True
215                self.debug = False
216                self.help = False
217                self.host = "0.0.0.0"
218                self.log = None
219                self.port = None
220                self.version = False
221                # well, this is a bit hackish. we store the socket of the last connected client
222                # here and notify it. maybe later notify all connected clients?
223                self.conn = None
224                # this will be read first by the input handler
225                self.buf = None
226
227
228        def usage(self, ret):
229                print """Usage: skyped [OPTION]...
230
231skyped is a daemon that acts as a tcp server on top of a Skype instance.
232
233Options:
234        -c      --config        path to configuration file (default: %s)
235        -d      --debug         enable debug messages
236        -h      --help          this help
237        -H      --host          set the tcp host (default: %s)
238        -l      --log           set the log file in background mode (default: none)
239        -n      --nofork        don't run as daemon in the background
240        -p      --port          set the tcp port (default: %s)
241        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
242                sys.exit(ret)
243
244if __name__=='__main__':
245        options = Options()
246        try:
247                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "daemon", "help", "host=", "log=", "nofork", "port=", "version"])
248        except getopt.GetoptError:
249                options.usage(1)
250        for opt, arg in opts:
251                if opt in ("-c", "--config"):
252                        options.cfgpath = arg
253                elif opt in ("-d", "--debug"):
254                        options.debug = True
255                elif opt in ("-h", "--help"):
256                        options.help = True
257                elif opt in ("-H", "--host"):
258                        options.host = arg
259                elif opt in ("-l", "--log"):
260                        options.log = arg
261                elif opt in ("-n", "--nofork"):
262                        options.daemon = False
263                elif opt in ("-p", "--port"):
264                        options.port = int(arg)
265                elif opt in ("-v", "--version"):
266                        options.version = True
267        if options.help:
268                options.usage(0)
269        elif options.version:
270                print "skyped %s" % __version__
271                sys.exit(0)
272        # parse our config
273        if not os.path.exists(options.cfgpath):
274                print "Can't find configuration file at '%s'." % options.cfgpath
275                print "Use the -c option to specify an alternate one."
276                sys.exit(1)
277        options.config = ConfigParser()
278        options.config.read(options.cfgpath)
279        options.config.username = options.config.get('skyped', 'username').split('#')[0]
280        options.config.password = options.config.get('skyped', 'password').split('#')[0]
281        options.config.sslkey = options.config.get('skyped', 'key').split('#')[0]
282        options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0]
283        # hack: we have to parse the parameters first to locate the
284        # config file but the -p option should overwrite the value from
285        # the config file
286        try:
287                options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
288                if not options.port:
289                        options.port = options.config.port
290        except NoOptionError:
291                pass
292        if not options.port:
293                options.port = 2727
294        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
295        if options.daemon:
296                pid = os.fork()
297                if pid == 0:
298                        nullin = file(os.devnull, 'r')
299                        nullout = file(os.devnull, 'w')
300                        os.dup2(nullin.fileno(), sys.stdin.fileno())
301                        os.dup2(nullout.fileno(), sys.stdout.fileno())
302                        os.dup2(nullout.fileno(), sys.stderr.fileno())
303                else:
304                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
305                        sys.exit(0)
306        else:
307                dprint('skyped is started on port %s' % options.port)
308        server(options.host, options.port)
309        try:
310                skype = SkypeApi()
311        except Skype4Py.SkypeAPIError, s:
312                sys.exit("%s. Are you sure you have started Skype?" % s)
313        gobject.timeout_add(2000, skype_idle_handler, skype)
314        gobject.timeout_add(60000, bitlbee_idle_handler, skype)
315        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.