source: skype/skyped.py @ b0d40f5

Last change on this file since b0d40f5 was b0d40f5, checked in by Miklos Vajna <vmiklos@…>, at 2008-04-30T23:57:49Z

add python-gnutls support and make it default if available

  • this change in general should be ok, since openssl has problems when using it from gpl software which is distributed as a binary.
  • anyway, i hope that this will solve that magic "Fatal Python error: PyEval_RestoreThread: NULL tstate" error. at least it worth a try.
  • Property mode set to 100644
File size: 7.9 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
[b0d40f5]76        try:
77                if "SKYPED_NO_GNUTLS" in os.environ.keys():
78                        dprint("Warning, using OpenSSL instead of gnutls as requested (not recommended).")
79                        raise ImportError
80                from gnutls import crypto, connection
81                cert = crypto.X509Certificate(open(options.config.sslcert).read())
82                key = crypto.X509PrivateKey(open(options.config.sslkey).read())
83                cred = connection.X509Credentials(cert, key)
84                sock = connection.ServerSessionFactory(socket.socket(), cred)
85        except ImportError:
86                from OpenSSL import SSL
87                ctx = SSL.Context(SSL.TLSv1_METHOD)
88                ctx.use_privatekey_file(options.config.sslkey)
89                ctx.use_certificate_file(options.config.sslcert)
90                sock = SSL.Connection(ctx, socket.socket())
[a316c4e]91        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
92        sock.bind((host, port))
93        sock.listen(1)
94        gobject.io_add_watch(sock, gobject.IO_IN, listener)
95
96def listener(sock, *args):
[5245e9d]97        global options
98        options.conn, addr = sock.accept()
[b0d40f5]99        if hasattr(options.conn, 'handshake'):
100                options.conn.handshake()
[5245e9d]101        ret = 0
[c7304b2]102        line = options.conn.recv(1024)
103        if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username:
104                ret += 1
105        line = options.conn.recv(1024)
106        if line.startswith("PASSWORD") and sha.sha(line.split(' ')[1].strip()).hexdigest() == options.config.password:
107                ret += 1
[5245e9d]108        if ret == 2:
109                dprint("Username and password OK.")
[c7304b2]110                options.conn.send("PASSWORD OK\n")
[5245e9d]111                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
112                return True
113        else:
114                dprint("Username and/or password WRONG.")
[c7304b2]115                options.conn.send("PASSWORD KO\n")
[5245e9d]116                return False
[a316c4e]117
118def dprint(msg):
[8237df5]119        global options
120
121        if options.debug:
[a316c4e]122                print msg
123
[944a941]124class SkypeApi:
[94bd28f]125        def __init__(self):
[c15f71a]126                self.skype = Skype4Py.Skype()
[5268bd7]127                self.skype.OnNotify = self.recv
[6af541d]128                self.skype.Client.Start()
[94bd28f]129
[5268bd7]130        def recv(self, msg_text):
[5245e9d]131                global options
[d86dfb1]132                if msg_text == "PONG":
133                        return
[c15f71a]134                if "\n" in msg_text:
[7613670]135                        # crappy skype prefixes only the first line for
136                        # multiline messages so we need to do so for the other
137                        # lines, too. this is something like:
138                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
139                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
[c15f71a]140                        prefix = " ".join(msg_text.split(" ")[:3])
141                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]142                else:
[c15f71a]143                        msg_text = [msg_text]
144                for i in msg_text:
[a75f2a7]145                        # use utf-8 here to solve the following problem:
146                        # people use env vars like LC_ALL=en_US (latin1) then
147                        # they complain about why can't they receive latin2
148                        # messages.. so here it is: always use utf-8 then
149                        # everybody will be happy
150                        e = i.encode('UTF-8')
[52d779e]151                        dprint('<< ' + e)
[5245e9d]152                        if options.conn:
[af8675f]153                                try:
[5245e9d]154                                        options.conn.send(e + "\n")
[80dfdce]155                                except Exception, s:
[a75f2a7]156                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[c15f71a]157
158        def send(self, msg_text):
159                if not len(msg_text):
160                        return
[52d779e]161                e = msg_text.decode(locale.getdefaultlocale()[1])
162                dprint('>> ' + e)
[c15f71a]163                try:
[05cf927]164                        c = self.skype.Command(e, Block=True)
165                        self.skype.SendCommand(c)
166                        self.recv(c.Reply)
167                except Skype4Py.SkypeError:
[c15f71a]168                        pass
[8b3beef]169                except Skype4Py.SkypeAPIError, s:
[a75f2a7]170                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[4ddda13]171
[8237df5]172class Options:
173        def __init__(self):
[c7304b2]174                self.cfgpath = "/usr/local/etc/skyped/skyped.conf"
[8237df5]175                self.daemon = True
176                self.debug = False
177                self.help = False
[7e450c3]178                self.host = "0.0.0.0"
[8237df5]179                self.port = 2727
180                self.version = False
[5245e9d]181                # well, this is a bit hackish. we store the socket of the last connected client
182                # here and notify it. maybe later notify all connected clients?
183                self.conn = None
184                # this will be read first by the input handler
185                self.buf = None
186
[8237df5]187
188        def usage(self, ret):
189                print """Usage: skyped [OPTION]...
190
191skyped is a daemon that acts as a tcp server on top of a Skype instance.
192
193Options:
[5245e9d]194        -c      --config        path to configuration file (default: %s)
[8237df5]195        -d      --debug         enable debug messages
196        -h      --help          this help
[7e450c3]197        -H      --host          set the tcp host (default: %s)
[8237df5]198        -n      --nofork        don't run as daemon in the background
199        -p      --port          set the tcp port (default: %d)
[5245e9d]200        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
[8237df5]201                sys.exit(ret)
202
[4ddda13]203if __name__=='__main__':
[8237df5]204        options = Options()
205        try:
[5245e9d]206                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"])
[8237df5]207        except getopt.GetoptError:
208                options.usage(1)
209        for opt, arg in opts:
[5245e9d]210                if opt in ("-c", "--config"):
211                        options.cfgpath = arg
212                elif opt in ("-d", "--debug"):
[8237df5]213                        options.debug = True
214                elif opt in ("-h", "--help"):
215                        options.help = True
[7e450c3]216                elif opt in ("-H", "--host"):
217                        options.host = arg
[8237df5]218                elif opt in ("-n", "--nofork"):
219                        options.daemon = False
220                elif opt in ("-p", "--port"):
221                        options.port = arg
222                elif opt in ("-v", "--version"):
223                        options.version = True
224        if options.help:
225                options.usage(0)
226        elif options.version:
227                print "skyped %s" % __version__
228                sys.exit(0)
[5245e9d]229        # parse our config
230        if not os.path.exists(options.cfgpath):
231                print "Can't find configuration file at '%s'." % options.cfgpath
232                print "Use the -c option to specify an alternate one."
233                sys.exit(1)
234        options.config = ConfigParser()
235        options.config.read(options.cfgpath)
236        options.config.username = options.config.get('skyped', 'username').split('#')[0]
237        options.config.password = options.config.get('skyped', 'password').split('#')[0]
[c7304b2]238        options.config.sslkey = options.config.get('skyped', 'key').split('#')[0]
239        options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0]
[5245e9d]240        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
241        if options.daemon:
[8237df5]242                pid = os.fork()
243                if pid == 0:
244                        nullin = file('/dev/null', 'r')
245                        nullout = file('/dev/null', 'w')
246                        os.dup2(nullin.fileno(), sys.stdin.fileno())
247                        os.dup2(nullout.fileno(), sys.stdout.fileno())
248                        os.dup2(nullout.fileno(), sys.stderr.fileno())
249                else:
250                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
251                        sys.exit(0)
[7e450c3]252        server(options.host, options.port)
[c15f71a]253        try:
[3953172]254                skype = SkypeApi()
[8b3beef]255        except Skype4Py.SkypeAPIError, s:
[c15f71a]256                sys.exit("%s. Are you sure you have started Skype?" % s)
[0fbeef1]257        gobject.timeout_add(2000, idle_handler, skype)
[c15f71a]258        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.