source: skype/skyped.py @ 69939608

Last change on this file since 69939608 was 4b0092e, checked in by Miklos Vajna <vmiklos@…>, at 2008-07-12T20:10:31Z

skyped: send periodically a 'PING' to the client

also ignore the 'PONG' output from it (so don't forward it to skype)

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