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
Line 
1#!/usr/bin/env python
2#
3#   skyped.py
4
5#   Copyright (c) 2007, 2008 by Miklos Vajna <vmiklos@frugalware.org>
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
23import sys
24import os
25import signal
26import locale
27import time
28import gobject
29import socket
30import getopt
31import Skype4Py
32import sha
33from ConfigParser import ConfigParser
34from traceback import print_exception
35
36__version__ = "0.1.1"
37
38SKYPE_SERVICE = 'com.Skype.API'
39CLIENT_NAME = 'SkypeApiPythonShell'
40
41def eh(type, value, tb):
42        if type != KeyboardInterrupt:
43                print_exception(type, value, tb)
44        gobject.MainLoop().quit()
45        skype.skype.Client.Shutdown()
46        sys.exit("Exiting.")
47
48sys.excepthook = eh
49
50def input_handler(fd, io_condition):
51        global options
52        if options.buf:
53                for i in options.buf:
54                        skype.send(i.strip())
55                options.buf = None
56        else:
57                try:
58                        input = fd.recv(1024)
59                except Exception, s:
60                        dprint("Warning, receiving 1024 bytes failed (%s)." % s)
61                        return True
62                for i in input.split("\n"):
63                        skype.send(i.strip())
64                return True
65
66def idle_handler(skype):
67        try:
68                c = skype.skype.Command("PING", Block=True)
69                skype.skype.SendCommand(c)
70        except Skype4Py.SkypeAPIError, s:
71                dprint("Warning, pinging Skype failed (%s)." % (s))
72        return True
73
74def server(host, port):
75        global options
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())
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):
97        global options
98        options.conn, addr = sock.accept()
99        if hasattr(options.conn, 'handshake'):
100                options.conn.handshake()
101        ret = 0
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
108        if ret == 2:
109                dprint("Username and password OK.")
110                options.conn.send("PASSWORD OK\n")
111                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
112                return True
113        else:
114                dprint("Username and/or password WRONG.")
115                options.conn.send("PASSWORD KO\n")
116                return False
117
118def dprint(msg):
119        global options
120
121        if options.debug:
122                print msg
123
124class SkypeApi:
125        def __init__(self):
126                self.skype = Skype4Py.Skype()
127                self.skype.OnNotify = self.recv
128                self.skype.Client.Start()
129
130        def recv(self, msg_text):
131                global options
132                if msg_text == "PONG":
133                        return
134                if "\n" in msg_text:
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'
140                        prefix = " ".join(msg_text.split(" ")[:3])
141                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
142                else:
143                        msg_text = [msg_text]
144                for i in msg_text:
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')
151                        dprint('<< ' + e)
152                        if options.conn:
153                                try:
154                                        options.conn.send(e + "\n")
155                                except Exception, s:
156                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
157
158        def send(self, msg_text):
159                if not len(msg_text):
160                        return
161                e = msg_text.decode(locale.getdefaultlocale()[1])
162                dprint('>> ' + e)
163                try:
164                        c = self.skype.Command(e, Block=True)
165                        self.skype.SendCommand(c)
166                        self.recv(c.Reply)
167                except Skype4Py.SkypeError:
168                        pass
169                except Skype4Py.SkypeAPIError, s:
170                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
171
172class Options:
173        def __init__(self):
174                self.cfgpath = "/usr/local/etc/skyped/skyped.conf"
175                self.daemon = True
176                self.debug = False
177                self.help = False
178                self.host = "0.0.0.0"
179                self.port = 2727
180                self.version = False
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
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:
194        -c      --config        path to configuration file (default: %s)
195        -d      --debug         enable debug messages
196        -h      --help          this help
197        -H      --host          set the tcp host (default: %s)
198        -n      --nofork        don't run as daemon in the background
199        -p      --port          set the tcp port (default: %d)
200        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
201                sys.exit(ret)
202
203if __name__=='__main__':
204        options = Options()
205        try:
206                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"])
207        except getopt.GetoptError:
208                options.usage(1)
209        for opt, arg in opts:
210                if opt in ("-c", "--config"):
211                        options.cfgpath = arg
212                elif opt in ("-d", "--debug"):
213                        options.debug = True
214                elif opt in ("-h", "--help"):
215                        options.help = True
216                elif opt in ("-H", "--host"):
217                        options.host = arg
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)
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]
238        options.config.sslkey = options.config.get('skyped', 'key').split('#')[0]
239        options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0]
240        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
241        if options.daemon:
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)
252        server(options.host, options.port)
253        try:
254                skype = SkypeApi()
255        except Skype4Py.SkypeAPIError, s:
256                sys.exit("%s. Are you sure you have started Skype?" % s)
257        gobject.timeout_add(2000, idle_handler, skype)
258        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.