source: skype/skyped.py @ eeab8bc

Last change on this file since eeab8bc was eeab8bc, checked in by Philippe Crama <pcfeb0009@…>, at 2010-12-17T20:57:04Z

Remove dependency on gobject and use select standard module

This is a restart of the windows-skyped branch based on the updated
bitlbee-skype using the builtin SSL libs of Python.

This version connects, but hangs for long times... to be continued

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