[133] | 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 |
---|
[136] | 9 | # - websocket-client-0.7.0 |
---|
| 10 | # - tornado-2.2.1 |
---|
[133] | 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 argparse |
---|
| 47 | import threading |
---|
| 48 | |
---|
| 49 | import pytun |
---|
| 50 | import websocket |
---|
| 51 | import tornado.httpserver |
---|
| 52 | import tornado.ioloop |
---|
| 53 | import tornado.web |
---|
| 54 | import tornado.websocket |
---|
| 55 | |
---|
| 56 | |
---|
[138] | 57 | class TapHandler(object): |
---|
[133] | 58 | def __init__(self, dev, debug=False): |
---|
| 59 | self._debug = debug |
---|
[138] | 60 | self._clients = [] |
---|
[133] | 61 | self._tap = pytun.TunTapDevice(dev, pytun.IFF_TAP | pytun.IFF_NO_PI) |
---|
[138] | 62 | self._tap.up() |
---|
| 63 | self._write_lock = threading.Lock() |
---|
[133] | 64 | |
---|
[138] | 65 | def fileno(self): |
---|
| 66 | return self._tap.fileno() |
---|
[133] | 67 | |
---|
| 68 | def register_client(self, client): |
---|
[138] | 69 | self._clients.append(client) |
---|
[133] | 70 | |
---|
| 71 | def unregister_client(self, client): |
---|
[138] | 72 | self._clients.remove(client) |
---|
[133] | 73 | |
---|
| 74 | def write(self, caller, message): |
---|
| 75 | if self._debug: |
---|
| 76 | sys.stderr.write('%s: %s\n' % (caller.__class__.__name__, |
---|
| 77 | message.encode('hex'))) |
---|
| 78 | |
---|
| 79 | try: |
---|
[138] | 80 | self._write_lock.acquire() |
---|
[137] | 81 | |
---|
[133] | 82 | clients = self._clients[:] |
---|
| 83 | |
---|
[137] | 84 | if caller is not self: |
---|
| 85 | clients.remove(caller) |
---|
[138] | 86 | self._tap.write(message) |
---|
[133] | 87 | |
---|
[137] | 88 | message = base64.b64encode(message) |
---|
[133] | 89 | |
---|
[137] | 90 | for c in clients: |
---|
| 91 | c.write_message(message) |
---|
[133] | 92 | |
---|
[137] | 93 | finally: |
---|
[138] | 94 | self._write_lock.release() |
---|
[137] | 95 | |
---|
[138] | 96 | def __call__(self, fd, events): |
---|
| 97 | self.write(self, self._tap.read(self._tap.mtu)) |
---|
[133] | 98 | |
---|
[135] | 99 | |
---|
[133] | 100 | class EtherWebSocket(tornado.websocket.WebSocketHandler): |
---|
| 101 | def __init__(self, app, req, tap, debug=False): |
---|
| 102 | super(EtherWebSocket, self).__init__(app, req) |
---|
| 103 | self._tap = tap |
---|
| 104 | self._debug = debug |
---|
| 105 | |
---|
| 106 | def open(self): |
---|
| 107 | self._tap.register_client(self) |
---|
| 108 | |
---|
| 109 | def on_message(self, message): |
---|
| 110 | self._tap.write(self, base64.b64decode(message)) |
---|
| 111 | |
---|
| 112 | def on_close(self): |
---|
| 113 | self._tap.unregister_client(self) |
---|
| 114 | |
---|
| 115 | |
---|
[134] | 116 | def daemonize(nochdir=False, noclose=False): |
---|
| 117 | if os.fork() > 0: |
---|
| 118 | sys.exit(0) |
---|
| 119 | |
---|
| 120 | os.setsid() |
---|
| 121 | |
---|
| 122 | if os.fork() > 0: |
---|
| 123 | sys.exit(0) |
---|
| 124 | |
---|
| 125 | if not nochdir: |
---|
| 126 | os.chdir('/') |
---|
| 127 | |
---|
| 128 | if not noclose: |
---|
| 129 | os.umask(0) |
---|
| 130 | sys.stdin.close() |
---|
| 131 | sys.stdout.close() |
---|
| 132 | sys.stderr.close() |
---|
| 133 | os.close(0) |
---|
| 134 | os.close(1) |
---|
| 135 | os.close(2) |
---|
| 136 | sys.stdin = open(os.devnull) |
---|
| 137 | sys.stdout = open(os.devnull, 'a') |
---|
| 138 | sys.stderr = open(os.devnull, 'a') |
---|
| 139 | |
---|
| 140 | |
---|
[133] | 141 | def server_main(args): |
---|
[138] | 142 | tap = TapHandler(args.device, debug=args.debug) |
---|
[133] | 143 | app = tornado.web.Application([ |
---|
| 144 | (args.path, EtherWebSocket, {'tap': tap, 'debug': args.debug}), |
---|
| 145 | ]) |
---|
| 146 | server = tornado.httpserver.HTTPServer(app) |
---|
| 147 | server.listen(args.port, address=args.address) |
---|
| 148 | |
---|
[138] | 149 | ioloop = tornado.ioloop.IOLoop.instance() |
---|
| 150 | ioloop.add_handler(tap.fileno(), tap, ioloop.READ) |
---|
| 151 | ioloop.start() |
---|
[133] | 152 | |
---|
| 153 | |
---|
| 154 | def client_main(args): |
---|
| 155 | if args.debug: |
---|
| 156 | websocket.enableTrace(True) |
---|
| 157 | |
---|
[138] | 158 | tap = TapHandler(args.device, debug=args.debug) |
---|
[133] | 159 | client = websocket.WebSocketApp(args.uri) |
---|
| 160 | client.write_message = client.send |
---|
| 161 | client.on_message = lambda s, m: tap.write(client, base64.b64decode(m)) |
---|
| 162 | tap.register_client(client) |
---|
| 163 | |
---|
[138] | 164 | t = threading.Thread(target=client.run_forever) |
---|
| 165 | t.setDaemon(True) |
---|
| 166 | t.start() |
---|
[133] | 167 | |
---|
[138] | 168 | ioloop = tornado.ioloop.IOLoop.instance() |
---|
| 169 | ioloop.add_handler(tap.fileno(), tap, ioloop.READ) |
---|
| 170 | ioloop.start() |
---|
[133] | 171 | |
---|
[138] | 172 | |
---|
[133] | 173 | def main(): |
---|
| 174 | parser = argparse.ArgumentParser() |
---|
| 175 | parser.add_argument('--device', action='store', default='ethws%d') |
---|
| 176 | parser.add_argument('--foreground', action='store_true', default=False) |
---|
| 177 | parser.add_argument('--debug', action='store_true', default=False) |
---|
| 178 | |
---|
| 179 | subparsers = parser.add_subparsers(dest='subcommand') |
---|
| 180 | |
---|
| 181 | parser_server = subparsers.add_parser('server') |
---|
| 182 | parser_server.add_argument('--address', action='store', default='') |
---|
| 183 | parser_server.add_argument('--port', action='store', type=int, default=80) |
---|
| 184 | parser_server.add_argument('--path', action='store', default='/') |
---|
| 185 | |
---|
| 186 | parser_client = subparsers.add_parser('client') |
---|
| 187 | parser_client.add_argument('--uri', action='store', required=True) |
---|
| 188 | |
---|
| 189 | args = parser.parse_args() |
---|
| 190 | |
---|
[134] | 191 | if not args.foreground: |
---|
| 192 | daemonize() |
---|
| 193 | |
---|
[133] | 194 | if args.subcommand == 'server': |
---|
| 195 | server_main(args) |
---|
| 196 | elif args.subcommand == 'client': |
---|
| 197 | client_main(args) |
---|
| 198 | |
---|
| 199 | |
---|
| 200 | if __name__ == '__main__': |
---|
| 201 | main() |
---|