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 | def daemonize(nochdir=False, noclose=False): |
---|
59 | if os.fork() > 0: |
---|
60 | sys.exit(0) |
---|
61 | |
---|
62 | os.setsid() |
---|
63 | |
---|
64 | if os.fork() > 0: |
---|
65 | sys.exit(0) |
---|
66 | |
---|
67 | if not nochdir: |
---|
68 | os.chdir('/') |
---|
69 | |
---|
70 | if not noclose: |
---|
71 | os.umask(0) |
---|
72 | sys.stdin.close() |
---|
73 | sys.stdout.close() |
---|
74 | sys.stderr.close() |
---|
75 | os.close(0) |
---|
76 | os.close(1) |
---|
77 | os.close(2) |
---|
78 | sys.stdin = open(os.devnull) |
---|
79 | sys.stdout = open(os.devnull, 'a') |
---|
80 | sys.stderr = open(os.devnull, 'a') |
---|
81 | |
---|
82 | |
---|
83 | class TapListener(threading.Thread): |
---|
84 | daemon = True |
---|
85 | |
---|
86 | def __init__(self, dev, debug=False): |
---|
87 | super(TapListener, self).__init__() |
---|
88 | |
---|
89 | self._debug = debug |
---|
90 | self._tap = pytun.TunTapDevice(dev, pytun.IFF_TAP | pytun.IFF_NO_PI) |
---|
91 | self._tap.up() |
---|
92 | |
---|
93 | self._clients = [] |
---|
94 | self._clients_lock = threading.Lock() |
---|
95 | |
---|
96 | def register_client(self, client): |
---|
97 | try: |
---|
98 | self._clients_lock.acquire() |
---|
99 | self._clients.append(client) |
---|
100 | finally: |
---|
101 | self._clients_lock.release() |
---|
102 | |
---|
103 | def unregister_client(self, client): |
---|
104 | try: |
---|
105 | self._clients_lock.acquire() |
---|
106 | self._clients.remove(client) |
---|
107 | except ValueError: |
---|
108 | pass |
---|
109 | finally: |
---|
110 | self._clients_lock.release() |
---|
111 | |
---|
112 | def write(self, caller, message): |
---|
113 | if self._debug: |
---|
114 | sys.stderr.write('%s: %s\n' % (caller.__class__.__name__, |
---|
115 | message.encode('hex'))) |
---|
116 | |
---|
117 | try: |
---|
118 | self._clients_lock.acquire() |
---|
119 | clients = self._clients[:] |
---|
120 | finally: |
---|
121 | self._clients_lock.release() |
---|
122 | |
---|
123 | if caller is not self: |
---|
124 | clients.remove(caller) |
---|
125 | self._tap.write(message) |
---|
126 | |
---|
127 | message = base64.b64encode(message) |
---|
128 | |
---|
129 | for c in clients: |
---|
130 | c.write_message(message) |
---|
131 | |
---|
132 | def run(self): |
---|
133 | epoll = select.epoll() |
---|
134 | epoll.register(self._tap.fileno(), select.EPOLLIN) |
---|
135 | |
---|
136 | while True: |
---|
137 | evts = epoll.poll(1) |
---|
138 | for fileno, evt in evts: |
---|
139 | self.write(self, self._tap.read(self._tap.mtu)) |
---|
140 | |
---|
141 | |
---|
142 | class EtherWebSocket(tornado.websocket.WebSocketHandler): |
---|
143 | def __init__(self, app, req, tap, debug=False): |
---|
144 | super(EtherWebSocket, self).__init__(app, req) |
---|
145 | self._tap = tap |
---|
146 | self._debug = debug |
---|
147 | |
---|
148 | def open(self): |
---|
149 | if self._debug: |
---|
150 | sys.stderr.write('[%s] opened\n' % self.request.remote_ip) |
---|
151 | self._tap.register_client(self) |
---|
152 | |
---|
153 | def on_message(self, message): |
---|
154 | if self._debug: |
---|
155 | sys.stderr.write('[%s] received\n' % self.request.remote_ip) |
---|
156 | self._tap.write(self, base64.b64decode(message)) |
---|
157 | |
---|
158 | def on_close(self): |
---|
159 | if self._debug: |
---|
160 | sys.stderr.write('[%s] closed\n' % self.request.remote_ip) |
---|
161 | self._tap.unregister_client(self) |
---|
162 | |
---|
163 | |
---|
164 | def server_main(args): |
---|
165 | tap = TapListener(args.device, debug=args.debug) |
---|
166 | tap.start() |
---|
167 | |
---|
168 | app = tornado.web.Application([ |
---|
169 | (args.path, EtherWebSocket, {'tap': tap, 'debug': args.debug}), |
---|
170 | ]) |
---|
171 | server = tornado.httpserver.HTTPServer(app) |
---|
172 | server.listen(args.port, address=args.address) |
---|
173 | |
---|
174 | if not args.foreground: |
---|
175 | daemonize() |
---|
176 | |
---|
177 | tornado.ioloop.IOLoop.instance().start() |
---|
178 | |
---|
179 | |
---|
180 | def client_main(args): |
---|
181 | if args.debug: |
---|
182 | websocket.enableTrace(True) |
---|
183 | |
---|
184 | tap = TapListener(args.device, debug=args.debug) |
---|
185 | client = websocket.WebSocketApp(args.uri) |
---|
186 | client.write_message = client.send |
---|
187 | client.on_message = lambda s, m: tap.write(client, base64.b64decode(m)) |
---|
188 | |
---|
189 | if args.debug: |
---|
190 | client.on_error = lambda s, e: sys.stderr.write(str(e) + '\n') |
---|
191 | client.on_close = lambda s: sys.stderr.write('closed\n') |
---|
192 | |
---|
193 | tap.register_client(client) |
---|
194 | tap.start() |
---|
195 | |
---|
196 | if not args.foreground: |
---|
197 | daemonize() |
---|
198 | |
---|
199 | client.run_forever() |
---|
200 | |
---|
201 | |
---|
202 | def main(): |
---|
203 | parser = argparse.ArgumentParser() |
---|
204 | parser.add_argument('--device', action='store', default='ethws%d') |
---|
205 | parser.add_argument('--foreground', action='store_true', default=False) |
---|
206 | parser.add_argument('--debug', action='store_true', default=False) |
---|
207 | |
---|
208 | subparsers = parser.add_subparsers(dest='subcommand') |
---|
209 | |
---|
210 | parser_server = subparsers.add_parser('server') |
---|
211 | parser_server.add_argument('--address', action='store', default='') |
---|
212 | parser_server.add_argument('--port', action='store', type=int, default=80) |
---|
213 | parser_server.add_argument('--path', action='store', default='/') |
---|
214 | |
---|
215 | parser_client = subparsers.add_parser('client') |
---|
216 | parser_client.add_argument('--uri', action='store', required=True) |
---|
217 | |
---|
218 | args = parser.parse_args() |
---|
219 | |
---|
220 | if args.subcommand == 'server': |
---|
221 | server_main(args) |
---|
222 | elif args.subcommand == 'client': |
---|
223 | client_main(args) |
---|
224 | |
---|
225 | |
---|
226 | if __name__ == '__main__': |
---|
227 | main() |
---|