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