[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] | 23 | import sys |
---|
[8237df5] | 24 | import os |
---|
[4ddda13] | 25 | import signal |
---|
| 26 | import locale |
---|
| 27 | import time |
---|
| 28 | import gobject |
---|
| 29 | import socket |
---|
[8237df5] | 30 | import getopt |
---|
[c15f71a] | 31 | import Skype4Py |
---|
[8edfc90] | 32 | import hashlib |
---|
[d891915] | 33 | from ConfigParser import ConfigParser, NoOptionError |
---|
[eeeb30e] | 34 | from traceback import print_exception |
---|
[4ddda13] | 35 | |
---|
[8237df5] | 36 | __version__ = "0.1.1" |
---|
[4ddda13] | 37 | |
---|
| 38 | SKYPE_SERVICE = 'com.Skype.API' |
---|
| 39 | |
---|
[eeeb30e] | 40 | def eh(type, value, tb): |
---|
[3a2a0b2] | 41 | if type != KeyboardInterrupt: |
---|
| 42 | print_exception(type, value, tb) |
---|
| 43 | gobject.MainLoop().quit() |
---|
[7415989] | 44 | # shut down client if it's running |
---|
| 45 | try: |
---|
| 46 | skype.skype.Client.Shutdown() |
---|
| 47 | except NameError: |
---|
| 48 | pass |
---|
[3a2a0b2] | 49 | sys.exit("Exiting.") |
---|
[eeeb30e] | 50 | |
---|
| 51 | sys.excepthook = eh |
---|
| 52 | |
---|
[4ddda13] | 53 | def input_handler(fd, io_condition): |
---|
[5245e9d] | 54 | global options |
---|
| 55 | if options.buf: |
---|
| 56 | for i in options.buf: |
---|
| 57 | skype.send(i.strip()) |
---|
| 58 | options.buf = None |
---|
| 59 | else: |
---|
[2eb4b1f] | 60 | try: |
---|
| 61 | input = fd.recv(1024) |
---|
[140ffc8] | 62 | except Exception, s: |
---|
| 63 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
[bd85ec5] | 64 | fd.close() |
---|
| 65 | return False |
---|
[5245e9d] | 66 | for i in input.split("\n"): |
---|
| 67 | skype.send(i.strip()) |
---|
| 68 | return True |
---|
[c15f71a] | 69 | |
---|
[4b0092e] | 70 | def skype_idle_handler(skype): |
---|
[3922d44] | 71 | try: |
---|
[6af541d] | 72 | c = skype.skype.Command("PING", Block=True) |
---|
| 73 | skype.skype.SendCommand(c) |
---|
[3922d44] | 74 | except Skype4Py.SkypeAPIError, s: |
---|
| 75 | dprint("Warning, pinging Skype failed (%s)." % (s)) |
---|
[94bd28f] | 76 | return True |
---|
[4ddda13] | 77 | |
---|
[4b0092e] | 78 | def bitlbee_idle_handler(skype): |
---|
| 79 | if options.conn: |
---|
| 80 | try: |
---|
| 81 | e = "PING" |
---|
| 82 | options.conn.send("%s\n" % e) |
---|
| 83 | except Exception, s: |
---|
| 84 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
| 85 | options.conn.close() |
---|
| 86 | return True |
---|
| 87 | |
---|
[a316c4e] | 88 | def server(host, port): |
---|
[c7304b2] | 89 | global options |
---|
[b0d40f5] | 90 | try: |
---|
| 91 | if "SKYPED_NO_GNUTLS" in os.environ.keys(): |
---|
| 92 | dprint("Warning, using OpenSSL instead of gnutls as requested (not recommended).") |
---|
| 93 | raise ImportError |
---|
| 94 | from gnutls import crypto, connection |
---|
| 95 | cert = crypto.X509Certificate(open(options.config.sslcert).read()) |
---|
| 96 | key = crypto.X509PrivateKey(open(options.config.sslkey).read()) |
---|
| 97 | cred = connection.X509Credentials(cert, key) |
---|
| 98 | sock = connection.ServerSessionFactory(socket.socket(), cred) |
---|
| 99 | except ImportError: |
---|
| 100 | from OpenSSL import SSL |
---|
| 101 | ctx = SSL.Context(SSL.TLSv1_METHOD) |
---|
| 102 | ctx.use_privatekey_file(options.config.sslkey) |
---|
| 103 | ctx.use_certificate_file(options.config.sslcert) |
---|
| 104 | sock = SSL.Connection(ctx, socket.socket()) |
---|
[a316c4e] | 105 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
| 106 | sock.bind((host, port)) |
---|
| 107 | sock.listen(1) |
---|
| 108 | gobject.io_add_watch(sock, gobject.IO_IN, listener) |
---|
| 109 | |
---|
| 110 | def listener(sock, *args): |
---|
[5245e9d] | 111 | global options |
---|
| 112 | options.conn, addr = sock.accept() |
---|
[b0d40f5] | 113 | if hasattr(options.conn, 'handshake'): |
---|
[5588f7c4] | 114 | try: |
---|
| 115 | options.conn.handshake() |
---|
| 116 | except Exception: |
---|
| 117 | dprint("Warning, handshake failed, closing connection.") |
---|
| 118 | return False |
---|
[5245e9d] | 119 | ret = 0 |
---|
[6b9cab1] | 120 | try: |
---|
| 121 | line = options.conn.recv(1024) |
---|
| 122 | if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username: |
---|
| 123 | ret += 1 |
---|
| 124 | line = options.conn.recv(1024) |
---|
[8edfc90] | 125 | if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password: |
---|
[6b9cab1] | 126 | ret += 1 |
---|
| 127 | except Exception, s: |
---|
| 128 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
| 129 | options.conn.close() |
---|
| 130 | return False |
---|
[5245e9d] | 131 | if ret == 2: |
---|
| 132 | dprint("Username and password OK.") |
---|
[c7304b2] | 133 | options.conn.send("PASSWORD OK\n") |
---|
[5245e9d] | 134 | gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler) |
---|
| 135 | return True |
---|
| 136 | else: |
---|
| 137 | dprint("Username and/or password WRONG.") |
---|
[c7304b2] | 138 | options.conn.send("PASSWORD KO\n") |
---|
[5245e9d] | 139 | return False |
---|
[a316c4e] | 140 | |
---|
| 141 | def dprint(msg): |
---|
[8237df5] | 142 | global options |
---|
| 143 | |
---|
| 144 | if options.debug: |
---|
[a316c4e] | 145 | print msg |
---|
| 146 | |
---|
[944a941] | 147 | class SkypeApi: |
---|
[94bd28f] | 148 | def __init__(self): |
---|
[c15f71a] | 149 | self.skype = Skype4Py.Skype() |
---|
[5268bd7] | 150 | self.skype.OnNotify = self.recv |
---|
[6af541d] | 151 | self.skype.Client.Start() |
---|
[94bd28f] | 152 | |
---|
[5268bd7] | 153 | def recv(self, msg_text): |
---|
[5245e9d] | 154 | global options |
---|
[d86dfb1] | 155 | if msg_text == "PONG": |
---|
| 156 | return |
---|
[c15f71a] | 157 | if "\n" in msg_text: |
---|
[7613670] | 158 | # crappy skype prefixes only the first line for |
---|
| 159 | # multiline messages so we need to do so for the other |
---|
| 160 | # lines, too. this is something like: |
---|
| 161 | # 'CHATMESSAGE id BODY first line\nsecond line' -> |
---|
| 162 | # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line' |
---|
[c15f71a] | 163 | prefix = " ".join(msg_text.split(" ")[:3]) |
---|
| 164 | msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")] |
---|
[7613670] | 165 | else: |
---|
[c15f71a] | 166 | msg_text = [msg_text] |
---|
| 167 | for i in msg_text: |
---|
[a75f2a7] | 168 | # use utf-8 here to solve the following problem: |
---|
| 169 | # people use env vars like LC_ALL=en_US (latin1) then |
---|
| 170 | # they complain about why can't they receive latin2 |
---|
| 171 | # messages.. so here it is: always use utf-8 then |
---|
| 172 | # everybody will be happy |
---|
| 173 | e = i.encode('UTF-8') |
---|
[52d779e] | 174 | dprint('<< ' + e) |
---|
[5245e9d] | 175 | if options.conn: |
---|
[af8675f] | 176 | try: |
---|
[5245e9d] | 177 | options.conn.send(e + "\n") |
---|
[80dfdce] | 178 | except Exception, s: |
---|
[a75f2a7] | 179 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
[bd85ec5] | 180 | options.conn.close() |
---|
[c15f71a] | 181 | |
---|
| 182 | def send(self, msg_text): |
---|
[4b0092e] | 183 | if not len(msg_text) or msg_text == "PONG": |
---|
[c15f71a] | 184 | return |
---|
[885e563e] | 185 | try: |
---|
[072c0fe] | 186 | encoding = locale.getdefaultlocale()[1] |
---|
| 187 | if not encoding: |
---|
| 188 | raise ValueError |
---|
| 189 | e = msg_text.decode(encoding) |
---|
[885e563e] | 190 | except ValueError: |
---|
| 191 | e = msg_text.decode('UTF-8') |
---|
[52d779e] | 192 | dprint('>> ' + e) |
---|
[c15f71a] | 193 | try: |
---|
[05cf927] | 194 | c = self.skype.Command(e, Block=True) |
---|
| 195 | self.skype.SendCommand(c) |
---|
| 196 | self.recv(c.Reply) |
---|
| 197 | except Skype4Py.SkypeError: |
---|
[c15f71a] | 198 | pass |
---|
[8b3beef] | 199 | except Skype4Py.SkypeAPIError, s: |
---|
[a75f2a7] | 200 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
[4ddda13] | 201 | |
---|
[8237df5] | 202 | class Options: |
---|
| 203 | def __init__(self): |
---|
[c7304b2] | 204 | self.cfgpath = "/usr/local/etc/skyped/skyped.conf" |
---|
[8237df5] | 205 | self.daemon = True |
---|
| 206 | self.debug = False |
---|
| 207 | self.help = False |
---|
[7e450c3] | 208 | self.host = "0.0.0.0" |
---|
[d891915] | 209 | self.port = None |
---|
[8237df5] | 210 | self.version = False |
---|
[5245e9d] | 211 | # well, this is a bit hackish. we store the socket of the last connected client |
---|
| 212 | # here and notify it. maybe later notify all connected clients? |
---|
| 213 | self.conn = None |
---|
| 214 | # this will be read first by the input handler |
---|
| 215 | self.buf = None |
---|
| 216 | |
---|
[8237df5] | 217 | |
---|
| 218 | def usage(self, ret): |
---|
| 219 | print """Usage: skyped [OPTION]... |
---|
| 220 | |
---|
| 221 | skyped is a daemon that acts as a tcp server on top of a Skype instance. |
---|
| 222 | |
---|
| 223 | Options: |
---|
[5245e9d] | 224 | -c --config path to configuration file (default: %s) |
---|
[8237df5] | 225 | -d --debug enable debug messages |
---|
| 226 | -h --help this help |
---|
[7e450c3] | 227 | -H --host set the tcp host (default: %s) |
---|
[8237df5] | 228 | -n --nofork don't run as daemon in the background |
---|
[a349932] | 229 | -p --port set the tcp port (default: %s) |
---|
[5245e9d] | 230 | -v --version display version information""" % (self.cfgpath, self.host, self.port) |
---|
[8237df5] | 231 | sys.exit(ret) |
---|
| 232 | |
---|
[4ddda13] | 233 | if __name__=='__main__': |
---|
[8237df5] | 234 | options = Options() |
---|
| 235 | try: |
---|
[5245e9d] | 236 | opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"]) |
---|
[8237df5] | 237 | except getopt.GetoptError: |
---|
| 238 | options.usage(1) |
---|
| 239 | for opt, arg in opts: |
---|
[5245e9d] | 240 | if opt in ("-c", "--config"): |
---|
| 241 | options.cfgpath = arg |
---|
| 242 | elif opt in ("-d", "--debug"): |
---|
[8237df5] | 243 | options.debug = True |
---|
| 244 | elif opt in ("-h", "--help"): |
---|
| 245 | options.help = True |
---|
[7e450c3] | 246 | elif opt in ("-H", "--host"): |
---|
| 247 | options.host = arg |
---|
[8237df5] | 248 | elif opt in ("-n", "--nofork"): |
---|
| 249 | options.daemon = False |
---|
| 250 | elif opt in ("-p", "--port"): |
---|
[d891915] | 251 | options.port = int(arg) |
---|
[8237df5] | 252 | elif opt in ("-v", "--version"): |
---|
| 253 | options.version = True |
---|
| 254 | if options.help: |
---|
| 255 | options.usage(0) |
---|
| 256 | elif options.version: |
---|
| 257 | print "skyped %s" % __version__ |
---|
| 258 | sys.exit(0) |
---|
[5245e9d] | 259 | # parse our config |
---|
| 260 | if not os.path.exists(options.cfgpath): |
---|
| 261 | print "Can't find configuration file at '%s'." % options.cfgpath |
---|
| 262 | print "Use the -c option to specify an alternate one." |
---|
| 263 | sys.exit(1) |
---|
| 264 | options.config = ConfigParser() |
---|
| 265 | options.config.read(options.cfgpath) |
---|
| 266 | options.config.username = options.config.get('skyped', 'username').split('#')[0] |
---|
| 267 | options.config.password = options.config.get('skyped', 'password').split('#')[0] |
---|
[c7304b2] | 268 | options.config.sslkey = options.config.get('skyped', 'key').split('#')[0] |
---|
| 269 | options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0] |
---|
[d891915] | 270 | # hack: we have to parse the parameters first to locate the |
---|
| 271 | # config file but the -p option should overwrite the value from |
---|
| 272 | # the config file |
---|
| 273 | try: |
---|
| 274 | options.config.port = int(options.config.get('skyped', 'port').split('#')[0]) |
---|
| 275 | if not options.port: |
---|
| 276 | options.port = options.config.port |
---|
| 277 | except NoOptionError: |
---|
| 278 | pass |
---|
| 279 | if not options.port: |
---|
| 280 | options.port = 2727 |
---|
[5245e9d] | 281 | dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username)) |
---|
| 282 | if options.daemon: |
---|
[8237df5] | 283 | pid = os.fork() |
---|
| 284 | if pid == 0: |
---|
[56ae398] | 285 | nullin = file(os.devnull, 'r') |
---|
| 286 | nullout = file(os.devnull, 'w') |
---|
[8237df5] | 287 | os.dup2(nullin.fileno(), sys.stdin.fileno()) |
---|
| 288 | os.dup2(nullout.fileno(), sys.stdout.fileno()) |
---|
| 289 | os.dup2(nullout.fileno(), sys.stderr.fileno()) |
---|
| 290 | else: |
---|
| 291 | print 'skyped is started on port %s, pid: %d' % (options.port, pid) |
---|
| 292 | sys.exit(0) |
---|
[d891915] | 293 | else: |
---|
| 294 | dprint('skyped is started on port %s' % options.port) |
---|
[7e450c3] | 295 | server(options.host, options.port) |
---|
[c15f71a] | 296 | try: |
---|
[3953172] | 297 | skype = SkypeApi() |
---|
[8b3beef] | 298 | except Skype4Py.SkypeAPIError, s: |
---|
[c15f71a] | 299 | sys.exit("%s. Are you sure you have started Skype?" % s) |
---|
[4b0092e] | 300 | gobject.timeout_add(2000, skype_idle_handler, skype) |
---|
| 301 | gobject.timeout_add(60000, bitlbee_idle_handler, skype) |
---|
[c15f71a] | 302 | gobject.MainLoop().run() |
---|