1 | #!/usr/bin/env python |
---|
2 | # |
---|
3 | # skyped.py |
---|
4 | # |
---|
5 | # Copyright (c) 2007, 2008 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 sha |
---|
33 | from ConfigParser import ConfigParser, NoOptionError |
---|
34 | from traceback import print_exception |
---|
35 | |
---|
36 | __version__ = "0.1.1" |
---|
37 | |
---|
38 | SKYPE_SERVICE = 'com.Skype.API' |
---|
39 | |
---|
40 | def eh(type, value, tb): |
---|
41 | if type != KeyboardInterrupt: |
---|
42 | print_exception(type, value, tb) |
---|
43 | gobject.MainLoop().quit() |
---|
44 | skype.skype.Client.Shutdown() |
---|
45 | sys.exit("Exiting.") |
---|
46 | |
---|
47 | sys.excepthook = eh |
---|
48 | |
---|
49 | def input_handler(fd, io_condition): |
---|
50 | global options |
---|
51 | if options.buf: |
---|
52 | for i in options.buf: |
---|
53 | skype.send(i.strip()) |
---|
54 | options.buf = None |
---|
55 | else: |
---|
56 | try: |
---|
57 | input = fd.recv(1024) |
---|
58 | except Exception, s: |
---|
59 | dprint("Warning, receiving 1024 bytes failed (%s)." % s) |
---|
60 | fd.close() |
---|
61 | return False |
---|
62 | for i in input.split("\n"): |
---|
63 | skype.send(i.strip()) |
---|
64 | return True |
---|
65 | |
---|
66 | def idle_handler(skype): |
---|
67 | try: |
---|
68 | c = skype.skype.Command("PING", Block=True) |
---|
69 | skype.skype.SendCommand(c) |
---|
70 | except Skype4Py.SkypeAPIError, s: |
---|
71 | dprint("Warning, pinging Skype failed (%s)." % (s)) |
---|
72 | return True |
---|
73 | |
---|
74 | def server(host, port): |
---|
75 | global options |
---|
76 | try: |
---|
77 | if "SKYPED_NO_GNUTLS" in os.environ.keys(): |
---|
78 | dprint("Warning, using OpenSSL instead of gnutls as requested (not recommended).") |
---|
79 | raise ImportError |
---|
80 | from gnutls import crypto, connection |
---|
81 | cert = crypto.X509Certificate(open(options.config.sslcert).read()) |
---|
82 | key = crypto.X509PrivateKey(open(options.config.sslkey).read()) |
---|
83 | cred = connection.X509Credentials(cert, key) |
---|
84 | sock = connection.ServerSessionFactory(socket.socket(), cred) |
---|
85 | except ImportError: |
---|
86 | from OpenSSL import SSL |
---|
87 | ctx = SSL.Context(SSL.TLSv1_METHOD) |
---|
88 | ctx.use_privatekey_file(options.config.sslkey) |
---|
89 | ctx.use_certificate_file(options.config.sslcert) |
---|
90 | sock = SSL.Connection(ctx, socket.socket()) |
---|
91 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
92 | sock.bind((host, port)) |
---|
93 | sock.listen(1) |
---|
94 | gobject.io_add_watch(sock, gobject.IO_IN, listener) |
---|
95 | |
---|
96 | def listener(sock, *args): |
---|
97 | global options |
---|
98 | options.conn, addr = sock.accept() |
---|
99 | if hasattr(options.conn, 'handshake'): |
---|
100 | try: |
---|
101 | options.conn.handshake() |
---|
102 | except Exception: |
---|
103 | dprint("Warning, handshake failed, closing connection.") |
---|
104 | return False |
---|
105 | ret = 0 |
---|
106 | line = options.conn.recv(1024) |
---|
107 | if line.startswith("USERNAME") and line.split(' ')[1].strip() == options.config.username: |
---|
108 | ret += 1 |
---|
109 | line = options.conn.recv(1024) |
---|
110 | if line.startswith("PASSWORD") and sha.sha(line.split(' ')[1].strip()).hexdigest() == options.config.password: |
---|
111 | ret += 1 |
---|
112 | if ret == 2: |
---|
113 | dprint("Username and password OK.") |
---|
114 | options.conn.send("PASSWORD OK\n") |
---|
115 | gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler) |
---|
116 | return True |
---|
117 | else: |
---|
118 | dprint("Username and/or password WRONG.") |
---|
119 | options.conn.send("PASSWORD KO\n") |
---|
120 | return False |
---|
121 | |
---|
122 | def dprint(msg): |
---|
123 | global options |
---|
124 | |
---|
125 | if options.debug: |
---|
126 | print msg |
---|
127 | |
---|
128 | class SkypeApi: |
---|
129 | def __init__(self): |
---|
130 | self.skype = Skype4Py.Skype() |
---|
131 | self.skype.OnNotify = self.recv |
---|
132 | self.skype.Client.Start() |
---|
133 | |
---|
134 | def recv(self, msg_text): |
---|
135 | global options |
---|
136 | if msg_text == "PONG": |
---|
137 | return |
---|
138 | if "\n" in msg_text: |
---|
139 | # crappy skype prefixes only the first line for |
---|
140 | # multiline messages so we need to do so for the other |
---|
141 | # lines, too. this is something like: |
---|
142 | # 'CHATMESSAGE id BODY first line\nsecond line' -> |
---|
143 | # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line' |
---|
144 | prefix = " ".join(msg_text.split(" ")[:3]) |
---|
145 | msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")] |
---|
146 | else: |
---|
147 | msg_text = [msg_text] |
---|
148 | for i in msg_text: |
---|
149 | # use utf-8 here to solve the following problem: |
---|
150 | # people use env vars like LC_ALL=en_US (latin1) then |
---|
151 | # they complain about why can't they receive latin2 |
---|
152 | # messages.. so here it is: always use utf-8 then |
---|
153 | # everybody will be happy |
---|
154 | e = i.encode('UTF-8') |
---|
155 | dprint('<< ' + e) |
---|
156 | if options.conn: |
---|
157 | try: |
---|
158 | options.conn.send(e + "\n") |
---|
159 | except Exception, s: |
---|
160 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
161 | options.conn.close() |
---|
162 | |
---|
163 | def send(self, msg_text): |
---|
164 | if not len(msg_text): |
---|
165 | return |
---|
166 | e = msg_text.decode(locale.getdefaultlocale()[1]) |
---|
167 | dprint('>> ' + e) |
---|
168 | try: |
---|
169 | c = self.skype.Command(e, Block=True) |
---|
170 | self.skype.SendCommand(c) |
---|
171 | self.recv(c.Reply) |
---|
172 | except Skype4Py.SkypeError: |
---|
173 | pass |
---|
174 | except Skype4Py.SkypeAPIError, s: |
---|
175 | dprint("Warning, sending '%s' failed (%s)." % (e, s)) |
---|
176 | |
---|
177 | class Options: |
---|
178 | def __init__(self): |
---|
179 | self.cfgpath = "/usr/local/etc/skyped/skyped.conf" |
---|
180 | self.daemon = True |
---|
181 | self.debug = False |
---|
182 | self.help = False |
---|
183 | self.host = "0.0.0.0" |
---|
184 | self.port = None |
---|
185 | self.version = False |
---|
186 | # well, this is a bit hackish. we store the socket of the last connected client |
---|
187 | # here and notify it. maybe later notify all connected clients? |
---|
188 | self.conn = None |
---|
189 | # this will be read first by the input handler |
---|
190 | self.buf = None |
---|
191 | |
---|
192 | |
---|
193 | def usage(self, ret): |
---|
194 | print """Usage: skyped [OPTION]... |
---|
195 | |
---|
196 | skyped is a daemon that acts as a tcp server on top of a Skype instance. |
---|
197 | |
---|
198 | Options: |
---|
199 | -c --config path to configuration file (default: %s) |
---|
200 | -d --debug enable debug messages |
---|
201 | -h --help this help |
---|
202 | -H --host set the tcp host (default: %s) |
---|
203 | -n --nofork don't run as daemon in the background |
---|
204 | -p --port set the tcp port (default: %d) |
---|
205 | -v --version display version information""" % (self.cfgpath, self.host, self.port) |
---|
206 | sys.exit(ret) |
---|
207 | |
---|
208 | if __name__=='__main__': |
---|
209 | options = Options() |
---|
210 | try: |
---|
211 | opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"]) |
---|
212 | except getopt.GetoptError: |
---|
213 | options.usage(1) |
---|
214 | for opt, arg in opts: |
---|
215 | if opt in ("-c", "--config"): |
---|
216 | options.cfgpath = arg |
---|
217 | elif opt in ("-d", "--debug"): |
---|
218 | options.debug = True |
---|
219 | elif opt in ("-h", "--help"): |
---|
220 | options.help = True |
---|
221 | elif opt in ("-H", "--host"): |
---|
222 | options.host = arg |
---|
223 | elif opt in ("-n", "--nofork"): |
---|
224 | options.daemon = False |
---|
225 | elif opt in ("-p", "--port"): |
---|
226 | options.port = int(arg) |
---|
227 | elif opt in ("-v", "--version"): |
---|
228 | options.version = True |
---|
229 | if options.help: |
---|
230 | options.usage(0) |
---|
231 | elif options.version: |
---|
232 | print "skyped %s" % __version__ |
---|
233 | sys.exit(0) |
---|
234 | # parse our config |
---|
235 | if not os.path.exists(options.cfgpath): |
---|
236 | print "Can't find configuration file at '%s'." % options.cfgpath |
---|
237 | print "Use the -c option to specify an alternate one." |
---|
238 | sys.exit(1) |
---|
239 | options.config = ConfigParser() |
---|
240 | options.config.read(options.cfgpath) |
---|
241 | options.config.username = options.config.get('skyped', 'username').split('#')[0] |
---|
242 | options.config.password = options.config.get('skyped', 'password').split('#')[0] |
---|
243 | options.config.sslkey = options.config.get('skyped', 'key').split('#')[0] |
---|
244 | options.config.sslcert = options.config.get('skyped', 'cert').split('#')[0] |
---|
245 | # hack: we have to parse the parameters first to locate the |
---|
246 | # config file but the -p option should overwrite the value from |
---|
247 | # the config file |
---|
248 | try: |
---|
249 | options.config.port = int(options.config.get('skyped', 'port').split('#')[0]) |
---|
250 | if not options.port: |
---|
251 | options.port = options.config.port |
---|
252 | except NoOptionError: |
---|
253 | pass |
---|
254 | if not options.port: |
---|
255 | options.port = 2727 |
---|
256 | dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username)) |
---|
257 | if options.daemon: |
---|
258 | pid = os.fork() |
---|
259 | if pid == 0: |
---|
260 | nullin = file('/dev/null', 'r') |
---|
261 | nullout = file('/dev/null', 'w') |
---|
262 | os.dup2(nullin.fileno(), sys.stdin.fileno()) |
---|
263 | os.dup2(nullout.fileno(), sys.stdout.fileno()) |
---|
264 | os.dup2(nullout.fileno(), sys.stderr.fileno()) |
---|
265 | else: |
---|
266 | print 'skyped is started on port %s, pid: %d' % (options.port, pid) |
---|
267 | sys.exit(0) |
---|
268 | else: |
---|
269 | dprint('skyped is started on port %s' % options.port) |
---|
270 | server(options.host, options.port) |
---|
271 | try: |
---|
272 | skype = SkypeApi() |
---|
273 | except Skype4Py.SkypeAPIError, s: |
---|
274 | sys.exit("%s. Are you sure you have started Skype?" % s) |
---|
275 | gobject.timeout_add(2000, idle_handler, skype) |
---|
276 | gobject.MainLoop().run() |
---|