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