source: etherws/trunk/etherws.py @ 134

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