source: etherws/trunk/etherws.py @ 166

Revision 166, 15.2 KB checked in by atzm, 12 years ago (diff)
  • restructure
  • Property svn:keywords set to Id
RevLine 
[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#   - servant mode support (like typical p2p software)
[140]14#
[133]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
[156]45import ssl
[160]46import time
[150]47import base64
48import hashlib
[151]49import getpass
[133]50import argparse
[165]51import traceback
[133]52
53import websocket
[160]54import tornado.web
[133]55import tornado.ioloop
56import tornado.websocket
[160]57import tornado.httpserver
[133]58
[166]59from pytun import TunTapDevice, IFF_TAP, IFF_NO_PI
[133]60
[166]61
[160]62class DebugMixIn(object):
[166]63    def dprintf(self, msg, func=lambda: ()):
[160]64        if self._debug:
65            prefix = '[%s] %s - ' % (time.asctime(), self.__class__.__name__)
[164]66            sys.stderr.write(prefix + (msg % func()))
[160]67
68
[164]69class EthernetFrame(object):
70    def __init__(self, data):
71        self.data = data
72
73    @property
74    def multicast(self):
75        return ord(self.data[0]) & 1
76
77    @property
78    def dst_mac(self):
79        return self.data[:6]
80
81    @property
82    def src_mac(self):
83        return self.data[6:12]
84
85    @property
86    def tagged(self):
87        return ord(self.data[12]) == 0x81 and ord(self.data[13]) == 0
88
89    @property
90    def vid(self):
91        if self.tagged:
92            return ((ord(self.data[14]) << 8) | ord(self.data[15])) & 0x0fff
93        return -1
94
95
[166]96class FDB(DebugMixIn):
[164]97    def __init__(self, ageout=300, debug=False):
98        self._ageout = ageout
99        self._debug = debug
[166]100        self._dict = {}
[164]101
102    def lookup(self, frame):
103        mac = frame.dst_mac
104        vid = frame.vid
105
[166]106        group = self._dict.get(vid, None)
[164]107        if not group:
108            return None
109
110        entry = group.get(mac, None)
111        if not entry:
112            return None
113
114        if time.time() - entry['time'] > self._ageout:
[166]115            del self._dict[vid][mac]
116            if not self._dict[vid]:
117                del self._dict[vid]
[164]118            self.dprintf('aged out: [%d] %s\n',
119                         lambda: (vid, mac.encode('hex')))
120            return None
121
122        return entry['port']
123
[166]124    def learn(self, port, frame):
125        mac = frame.src_mac
126        vid = frame.vid
127
128        if vid not in self._dict:
129            self._dict[vid] = {}
130
131        self._dict[vid][mac] = {'time': time.time(), 'port': port}
132        self.dprintf('learned: [%d] %s\n',
133                     lambda: (vid, mac.encode('hex')))
134
[164]135    def delete(self, port):
[166]136        for vid in self._dict.keys():
137            for mac in self._dict[vid].keys():
138                if self._dict[vid][mac]['port'] is port:
139                    del self._dict[vid][mac]
[164]140                    self.dprintf('deleted: [%d] %s\n',
141                                 lambda: (vid, mac.encode('hex')))
[166]142            if not self._dict[vid]:
143                del self._dict[vid]
[164]144
145
[166]146class SwitchingHub(DebugMixIn):
147    def __init__(self, fdb, debug=False):
148        self._fdb = fdb
[133]149        self._debug = debug
[166]150        self._ports = []
[133]151
[166]152    def register_port(self, port):
153        self._ports.append(port)
[133]154
[166]155    def unregister_port(self, port):
156        self._fdb.delete(port)
157        self._ports.remove(port)
[133]158
[166]159    def forward(self, src_port, frame):
160        try:
161            self._fdb.learn(src_port, frame)
[133]162
[166]163            if not frame.multicast:
164                dst_port = self._fdb.lookup(frame)
[164]165
[166]166                if dst_port:
167                    self._unicast(frame, dst_port)
168                    return
[133]169
[166]170            self._broadcast(frame, src_port)
[162]171
[166]172        except:  # ex. received invalid frame
173            traceback.print_exc()
[133]174
[166]175    def _unicast(self, frame, port):
176        port.write_message(frame.data, True)
177        self.dprintf('sent unicast: [%d] %s -> %s\n',
178                     lambda: (frame.vid,
179                              frame.src_mac.encode('hex'),
180                              frame.dst_mac.encode('hex')))
[164]181
[166]182    def _broadcast(self, frame, *except_ports):
183        ports = self._ports[:]
184        for port in except_ports:
185            ports.remove(port)
186        for port in ports:
187            port.write_message(frame.data, True)
[164]188        self.dprintf('sent broadcast: [%d] %s -> %s\n',
189                     lambda: (frame.vid,
190                              frame.src_mac.encode('hex'),
191                              frame.dst_mac.encode('hex')))
192
[166]193
194class TapHandler(DebugMixIn):
195    READ_SIZE = 65535
196
197    def __init__(self, switch, dev, debug=False):
198        self._switch = switch
199        self._dev = dev
200        self._debug = debug
201        self._tap = None
202
203    @property
204    def closed(self):
205        return not self._tap
206
207    def open(self):
208        if not self.closed:
209            raise ValueError('already opened')
210        self._tap = TunTapDevice(self._dev, IFF_TAP | IFF_NO_PI)
211        self._tap.up()
212        self._switch.register_port(self)
213
214    def close(self):
215        if self.closed:
216            raise ValueError('I/O operation on closed tap')
217        self._switch.unregister_port(self)
218        self._tap.close()
219        self._tap = None
220
221    def fileno(self):
222        if self.closed:
223            raise ValueError('I/O operation on closed tap')
224        return self._tap.fileno()
225
226    def write_message(self, message, binary=False):
227        if self.closed:
228            raise ValueError('I/O operation on closed tap')
229        self._tap.write(message)
230
[138]231    def __call__(self, fd, events):
[166]232        try:
233            self._switch.forward(self, EthernetFrame(self._read()))
234            return
235        except:
236            traceback.print_exc()
237        tornado.ioloop.IOLoop.instance().stop()
238
239    def _read(self):
240        if self.closed:
241            raise ValueError('I/O operation on closed tap')
[162]242        buf = []
243        while True:
[166]244            buf.append(self._tap.read(self.READ_SIZE))
245            if len(buf[-1]) < self.READ_SIZE:
[162]246                break
[166]247        return ''.join(buf)
[162]248
249
[160]250class EtherWebSocketHandler(tornado.websocket.WebSocketHandler, DebugMixIn):
[166]251    def __init__(self, app, req, switch, debug=False):
[160]252        super(EtherWebSocketHandler, self).__init__(app, req)
[166]253        self._switch = switch
[133]254        self._debug = debug
255
256    def open(self):
[166]257        self._switch.register_port(self)
[164]258        self.dprintf('connected: %s\n', lambda: self.request.remote_ip)
[133]259
260    def on_message(self, message):
[166]261        self._switch.forward(self, EthernetFrame(message))
[133]262
263    def on_close(self):
[166]264        self._switch.unregister_port(self)
[164]265        self.dprintf('disconnected: %s\n', lambda: self.request.remote_ip)
[133]266
267
[160]268class EtherWebSocketClient(DebugMixIn):
[166]269    def __init__(self, switch, url, user=None, passwd=None, debug=False):
270        self._switch = switch
[151]271        self._url = url
[160]272        self._debug = debug
[166]273        self._sock = None
[151]274        self._options = {}
275
276        if user and passwd:
277            token = base64.b64encode('%s:%s' % (user, passwd))
278            auth = ['Authorization: Basic %s' % token]
279            self._options['header'] = auth
280
[160]281    @property
282    def closed(self):
283        return not self._sock
284
[151]285    def open(self):
[160]286        if not self.closed:
287            raise websocket.WebSocketException('already opened')
[151]288        self._sock = websocket.WebSocket()
289        self._sock.connect(self._url, **self._options)
[166]290        self._switch.register_port(self)
[164]291        self.dprintf('connected: %s\n', lambda: self._url)
[151]292
293    def close(self):
[160]294        if self.closed:
295            raise websocket.WebSocketException('already closed')
[166]296        self._switch.unregister_port(self)
[151]297        self._sock.close()
298        self._sock = None
[164]299        self.dprintf('disconnected: %s\n', lambda: self._url)
[151]300
[165]301    def fileno(self):
302        if self.closed:
303            raise websocket.WebSocketException('closed socket')
304        return self._sock.io_sock.fileno()
305
[151]306    def write_message(self, message, binary=False):
[160]307        if self.closed:
308            raise websocket.WebSocketException('closed socket')
[151]309        if binary:
310            flag = websocket.ABNF.OPCODE_BINARY
[160]311        else:
312            flag = websocket.ABNF.OPCODE_TEXT
[151]313        self._sock.send(message, flag)
314
[165]315    def __call__(self, fd, events):
[151]316        try:
[165]317            data = self._sock.recv()
318            if data is not None:
[166]319                self._switch.forward(self, EthernetFrame(data))
[165]320                return
321        except:
322            traceback.print_exc()
323        tornado.ioloop.IOLoop.instance().stop()
[151]324
325
[134]326def daemonize(nochdir=False, noclose=False):
327    if os.fork() > 0:
328        sys.exit(0)
329
330    os.setsid()
331
332    if os.fork() > 0:
333        sys.exit(0)
334
335    if not nochdir:
336        os.chdir('/')
337
338    if not noclose:
339        os.umask(0)
340        sys.stdin.close()
341        sys.stdout.close()
342        sys.stderr.close()
343        os.close(0)
344        os.close(1)
345        os.close(2)
346        sys.stdin = open(os.devnull)
347        sys.stdout = open(os.devnull, 'a')
348        sys.stderr = open(os.devnull, 'a')
349
350
[160]351def realpath(ns, *keys):
352    for k in keys:
353        v = getattr(ns, k, None)
354        if v is not None:
355            v = os.path.realpath(v)
356            setattr(ns, k, v)
357            open(v).close()  # check readable
358    return ns
359
360
[133]361def server_main(args):
[160]362    def wrap_basic_auth(cls, users):
363        o_exec = cls._execute
364
[150]365        if not users:
366            return cls
367
[160]368        def execute(self, transforms, *args, **kwargs):
[150]369            def auth_required():
370                self.stream.write(tornado.escape.utf8(
371                    'HTTP/1.1 401 Authorization Required\r\n'
372                    'WWW-Authenticate: Basic realm=etherws\r\n\r\n'
373                ))
374                self.stream.close()
375
[160]376            creds = self.request.headers.get('Authorization')
[150]377
[160]378            if not creds or not creds.startswith('Basic '):
379                return auth_required()
[150]380
[160]381            try:
382                name, passwd = base64.b64decode(creds[6:]).split(':', 1)
[150]383                passwd = base64.b64encode(hashlib.sha1(passwd).digest())
384
385                if name not in users or users[name] != passwd:
386                    return auth_required()
387
[160]388                return o_exec(self, transforms, *args, **kwargs)
[150]389
390            except:
391                return auth_required()
392
[160]393        cls._execute = execute
[150]394        return cls
395
396    def load_htpasswd(path):
397        users = {}
398        try:
399            with open(path) as fp:
400                for line in fp:
401                    line = line.strip()
402                    if 0 <= line.find(':'):
[160]403                        name, passwd = line.split(':', 1)
[150]404                        if passwd.startswith('{SHA}'):
405                            users[name] = passwd[5:]
[156]406            if not users:
[160]407                raise ValueError('no valid users found')
[150]408        except TypeError:
409            pass
410        return users
411
[160]412    realpath(args, 'keyfile', 'certfile', 'htpasswd')
[143]413
[160]414    if args.keyfile and args.certfile:
415        ssl_options = {'keyfile': args.keyfile, 'certfile': args.certfile}
416    elif args.keyfile or args.certfile:
[143]417        raise ValueError('both keyfile and certfile are required')
[160]418    else:
[143]419        ssl_options = None
420
[160]421    if args.port is None:
[143]422        if ssl_options:
423            args.port = 443
424        else:
425            args.port = 80
[160]426    elif not (0 <= args.port <= 65535):
427        raise ValueError('invalid port: %s' % args.port)
[143]428
[160]429    handler = wrap_basic_auth(EtherWebSocketHandler,
430                              load_htpasswd(args.htpasswd))
431
[166]432    fdb = FDB(debug=args.debug)
433    switch = SwitchingHub(fdb, debug=args.debug)
434    tap = TapHandler(switch, args.device, debug=args.debug)
[133]435    app = tornado.web.Application([
[166]436        (args.path, handler, {'switch': switch, 'debug': args.debug}),
[133]437    ])
[143]438    server = tornado.httpserver.HTTPServer(app, ssl_options=ssl_options)
[166]439
440    tap.open()
[133]441    server.listen(args.port, address=args.address)
442
[138]443    ioloop = tornado.ioloop.IOLoop.instance()
444    ioloop.add_handler(tap.fileno(), tap, ioloop.READ)
[151]445
446    if not args.foreground:
447        daemonize()
448
[138]449    ioloop.start()
[133]450
451
452def client_main(args):
[160]453    realpath(args, 'cacerts')
454
[133]455    if args.debug:
456        websocket.enableTrace(True)
457
[156]458    if not args.insecure:
459        websocket._SSLSocketWrapper = \
460            lambda s: ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED,
461                                      ca_certs=args.cacerts)
462
[160]463    if args.user and args.passwd is None:
464        args.passwd = getpass.getpass()
[143]465
[166]466    fdb = FDB(debug=args.debug)
467    switch = SwitchingHub(fdb, debug=args.debug)
468    tap = TapHandler(switch, args.device, debug=args.debug)
469    client = EtherWebSocketClient(switch, args.uri,
[160]470                                  args.user, args.passwd, args.debug)
[151]471
[166]472    tap.open()
[151]473    client.open()
[133]474
[138]475    ioloop = tornado.ioloop.IOLoop.instance()
476    ioloop.add_handler(tap.fileno(), tap, ioloop.READ)
[165]477    ioloop.add_handler(client.fileno(), client, ioloop.READ)
[151]478
479    if not args.foreground:
480        daemonize()
481
[165]482    ioloop.start()
[133]483
[138]484
[133]485def main():
486    parser = argparse.ArgumentParser()
487    parser.add_argument('--device', action='store', default='ethws%d')
488    parser.add_argument('--foreground', action='store_true', default=False)
489    parser.add_argument('--debug', action='store_true', default=False)
490
491    subparsers = parser.add_subparsers(dest='subcommand')
492
[158]493    parser_s = subparsers.add_parser('server')
494    parser_s.add_argument('--address', action='store', default='')
495    parser_s.add_argument('--port', action='store', type=int)
496    parser_s.add_argument('--path', action='store', default='/')
497    parser_s.add_argument('--htpasswd', action='store')
498    parser_s.add_argument('--keyfile', action='store')
499    parser_s.add_argument('--certfile', action='store')
[133]500
[158]501    parser_c = subparsers.add_parser('client')
502    parser_c.add_argument('--uri', action='store', required=True)
503    parser_c.add_argument('--insecure', action='store_true', default=False)
504    parser_c.add_argument('--cacerts', action='store')
505    parser_c.add_argument('--user', action='store')
[160]506    parser_c.add_argument('--passwd', action='store')
[133]507
508    args = parser.parse_args()
509
510    if args.subcommand == 'server':
511        server_main(args)
512    elif args.subcommand == 'client':
513        client_main(args)
514
515
516if __name__ == '__main__':
517    main()
Note: See TracBrowser for help on using the repository browser.