source: skype/skyped.py @ a618ea6

Last change on this file since a618ea6 was a618ea6, checked in by Miklos Vajna <vmiklos@…>, at 2010-12-13T03:37:30Z

new testcase

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