1 | #!/usr/bin/env python2.7 |
---|
2 | # |
---|
3 | # skyped.py |
---|
4 | # |
---|
5 | # Copyright (c) 2007, 2008, 2009, 2010 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 | |
---|
23 | import sys |
---|
24 | import os |
---|
25 | import signal |
---|
26 | import locale |
---|
27 | import time |
---|
28 | import socket |
---|
29 | import getopt |
---|
30 | import Skype4Py |
---|
31 | import hashlib |
---|
32 | from ConfigParser import ConfigParser, NoOptionError |
---|
33 | from traceback import print_exception |
---|
34 | import ssl |
---|
35 | import select |
---|
36 | |
---|
37 | __version__ = "0.1.1" |
---|
38 | |
---|
39 | def eh(type, value, tb): |
---|
40 | global options |
---|
41 | |
---|
42 | if type != KeyboardInterrupt: |
---|
43 | print_exception(type, value, tb) |
---|
44 | if options.conn: options.conn.close() |
---|
45 | # shut down client if it's running |
---|
46 | try: |
---|
47 | skype.skype.Client.Shutdown() |
---|
48 | except NameError: |
---|
49 | pass |
---|
50 | sys.exit("Exiting.") |
---|
51 | |
---|
52 | sys.excepthook = eh |
---|
53 | |
---|
54 | def input_handler(fd): |
---|
55 | global options |
---|
56 | global skype |
---|
57 | if options.buf: |
---|
58 | for i in options.buf: |
---|
59 | skype.send(i.strip()) |
---|
60 | options.buf = None |
---|
61 | return True |
---|
62 | else: |
---|
63 | try: |
---|
64 | input = fd.recv(1024) |
---|
65 | except Exception, s: |
---|
66 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
67 | fd.close() |
---|
68 | options.conn = False |
---|
69 | return False |
---|
70 | for i in input.split("\n"): |
---|
71 | skype.send(i.strip()) |
---|
72 | return True |
---|
73 | |
---|
74 | def skype_idle_handler(skype): |
---|
75 | try: |
---|
76 | c = skype.skype.Command("PING", Block=True) |
---|
77 | skype.skype.SendCommand(c) |
---|
78 | dprint("... skype pinged") |
---|
79 | except Skype4Py.SkypeAPIError, s: |
---|
80 | dprint("Warning, pinging Skype failed (%s)." % (s)) |
---|
81 | return True |
---|
82 | |
---|
83 | def send(sock, txt): |
---|
84 | count = 1 |
---|
85 | done = False |
---|
86 | while (not done) and (count < 10): |
---|
87 | try: |
---|
88 | sock.send(txt) |
---|
89 | done = True |
---|
90 | except Exception, s: |
---|
91 | count += 1 |
---|
92 | dprint("Warning, sending '%s' failed (%s). count=%d" % (txt, s, count)) |
---|
93 | time.sleep(1) |
---|
94 | if not done: |
---|
95 | if options.conn: options.conn.close() |
---|
96 | options.conn = False |
---|
97 | return done |
---|
98 | |
---|
99 | def bitlbee_idle_handler(skype): |
---|
100 | global options |
---|
101 | done = False |
---|
102 | if options.conn: |
---|
103 | try: |
---|
104 | e = "PING" |
---|
105 | done = send(options.conn, "%s\n" % e) |
---|
106 | dprint("... pinged Bitlbee") |
---|
107 | except Exception, s: |
---|
108 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
109 | if options.conn: options.conn.close() |
---|
110 | options.conn = False |
---|
111 | done = False |
---|
112 | return done |
---|
113 | |
---|
114 | def server(host, port, skype): |
---|
115 | global options |
---|
116 | sock = socket.socket() |
---|
117 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
118 | sock.bind((host, port)) |
---|
119 | sock.listen(1) |
---|
120 | dprint("Waiting for connection...") |
---|
121 | listener(sock, skype) |
---|
122 | |
---|
123 | def listener(sock, skype): |
---|
124 | global options |
---|
125 | rawsock, addr = sock.accept() |
---|
126 | options.conn = ssl.wrap_socket(rawsock, |
---|
127 | server_side=True, |
---|
128 | certfile=options.config.sslcert, |
---|
129 | keyfile=options.config.sslkey, |
---|
130 | ssl_version=ssl.PROTOCOL_TLSv1) |
---|
131 | if hasattr(options.conn, 'handshake'): |
---|
132 | try: |
---|
133 | options.conn.handshake() |
---|
134 | except Exception: |
---|
135 | dprint("Warning, handshake failed, closing connection.") |
---|
136 | return False |
---|
137 | ret = 0 |
---|
138 | try: |
---|
139 | line = options.conn.recv(1024) |
---|
140 | if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username: |
---|
141 | ret += 1 |
---|
142 | line = options.conn.recv(1024) |
---|
143 | if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password: |
---|
144 | ret += 1 |
---|
145 | except Exception, s: |
---|
146 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
147 | options.conn.close() |
---|
148 | options.conn = False |
---|
149 | return False |
---|
150 | if ret == 2: |
---|
151 | dprint("Username and password OK.") |
---|
152 | options.conn.send("PASSWORD OK\n") |
---|
153 | serverloop(options, skype) |
---|
154 | return True |
---|
155 | else: |
---|
156 | dprint("Username and/or password WRONG.") |
---|
157 | options.conn.send("PASSWORD KO\n") |
---|
158 | options.conn.close() |
---|
159 | options.conn = False |
---|
160 | return False |
---|
161 | |
---|
162 | def dprint(msg): |
---|
163 | from time import strftime |
---|
164 | global options |
---|
165 | |
---|
166 | now = strftime("%Y-%m-%d %H:%M:%S") |
---|
167 | |
---|
168 | if options.debug: |
---|
169 | print now + ": " + msg |
---|
170 | sys.stdout.flush() |
---|
171 | if options.log: |
---|
172 | sock = open(options.log, "a") |
---|
173 | sock.write("%s: %s\n" % (now, msg)) |
---|
174 | sock.close() |
---|
175 | |
---|
176 | class SkypeApi: |
---|
177 | def __init__(self): |
---|
178 | self.skype = Skype4Py.Skype() |
---|
179 | self.skype.OnNotify = self.recv |
---|
180 | self.skype.Client.Start() |
---|
181 | |
---|
182 | def recv(self, msg_text): |
---|
183 | global options |
---|
184 | if msg_text == "PONG": |
---|
185 | return |
---|
186 | if "\n" in msg_text: |
---|
187 | # crappy skype prefixes only the first line for |
---|
188 | # multiline messages so we need to do so for the other |
---|
189 | # lines, too. this is something like: |
---|
190 | # 'CHATMESSAGE id BODY first line\nsecond line' -> |
---|
191 | # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line' |
---|
192 | prefix = " ".join(msg_text.split(" ")[:3]) |
---|
193 | msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")] |
---|
194 | else: |
---|
195 | msg_text = [msg_text] |
---|
196 | for i in msg_text: |
---|
197 | # use utf-8 here to solve the following problem: |
---|
198 | # people use env vars like LC_ALL=en_US (latin1) then |
---|
199 | # they complain about why can't they receive latin2 |
---|
200 | # messages.. so here it is: always use utf-8 then |
---|
201 | # everybody will be happy |
---|
202 | e = i.encode('UTF-8') |
---|
203 | if options.conn: |
---|
204 | dprint('<< ' + e) |
---|
205 | try: |
---|
206 | # I called the send function really_send |
---|
207 | send(options.conn, e + "\n") |
---|
208 | except Exception, s: |
---|
209 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
210 | if options.conn: options.conn.close() |
---|
211 | options.conn = False |
---|
212 | else: |
---|
213 | dprint('---' + e) |
---|
214 | |
---|
215 | def send(self, msg_text): |
---|
216 | if not len(msg_text) or msg_text == "PONG": |
---|
217 | if msg_text == "PONG": options.last_bitlbee_pong = time.time() |
---|
218 | return |
---|
219 | try: |
---|
220 | encoding = locale.getdefaultlocale()[1] |
---|
221 | if not encoding: |
---|
222 | raise ValueError |
---|
223 | e = msg_text.decode(encoding) |
---|
224 | except ValueError: |
---|
225 | e = msg_text.decode('UTF-8') |
---|
226 | dprint('>> ' + e) |
---|
227 | try: |
---|
228 | c = self.skype.Command(e, Block=True) |
---|
229 | self.skype.SendCommand(c) |
---|
230 | self.recv(c.Reply) |
---|
231 | except Skype4Py.SkypeError: |
---|
232 | pass |
---|
233 | except Skype4Py.SkypeAPIError, s: |
---|
234 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
235 | |
---|
236 | class Options: |
---|
237 | def __init__(self): |
---|
238 | self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf") |
---|
239 | # for backwards compatibility |
---|
240 | self.syscfgpath = "/usr/local/etc/skyped/skyped.conf" |
---|
241 | if os.path.exists(self.syscfgpath): |
---|
242 | self.cfgpath = self.syscfgpath |
---|
243 | self.daemon = True |
---|
244 | self.debug = False |
---|
245 | self.help = False |
---|
246 | self.host = "0.0.0.0" |
---|
247 | self.log = None |
---|
248 | self.port = None |
---|
249 | self.version = False |
---|
250 | # well, this is a bit hackish. we store the socket of the last connected client |
---|
251 | # here and notify it. maybe later notify all connected clients? |
---|
252 | self.conn = None |
---|
253 | # this will be read first by the input handler |
---|
254 | self.buf = None |
---|
255 | |
---|
256 | |
---|
257 | def usage(self, ret): |
---|
258 | print """Usage: skyped [OPTION]... |
---|
259 | |
---|
260 | skyped is a daemon that acts as a tcp server on top of a Skype instance. |
---|
261 | |
---|
262 | Options: |
---|
263 | -c --config path to configuration file (default: %s) |
---|
264 | -d --debug enable debug messages |
---|
265 | -h --help this help |
---|
266 | -H --host set the tcp host (default: %s) |
---|
267 | -l --log set the log file in background mode (default: none) |
---|
268 | -n --nofork don't run as daemon in the background |
---|
269 | -p --port set the tcp port (default: %s) |
---|
270 | -v --version display version information""" % (self.cfgpath, self.host, self.port) |
---|
271 | sys.exit(ret) |
---|
272 | |
---|
273 | def serverloop(options, skype): |
---|
274 | timeout = 1; # in seconds |
---|
275 | skype_ping_period = 5 |
---|
276 | bitlbee_ping_period = 10 |
---|
277 | bitlbee_pong_timeout = 30 |
---|
278 | now = time.time() |
---|
279 | skype_ping_start_time = now |
---|
280 | bitlbee_ping_start_time = now |
---|
281 | options.last_bitlbee_pong = now |
---|
282 | in_error = [] |
---|
283 | handler_ok = True |
---|
284 | while (len(in_error) == 0) and handler_ok and options.conn: |
---|
285 | ready_to_read, ready_to_write, in_error = \ |
---|
286 | select.select([options.conn], [], [options.conn], \ |
---|
287 | timeout) |
---|
288 | now = time.time() |
---|
289 | handler_ok = len(in_error) == 0 |
---|
290 | if (len(ready_to_read) == 1) and handler_ok: |
---|
291 | handler_ok = input_handler(ready_to_read.pop()) |
---|
292 | # don't ping bitlbee/skype if they already received data |
---|
293 | now = time.time() # allow for the input_handler to take some time |
---|
294 | bitlbee_ping_start_time = now |
---|
295 | skype_ping_start_time = now |
---|
296 | options.last_bitlbee_pong = now |
---|
297 | if (now - skype_ping_period > skype_ping_start_time) and handler_ok: |
---|
298 | handler_ok = skype_idle_handler(skype) |
---|
299 | skype_ping_start_time = now |
---|
300 | if now - bitlbee_ping_period > bitlbee_ping_start_time: |
---|
301 | handler_ok = bitlbee_idle_handler(skype) |
---|
302 | bitlbee_ping_start_time = now |
---|
303 | if options.last_bitlbee_pong: |
---|
304 | if (now - options.last_bitlbee_pong) > bitlbee_pong_timeout: |
---|
305 | dprint("Bitlbee pong timeout") |
---|
306 | # TODO is following line necessary? Should there be a options.conn.unwrap() somewhere? |
---|
307 | # options.conn.shutdown() |
---|
308 | if options.conn: options.conn.close() |
---|
309 | options.conn = False |
---|
310 | else: |
---|
311 | dprint("%f seconds since last PONG" % (now - options.last_bitlbee_pong)) |
---|
312 | else: |
---|
313 | options.last_bitlbee_pong = now |
---|
314 | dprint("Serverloop done") |
---|
315 | |
---|
316 | if __name__=='__main__': |
---|
317 | options = Options() |
---|
318 | try: |
---|
319 | opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"]) |
---|
320 | except getopt.GetoptError: |
---|
321 | options.usage(1) |
---|
322 | for opt, arg in opts: |
---|
323 | if opt in ("-c", "--config"): |
---|
324 | options.cfgpath = arg |
---|
325 | elif opt in ("-d", "--debug"): |
---|
326 | options.debug = True |
---|
327 | elif opt in ("-h", "--help"): |
---|
328 | options.help = True |
---|
329 | elif opt in ("-H", "--host"): |
---|
330 | options.host = arg |
---|
331 | elif opt in ("-l", "--log"): |
---|
332 | options.log = arg |
---|
333 | elif opt in ("-n", "--nofork"): |
---|
334 | options.daemon = False |
---|
335 | elif opt in ("-p", "--port"): |
---|
336 | options.port = int(arg) |
---|
337 | elif opt in ("-v", "--version"): |
---|
338 | options.version = True |
---|
339 | if options.help: |
---|
340 | options.usage(0) |
---|
341 | elif options.version: |
---|
342 | print "skyped %s" % __version__ |
---|
343 | sys.exit(0) |
---|
344 | # parse our config |
---|
345 | if not os.path.exists(options.cfgpath): |
---|
346 | print "Can't find configuration file at '%s'." % options.cfgpath |
---|
347 | print "Use the -c option to specify an alternate one." |
---|
348 | sys.exit(1) |
---|
349 | options.config = ConfigParser() |
---|
350 | options.config.read(options.cfgpath) |
---|
351 | options.config.username = options.config.get('skyped', 'username').split('#')[0] |
---|
352 | options.config.password = options.config.get('skyped', 'password').split('#')[0] |
---|
353 | options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0]) |
---|
354 | options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0]) |
---|
355 | # hack: we have to parse the parameters first to locate the |
---|
356 | # config file but the -p option should overwrite the value from |
---|
357 | # the config file |
---|
358 | try: |
---|
359 | options.config.port = int(options.config.get('skyped', 'port').split('#')[0]) |
---|
360 | if not options.port: |
---|
361 | options.port = options.config.port |
---|
362 | except NoOptionError: |
---|
363 | pass |
---|
364 | if not options.port: |
---|
365 | options.port = 2727 |
---|
366 | dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username)) |
---|
367 | if options.daemon: |
---|
368 | pid = os.fork() |
---|
369 | if pid == 0: |
---|
370 | nullin = file(os.devnull, 'r') |
---|
371 | nullout = file(os.devnull, 'w') |
---|
372 | os.dup2(nullin.fileno(), sys.stdin.fileno()) |
---|
373 | os.dup2(nullout.fileno(), sys.stdout.fileno()) |
---|
374 | os.dup2(nullout.fileno(), sys.stderr.fileno()) |
---|
375 | else: |
---|
376 | print 'skyped is started on port %s, pid: %d' % (options.port, pid) |
---|
377 | sys.exit(0) |
---|
378 | else: |
---|
379 | dprint('skyped is started on port %s' % options.port) |
---|
380 | try: |
---|
381 | skype = SkypeApi() |
---|
382 | except Skype4Py.SkypeAPIError, s: |
---|
383 | sys.exit("%s. Are you sure you have started Skype?" % s) |
---|
384 | while 1: |
---|
385 | options.conn = False |
---|
386 | server(options.host, options.port, skype) |
---|