source: skype/skyped.py @ d891915

Last change on this file since d891915 was d891915, checked in by Miklos Vajna <vmiklos@…>, at 2008-05-19T18:22:03Z

allow setting the port from the config file

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