source: skype/skyped.py @ 7cc2c1e

Last change on this file since 7cc2c1e was 7cc2c1e, checked in by Miklos Vajna <vmiklos@…>, at 2010-04-12T15:37:33Z

skyped: use os.path.expanduser for file paths in config

Requested-by: ilf <ilf@…>

  • Property mode set to 100644
File size: 9.6 KB
RevLine 
[4ddda13]1#!/usr/bin/env python
[cd3022c]2#
3#   skyped.py
4
[bcdc24b]5#   Copyright (c) 2007, 2008, 2009 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
[4ddda13]35
[8237df5]36__version__ = "0.1.1"
[4ddda13]37
[eeeb30e]38def eh(type, value, tb):
[3a2a0b2]39        if type != KeyboardInterrupt:
40                print_exception(type, value, tb)
41        gobject.MainLoop().quit()
[7415989]42        # shut down client if it's running
43        try:
44                skype.skype.Client.Shutdown()
45        except NameError:
46                pass
[3a2a0b2]47        sys.exit("Exiting.")
[eeeb30e]48
49sys.excepthook = eh
50
[4ddda13]51def input_handler(fd, io_condition):
[5245e9d]52        global options
53        if options.buf:
54                for i in options.buf:
55                        skype.send(i.strip())
56                options.buf = None
57        else:
[2eb4b1f]58                try:
59                        input = fd.recv(1024)
[140ffc8]60                except Exception, s:
61                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
[bd85ec5]62                        fd.close()
63                        return False
[5245e9d]64                for i in input.split("\n"):
65                        skype.send(i.strip())
66                return True
[c15f71a]67
[4b0092e]68def skype_idle_handler(skype):
[3922d44]69        try:
[6af541d]70                c = skype.skype.Command("PING", Block=True)
71                skype.skype.SendCommand(c)
[3922d44]72        except Skype4Py.SkypeAPIError, s:
73                dprint("Warning, pinging Skype failed (%s)." % (s))
[94bd28f]74        return True
[4ddda13]75
[4b0092e]76def bitlbee_idle_handler(skype):
77        if options.conn:
78                try:
79                        e = "PING"
80                        options.conn.send("%s\n" % e)
81                except Exception, s:
82                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
83                        options.conn.close()
84        return True
85
[a316c4e]86def server(host, port):
[c7304b2]87        global options
[b0d40f5]88        try:
89                if "SKYPED_NO_GNUTLS" in os.environ.keys():
90                        dprint("Warning, using OpenSSL instead of gnutls as requested (not recommended).")
91                        raise ImportError
92                from gnutls import crypto, connection
93                cert = crypto.X509Certificate(open(options.config.sslcert).read())
94                key = crypto.X509PrivateKey(open(options.config.sslkey).read())
95                cred = connection.X509Credentials(cert, key)
96                sock = connection.ServerSessionFactory(socket.socket(), cred)
97        except ImportError:
98                from OpenSSL import SSL
99                ctx = SSL.Context(SSL.TLSv1_METHOD)
100                ctx.use_privatekey_file(options.config.sslkey)
101                ctx.use_certificate_file(options.config.sslcert)
102                sock = SSL.Connection(ctx, socket.socket())
[a316c4e]103        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
104        sock.bind((host, port))
105        sock.listen(1)
106        gobject.io_add_watch(sock, gobject.IO_IN, listener)
107
108def listener(sock, *args):
[5245e9d]109        global options
110        options.conn, addr = sock.accept()
[b0d40f5]111        if hasattr(options.conn, 'handshake'):
[5588f7c4]112                try:
113                        options.conn.handshake()
114                except Exception:
115                        dprint("Warning, handshake failed, closing connection.")
116                        return False
[5245e9d]117        ret = 0
[6b9cab1]118        try:
119                line = options.conn.recv(1024)
120                if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
121                        ret += 1
122                line = options.conn.recv(1024)
[8edfc90]123                if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password:
[6b9cab1]124                        ret += 1
125        except Exception, s:
126                dprint("Warning, receiving 1024 bytes failed (%s)." % s)
127                options.conn.close()
128                return False
[5245e9d]129        if ret == 2:
130                dprint("Username and password OK.")
[c7304b2]131                options.conn.send("PASSWORD OK\n")
[5245e9d]132                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
133                return True
134        else:
135                dprint("Username and/or password WRONG.")
[c7304b2]136                options.conn.send("PASSWORD KO\n")
[5245e9d]137                return False
[a316c4e]138
139def dprint(msg):
[ffd078a]140        from time import strftime
[8237df5]141        global options
142
[ffd078a]143        now = strftime("%Y-%m-%d %H:%M:%S")
144
[8237df5]145        if options.debug:
[ffd078a]146                print now + ": " + msg
[bcdc24b]147        if options.log:
148                sock = open(options.log, "a")
[ea1d796]149                sock.write("%s: %s\n" % (now, msg))
[bcdc24b]150                sock.close()
[a316c4e]151
[944a941]152class SkypeApi:
[94bd28f]153        def __init__(self):
[c15f71a]154                self.skype = Skype4Py.Skype()
[5268bd7]155                self.skype.OnNotify = self.recv
[6af541d]156                self.skype.Client.Start()
[94bd28f]157
[5268bd7]158        def recv(self, msg_text):
[5245e9d]159                global options
[d86dfb1]160                if msg_text == "PONG":
161                        return
[c15f71a]162                if "\n" in msg_text:
[7613670]163                        # crappy skype prefixes only the first line for
164                        # multiline messages so we need to do so for the other
165                        # lines, too. this is something like:
166                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
167                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
[c15f71a]168                        prefix = " ".join(msg_text.split(" ")[:3])
169                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]170                else:
[c15f71a]171                        msg_text = [msg_text]
172                for i in msg_text:
[a75f2a7]173                        # use utf-8 here to solve the following problem:
174                        # people use env vars like LC_ALL=en_US (latin1) then
175                        # they complain about why can't they receive latin2
176                        # messages.. so here it is: always use utf-8 then
177                        # everybody will be happy
178                        e = i.encode('UTF-8')
[52d779e]179                        dprint('<< ' + e)
[5245e9d]180                        if options.conn:
[af8675f]181                                try:
[5245e9d]182                                        options.conn.send(e + "\n")
[80dfdce]183                                except Exception, s:
[a75f2a7]184                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[bd85ec5]185                                        options.conn.close()
[c15f71a]186
187        def send(self, msg_text):
[4b0092e]188                if not len(msg_text) or msg_text == "PONG":
[c15f71a]189                        return
[885e563e]190                try:
[072c0fe]191                        encoding = locale.getdefaultlocale()[1]
192                        if not encoding:
193                                raise ValueError
194                        e = msg_text.decode(encoding)
[885e563e]195                except ValueError:
196                        e = msg_text.decode('UTF-8')
[52d779e]197                dprint('>> ' + e)
[c15f71a]198                try:
[05cf927]199                        c = self.skype.Command(e, Block=True)
200                        self.skype.SendCommand(c)
201                        self.recv(c.Reply)
202                except Skype4Py.SkypeError:
[c15f71a]203                        pass
[8b3beef]204                except Skype4Py.SkypeAPIError, s:
[a75f2a7]205                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[4ddda13]206
[8237df5]207class Options:
208        def __init__(self):
[1b48afb]209                self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
[1a575f69]210                # for backwards compatibility
211                self.syscfgpath = "/usr/local/etc/skyped/skyped.conf"
212                if os.path.exists(self.syscfgpath):
213                        self.cfgpath = self.syscfgpath
[8237df5]214                self.daemon = True
215                self.debug = False
216                self.help = False
[7e450c3]217                self.host = "0.0.0.0"
[bcdc24b]218                self.log = None
[d891915]219                self.port = None
[8237df5]220                self.version = False
[5245e9d]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
[8237df5]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:
[5245e9d]234        -c      --config        path to configuration file (default: %s)
[8237df5]235        -d      --debug         enable debug messages
236        -h      --help          this help
[7e450c3]237        -H      --host          set the tcp host (default: %s)
[bcdc24b]238        -l      --log           set the log file in background mode (default: none)
[8237df5]239        -n      --nofork        don't run as daemon in the background
[a349932]240        -p      --port          set the tcp port (default: %s)
[5245e9d]241        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
[8237df5]242                sys.exit(ret)
243
[4ddda13]244if __name__=='__main__':
[8237df5]245        options = Options()
246        try:
[bcdc24b]247                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "daemon", "help", "host=", "log=", "nofork", "port=", "version"])
[8237df5]248        except getopt.GetoptError:
249                options.usage(1)
250        for opt, arg in opts:
[5245e9d]251                if opt in ("-c", "--config"):
252                        options.cfgpath = arg
253                elif opt in ("-d", "--debug"):
[8237df5]254                        options.debug = True
255                elif opt in ("-h", "--help"):
256                        options.help = True
[7e450c3]257                elif opt in ("-H", "--host"):
258                        options.host = arg
[bcdc24b]259                elif opt in ("-l", "--log"):
260                        options.log = arg
[8237df5]261                elif opt in ("-n", "--nofork"):
262                        options.daemon = False
263                elif opt in ("-p", "--port"):
[d891915]264                        options.port = int(arg)
[8237df5]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)
[5245e9d]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]
[7cc2c1e]281        options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0])
282        options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0])
[d891915]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
[5245e9d]294        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
295        if options.daemon:
[8237df5]296                pid = os.fork()
297                if pid == 0:
[56ae398]298                        nullin = file(os.devnull, 'r')
299                        nullout = file(os.devnull, 'w')
[8237df5]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)
[d891915]306        else:
307                dprint('skyped is started on port %s' % options.port)
[7e450c3]308        server(options.host, options.port)
[c15f71a]309        try:
[3953172]310                skype = SkypeApi()
[8b3beef]311        except Skype4Py.SkypeAPIError, s:
[c15f71a]312                sys.exit("%s. Are you sure you have started Skype?" % s)
[4b0092e]313        gobject.timeout_add(2000, skype_idle_handler, skype)
314        gobject.timeout_add(60000, bitlbee_idle_handler, skype)
[c15f71a]315        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.