source: skype/skyped.py @ 68c162b

Last change on this file since 68c162b was 885e563e, checked in by Miklos Vajna <vmiklos@…>, at 2008-09-08T01:10:00Z

skyped: when sending, encode using utf8 if we can't get the system default

this fixes a runtime error on osx

  • Property mode set to 100644
File size: 8.8 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        # 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        line = options.conn.recv(1024)
121        if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
122                ret += 1
123        line = options.conn.recv(1024)
124        if line.startswith("PASSWORD") and sha.sha(line.split(' ')[1].strip()).hexdigest() == options.config.password:
125                ret += 1
126        if ret == 2:
127                dprint("Username and password OK.")
128                options.conn.send("PASSWORD OK\n")
129                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
130                return True
131        else:
132                dprint("Username and/or password WRONG.")
133                options.conn.send("PASSWORD KO\n")
134                return False
135
136def dprint(msg):
137        global options
138
139        if options.debug:
140                print msg
141
142class SkypeApi:
143        def __init__(self):
144                self.skype = Skype4Py.Skype()
145                self.skype.OnNotify = self.recv
146                self.skype.Client.Start()
147
148        def recv(self, msg_text):
149                global options
150                if msg_text == "PONG":
151                        return
152                if "\n" in msg_text:
153                        # crappy skype prefixes only the first line for
154                        # multiline messages so we need to do so for the other
155                        # lines, too. this is something like:
156                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
157                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
158                        prefix = " ".join(msg_text.split(" ")[:3])
159                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
160                else:
161                        msg_text = [msg_text]
162                for i in msg_text:
163                        # use utf-8 here to solve the following problem:
164                        # people use env vars like LC_ALL=en_US (latin1) then
165                        # they complain about why can't they receive latin2
166                        # messages.. so here it is: always use utf-8 then
167                        # everybody will be happy
168                        e = i.encode('UTF-8')
169                        dprint('<< ' + e)
170                        if options.conn:
171                                try:
172                                        options.conn.send(e + "\n")
173                                except Exception, s:
174                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
175                                        options.conn.close()
176
177        def send(self, msg_text):
178                if not len(msg_text) or msg_text == "PONG":
179                        return
180                try:
181                        e = msg_text.decode(locale.getdefaultlocale()[1])
182                except ValueError:
183                        e = msg_text.decode('UTF-8')
184                dprint('>> ' + e)
185                try:
186                        c = self.skype.Command(e, Block=True)
187                        self.skype.SendCommand(c)
188                        self.recv(c.Reply)
189                except Skype4Py.SkypeError:
190                        pass
191                except Skype4Py.SkypeAPIError, s:
192                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
193
194class Options:
195        def __init__(self):
196                self.cfgpath = "/usr/local/etc/skyped/skyped.conf"
197                self.daemon = True
198                self.debug = False
199                self.help = False
200                self.host = "0.0.0.0"
201                self.port = None
202                self.version = False
203                # well, this is a bit hackish. we store the socket of the last connected client
204                # here and notify it. maybe later notify all connected clients?
205                self.conn = None
206                # this will be read first by the input handler
207                self.buf = None
208
209
210        def usage(self, ret):
211                print """Usage: skyped [OPTION]...
212
213skyped is a daemon that acts as a tcp server on top of a Skype instance.
214
215Options:
216        -c      --config        path to configuration file (default: %s)
217        -d      --debug         enable debug messages
218        -h      --help          this help
219        -H      --host          set the tcp host (default: %s)
220        -n      --nofork        don't run as daemon in the background
221        -p      --port          set the tcp port (default: %d)
222        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
223                sys.exit(ret)
224
225if __name__=='__main__':
226        options = Options()
227        try:
228                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"])
229        except getopt.GetoptError:
230                options.usage(1)
231        for opt, arg in opts:
232                if opt in ("-c", "--config"):
233                        options.cfgpath = arg
234                elif opt in ("-d", "--debug"):
235                        options.debug = True
236                elif opt in ("-h", "--help"):
237                        options.help = True
238                elif opt in ("-H", "--host"):
239                        options.host = arg
240                elif opt in ("-n", "--nofork"):
241                        options.daemon = False
242                elif opt in ("-p", "--port"):
243                        options.port = int(arg)
244                elif opt in ("-v", "--version"):
245                        options.version = True
246        if options.help:
247                options.usage(0)
248        elif options.version:
249                print "skyped %s" % __version__
250                sys.exit(0)
251        # parse our config
252        if not os.path.exists(options.cfgpath):
253                print "Can't find configuration file at '%s'." % options.cfgpath
254                print "Use the -c option to specify an alternate one."
255                sys.exit(1)
256        options.config = ConfigParser()
257        options.config.read(options.cfgpath)
258        options.config.username = options.config.get('skyped', 'username').split('#')[0]
259        options.config.password = options.config.get('skyped', 'password').split('#')[0]
260        options.config.sslkey = options.config.get('skyped', 'key').split('#')[0]
261        options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0]
262        # hack: we have to parse the parameters first to locate the
263        # config file but the -p option should overwrite the value from
264        # the config file
265        try:
266                options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
267                if not options.port:
268                        options.port = options.config.port
269        except NoOptionError:
270                pass
271        if not options.port:
272                options.port = 2727
273        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
274        if options.daemon:
275                pid = os.fork()
276                if pid == 0:
277                        nullin = file('/dev/null', 'r')
278                        nullout = file('/dev/null', 'w')
279                        os.dup2(nullin.fileno(), sys.stdin.fileno())
280                        os.dup2(nullout.fileno(), sys.stdout.fileno())
281                        os.dup2(nullout.fileno(), sys.stderr.fileno())
282                else:
283                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
284                        sys.exit(0)
285        else:
286                dprint('skyped is started on port %s' % options.port)
287        server(options.host, options.port)
288        try:
289                skype = SkypeApi()
290        except Skype4Py.SkypeAPIError, s:
291                sys.exit("%s. Are you sure you have started Skype?" % s)
292        gobject.timeout_add(2000, skype_idle_handler, skype)
293        gobject.timeout_add(60000, bitlbee_idle_handler, skype)
294        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.