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