[133] | 1 | #!/usr/bin/env python |
---|
| 2 | # -*- coding: utf-8 -*- |
---|
| 3 | # |
---|
[141] | 4 | # Ethernet over WebSocket tunneling server/client |
---|
[133] | 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 | # |
---|
[140] | 12 | # todo: |
---|
[143] | 13 | # - authentication support |
---|
| 14 | # - servant mode support (like typical p2p software) |
---|
[140] | 15 | # |
---|
[133] | 16 | # =========================================================================== |
---|
| 17 | # Copyright (c) 2012, Atzm WATANABE <atzm@atzm.org> |
---|
| 18 | # All rights reserved. |
---|
| 19 | # |
---|
| 20 | # Redistribution and use in source and binary forms, with or without |
---|
| 21 | # modification, are permitted provided that the following conditions are met: |
---|
| 22 | # |
---|
| 23 | # 1. Redistributions of source code must retain the above copyright notice, |
---|
| 24 | # this list of conditions and the following disclaimer. |
---|
| 25 | # 2. Redistributions in binary form must reproduce the above copyright |
---|
| 26 | # notice, this list of conditions and the following disclaimer in the |
---|
| 27 | # documentation and/or other materials provided with the distribution. |
---|
| 28 | # |
---|
| 29 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
---|
| 30 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
---|
| 31 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
---|
| 32 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
---|
| 33 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
---|
| 34 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
---|
| 35 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
---|
| 36 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
---|
| 37 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
---|
| 38 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
---|
| 39 | # POSSIBILITY OF SUCH DAMAGE. |
---|
| 40 | # =========================================================================== |
---|
| 41 | # |
---|
| 42 | # $Id$ |
---|
| 43 | |
---|
| 44 | import os |
---|
| 45 | import sys |
---|
[143] | 46 | import time |
---|
[133] | 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 | |
---|
[138] | 58 | class TapHandler(object): |
---|
[133] | 59 | def __init__(self, dev, debug=False): |
---|
| 60 | self._debug = debug |
---|
[138] | 61 | self._clients = [] |
---|
[133] | 62 | self._tap = pytun.TunTapDevice(dev, pytun.IFF_TAP | pytun.IFF_NO_PI) |
---|
[138] | 63 | self._tap.up() |
---|
| 64 | self._write_lock = threading.Lock() |
---|
[133] | 65 | |
---|
[138] | 66 | def fileno(self): |
---|
| 67 | return self._tap.fileno() |
---|
[133] | 68 | |
---|
| 69 | def register_client(self, client): |
---|
[138] | 70 | self._clients.append(client) |
---|
[133] | 71 | |
---|
| 72 | def unregister_client(self, client): |
---|
[138] | 73 | self._clients.remove(client) |
---|
[133] | 74 | |
---|
| 75 | def write(self, caller, message): |
---|
| 76 | if self._debug: |
---|
| 77 | sys.stderr.write('%s: %s\n' % (caller.__class__.__name__, |
---|
| 78 | message.encode('hex'))) |
---|
| 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 | for c in clients: |
---|
[139] | 89 | c.write_message(message, True) |
---|
[133] | 90 | |
---|
[137] | 91 | finally: |
---|
[138] | 92 | self._write_lock.release() |
---|
[137] | 93 | |
---|
[138] | 94 | def __call__(self, fd, events): |
---|
| 95 | self.write(self, self._tap.read(self._tap.mtu)) |
---|
[133] | 96 | |
---|
[135] | 97 | |
---|
[133] | 98 | class EtherWebSocket(tornado.websocket.WebSocketHandler): |
---|
| 99 | def __init__(self, app, req, tap, debug=False): |
---|
| 100 | super(EtherWebSocket, self).__init__(app, req) |
---|
| 101 | self._tap = tap |
---|
| 102 | self._debug = debug |
---|
| 103 | |
---|
| 104 | def open(self): |
---|
| 105 | self._tap.register_client(self) |
---|
| 106 | |
---|
| 107 | def on_message(self, message): |
---|
[139] | 108 | self._tap.write(self, message) |
---|
[133] | 109 | |
---|
| 110 | def on_close(self): |
---|
| 111 | self._tap.unregister_client(self) |
---|
| 112 | |
---|
| 113 | |
---|
[134] | 114 | def daemonize(nochdir=False, noclose=False): |
---|
| 115 | if os.fork() > 0: |
---|
| 116 | sys.exit(0) |
---|
| 117 | |
---|
| 118 | os.setsid() |
---|
| 119 | |
---|
| 120 | if os.fork() > 0: |
---|
| 121 | sys.exit(0) |
---|
| 122 | |
---|
| 123 | if not nochdir: |
---|
| 124 | os.chdir('/') |
---|
| 125 | |
---|
| 126 | if not noclose: |
---|
| 127 | os.umask(0) |
---|
| 128 | sys.stdin.close() |
---|
| 129 | sys.stdout.close() |
---|
| 130 | sys.stderr.close() |
---|
| 131 | os.close(0) |
---|
| 132 | os.close(1) |
---|
| 133 | os.close(2) |
---|
| 134 | sys.stdin = open(os.devnull) |
---|
| 135 | sys.stdout = open(os.devnull, 'a') |
---|
| 136 | sys.stderr = open(os.devnull, 'a') |
---|
| 137 | |
---|
| 138 | |
---|
[133] | 139 | def server_main(args): |
---|
[143] | 140 | ssl_options = {} |
---|
| 141 | |
---|
| 142 | for k in ['keyfile', 'certfile']: |
---|
| 143 | v = getattr(args, k, None) |
---|
| 144 | if v: |
---|
| 145 | v = os.path.realpath(v) |
---|
| 146 | ssl_options[k] = v |
---|
| 147 | open(v).close() # readable test |
---|
| 148 | |
---|
| 149 | if len(ssl_options) == 1: |
---|
| 150 | raise ValueError('both keyfile and certfile are required') |
---|
| 151 | elif not ssl_options: |
---|
| 152 | ssl_options = None |
---|
| 153 | |
---|
| 154 | if not args.port: |
---|
| 155 | if ssl_options: |
---|
| 156 | args.port = 443 |
---|
| 157 | else: |
---|
| 158 | args.port = 80 |
---|
| 159 | |
---|
| 160 | if not args.foreground: |
---|
| 161 | daemonize() |
---|
| 162 | |
---|
[138] | 163 | tap = TapHandler(args.device, debug=args.debug) |
---|
[133] | 164 | app = tornado.web.Application([ |
---|
| 165 | (args.path, EtherWebSocket, {'tap': tap, 'debug': args.debug}), |
---|
| 166 | ]) |
---|
[143] | 167 | server = tornado.httpserver.HTTPServer(app, ssl_options=ssl_options) |
---|
[133] | 168 | server.listen(args.port, address=args.address) |
---|
| 169 | |
---|
[138] | 170 | ioloop = tornado.ioloop.IOLoop.instance() |
---|
| 171 | ioloop.add_handler(tap.fileno(), tap, ioloop.READ) |
---|
| 172 | ioloop.start() |
---|
[133] | 173 | |
---|
| 174 | |
---|
| 175 | def client_main(args): |
---|
| 176 | if args.debug: |
---|
| 177 | websocket.enableTrace(True) |
---|
| 178 | |
---|
[143] | 179 | if not args.foreground: |
---|
| 180 | daemonize() |
---|
| 181 | |
---|
[138] | 182 | tap = TapHandler(args.device, debug=args.debug) |
---|
[133] | 183 | client = websocket.WebSocketApp(args.uri) |
---|
[139] | 184 | client.on_message = lambda s, m: tap.write(client, m) |
---|
| 185 | client.write_message = \ |
---|
| 186 | lambda m, b: client.sock.send(m, websocket.ABNF.OPCODE_BINARY) |
---|
[133] | 187 | tap.register_client(client) |
---|
| 188 | |
---|
[138] | 189 | t = threading.Thread(target=client.run_forever) |
---|
| 190 | t.setDaemon(True) |
---|
| 191 | t.start() |
---|
[133] | 192 | |
---|
[143] | 193 | while not client.sock: |
---|
| 194 | time.sleep(0.1) |
---|
| 195 | |
---|
[138] | 196 | ioloop = tornado.ioloop.IOLoop.instance() |
---|
| 197 | ioloop.add_handler(tap.fileno(), tap, ioloop.READ) |
---|
| 198 | ioloop.start() |
---|
[133] | 199 | |
---|
[138] | 200 | |
---|
[133] | 201 | def main(): |
---|
| 202 | parser = argparse.ArgumentParser() |
---|
| 203 | parser.add_argument('--device', action='store', default='ethws%d') |
---|
| 204 | parser.add_argument('--foreground', action='store_true', default=False) |
---|
| 205 | parser.add_argument('--debug', action='store_true', default=False) |
---|
| 206 | |
---|
| 207 | subparsers = parser.add_subparsers(dest='subcommand') |
---|
| 208 | |
---|
| 209 | parser_server = subparsers.add_parser('server') |
---|
| 210 | parser_server.add_argument('--address', action='store', default='') |
---|
[143] | 211 | parser_server.add_argument('--port', action='store', type=int) |
---|
[133] | 212 | parser_server.add_argument('--path', action='store', default='/') |
---|
[143] | 213 | parser_server.add_argument('--keyfile', action='store') |
---|
| 214 | parser_server.add_argument('--certfile', action='store') |
---|
[133] | 215 | |
---|
| 216 | parser_client = subparsers.add_parser('client') |
---|
| 217 | parser_client.add_argument('--uri', action='store', required=True) |
---|
| 218 | |
---|
| 219 | args = parser.parse_args() |
---|
| 220 | |
---|
| 221 | if args.subcommand == 'server': |
---|
| 222 | server_main(args) |
---|
| 223 | elif args.subcommand == 'client': |
---|
| 224 | client_main(args) |
---|
| 225 | |
---|
| 226 | |
---|
| 227 | if __name__ == '__main__': |
---|
| 228 | main() |
---|