1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | # |
---|
4 | # EtherWebSocket tunneling Server/Client |
---|
5 | # |
---|
6 | # depends on: |
---|
7 | # - python-2.7.2 |
---|
8 | # - python-pytun-0.2 |
---|
9 | # - websocket-client-0.4.1 |
---|
10 | # - tornado-1.2.1 |
---|
11 | # |
---|
12 | # todo: |
---|
13 | # - direct binary transmission support (to improve performance) |
---|
14 | # |
---|
15 | # =========================================================================== |
---|
16 | # Copyright (c) 2012, Atzm WATANABE <atzm@atzm.org> |
---|
17 | # All rights reserved. |
---|
18 | # |
---|
19 | # Redistribution and use in source and binary forms, with or without |
---|
20 | # modification, are permitted provided that the following conditions are met: |
---|
21 | # |
---|
22 | # 1. Redistributions of source code must retain the above copyright notice, |
---|
23 | # this list of conditions and the following disclaimer. |
---|
24 | # 2. Redistributions in binary form must reproduce the above copyright |
---|
25 | # notice, this list of conditions and the following disclaimer in the |
---|
26 | # documentation and/or other materials provided with the distribution. |
---|
27 | # |
---|
28 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
---|
29 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
---|
30 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
---|
31 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
---|
32 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
---|
33 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
---|
34 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
---|
35 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
---|
36 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
---|
37 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
---|
38 | # POSSIBILITY OF SUCH DAMAGE. |
---|
39 | # =========================================================================== |
---|
40 | # |
---|
41 | # $Id$ |
---|
42 | |
---|
43 | import os |
---|
44 | import sys |
---|
45 | import base64 |
---|
46 | import select |
---|
47 | import argparse |
---|
48 | import threading |
---|
49 | |
---|
50 | import pytun |
---|
51 | import websocket |
---|
52 | import tornado.httpserver |
---|
53 | import tornado.ioloop |
---|
54 | import tornado.web |
---|
55 | import tornado.websocket |
---|
56 | |
---|
57 | |
---|
58 | class TapListener(threading.Thread): |
---|
59 | daemon = True |
---|
60 | |
---|
61 | def __init__(self, dev, debug=False): |
---|
62 | super(TapListener, self).__init__() |
---|
63 | |
---|
64 | self._debug = debug |
---|
65 | self._tap = pytun.TunTapDevice(dev, pytun.IFF_TAP | pytun.IFF_NO_PI) |
---|
66 | self._tap_lock = threading.Lock() |
---|
67 | |
---|
68 | self._clients = [] |
---|
69 | self._clients_lock = threading.Lock() |
---|
70 | |
---|
71 | try: |
---|
72 | self._tap_lock.acquire() |
---|
73 | self._tap.up() |
---|
74 | finally: |
---|
75 | self._tap_lock.release() |
---|
76 | |
---|
77 | def register_client(self, client): |
---|
78 | try: |
---|
79 | self._clients_lock.acquire() |
---|
80 | self._clients.append(client) |
---|
81 | finally: |
---|
82 | self._clients_lock.release() |
---|
83 | |
---|
84 | def unregister_client(self, client): |
---|
85 | try: |
---|
86 | self._clients_lock.acquire() |
---|
87 | self._clients.remove(client) |
---|
88 | except ValueError: |
---|
89 | pass |
---|
90 | finally: |
---|
91 | self._clients_lock.release() |
---|
92 | |
---|
93 | def write(self, caller, message): |
---|
94 | if self._debug: |
---|
95 | sys.stderr.write('%s: %s\n' % (caller.__class__.__name__, |
---|
96 | message.encode('hex'))) |
---|
97 | |
---|
98 | try: |
---|
99 | self._clients_lock.acquire() |
---|
100 | clients = self._clients[:] |
---|
101 | finally: |
---|
102 | self._clients_lock.release() |
---|
103 | |
---|
104 | if caller is not self: |
---|
105 | clients.remove(caller) |
---|
106 | try: |
---|
107 | self._tap_lock.acquire() |
---|
108 | self._tap.write(message) |
---|
109 | finally: |
---|
110 | self._tap_lock.release() |
---|
111 | |
---|
112 | message = base64.b64encode(message) |
---|
113 | |
---|
114 | for c in clients: |
---|
115 | c.write_message(message) |
---|
116 | |
---|
117 | def run(self): |
---|
118 | epoll = select.epoll() |
---|
119 | |
---|
120 | try: |
---|
121 | self._tap_lock.acquire() |
---|
122 | epoll.register(self._tap.fileno(), select.EPOLLIN) |
---|
123 | finally: |
---|
124 | self._tap_lock.release() |
---|
125 | |
---|
126 | while True: |
---|
127 | evts = epoll.poll(1) |
---|
128 | for fileno, evt in evts: |
---|
129 | try: |
---|
130 | self._tap_lock.acquire() |
---|
131 | data = self._tap.read(self._tap.mtu) |
---|
132 | finally: |
---|
133 | self._tap_lock.release() |
---|
134 | self.write(self, data) |
---|
135 | |
---|
136 | |
---|
137 | class EtherWebSocket(tornado.websocket.WebSocketHandler): |
---|
138 | def __init__(self, app, req, tap, debug=False): |
---|
139 | super(EtherWebSocket, self).__init__(app, req) |
---|
140 | self._tap = tap |
---|
141 | self._debug = debug |
---|
142 | |
---|
143 | def open(self): |
---|
144 | if self._debug: |
---|
145 | sys.stderr.write('[%s] opened\n' % self.request.remote_ip) |
---|
146 | self._tap.register_client(self) |
---|
147 | |
---|
148 | def on_message(self, message): |
---|
149 | if self._debug: |
---|
150 | sys.stderr.write('[%s] received\n' % self.request.remote_ip) |
---|
151 | self._tap.write(self, base64.b64decode(message)) |
---|
152 | |
---|
153 | def on_close(self): |
---|
154 | if self._debug: |
---|
155 | sys.stderr.write('[%s] closed\n' % self.request.remote_ip) |
---|
156 | self._tap.unregister_client(self) |
---|
157 | |
---|
158 | |
---|
159 | def daemonize(nochdir=False, noclose=False): |
---|
160 | if os.fork() > 0: |
---|
161 | sys.exit(0) |
---|
162 | |
---|
163 | os.setsid() |
---|
164 | |
---|
165 | if os.fork() > 0: |
---|
166 | sys.exit(0) |
---|
167 | |
---|
168 | if not nochdir: |
---|
169 | os.chdir('/') |
---|
170 | |
---|
171 | if not noclose: |
---|
172 | os.umask(0) |
---|
173 | sys.stdin.close() |
---|
174 | sys.stdout.close() |
---|
175 | sys.stderr.close() |
---|
176 | os.close(0) |
---|
177 | os.close(1) |
---|
178 | os.close(2) |
---|
179 | sys.stdin = open(os.devnull) |
---|
180 | sys.stdout = open(os.devnull, 'a') |
---|
181 | sys.stderr = open(os.devnull, 'a') |
---|
182 | |
---|
183 | |
---|
184 | def server_main(args): |
---|
185 | tap = TapListener(args.device, debug=args.debug) |
---|
186 | tap.start() |
---|
187 | |
---|
188 | app = tornado.web.Application([ |
---|
189 | (args.path, EtherWebSocket, {'tap': tap, 'debug': args.debug}), |
---|
190 | ]) |
---|
191 | server = tornado.httpserver.HTTPServer(app) |
---|
192 | server.listen(args.port, address=args.address) |
---|
193 | |
---|
194 | tornado.ioloop.IOLoop.instance().start() |
---|
195 | |
---|
196 | |
---|
197 | def client_main(args): |
---|
198 | if args.debug: |
---|
199 | websocket.enableTrace(True) |
---|
200 | |
---|
201 | tap = TapListener(args.device, debug=args.debug) |
---|
202 | client = websocket.WebSocketApp(args.uri) |
---|
203 | client.write_message = client.send |
---|
204 | client.on_message = lambda s, m: tap.write(client, base64.b64decode(m)) |
---|
205 | |
---|
206 | if args.debug: |
---|
207 | client.on_error = lambda s, e: sys.stderr.write(str(e) + '\n') |
---|
208 | client.on_close = lambda s: sys.stderr.write('closed\n') |
---|
209 | |
---|
210 | tap.register_client(client) |
---|
211 | tap.start() |
---|
212 | |
---|
213 | client.run_forever() |
---|
214 | |
---|
215 | |
---|
216 | def main(): |
---|
217 | parser = argparse.ArgumentParser() |
---|
218 | parser.add_argument('--device', action='store', default='ethws%d') |
---|
219 | parser.add_argument('--foreground', action='store_true', default=False) |
---|
220 | parser.add_argument('--debug', action='store_true', default=False) |
---|
221 | |
---|
222 | subparsers = parser.add_subparsers(dest='subcommand') |
---|
223 | |
---|
224 | parser_server = subparsers.add_parser('server') |
---|
225 | parser_server.add_argument('--address', action='store', default='') |
---|
226 | parser_server.add_argument('--port', action='store', type=int, default=80) |
---|
227 | parser_server.add_argument('--path', action='store', default='/') |
---|
228 | |
---|
229 | parser_client = subparsers.add_parser('client') |
---|
230 | parser_client.add_argument('--uri', action='store', required=True) |
---|
231 | |
---|
232 | args = parser.parse_args() |
---|
233 | |
---|
234 | if not args.foreground: |
---|
235 | daemonize() |
---|
236 | |
---|
237 | if args.subcommand == 'server': |
---|
238 | server_main(args) |
---|
239 | elif args.subcommand == 'client': |
---|
240 | client_main(args) |
---|
241 | |
---|
242 | |
---|
243 | if __name__ == '__main__': |
---|
244 | main() |
---|