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 | if type != KeyboardInterrupt: |
---|
41 | print_exception(type, value, tb) |
---|
42 | gobject.MainLoop().quit() |
---|
43 | # shut down client if it's running |
---|
44 | try: |
---|
45 | skype.skype.Client.Shutdown() |
---|
46 | except NameError: |
---|
47 | pass |
---|
48 | sys.exit("Exiting.") |
---|
49 | |
---|
50 | sys.excepthook = eh |
---|
51 | |
---|
52 | def input_handler(fd, io_condition): |
---|
53 | global options |
---|
54 | if options.buf: |
---|
55 | for i in options.buf: |
---|
56 | skype.send(i.strip()) |
---|
57 | options.buf = None |
---|
58 | else: |
---|
59 | try: |
---|
60 | input = fd.recv(1024) |
---|
61 | except Exception, s: |
---|
62 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
63 | fd.close() |
---|
64 | return False |
---|
65 | for i in input.split("\n"): |
---|
66 | skype.send(i.strip()) |
---|
67 | return True |
---|
68 | |
---|
69 | def skype_idle_handler(skype): |
---|
70 | try: |
---|
71 | c = skype.skype.Command("PING", Block=True) |
---|
72 | skype.skype.SendCommand(c) |
---|
73 | except Skype4Py.SkypeAPIError, s: |
---|
74 | dprint("Warning, pinging Skype failed (%s)." % (s)) |
---|
75 | return True |
---|
76 | |
---|
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 | |
---|
87 | def server(host, port): |
---|
88 | global options |
---|
89 | sock = socket.socket() |
---|
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): |
---|
96 | global options |
---|
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) |
---|
103 | if hasattr(options.conn, 'handshake'): |
---|
104 | try: |
---|
105 | options.conn.handshake() |
---|
106 | except Exception: |
---|
107 | dprint("Warning, handshake failed, closing connection.") |
---|
108 | return False |
---|
109 | ret = 0 |
---|
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) |
---|
115 | if line.startswith("PASSWORD") and hashlib.sha1(line.split(' ')[1].strip()).hexdigest() == options.config.password: |
---|
116 | ret += 1 |
---|
117 | except Exception, s: |
---|
118 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
119 | options.conn.close() |
---|
120 | return False |
---|
121 | if ret == 2: |
---|
122 | dprint("Username and password OK.") |
---|
123 | options.conn.send("PASSWORD OK\n") |
---|
124 | gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler) |
---|
125 | return True |
---|
126 | else: |
---|
127 | dprint("Username and/or password WRONG.") |
---|
128 | options.conn.send("PASSWORD KO\n") |
---|
129 | return False |
---|
130 | |
---|
131 | def dprint(msg): |
---|
132 | from time import strftime |
---|
133 | global options |
---|
134 | |
---|
135 | now = strftime("%Y-%m-%d %H:%M:%S") |
---|
136 | |
---|
137 | if options.debug: |
---|
138 | print now + ": " + msg |
---|
139 | if options.log: |
---|
140 | sock = open(options.log, "a") |
---|
141 | sock.write("%s: %s\n" % (now, msg)) |
---|
142 | sock.close() |
---|
143 | |
---|
144 | class SkypeApi: |
---|
145 | def __init__(self): |
---|
146 | self.skype = Skype4Py.Skype() |
---|
147 | self.skype.OnNotify = self.recv |
---|
148 | self.skype.Client.Start() |
---|
149 | |
---|
150 | def recv(self, msg_text): |
---|
151 | global options |
---|
152 | if msg_text == "PONG": |
---|
153 | return |
---|
154 | if "\n" in msg_text: |
---|
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' |
---|
160 | prefix = " ".join(msg_text.split(" ")[:3]) |
---|
161 | msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")] |
---|
162 | else: |
---|
163 | msg_text = [msg_text] |
---|
164 | for i in msg_text: |
---|
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') |
---|
171 | dprint('<< ' + e) |
---|
172 | if options.conn: |
---|
173 | try: |
---|
174 | options.conn.send(e + "\n") |
---|
175 | except Exception, s: |
---|
176 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
177 | options.conn.close() |
---|
178 | |
---|
179 | def send(self, msg_text): |
---|
180 | if not len(msg_text) or msg_text == "PONG": |
---|
181 | return |
---|
182 | try: |
---|
183 | encoding = locale.getdefaultlocale()[1] |
---|
184 | if not encoding: |
---|
185 | raise ValueError |
---|
186 | e = msg_text.decode(encoding) |
---|
187 | except ValueError: |
---|
188 | e = msg_text.decode('UTF-8') |
---|
189 | dprint('>> ' + e) |
---|
190 | try: |
---|
191 | c = self.skype.Command(e, Block=True) |
---|
192 | self.skype.SendCommand(c) |
---|
193 | self.recv(c.Reply) |
---|
194 | except Skype4Py.SkypeError: |
---|
195 | pass |
---|
196 | except Skype4Py.SkypeAPIError, s: |
---|
197 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
198 | |
---|
199 | class Options: |
---|
200 | def __init__(self): |
---|
201 | self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf") |
---|
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 |
---|
206 | self.daemon = True |
---|
207 | self.debug = False |
---|
208 | self.help = False |
---|
209 | self.host = "0.0.0.0" |
---|
210 | self.log = None |
---|
211 | self.port = None |
---|
212 | self.version = False |
---|
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 | |
---|
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: |
---|
226 | -c --config path to configuration file (default: %s) |
---|
227 | -d --debug enable debug messages |
---|
228 | -h --help this help |
---|
229 | -H --host set the tcp host (default: %s) |
---|
230 | -l --log set the log file in background mode (default: none) |
---|
231 | -n --nofork don't run as daemon in the background |
---|
232 | -p --port set the tcp port (default: %s) |
---|
233 | -v --version display version information""" % (self.cfgpath, self.host, self.port) |
---|
234 | sys.exit(ret) |
---|
235 | |
---|
236 | if __name__=='__main__': |
---|
237 | options = Options() |
---|
238 | try: |
---|
239 | opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:np:v", ["config=", "debug", "help", "host=", "log=", "nofork", "port=", "version"]) |
---|
240 | except getopt.GetoptError: |
---|
241 | options.usage(1) |
---|
242 | for opt, arg in opts: |
---|
243 | if opt in ("-c", "--config"): |
---|
244 | options.cfgpath = arg |
---|
245 | elif opt in ("-d", "--debug"): |
---|
246 | options.debug = True |
---|
247 | elif opt in ("-h", "--help"): |
---|
248 | options.help = True |
---|
249 | elif opt in ("-H", "--host"): |
---|
250 | options.host = arg |
---|
251 | elif opt in ("-l", "--log"): |
---|
252 | options.log = arg |
---|
253 | elif opt in ("-n", "--nofork"): |
---|
254 | options.daemon = False |
---|
255 | elif opt in ("-p", "--port"): |
---|
256 | options.port = int(arg) |
---|
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) |
---|
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] |
---|
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]) |
---|
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 |
---|
286 | dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username)) |
---|
287 | if options.daemon: |
---|
288 | pid = os.fork() |
---|
289 | if pid == 0: |
---|
290 | nullin = file(os.devnull, 'r') |
---|
291 | nullout = file(os.devnull, 'w') |
---|
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) |
---|
298 | else: |
---|
299 | dprint('skyped is started on port %s' % options.port) |
---|
300 | server(options.host, options.port) |
---|
301 | try: |
---|
302 | skype = SkypeApi() |
---|
303 | except Skype4Py.SkypeAPIError, s: |
---|
304 | sys.exit("%s. Are you sure you have started Skype?" % s) |
---|
305 | gobject.timeout_add(2000, skype_idle_handler, skype) |
---|
306 | gobject.timeout_add(60000, bitlbee_idle_handler, skype) |
---|
307 | gobject.MainLoop().run() |
---|