source: etherws/trunk/etherws.py @ 138

Revision 138, 5.9 KB checked in by atzm, 13 years ago (diff)
  • change handler structure
  • Property svn:keywords set to Id
Line 
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.7.0
10#   - tornado-2.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
43import os
44import sys
45import base64
46import argparse
47import threading
48
49import pytun
50import websocket
51import tornado.httpserver
52import tornado.ioloop
53import tornado.web
54import tornado.websocket
55
56
57class TapHandler(object):
58    def __init__(self, dev, debug=False):
59        self._debug = debug
60        self._clients = []
61        self._tap = pytun.TunTapDevice(dev, pytun.IFF_TAP | pytun.IFF_NO_PI)
62        self._tap.up()
63        self._write_lock = threading.Lock()
64
65    def fileno(self):
66        return self._tap.fileno()
67
68    def register_client(self, client):
69        self._clients.append(client)
70
71    def unregister_client(self, client):
72        self._clients.remove(client)
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:
80            self._write_lock.acquire()
81
82            clients = self._clients[:]
83
84            if caller is not self:
85                clients.remove(caller)
86                self._tap.write(message)
87
88            message = base64.b64encode(message)
89
90            for c in clients:
91                c.write_message(message)
92
93        finally:
94            self._write_lock.release()
95
96    def __call__(self, fd, events):
97        self.write(self, self._tap.read(self._tap.mtu))
98
99
100class 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
116def 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
141def server_main(args):
142    tap = TapHandler(args.device, debug=args.debug)
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
149    ioloop = tornado.ioloop.IOLoop.instance()
150    ioloop.add_handler(tap.fileno(), tap, ioloop.READ)
151    ioloop.start()
152
153
154def client_main(args):
155    if args.debug:
156        websocket.enableTrace(True)
157
158    tap = TapHandler(args.device, debug=args.debug)
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
164    t = threading.Thread(target=client.run_forever)
165    t.setDaemon(True)
166    t.start()
167
168    ioloop = tornado.ioloop.IOLoop.instance()
169    ioloop.add_handler(tap.fileno(), tap, ioloop.READ)
170    ioloop.start()
171
172
173def 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
191    if not args.foreground:
192        daemonize()
193
194    if args.subcommand == 'server':
195        server_main(args)
196    elif args.subcommand == 'client':
197        client_main(args)
198
199
200if __name__ == '__main__':
201    main()
Note: See TracBrowser for help on using the repository browser.