source: skype/skyped.py @ 4c340e9

Last change on this file since 4c340e9 was 4c340e9, checked in by Miklos Vajna <vmiklos@…>, at 2008-04-30T22:17:55Z

modularize openssl code

  • so that later we may use gnutls as well (or other ssl implementations)
  • Property mode set to 100644
File size: 7.3 KB
RevLine 
[4ddda13]1#!/usr/bin/env python
[cd3022c]2#
3#   skyped.py
4
[a74f5b5]5#   Copyright (c) 2007, 2008 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
[5245e9d]32import sha
33from ConfigParser import ConfigParser
[eeeb30e]34from traceback import print_exception
[4ddda13]35
[8237df5]36__version__ = "0.1.1"
[4ddda13]37
38SKYPE_SERVICE = 'com.Skype.API'
39CLIENT_NAME = 'SkypeApiPythonShell'
40
[eeeb30e]41def eh(type, value, tb):
[3a2a0b2]42        if type != KeyboardInterrupt:
43                print_exception(type, value, tb)
44        gobject.MainLoop().quit()
45        skype.skype.Client.Shutdown()
46        sys.exit("Exiting.")
[eeeb30e]47
48sys.excepthook = eh
49
[4ddda13]50def input_handler(fd, io_condition):
[5245e9d]51        global options
52        if options.buf:
53                for i in options.buf:
54                        skype.send(i.strip())
55                options.buf = None
56        else:
[2eb4b1f]57                try:
58                        input = fd.recv(1024)
[140ffc8]59                except Exception, s:
60                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
[2eb4b1f]61                        return True
[5245e9d]62                for i in input.split("\n"):
63                        skype.send(i.strip())
64                return True
[c15f71a]65
66def idle_handler(skype):
[3922d44]67        try:
[6af541d]68                c = skype.skype.Command("PING", Block=True)
69                skype.skype.SendCommand(c)
[3922d44]70        except Skype4Py.SkypeAPIError, s:
71                dprint("Warning, pinging Skype failed (%s)." % (s))
[94bd28f]72        return True
[4ddda13]73
[a316c4e]74def server(host, port):
[c7304b2]75        global options
76
[4c340e9]77        from OpenSSL import SSL
[c7304b2]78        ctx = SSL.Context(SSL.TLSv1_METHOD)
79        ctx.use_privatekey_file(options.config.sslkey)
80        ctx.use_certificate_file(options.config.sslcert)
81        sock = SSL.Connection(ctx, socket.socket())
[4c340e9]82
[a316c4e]83        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
84        sock.bind((host, port))
85        sock.listen(1)
86        gobject.io_add_watch(sock, gobject.IO_IN, listener)
87
88def listener(sock, *args):
[5245e9d]89        global options
90        options.conn, addr = sock.accept()
91        ret = 0
[c7304b2]92        line = options.conn.recv(1024)
93        if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
94                ret += 1
95        line = options.conn.recv(1024)
96        if line.startswith("PASSWORD") and sha.sha(line.split(' ')[1].strip()).hexdigest() == options.config.password:
97                ret += 1
[5245e9d]98        if ret == 2:
99                dprint("Username and password OK.")
[c7304b2]100                options.conn.send("PASSWORD OK\n")
[5245e9d]101                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
102                return True
103        else:
104                dprint("Username and/or password WRONG.")
[c7304b2]105                options.conn.send("PASSWORD KO\n")
[5245e9d]106                return False
[a316c4e]107
108def dprint(msg):
[8237df5]109        global options
110
111        if options.debug:
[a316c4e]112                print msg
113
[944a941]114class SkypeApi:
[94bd28f]115        def __init__(self):
[c15f71a]116                self.skype = Skype4Py.Skype()
[5268bd7]117                self.skype.OnNotify = self.recv
[6af541d]118                self.skype.Client.Start()
[94bd28f]119
[5268bd7]120        def recv(self, msg_text):
[5245e9d]121                global options
[d86dfb1]122                if msg_text == "PONG":
123                        return
[c15f71a]124                if "\n" in msg_text:
[7613670]125                        # crappy skype prefixes only the first line for
126                        # multiline messages so we need to do so for the other
127                        # lines, too. this is something like:
128                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
129                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
[c15f71a]130                        prefix = " ".join(msg_text.split(" ")[:3])
131                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]132                else:
[c15f71a]133                        msg_text = [msg_text]
134                for i in msg_text:
[a75f2a7]135                        # use utf-8 here to solve the following problem:
136                        # people use env vars like LC_ALL=en_US (latin1) then
137                        # they complain about why can't they receive latin2
138                        # messages.. so here it is: always use utf-8 then
139                        # everybody will be happy
140                        e = i.encode('UTF-8')
[52d779e]141                        dprint('<< ' + e)
[5245e9d]142                        if options.conn:
[af8675f]143                                try:
[5245e9d]144                                        options.conn.send(e + "\n")
[80dfdce]145                                except Exception, s:
[a75f2a7]146                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[c15f71a]147
148        def send(self, msg_text):
149                if not len(msg_text):
150                        return
[52d779e]151                e = msg_text.decode(locale.getdefaultlocale()[1])
152                dprint('>> ' + e)
[c15f71a]153                try:
[05cf927]154                        c = self.skype.Command(e, Block=True)
155                        self.skype.SendCommand(c)
156                        self.recv(c.Reply)
157                except Skype4Py.SkypeError:
[c15f71a]158                        pass
[8b3beef]159                except Skype4Py.SkypeAPIError, s:
[a75f2a7]160                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[4ddda13]161
[8237df5]162class Options:
163        def __init__(self):
[c7304b2]164                self.cfgpath = "/usr/local/etc/skyped/skyped.conf"
[8237df5]165                self.daemon = True
166                self.debug = False
167                self.help = False
[7e450c3]168                self.host = "0.0.0.0"
[8237df5]169                self.port = 2727
170                self.version = False
[5245e9d]171                # well, this is a bit hackish. we store the socket of the last connected client
172                # here and notify it. maybe later notify all connected clients?
173                self.conn = None
174                # this will be read first by the input handler
175                self.buf = None
176
[8237df5]177
178        def usage(self, ret):
179                print """Usage: skyped [OPTION]...
180
181skyped is a daemon that acts as a tcp server on top of a Skype instance.
182
183Options:
[5245e9d]184        -c      --config        path to configuration file (default: %s)
[8237df5]185        -d      --debug         enable debug messages
186        -h      --help          this help
[7e450c3]187        -H      --host          set the tcp host (default: %s)
[8237df5]188        -n      --nofork        don't run as daemon in the background
189        -p      --port          set the tcp port (default: %d)
[5245e9d]190        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
[8237df5]191                sys.exit(ret)
192
[4ddda13]193if __name__=='__main__':
[8237df5]194        options = Options()
195        try:
[5245e9d]196                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"])
[8237df5]197        except getopt.GetoptError:
198                options.usage(1)
199        for opt, arg in opts:
[5245e9d]200                if opt in ("-c", "--config"):
201                        options.cfgpath = arg
202                elif opt in ("-d", "--debug"):
[8237df5]203                        options.debug = True
204                elif opt in ("-h", "--help"):
205                        options.help = True
[7e450c3]206                elif opt in ("-H", "--host"):
207                        options.host = arg
[8237df5]208                elif opt in ("-n", "--nofork"):
209                        options.daemon = False
210                elif opt in ("-p", "--port"):
211                        options.port = arg
212                elif opt in ("-v", "--version"):
213                        options.version = True
214        if options.help:
215                options.usage(0)
216        elif options.version:
217                print "skyped %s" % __version__
218                sys.exit(0)
[5245e9d]219        # parse our config
220        if not os.path.exists(options.cfgpath):
221                print "Can't find configuration file at '%s'." % options.cfgpath
222                print "Use the -c option to specify an alternate one."
223                sys.exit(1)
224        options.config = ConfigParser()
225        options.config.read(options.cfgpath)
226        options.config.username = options.config.get('skyped', 'username').split('#')[0]
227        options.config.password = options.config.get('skyped', 'password').split('#')[0]
[c7304b2]228        options.config.sslkey = options.config.get('skyped', 'key').split('#')[0]
229        options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0]
[5245e9d]230        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
231        if options.daemon:
[8237df5]232                pid = os.fork()
233                if pid == 0:
234                        nullin = file('/dev/null', 'r')
235                        nullout = file('/dev/null', 'w')
236                        os.dup2(nullin.fileno(), sys.stdin.fileno())
237                        os.dup2(nullout.fileno(), sys.stdout.fileno())
238                        os.dup2(nullout.fileno(), sys.stderr.fileno())
239                else:
240                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
241                        sys.exit(0)
[7e450c3]242        server(options.host, options.port)
[c15f71a]243        try:
[3953172]244                skype = SkypeApi()
[8b3beef]245        except Skype4Py.SkypeAPIError, s:
[c15f71a]246                sys.exit("%s. Are you sure you have started Skype?" % s)
[0fbeef1]247        gobject.timeout_add(2000, idle_handler, skype)
[c15f71a]248        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.