├── tashrouter ├── __init__.py ├── router │ ├── __init__.py │ ├── zone_information_table.py │ ├── routing_table.py │ └── router.py ├── netlog │ ├── __init__.py │ └── netlogger.py ├── service │ ├── __init__.py │ ├── zip │ │ ├── __init__.py │ │ ├── sending.py │ │ └── responding.py │ ├── routing_table_aging.py │ ├── echo.py │ ├── rtmp │ │ ├── sending.py │ │ ├── __init__.py │ │ └── responding.py │ └── name_information.py ├── port │ ├── ethertalk │ │ ├── virtual.py │ │ ├── tap.py │ │ ├── macvtap.py │ │ └── __init__.py │ ├── localtalk │ │ ├── virtual.py │ │ ├── ltoudp.py │ │ ├── tashtalk.py │ │ └── __init__.py │ └── __init__.py └── datagram.py ├── .github └── FUNDING.yml ├── README.md └── LICENSE /tashrouter/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tashrouter/router/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | ko_fi: tashtari 2 | -------------------------------------------------------------------------------- /tashrouter/netlog/__init__.py: -------------------------------------------------------------------------------- 1 | '''Facilities for logging of network traffic for debug and test purposes.''' 2 | 3 | from .netlogger import NetLogger 4 | 5 | 6 | DEFAULT_LOGGER = NetLogger() 7 | 8 | log_datagram_inbound = DEFAULT_LOGGER.log_datagram_inbound 9 | log_datagram_unicast = DEFAULT_LOGGER.log_datagram_unicast 10 | log_datagram_broadcast = DEFAULT_LOGGER.log_datagram_broadcast 11 | log_datagram_multicast = DEFAULT_LOGGER.log_datagram_multicast 12 | log_ethernet_frame_inbound = DEFAULT_LOGGER.log_ethernet_frame_inbound 13 | log_ethernet_frame_outbound = DEFAULT_LOGGER.log_ethernet_frame_outbound 14 | log_localtalk_frame_inbound = DEFAULT_LOGGER.log_localtalk_frame_inbound 15 | log_localtalk_frame_outbound = DEFAULT_LOGGER.log_localtalk_frame_outbound 16 | set_log_str_func = DEFAULT_LOGGER.set_log_str_func 17 | -------------------------------------------------------------------------------- /tashrouter/service/__init__.py: -------------------------------------------------------------------------------- 1 | '''Service base class.''' 2 | 3 | 4 | class Service: 5 | '''A service that lives on a router and sends/receives on a static socket. 6 | 7 | This class does not extend Thread because it may have multiple threads according to the implementer's design. 8 | ''' 9 | 10 | def start(self, router): 11 | '''Starts the Service connected to a given router.''' 12 | raise NotImplementedError('subclass must override "start" method') 13 | 14 | def stop(self): 15 | '''Stops the Service.''' 16 | raise NotImplementedError('subclass must override "stop" method') 17 | 18 | def inbound(self, datagram, rx_port): 19 | '''Called when a Datagram comes in over a Port from the Router to which this Service is connected.''' 20 | raise NotImplementedError('subclass must override "inbound" method') 21 | -------------------------------------------------------------------------------- /tashrouter/service/zip/__init__.py: -------------------------------------------------------------------------------- 1 | '''Mixin containing constants used by services that use ZIP (Zone Information Protocol).''' 2 | 3 | class ZipService: 4 | '''Mixin containing constants used by services that use ZIP (Zone Information Protocol).''' 5 | 6 | ZIP_SAS = 6 7 | ZIP_DDP_TYPE = 6 8 | 9 | ZIP_FUNC_QUERY = 1 10 | ZIP_FUNC_REPLY = 2 11 | ZIP_FUNC_GETNETINFO_REQUEST = 5 12 | ZIP_FUNC_GETNETINFO_REPLY = 6 13 | ZIP_FUNC_NOTIFY = 7 14 | ZIP_FUNC_EXT_REPLY = 8 15 | 16 | ZIP_ATP_FUNC_GETMYZONE = 7 17 | ZIP_ATP_FUNC_GETZONELIST = 8 18 | ZIP_ATP_FUNC_GETLOCALZONES = 9 19 | 20 | ZIP_GETNETINFO_ZONE_INVALID = 0b10000000 21 | ZIP_GETNETINFO_USE_BROADCAST = 0b01000000 22 | ZIP_GETNETINFO_ONLY_ONE_ZONE = 0b00100000 23 | 24 | ATP_DDP_TYPE = 3 25 | 26 | ATP_FUNC_TREQ = 0b01000000 27 | ATP_FUNC_TRESP = 0b10000000 28 | ATP_FUNC_TREL = 0b11000000 29 | ATP_EOM = 0b00010000 30 | -------------------------------------------------------------------------------- /tashrouter/service/routing_table_aging.py: -------------------------------------------------------------------------------- 1 | '''RoutingTable aging service.''' 2 | 3 | from threading import Thread, Event 4 | 5 | from . import Service 6 | 7 | 8 | class RoutingTableAgingService(Service): 9 | '''A Service which ages the Router's RoutingTable on a regular basis.''' 10 | 11 | DEFAULT_TIMEOUT = 20 # seconds 12 | 13 | def __init__(self, timeout=DEFAULT_TIMEOUT): 14 | self.timeout = timeout 15 | self.thread = None 16 | self.started_event = Event() 17 | self.stop_requested_event = Event() 18 | self.stopped_event = Event() 19 | 20 | def start(self, router): 21 | self.thread = Thread(target=self._run, args=(router,)) 22 | self.thread.start() 23 | self.started_event.wait() 24 | 25 | def stop(self): 26 | self.stop_requested_event.set() 27 | self.stopped_event.wait() 28 | 29 | def _run(self, router): 30 | self.started_event.set() 31 | while True: 32 | if self.stop_requested_event.wait(timeout=self.timeout): break 33 | router.routing_table.age() 34 | self.stopped_event.set() 35 | 36 | def inbound(self, datagram, rx_port): 37 | pass 38 | -------------------------------------------------------------------------------- /tashrouter/service/echo.py: -------------------------------------------------------------------------------- 1 | '''Echo service.''' 2 | 3 | from queue import Queue 4 | from threading import Thread, Event 5 | 6 | from . import Service 7 | 8 | 9 | class EchoService(Service): 10 | '''A Service which implements AppleTalk Echo Protocol (AEP).''' 11 | 12 | ECHO_SAS = 4 13 | ECHO_DDP_TYPE = 4 14 | 15 | ECHO_FUNC_REQUEST_BYTE = b'\x01' 16 | ECHO_FUNC_REPLY_BYTE = b'\x02' 17 | 18 | def __init__(self): 19 | self.thread = None 20 | self.queue = Queue() 21 | self.stop_flag = object() 22 | self.started_event = Event() 23 | self.stopped_event = Event() 24 | 25 | def start(self, router): 26 | self.thread = Thread(target=self._run, args=(router,)) 27 | self.thread.start() 28 | self.started_event.wait() 29 | 30 | def stop(self): 31 | self.queue.put(self.stop_flag) 32 | self.stopped_event.wait() 33 | 34 | def _run(self, router): 35 | self.started_event.set() 36 | while True: 37 | item = self.queue.get() 38 | if item is self.stop_flag: break 39 | datagram, rx_port = item 40 | if datagram.ddp_type != self.ECHO_DDP_TYPE: continue 41 | if not datagram.data: continue 42 | if datagram.data[0:1] != self.ECHO_FUNC_REQUEST_BYTE: continue 43 | router.reply(datagram, rx_port, self.ECHO_DDP_TYPE, self.ECHO_FUNC_REPLY_BYTE + datagram.data[1:]) 44 | self.stopped_event.set() 45 | 46 | def inbound(self, datagram, rx_port): 47 | self.queue.put((datagram, rx_port)) 48 | -------------------------------------------------------------------------------- /tashrouter/port/ethertalk/virtual.py: -------------------------------------------------------------------------------- 1 | '''Classes for virtual EtherTalk networks.''' 2 | 3 | from collections import deque 4 | from threading import Lock 5 | 6 | from . import EtherTalkPort 7 | 8 | 9 | class VirtualEtherTalkPort(EtherTalkPort): 10 | '''Virtual EtherTalk Port.''' 11 | 12 | def __init__(self, virtual_network, hw_addr, short_str=None, **kwargs): 13 | super().__init__(hw_addr, **kwargs) 14 | self._virtual_network = virtual_network 15 | self._short_str = short_str or 'Virtual' 16 | 17 | def short_str(self): return self._short_str 18 | __str__ = short_str 19 | __repr__ = short_str 20 | 21 | def start(self, router): 22 | self._virtual_network.plug(self._hw_addr, self.inbound_frame) 23 | super().start(router) 24 | 25 | def stop(self): 26 | super().stop() 27 | self._virtual_network.unplug(self._hw_addr) 28 | 29 | def send_frame(self, frame_data): 30 | self._virtual_network.send_frame(frame_data, self._hw_addr) 31 | 32 | 33 | class VirtualEtherTalkNetwork: 34 | '''Virtual EtherTalk network.''' 35 | 36 | def __init__(self): 37 | self._plugged = {} # ethernet address -> receive frame function 38 | self._lock = Lock() 39 | 40 | def plug(self, hw_addr, recv_func): 41 | '''Plug a VirtualEtherTalkPort into this network.''' 42 | with self._lock: self._plugged[hw_addr] = recv_func 43 | 44 | def unplug(self, hw_addr): 45 | '''Unplug a VirtualEtherTalkPort from this network.''' 46 | with self._lock: self._plugged.pop(hw_addr) 47 | 48 | def send_frame(self, frame_data, recv_hw_addr): 49 | '''Send an Ethernet frame to all ports plugged into this network.''' 50 | if not frame_data: return 51 | is_multicast = True if frame_data[0] & 0x01 else False 52 | functions_to_call = deque() 53 | with self._lock: 54 | for hw_addr, func in self._plugged.items(): 55 | if hw_addr == recv_hw_addr: continue 56 | if is_multicast or frame_data[0:6] == hw_addr: functions_to_call.append(func) 57 | for func in functions_to_call: func(frame_data) 58 | -------------------------------------------------------------------------------- /tashrouter/port/localtalk/virtual.py: -------------------------------------------------------------------------------- 1 | '''Classes for virtual LocalTalk networks.''' 2 | 3 | from collections import deque 4 | from threading import Lock 5 | 6 | from . import LocalTalkPort 7 | from ...netlog import log_localtalk_frame_inbound, log_localtalk_frame_outbound 8 | 9 | 10 | class VirtualLocalTalkPort(LocalTalkPort): 11 | '''Virtual LocalTalk Port.''' 12 | 13 | def __init__(self, virtual_network, short_str=None, **kwargs): 14 | super().__init__(respond_to_enq=True, **kwargs) 15 | self._virtual_network = virtual_network 16 | self._short_str = short_str or 'Virtual' 17 | 18 | def short_str(self): return self._short_str 19 | __str__ = short_str 20 | __repr__ = short_str 21 | 22 | def _recv_frame(self, frame_data): 23 | log_localtalk_frame_inbound(frame_data, self) 24 | self.inbound_frame(frame_data) 25 | 26 | def start(self, router): 27 | self._virtual_network.plug(self._recv_frame) 28 | super().start(router) 29 | 30 | def stop(self): 31 | super().stop() 32 | self._virtual_network.unplug(self._recv_frame) 33 | 34 | def send_frame(self, frame_data): 35 | log_localtalk_frame_outbound(frame_data, self) 36 | self._virtual_network.send_frame(frame_data, self._recv_frame) 37 | 38 | 39 | class VirtualLocalTalkNetwork: 40 | '''Virtual LocalTalk network.''' 41 | 42 | def __init__(self): 43 | self._plugged = deque() 44 | self._lock = Lock() 45 | 46 | def plug(self, recv_func): 47 | '''Plug a VirtualLocalTalkPort into this network.''' 48 | with self._lock: self._plugged.append(recv_func) 49 | 50 | def unplug(self, recv_func): 51 | '''Unplug a VirtualLocalTalkPort from this network.''' 52 | with self._lock: self._plugged.remove(recv_func) 53 | 54 | def send_frame(self, frame_data, recv_func): 55 | '''Send a LocalTalk frame to all ports plugged into this network.''' 56 | functions_to_call = deque() 57 | with self._lock: 58 | for func in self._plugged: 59 | if func == recv_func: continue 60 | functions_to_call.append(func) 61 | for func in functions_to_call: func(frame_data) 62 | -------------------------------------------------------------------------------- /tashrouter/port/__init__.py: -------------------------------------------------------------------------------- 1 | '''Port base class.''' 2 | 3 | 4 | class Port: 5 | '''An abstraction of a router port, a connection to a physical network. 6 | 7 | Note that this covers only the case of a connection to an AppleTalk network, not the "half router" or "backbone network" cases 8 | detailed in Inside AppleTalk. 9 | 10 | Note also that a Port should only deliver Datagrams addressed to it (and broadcast Datagrams) to its Router. 11 | 12 | This class does not extend Thread because it may have multiple threads according to the implementer's design. 13 | ''' 14 | 15 | network: int 16 | node: int 17 | network_min: int 18 | network_max: int 19 | extended_network: bool 20 | 21 | def short_str(self): 22 | '''Return a short string representation of this Port.''' 23 | raise NotImplementedError('subclass must override "short_str" method') 24 | 25 | def start(self, router): 26 | '''Start this Port running.''' 27 | raise NotImplementedError('subclass must override "start" method') 28 | 29 | def stop(self): 30 | '''Stop this Port from running.''' 31 | raise NotImplementedError('subclass must override "stop" method') 32 | 33 | def unicast(self, network, node, datagram): 34 | '''Send a Datagram to a single address over this Port.''' 35 | raise NotImplementedError('subclass must override "unicast" method') 36 | 37 | def broadcast(self, datagram): 38 | '''Broadcast a Datagram over this Port.''' 39 | raise NotImplementedError('subclass must override "broadcast" method') 40 | 41 | def multicast(self, zone_name, datagram): 42 | '''Multicast a Datagram to a zone over this Port.''' 43 | raise NotImplementedError('subclass must override "multicast" method') 44 | 45 | def set_network_range(self, network_min, network_max): 46 | '''Set this Port's network range according to a seed router.''' 47 | raise NotImplementedError('subclass must override "set_network_range" method') 48 | 49 | @staticmethod 50 | def multicast_address(zone_name): 51 | '''Return the multicast address for the given zone.''' 52 | raise NotImplementedError('subclass must override "multicast_address" method') 53 | -------------------------------------------------------------------------------- /tashrouter/service/rtmp/sending.py: -------------------------------------------------------------------------------- 1 | '''RoutingTable sending Service.''' 2 | 3 | from queue import Queue, Empty 4 | from threading import Thread, Event 5 | 6 | from . import RtmpService 7 | from .. import Service 8 | from ...datagram import Datagram 9 | 10 | 11 | class RtmpSendingService(Service, RtmpService): 12 | '''A Service which sends RTMP Datagrams containing the Router's RoutingTable to its Ports on a regular basis.''' 13 | 14 | DEFAULT_TIMEOUT = 10 # seconds 15 | 16 | def __init__(self, timeout=DEFAULT_TIMEOUT): 17 | self.timeout = timeout 18 | self.thread = None 19 | self.started_event = Event() 20 | self.queue = Queue() 21 | self.stop_flag = object() 22 | self.force_send_flag = object() 23 | 24 | def start(self, router): 25 | self.thread = Thread(target=self._run, args=(router,)) 26 | self.thread.start() 27 | self.started_event.wait() 28 | 29 | def stop(self): 30 | self.queue.put(self.stop_flag) 31 | self.queue.join() 32 | 33 | def _run(self, router): 34 | self.started_event.set() 35 | while True: 36 | try: 37 | item = self.queue.get(timeout=self.timeout) 38 | except Empty: 39 | item = None 40 | if item is self.stop_flag: break 41 | for port in router.ports: 42 | if 0 in (port.node, port.network): continue 43 | for datagram_data in self.make_routing_table_datagram_data(router, port): 44 | port.broadcast(Datagram(hop_count=0, 45 | destination_network=0x0000, 46 | source_network=port.network, 47 | destination_node=0xFF, 48 | source_node=port.node, 49 | destination_socket=self.RTMP_SAS, 50 | source_socket=self.RTMP_SAS, 51 | ddp_type=self.RTMP_DDP_TYPE_DATA, 52 | data=datagram_data)) 53 | if item is not None: self.queue.task_done() 54 | self.queue.task_done() 55 | 56 | def inbound(self, datagram, rx_port): 57 | pass 58 | 59 | def force_send(self): 60 | '''Force this service to immediately send an RTMP Datagram for testing purposes.''' 61 | self.queue.put(self.force_send_flag) 62 | self.queue.join() 63 | -------------------------------------------------------------------------------- /tashrouter/service/rtmp/__init__.py: -------------------------------------------------------------------------------- 1 | '''RTMP service mixin.''' 2 | 3 | from collections import deque 4 | from itertools import chain 5 | import struct 6 | 7 | from ...datagram import Datagram 8 | 9 | 10 | class RtmpService: 11 | '''Mixin class that contains constants and common functions used by RTMP services.''' 12 | 13 | RTMP_SAS = 1 14 | RTMP_DDP_TYPE_DATA = 1 15 | RTMP_DDP_TYPE_REQUEST = 5 16 | RTMP_VERSION = 0x82 17 | RTMP_FUNC_REQUEST = 1 18 | RTMP_FUNC_RDR_SPLIT_HORIZON = 2 19 | RTMP_FUNC_RDR_NO_SPLIT_HORIZON = 3 20 | 21 | NOTIFY_NEIGHBOR = 31 22 | 23 | def make_routing_table_datagram_data(self, router, port, split_horizon=True): 24 | '''Build Datagram data for the given Router's RoutingTable.''' 25 | 26 | if 0 in (port.network_min, port.network_max): return 27 | 28 | binary_tuples = deque() 29 | this_net = None 30 | for entry, is_bad in router.routing_table.entries(): 31 | distance = self.NOTIFY_NEIGHBOR if is_bad else entry.distance 32 | if not entry.extended_network: 33 | binary_tuple = struct.pack('>HB', entry.network_min, distance & 0x1F) 34 | else: 35 | binary_tuple = struct.pack('>HBHB', entry.network_min, (distance & 0x1F) | 0x80, entry.network_max, self.RTMP_VERSION) 36 | if port.extended_network and port.network_min == entry.network_min and port.network_max == entry.network_max: 37 | this_net = binary_tuple 38 | elif entry.port is port and split_horizon: 39 | pass # split horizon 40 | else: 41 | binary_tuples.append(binary_tuple) 42 | if port.extended_network and not this_net: raise ValueError("port's network range was not found in routing table") 43 | 44 | if port.extended_network: 45 | rtmp_datagram_header = struct.pack('>HBB', port.network, 8, port.node) + this_net 46 | else: 47 | rtmp_datagram_header = struct.pack('>HBBHB', port.network, 8, port.node, 0, self.RTMP_VERSION) 48 | 49 | next_datagram_data = deque((rtmp_datagram_header,)) 50 | next_datagram_data_length = len(rtmp_datagram_header) 51 | for binary_tuple in chain(binary_tuples, (None,)): 52 | if binary_tuple is None or next_datagram_data_length + len(binary_tuple) > Datagram.MAX_DATA_LENGTH: 53 | yield b''.join(next_datagram_data) 54 | if binary_tuple is not None: 55 | next_datagram_data = deque((rtmp_datagram_header, binary_tuple)) 56 | next_datagram_data_length = len(rtmp_datagram_header) + len(binary_tuple) 57 | else: 58 | next_datagram_data.append(binary_tuple) 59 | next_datagram_data_length += len(binary_tuple) 60 | -------------------------------------------------------------------------------- /tashrouter/port/ethertalk/tap.py: -------------------------------------------------------------------------------- 1 | '''Port driver for EtherTalk using TUN/TAP.''' 2 | 3 | from fcntl import ioctl 4 | import os 5 | from queue import Queue 6 | from select import select 7 | import struct 8 | from threading import Thread, Event 9 | 10 | from . import EtherTalkPort 11 | 12 | 13 | class TapPort(EtherTalkPort): 14 | '''Port driver for EtherTalk using TUN/TAP.''' 15 | 16 | SELECT_TIMEOUT = 0.25 # seconds 17 | 18 | TUNSETIFF = 0x400454CA 19 | IFF_TAP = 0x0002 20 | IFF_NO_PI = 0x1000 21 | 22 | def __init__(self, tap_name, hw_addr, **kwargs): 23 | super().__init__(hw_addr, **kwargs) 24 | self._reader_thread = None 25 | self._reader_started_event = Event() 26 | self._reader_stop_requested = False 27 | self._reader_stopped_event = Event() 28 | self._tap_name = tap_name 29 | self._fp = None 30 | self._writer_thread = None 31 | self._writer_started_event = Event() 32 | self._writer_stop_flag = object() 33 | self._writer_stopped_event = Event() 34 | self._writer_queue = Queue() 35 | 36 | def short_str(self): 37 | return self._tap_name 38 | 39 | __str__ = short_str 40 | __repr__ = short_str 41 | 42 | def start(self, router): 43 | self._fp = os.open('/dev/net/tun', os.O_RDWR) 44 | ioctl(self._fp, self.TUNSETIFF, struct.pack('16sH22x', self._tap_name.encode('ascii') or b'', self.IFF_TAP | self.IFF_NO_PI)) 45 | super().start(router) 46 | self._reader_thread = Thread(target=self._reader_run) 47 | self._reader_thread.start() 48 | self._writer_thread = Thread(target=self._writer_run) 49 | self._writer_thread.start() 50 | self._reader_started_event.wait() 51 | self._writer_started_event.wait() 52 | 53 | def stop(self): 54 | self._reader_stop_requested = True 55 | self._writer_queue.put(self._writer_stop_flag) 56 | self._reader_stopped_event.wait() 57 | self._writer_stopped_event.wait() 58 | os.close(self._fp) 59 | super().stop() 60 | 61 | def send_frame(self, frame_data): 62 | self._writer_queue.put(frame_data) 63 | 64 | def _reader_run(self): 65 | self._reader_started_event.set() 66 | while not self._reader_stop_requested: 67 | rlist, _, _ = select((self._fp,), (), (), self.SELECT_TIMEOUT) 68 | if self._fp not in rlist: continue 69 | self.inbound_frame(os.read(self._fp, 65535)) 70 | self._reader_stopped_event.set() 71 | 72 | def _writer_run(self): 73 | self._writer_started_event.set() 74 | while True: 75 | frame_data = self._writer_queue.get() 76 | if frame_data is self._writer_stop_flag: break 77 | select((), (self._fp,), ()) 78 | os.write(self._fp, frame_data) 79 | self._writer_stopped_event.set() 80 | -------------------------------------------------------------------------------- /tashrouter/port/localtalk/ltoudp.py: -------------------------------------------------------------------------------- 1 | '''Port that connects to LToUDP.''' 2 | 3 | import errno 4 | import os 5 | import select 6 | import socket 7 | import struct 8 | from threading import Thread, Event 9 | import time 10 | 11 | from . import LocalTalkPort 12 | from ...netlog import log_localtalk_frame_inbound, log_localtalk_frame_outbound 13 | 14 | 15 | class LtoudpPort(LocalTalkPort): 16 | '''Port that connects to LToUDP.''' 17 | 18 | LTOUDP_GROUP = '239.192.76.84' # the last two octets spell 'LT' 19 | LTOUDP_PORT = 1954 20 | 21 | DEFAULT_INTF_ADDRESS = '0.0.0.0' 22 | 23 | SELECT_TIMEOUT = 0.25 # seconds 24 | NETWORK_UP_RETRY_TIMEOUT = 1 # seconds 25 | NETWORK_UP_RETRY_COUNT = 10 26 | 27 | def __init__(self, intf_address=DEFAULT_INTF_ADDRESS, **kwargs): 28 | super().__init__(respond_to_enq=True, **kwargs) 29 | self._intf_address = intf_address 30 | self._socket = None 31 | self._sender_id = None 32 | self._thread = None 33 | self._started_event = Event() 34 | self._stop_requested = False 35 | self._stopped_event = Event() 36 | 37 | def short_str(self): 38 | if self._intf_address == self.DEFAULT_INTF_ADDRESS: 39 | return 'LToUDP' 40 | else: 41 | return self._intf_address 42 | 43 | __str__ = short_str 44 | __repr__ = short_str 45 | 46 | def start(self, router): 47 | self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) 48 | self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 49 | if hasattr(socket, 'SO_REUSEPORT'): self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) 50 | self._socket.bind((self._intf_address, self.LTOUDP_PORT)) 51 | self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1) 52 | for attempt in range(self.NETWORK_UP_RETRY_COUNT): 53 | try: 54 | # this raises "OSError: [Errno 19] No such device" if network is not up, so build in some retry logic 55 | self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, 56 | socket.inet_aton(self.LTOUDP_GROUP) + socket.inet_aton(self._intf_address)) 57 | break 58 | except OSError as e: 59 | if e.errno != errno.ENODEV or attempt + 1 == self.NETWORK_UP_RETRY_COUNT: raise 60 | time.sleep(self.NETWORK_UP_RETRY_TIMEOUT) 61 | self._sender_id = struct.pack('>L', os.getpid()) 62 | super().start(router) 63 | self._thread = Thread(target=self._run) 64 | self._thread.start() 65 | self._started_event.wait() 66 | 67 | def stop(self): 68 | super().stop() 69 | self._stop_requested = True 70 | self._stopped_event.wait() 71 | 72 | def send_frame(self, frame_data): 73 | log_localtalk_frame_outbound(frame_data, self) 74 | self._socket.sendto(self._sender_id + frame_data, (self.LTOUDP_GROUP, self.LTOUDP_PORT)) 75 | 76 | def _run(self): 77 | self._started_event.set() 78 | while not self._stop_requested: 79 | rlist, _, _ = select.select((self._socket,), (), (), self.SELECT_TIMEOUT) 80 | if self._socket not in rlist: continue 81 | data, sender_addr = self._socket.recvfrom(65507) 82 | if len(data) < 7: continue 83 | if data[0:4] == self._sender_id: continue #TODO check sender_addr too 84 | log_localtalk_frame_inbound(data[4:], self) 85 | self.inbound_frame(data[4:]) 86 | self._stopped_event.set() 87 | -------------------------------------------------------------------------------- /tashrouter/service/zip/sending.py: -------------------------------------------------------------------------------- 1 | '''ZIP (Zone Information Protocol) sending service.''' 2 | 3 | from collections import deque 4 | from itertools import chain 5 | import logging 6 | import struct 7 | from threading import Thread, Event 8 | 9 | from . import ZipService 10 | from .. import Service 11 | from ...datagram import Datagram 12 | 13 | 14 | class ZipSendingService(Service, ZipService): 15 | '''A Service which sends ZIP queries to fill out its router's Zone Information Table.''' 16 | 17 | DEFAULT_TIMEOUT = 10 # seconds 18 | 19 | def __init__(self, timeout=DEFAULT_TIMEOUT): 20 | self.timeout = timeout 21 | self.thread = None 22 | self.started_event = Event() 23 | self.stop_requested_event = Event() 24 | self.stopped_event = Event() 25 | 26 | def start(self, router): 27 | self.thread = Thread(target=self._run, args=(router,)) 28 | self.thread.start() 29 | self.started_event.wait() 30 | 31 | def stop(self): 32 | self.stop_requested_event.set() 33 | self.stopped_event.wait() 34 | 35 | def _run(self, router): 36 | 37 | self.started_event.set() 38 | 39 | while True: 40 | 41 | if self.stop_requested_event.wait(timeout=self.timeout): break 42 | 43 | queries = {} # (port, network, node) -> network_mins 44 | for entry in router.routing_table: 45 | try: 46 | if next(iter(router.zone_information_table.zones_in_network_range(entry.network_min, entry.network_max)), None): continue 47 | except ValueError as e: 48 | logging.warning('%s apparent disjoin between routing table and zone information table: %s', router, e.args[0]) 49 | continue 50 | if entry.distance == 0: 51 | key = (entry.port, 0x0000, 0xFF) 52 | else: 53 | key = (entry.port, entry.next_network, entry.next_node) 54 | if key not in queries: queries[key] = deque() 55 | queries[key].append(entry.network_min) 56 | 57 | for port_network_node, network_mins in queries.items(): 58 | port, network, node = port_network_node 59 | if 0 in (port.node, port.network): continue 60 | datagram_data = deque() 61 | for network_min in chain(network_mins, (None,)): 62 | if network_min is None or len(datagram_data) * 2 + 4 > Datagram.MAX_DATA_LENGTH: 63 | datagram_data.appendleft(struct.pack('>BB', self.ZIP_FUNC_QUERY, len(datagram_data))) 64 | if (network, node) == (0x0000, 0xFF): 65 | port.broadcast(Datagram(hop_count=0, 66 | destination_network=network, 67 | source_network=port.network, 68 | destination_node=node, 69 | source_node=port.node, 70 | destination_socket=self.ZIP_SAS, 71 | source_socket=self.ZIP_SAS, 72 | ddp_type=self.ZIP_DDP_TYPE, 73 | data=b''.join(datagram_data))) 74 | else: 75 | port.unicast(network, node, Datagram(hop_count=0, 76 | destination_network=network, 77 | source_network=port.network, 78 | destination_node=node, 79 | source_node=port.node, 80 | destination_socket=self.ZIP_SAS, 81 | source_socket=self.ZIP_SAS, 82 | ddp_type=self.ZIP_DDP_TYPE, 83 | data=b''.join(datagram_data))) 84 | if network_min is not None: datagram_data = deque((struct.pack('>H', network_min),)) 85 | else: 86 | datagram_data.append(struct.pack('>H', network_min)) 87 | 88 | self.stopped_event.set() 89 | 90 | def inbound(self, datagram, rx_port): 91 | pass 92 | -------------------------------------------------------------------------------- /tashrouter/port/ethertalk/macvtap.py: -------------------------------------------------------------------------------- 1 | '''Port driver for EtherTalk using MACVTAP.''' 2 | 3 | from fcntl import ioctl 4 | import os 5 | from queue import Queue 6 | from select import select 7 | import struct 8 | from threading import Thread, Event 9 | 10 | from . import EtherTalkPort 11 | 12 | 13 | class MacvtapPort(EtherTalkPort): 14 | '''Port driver for EtherTalk using MACVTAP. 15 | 16 | To create a MACVTAP for use with this Port: 17 | # ip link add link eth0 name macvtap0 type macvtap # this creates /dev/tapX because Xth interface 18 | # ip link set dev macvtap0 promisc on # this is important, otherwise we don't get broadcast frames 19 | 20 | Then pass 'macvtap0' to the constructor's macvtap parameter. If left as None, the first macvtap found will be used. 21 | ''' 22 | 23 | SELECT_TIMEOUT = 0.25 # seconds 24 | 25 | TUNGETIFF = 0x800454D2 26 | TUNSETIFF = 0x400454CA 27 | IFF_VNET_HDR = 0x4000 28 | 29 | def __init__(self, macvtap_name=None, **kwargs): 30 | super().__init__(None, **kwargs) 31 | self._reader_thread = None 32 | self._reader_started_event = Event() 33 | self._reader_stop_requested = False 34 | self._reader_stopped_event = Event() 35 | self._macvtap_name = macvtap_name 36 | self._fp = None 37 | self._writer_thread = None 38 | self._writer_started_event = Event() 39 | self._writer_stop_flag = object() 40 | self._writer_stopped_event = Event() 41 | self._writer_queue = Queue() 42 | 43 | def short_str(self): 44 | return self._macvtap_name 45 | 46 | __str__ = short_str 47 | __repr__ = short_str 48 | 49 | def start(self, router): 50 | 51 | if not os.path.exists('/sys/class/net/'): raise FileNotFoundError("can't find /sys/class/net/") 52 | if not self._macvtap_name: 53 | if macvtaps := [i for i in os.listdir('/sys/class/net/') if i.startswith('macvtap')]: 54 | self._macvtap_name = macvtaps[0] 55 | else: 56 | raise FileNotFoundError("can't find any macvtaps") 57 | 58 | address_path = '/sys/class/net/%s/address' % self._macvtap_name 59 | if not os.path.exists(address_path): raise FileNotFoundError("can't find %s" % address_path) 60 | with open(address_path, 'r') as fp: self._hw_addr = bytes(int(i, 16) for i in fp.read().strip().split(':')) 61 | ifindex_path = '/sys/class/net/%s/ifindex' % self._macvtap_name 62 | if not os.path.exists(ifindex_path): raise FileNotFoundError("can't find %s" % ifindex_path) 63 | with open(ifindex_path, 'r') as fp: tap_device = '/dev/tap%d' % int(fp.read()) 64 | if not os.path.exists(tap_device): raise FileNotFoundError("can't find %s" % tap_device) 65 | self._fp = os.open(tap_device, os.O_RDWR) 66 | 67 | # Necessary to clear IFF_VNET_HDR or else we'd get a virtio_net_hdr struct before every frame 68 | ifreq = bytearray(40) 69 | ioctl(self._fp, self.TUNGETIFF, ifreq) 70 | ifreq[16:18] = struct.pack('H', struct.unpack('H', ifreq[16:18])[0] & ~self.IFF_VNET_HDR) 71 | ioctl(self._fp, self.TUNSETIFF, ifreq) 72 | 73 | super().start(router) 74 | self._reader_thread = Thread(target=self._reader_run) 75 | self._reader_thread.start() 76 | self._writer_thread = Thread(target=self._writer_run) 77 | self._writer_thread.start() 78 | self._reader_started_event.wait() 79 | self._writer_started_event.wait() 80 | 81 | def stop(self): 82 | self._reader_stop_requested = True 83 | self._writer_queue.put(self._writer_stop_flag) 84 | self._reader_stopped_event.wait() 85 | self._writer_stopped_event.wait() 86 | os.close(self._fp) 87 | super().stop() 88 | 89 | def send_frame(self, frame_data): 90 | self._writer_queue.put(frame_data) 91 | 92 | def _reader_run(self): 93 | self._reader_started_event.set() 94 | while not self._reader_stop_requested: 95 | rlist, _, _ = select((self._fp,), (), (), self.SELECT_TIMEOUT) 96 | if self._fp not in rlist: continue 97 | self.inbound_frame(os.read(self._fp, 65535)) 98 | self._reader_stopped_event.set() 99 | 100 | def _writer_run(self): 101 | self._writer_started_event.set() 102 | while True: 103 | frame_data = self._writer_queue.get() 104 | if frame_data is self._writer_stop_flag: break 105 | select((), (self._fp,), ()) 106 | os.write(self._fp, frame_data) 107 | self._writer_stopped_event.set() 108 | -------------------------------------------------------------------------------- /tashrouter/port/localtalk/tashtalk.py: -------------------------------------------------------------------------------- 1 | '''Port that connects to LocalTalk via TashTalk on a serial port.''' 2 | 3 | from queue import Queue, Empty 4 | from threading import Thread, Event 5 | 6 | import serial 7 | 8 | from . import LocalTalkPort, FcsCalculator 9 | from ...netlog import log_localtalk_frame_inbound, log_localtalk_frame_outbound 10 | 11 | 12 | class TashTalkPort(LocalTalkPort): 13 | '''Port that connects to LocalTalk via TashTalk on a serial port.''' 14 | 15 | SERIAL_TIMEOUT = 0.25 # seconds 16 | 17 | def __init__(self, serial_port, **kwargs): 18 | super().__init__(respond_to_enq=False, **kwargs) 19 | self._serial_port = serial_port 20 | self._serial_obj = serial.Serial(port=serial_port, baudrate=1000000, rtscts=True, timeout=None) 21 | self._reader_thread = None 22 | self._reader_started_event = Event() 23 | self._reader_stop_requested = False 24 | self._reader_stopped_event = Event() 25 | self._writer_thread = None 26 | self._writer_started_event = Event() 27 | self._writer_queue = Queue() 28 | self._writer_stop_flag = object() 29 | self._writer_stopped_event = Event() 30 | 31 | def short_str(self): 32 | return self._serial_port[5:] if self._serial_port.startswith('/dev/') else self._serial_port 33 | 34 | __str__ = short_str 35 | __repr__ = short_str 36 | 37 | def start(self, router): 38 | self._writer_queue.put(b''.join(( 39 | b'\0' * 1024, # make sure TashTalk is in a known state, first of all 40 | b'\x02' + (b'\0' * 32), # set node IDs bitmap to zeroes so we don't respond to any RTSes or ENQs yet 41 | b'\x03\0', # turn off optional TashTalk features 42 | ))) 43 | super().start(router) 44 | self._reader_thread = Thread(target=self._reader_run) 45 | self._reader_thread.start() 46 | self._writer_thread = Thread(target=self._writer_run) 47 | self._writer_thread.start() 48 | self._reader_started_event.wait() 49 | self._writer_started_event.wait() 50 | 51 | def stop(self): 52 | super().stop() 53 | self._reader_stop_requested = True 54 | self._writer_queue.put(self._writer_stop_flag) 55 | self._reader_stopped_event.wait() 56 | self._writer_stopped_event.wait() 57 | 58 | def send_frame(self, frame_data): 59 | fcs = FcsCalculator() 60 | fcs.feed(frame_data) 61 | log_localtalk_frame_outbound(frame_data, self) 62 | self._writer_queue.put(b''.join((b'\x01', frame_data, bytes((fcs.byte1(), fcs.byte2()))))) 63 | 64 | @staticmethod 65 | def _set_node_address_cmd(desired_node_address): 66 | if not 1 <= desired_node_address <= 254: raise ValueError('node address %d not between 1 and 254' % desired_node_address) 67 | retval = bytearray(33) 68 | retval[0] = 0x02 69 | byte, bit = divmod(desired_node_address, 8) 70 | retval[byte + 1] = 1 << bit 71 | return bytes(retval) 72 | 73 | def set_node_id(self, node): 74 | self._writer_queue.put(self._set_node_address_cmd(node)) 75 | super().set_node_id(node) 76 | 77 | def _reader_run(self): 78 | self._reader_started_event.set() 79 | fcs = FcsCalculator() 80 | buf = bytearray(605) 81 | buf_ptr = 0 82 | escaped = False 83 | while not self._reader_stop_requested: 84 | for byte in self._serial_obj.read(self._serial_obj.in_waiting or 1): 85 | if not escaped and byte == 0x00: 86 | escaped = True 87 | continue 88 | elif escaped: 89 | escaped = False 90 | if byte == 0xFF: # literal 0x00 byte 91 | byte = 0x00 92 | else: 93 | if byte == 0xFD and fcs.is_okay() and buf_ptr >= 5: 94 | data = bytes(buf[:buf_ptr - 2]) 95 | log_localtalk_frame_inbound(data, self) 96 | self.inbound_frame(data) 97 | fcs.reset() 98 | buf_ptr = 0 99 | continue 100 | if buf_ptr < len(buf): 101 | fcs.feed_byte(byte) 102 | buf[buf_ptr] = byte 103 | buf_ptr += 1 104 | self._reader_stopped_event.set() 105 | 106 | def _writer_run(self): 107 | self._writer_started_event.set() 108 | while True: 109 | try: 110 | item = self._writer_queue.get(block=True, timeout=self.SERIAL_TIMEOUT) 111 | except Empty: 112 | item = None 113 | #TODO make sure OS queue isn't overflowing? 114 | self._serial_obj.cancel_read() 115 | if item is self._writer_stop_flag: break 116 | if item: self._serial_obj.write(item) 117 | self._writer_stopped_event.set() 118 | -------------------------------------------------------------------------------- /tashrouter/netlog/netlogger.py: -------------------------------------------------------------------------------- 1 | '''Facilities for logging of network traffic for debug and test purposes.''' 2 | 3 | import struct 4 | 5 | 6 | def datagram_header(datagram): 7 | '''Return a string that contains a Datagram's header information.''' 8 | return '%2d %d.%-3d %d.%-3d %3d %3d %d' % (datagram.hop_count, 9 | datagram.destination_network, 10 | datagram.destination_node, 11 | datagram.source_network, 12 | datagram.source_node, 13 | datagram.destination_socket, 14 | datagram.source_socket, 15 | datagram.ddp_type) 16 | 17 | 18 | def ethernet_frame_header(frame_data): 19 | '''Return a string that contains an Ethernet frame's header information.''' 20 | if len(frame_data) < 12: return '' 21 | return ' '.join((''.join(('%02X' % i) for i in frame_data[0:6]), ''.join(('%02X' % i) for i in frame_data[6:12]))) 22 | 23 | 24 | def localtalk_frame_header(frame_data): 25 | '''Return a string that contains a LocalTalk frame's header information.''' 26 | if len(frame_data) < 3: return '' 27 | return '%3d %3d type %02X' % struct.unpack('>BBB', frame_data[0:3]) 28 | 29 | 30 | class NetLogger: 31 | '''Class for logging of network traffic for debug and test purposes.''' 32 | 33 | def __init__(self): 34 | self._logging_on = False 35 | self._log_str_func = lambda msg: None 36 | self._direction_width = 0 37 | self._port_width = 0 38 | self._header_width = 0 39 | 40 | def _log_str(self, direction_str, port_str, header_str, data): 41 | self._direction_width = max(self._direction_width, len(direction_str)) 42 | self._port_width = max(self._port_width, len(port_str)) 43 | self._header_width = max(self._header_width, len(header_str)) 44 | self._log_str_func(' '.join((direction_str.ljust(self._direction_width), 45 | port_str.ljust(self._port_width), 46 | header_str.ljust(self._header_width), 47 | str(data)))) 48 | 49 | def log_datagram_inbound(self, network, node, datagram, port): 50 | '''Log an inbound DDP Datagram.''' 51 | if not self._logging_on: return 52 | self._log_str('in to %d.%d' % (network, node), port.short_str(), datagram_header(datagram), datagram.data) 53 | 54 | def log_datagram_unicast(self, network, node, datagram, port): 55 | '''Log a unicast DDP Datagram.''' 56 | if not self._logging_on: return 57 | self._log_str('out to %d.%d' % (network, node), port.short_str(), datagram_header(datagram), datagram.data) 58 | 59 | def log_datagram_broadcast(self, datagram, port): 60 | '''Log a broadcast DDP Datagram.''' 61 | if not self._logging_on: return 62 | self._log_str('out broadcast', port.short_str(), datagram_header(datagram), datagram.data) 63 | 64 | def log_datagram_multicast(self, zone_name, datagram, port): 65 | '''Log a multicast DDP Datagram.''' 66 | if not self._logging_on: return 67 | zone_name = zone_name.decode('mac_roman', 'replace') 68 | self._log_str('out to %s' % zone_name, port.short_str(), datagram_header(datagram), datagram.data) 69 | 70 | def log_ethernet_frame_inbound(self, frame_data, port): 71 | '''Log an inbound Ethernet frame.''' 72 | if not self._logging_on: return 73 | if len(frame_data) < 14: return 74 | length = struct.unpack('>H', frame_data[12:14])[0] 75 | self._log_str('frame in', port.short_str(), ethernet_frame_header(frame_data), frame_data[14:14 + length]) 76 | 77 | def log_ethernet_frame_outbound(self, frame_data, port): 78 | '''Log an outbound Ethernet frame.''' 79 | if not self._logging_on: return 80 | if len(frame_data) < 14: return 81 | length = struct.unpack('>H', frame_data[12:14])[0] 82 | self._log_str('frame out', port.short_str(), ethernet_frame_header(frame_data), frame_data[14:14 + length]) 83 | 84 | def log_localtalk_frame_inbound(self, frame_data, port): 85 | '''Log an inbound LocalTalk frame.''' 86 | if not self._logging_on: return 87 | self._log_str('frame in', port.short_str(), localtalk_frame_header(frame_data), frame_data[3:]) 88 | 89 | def log_localtalk_frame_outbound(self, frame_data, port): 90 | '''Log an outbound LocalTalk frame.''' 91 | if not self._logging_on: return 92 | self._log_str('frame out', port.short_str(), localtalk_frame_header(frame_data), frame_data[3:]) 93 | 94 | def set_log_str_func(self, func): 95 | '''Activate network traffic logging and set the function called with logging strings (such as logging.debug).''' 96 | self._logging_on = True 97 | self._log_str_func = func 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TashRouter 2 | 3 | ## Introduction 4 | 5 | ### What is it? 6 | 7 | TashRouter is a fully standards-compliant AppleTalk router that supports LocalTalk (via [LToUDP](https://windswept.home.blog/2019/12/10/localtalk-over-udp/) and/or [TashTalk](https://github.com/lampmerchant/tashtalk)) in addition to EtherTalk. 8 | 9 | ### What can it do? 10 | 11 | TashRouter can connect multiple AppleTalk networks of different types and define zones in them. It can fully replace the functionality of EtherTalk bridge devices (such as AsantéTalk) without resorting to the kinds of standards-breaking hacks that they use. For example, you could connect an instance of [Mini vMac](https://www.gryphel.com/c/minivmac/index.html) [v37](https://68kmla.org/bb/index.php?threads/emulation-binaries-for-mini-vmac-37-with-ltoudp.46443/) (which can emulate LocalTalk over LToUDP) and a Macintosh 512k (which can connect to a LocalTalk network that TashRouter can access using [TashTalk](https://github.com/lampmerchant/tashtalk)) to a [Netatalk](https://github.com/Netatalk/netatalk) v2.x server to share files and printers. 12 | 13 | ### What do I need to run it? 14 | 15 | A single-board computer such as a Raspberry Pi makes an ideal host for TashRouter. A [TashTalk Hat](https://ko-fi.com/s/60b561a0e3) will allow a device with a Raspberry Pi-compatible GPIO header to connect to a LocalTalk network. 16 | 17 | However, a single-board computer is not required - any computer that can run [Python](https://www.python.org/) v3.x can run TashRouter. For example, a server running [Void Linux](https://voidlinux.org/) can route between an EtherTalk network and a LocalTalk network running LToUDP, while an [AirTalk](https://airtalk.shop/product/airtalk-complete/) wirelessly bridges the LToUDP network to a physical LocalTalk network. TashRouter will also run on Windows, but since it currently has no EtherTalk port drivers that support Windows, it is limited to routing between LocalTalk networks via LToUDP and TashTalk. 18 | 19 | ### Where can I get support? 20 | 21 | There is a thread on the [68kMLA forum](https://68kmla.org/bb/index.php?threads/tashrouter-an-appletalk-router.46047/) frequented by the author and other knowledgeable vintage Mac enthusiasts. 22 | 23 | ## Status 24 | 25 | Fully usable, code-complete, and ready for some real-world experience. Codebase is not yet mature, however - undetected bugs may exist. 26 | 27 | ## Quick Start - macvtap 28 | 29 | ### Creating a macvtap device 30 | 31 | A macvtap device is necessary to support EtherTalk. Not all kernels may have support for this built in; [Void Linux](https://voidlinux.org/) for Raspberry Pi is known to have support for macvtap out of the box. Use the following shell commands (as root) to set up a macvtap device for use with TashRouter: 32 | 33 | ``` 34 | # ip link add link eth0 name macvtap0 type macvtap 35 | # ip link set dev macvtap0 promisc on 36 | # ip link set dev macvtap0 up 37 | ``` 38 | 39 | This process can be automated, though the method of doing so depends on your operating system. In Void Linux, for example, the above commands can be added to `rc.local`. 40 | 41 | ### Running TashRouter 42 | 43 | Download and unzip the Python v3.x source code for TashRouter. 44 | 45 | Put the following into a file called `test_router.py` at the same level as the `tashrouter` directory, optionally customizing parameters such as the serial port for TashTalk, network numbers, and zone names: 46 | 47 | ```python 48 | import logging 49 | import time 50 | import signal 51 | import sys 52 | 53 | from tashrouter.netlog import set_log_str_func 54 | from tashrouter.port.ethertalk.macvtap import MacvtapPort 55 | from tashrouter.port.localtalk.ltoudp import LtoudpPort 56 | from tashrouter.port.localtalk.tashtalk import TashTalkPort 57 | from tashrouter.router.router import Router 58 | 59 | 60 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s') 61 | set_log_str_func(logging.debug) # comment this line for speed and reduced spam 62 | 63 | router = Router('router', ports=( 64 | LtoudpPort(seed_network=1, seed_zone_name=b'LToUDP Network'), 65 | TashTalkPort(serial_port='/dev/ttyAMA0', seed_network=2, seed_zone_name=b'TashTalk Network'), 66 | MacvtapPort(macvtap_name='macvtap0', seed_network_min=3, seed_network_max=5, seed_zone_names=[b'EtherTalk Network']), 67 | )) 68 | 69 | print('router away!') 70 | router.start() 71 | signal.signal(signal.SIGTERM, lambda _signo, _stack_frame: sys.exit(0)) # raises SystemExit on SIGTERM 72 | 73 | try: 74 | while True: time.sleep(1) 75 | except (KeyboardInterrupt, SystemExit): 76 | router.stop() 77 | ``` 78 | 79 | Run the script you just created: `python3 test_router.py` 80 | 81 | ## Using TashRouter with a tap and Netatalk 2.x 82 | 83 | See [this post](https://68kmla.org/bb/index.php?threads/tashrouter-an-appletalk-router.46047/post-518796) on the 68kMLA forum. 84 | -------------------------------------------------------------------------------- /tashrouter/service/rtmp/responding.py: -------------------------------------------------------------------------------- 1 | '''RTMP responding Service.''' 2 | 3 | from collections import deque 4 | from queue import Queue 5 | import struct 6 | from threading import Thread, Event 7 | 8 | from . import RtmpService 9 | from .. import Service 10 | from ...router.routing_table import RoutingTableEntry 11 | 12 | 13 | class RtmpRespondingService(Service, RtmpService): 14 | '''A Service which responds to inbound RTMP Datagrams and maintains the Router's RoutingTable.''' 15 | 16 | def __init__(self): 17 | self.thread = None 18 | self.started_event = Event() 19 | self.queue = Queue() 20 | self.stop_flag = object() 21 | 22 | def start(self, router): 23 | self.thread = Thread(target=self._run, args=(router,)) 24 | self.thread.start() 25 | self.started_event.wait() 26 | 27 | def stop(self): 28 | self.queue.put(self.stop_flag) 29 | self.queue.join() 30 | 31 | def _run(self, router): 32 | 33 | while True: 34 | 35 | if self.started_event.is_set(): 36 | self.queue.task_done() 37 | else: 38 | self.started_event.set() 39 | 40 | item = self.queue.get() 41 | if item is self.stop_flag: break 42 | datagram, rx_port = item 43 | 44 | if datagram.ddp_type == self.RTMP_DDP_TYPE_DATA: 45 | 46 | # process header 47 | if len(datagram.data) < 4: continue # invalid, datagram too short 48 | sender_network, id_length, sender_node = struct.unpack('>HBB', datagram.data[0:4]) 49 | if id_length != 8: continue # invalid, AppleTalk node numbers are only 8 bits in length 50 | data = datagram.data[4:] 51 | if rx_port.extended_network: 52 | if len(data) < 6: continue # invalid, datagram too short to contain at least one extended network tuple 53 | sender_network_min, range_distance, sender_network_max, rtmp_version = struct.unpack('>HBHB', data[0:6]) 54 | if range_distance != 0x80: continue # invalid, first tuple must be the sender's extended network tuple 55 | else: 56 | if len(data) < 3: continue 57 | sender_network_min = sender_network_max = sender_network 58 | zero, rtmp_version = struct.unpack('>HB', data[0:3]) 59 | if zero != 0: continue # invalid, this word must be zero on a nonextended network 60 | data = data[3:] 61 | if rtmp_version != self.RTMP_VERSION: continue # invalid, don't recognize this RTMP format 62 | 63 | # interpret tuples 64 | tuples = deque() 65 | data_idx = 0 66 | while True: 67 | packed = data[data_idx:data_idx + 3] 68 | if len(packed) != 3: break 69 | network_min, range_distance = struct.unpack('>HB', packed) 70 | if range_distance & 0x80: 71 | extended_network = True 72 | packed = data[data_idx + 3:data_idx + 6] 73 | if len(packed) != 3: break 74 | network_max, _ = struct.unpack('>HB', packed) 75 | data_idx += 6 76 | else: 77 | extended_network = False 78 | network_max = network_min 79 | data_idx += 3 80 | tuples.append((extended_network, network_min, network_max, range_distance & 0x1F)) 81 | if data_idx != len(data): continue # invalid, tuples did not end where expected 82 | 83 | # if this Port doesn't know its network range yet, accept that this is from the network's seed router 84 | if rx_port.network_min == rx_port.network_max == 0: rx_port.set_network_range(sender_network_min, sender_network_max) 85 | 86 | # resolve the given tuples with the current RoutingTable 87 | for extended_network, network_min, network_max, distance in tuples: 88 | # if the entry is too many hops away or is a notify-neighbor entry, mark any entry we have as bad 89 | if distance >= 15: 90 | router.routing_table.mark_bad(network_min, network_max) 91 | # otherwise have the table consider a new entry based on this tuple 92 | else: 93 | router.routing_table.consider(RoutingTableEntry(extended_network=extended_network, 94 | network_min=network_min, 95 | network_max=network_max, 96 | distance=distance + 1, 97 | port=rx_port, 98 | next_network=sender_network, 99 | next_node=sender_node)) 100 | 101 | elif datagram.ddp_type != self.RTMP_DDP_TYPE_REQUEST or not datagram.data: 102 | 103 | continue 104 | 105 | elif datagram.data[0] == self.RTMP_FUNC_REQUEST: 106 | 107 | if 0 in (rx_port.network_min, rx_port.network_max): continue 108 | if datagram.hop_count != 0: continue # we have to send responses out of the same port they came in, no routing 109 | response_data = struct.pack('>HBB', rx_port.network, 8, rx_port.node) 110 | if rx_port.extended_network: 111 | response_data += struct.pack('>HBHB', rx_port.network_min, 0x80, rx_port.network_max, self.RTMP_VERSION) 112 | router.reply(datagram, rx_port, self.RTMP_DDP_TYPE_DATA, response_data) 113 | 114 | elif datagram.data[0] in (self.RTMP_FUNC_RDR_SPLIT_HORIZON, self.RTMP_FUNC_RDR_NO_SPLIT_HORIZON): 115 | 116 | split_horizon = True if datagram.data[0] == self.RTMP_FUNC_RDR_SPLIT_HORIZON else False 117 | for datagram_data in self.make_routing_table_datagram_data(router, rx_port, split_horizon): 118 | router.reply(datagram, rx_port, self.RTMP_DDP_TYPE_DATA, datagram_data) 119 | 120 | self.queue.task_done() 121 | 122 | def inbound(self, datagram, rx_port): 123 | self.queue.put((datagram, rx_port)) 124 | -------------------------------------------------------------------------------- /tashrouter/router/zone_information_table.py: -------------------------------------------------------------------------------- 1 | '''Zone Information Table (ZIT) class and associated things.''' 2 | 3 | from collections import deque 4 | import logging 5 | from threading import Lock 6 | 7 | 8 | ATALK_LCASE = b'abcdefghijklmnopqrstuvwxyz\x88\x8A\x8B\x8C\x8D\x8E\x96\x9A\x9B\x9F\xBE\xBF\xCF' 9 | ATALK_UCASE = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ\xCB\x80\xCC\x81\x82\x83\x84\x85\xCD\x86\xAE\xAF\xCE' 10 | 11 | 12 | def ucase_char(byte): 13 | '''Convert a single byte to its uppercase representation using the correspondence table laid out in IA Appendix D.''' 14 | try: 15 | return ATALK_UCASE[ATALK_LCASE.index(byte)] 16 | except ValueError: 17 | return byte 18 | 19 | 20 | def ucase(b): 21 | '''Convert a bytes-like to uppercase using the correspondence table laid out in IA Appendix D.''' 22 | return bytes(ucase_char(byte) for byte in b) 23 | 24 | 25 | class ZoneInformationTable: 26 | '''Zone Information Table (ZIT).''' 27 | 28 | def __init__(self, router): 29 | self._router = router 30 | self._network_min_to_network_max = {} 31 | self._network_min_to_zone_name_set = {} 32 | self._network_min_to_default_zone_name = {} 33 | self._zone_name_to_network_min_set = {} 34 | self._ucased_zone_name_to_zone_name = {} 35 | self._lock = Lock() 36 | 37 | def _check_range(self, network_min, network_max=None): 38 | looked_up_network_max = self._network_min_to_network_max.get(network_min) 39 | if network_max is None: 40 | if looked_up_network_max is None: 41 | raise ValueError('network range %d-? does not exist' % network_min) 42 | else: 43 | return looked_up_network_max 44 | elif looked_up_network_max == network_max: # if network range exists as given 45 | return network_max 46 | elif looked_up_network_max is not None: 47 | raise ValueError('network range %d-%d overlaps %d-%d' % (network_min, network_max, network_min, looked_up_network_max)) 48 | else: # check for overlap 49 | for existing_min, existing_max in self._network_min_to_network_max.items(): 50 | if existing_min > network_max or existing_max < network_min: continue 51 | raise ValueError('network range %d-%d overlaps %d-%d' % (network_min, network_max, existing_min, existing_max)) 52 | return None 53 | 54 | def add_networks_to_zone(self, zone_name, network_min, network_max=None): 55 | '''Add a range of networks to a zone, adding the zone if it isn't in the table.''' 56 | 57 | if network_max and network_max < network_min: raise ValueError('range %d-%d is backwards' % (network_min, network_max)) 58 | ucased_zone_name = ucase(zone_name) 59 | 60 | with self._lock: 61 | 62 | if ucased_zone_name in self._ucased_zone_name_to_zone_name: 63 | zone_name = self._ucased_zone_name_to_zone_name[ucased_zone_name] 64 | else: 65 | self._ucased_zone_name_to_zone_name[ucased_zone_name] = zone_name 66 | self._zone_name_to_network_min_set[zone_name] = set() 67 | 68 | check_range = self._check_range(network_min, network_max) 69 | if check_range: 70 | network_max = check_range 71 | self._network_min_to_zone_name_set[network_min].add(zone_name) 72 | now_default = False 73 | else: 74 | self._network_min_to_network_max[network_min] = network_max 75 | self._network_min_to_zone_name_set[network_min] = set((zone_name,)) 76 | self._network_min_to_default_zone_name[network_min] = zone_name 77 | now_default = True 78 | 79 | logging.debug('%s adding network range %d-%d to zone %s%s', str(self._router), network_min, network_max, 80 | zone_name.decode('mac_roman', 'replace'), ' (now default zone for this range)' if now_default else '') 81 | self._zone_name_to_network_min_set[zone_name].add(network_min) 82 | 83 | def remove_networks(self, network_min, network_max=None): 84 | '''Remove a range of networks from all zones, removing associated zones if now empty of networks.''' 85 | if network_max and network_max < network_min: raise ValueError('range %d-%d is backwards' % (network_min, network_max)) 86 | with self._lock: 87 | network_max = self._check_range(network_min, network_max) 88 | if not network_max: return 89 | logging.debug('%s removing network range %d-%d from all zones', str(self._router), network_min, network_max) 90 | for zone_name in self._network_min_to_zone_name_set[network_min]: 91 | s = self._zone_name_to_network_min_set[zone_name] 92 | s.remove(network_min) 93 | if not s: 94 | logging.debug('%s removing zone %s because it no longer contains any networks', str(self._router), 95 | zone_name.decode('mac_roman', 'replace')) 96 | self._zone_name_to_network_min_set.pop(zone_name) 97 | self._ucased_zone_name_to_zone_name.pop(ucase(zone_name)) 98 | self._network_min_to_default_zone_name.pop(network_min) 99 | self._network_min_to_zone_name_set.pop(network_min) 100 | self._network_min_to_network_max.pop(network_min) 101 | 102 | def zones(self): 103 | '''Return the zones in this ZIT.''' 104 | with self._lock: 105 | return list(self._zone_name_to_network_min_set.keys()) 106 | 107 | def zones_in_network_range(self, network_min, network_max=None): 108 | '''Return a deque containing the names of all zones in the given range of networks, default zone name first.''' 109 | if network_max and network_max < network_min: raise ValueError('range %d-%d is backwards' % (network_min, network_max)) 110 | with self._lock: 111 | if not self._check_range(network_min, network_max): return deque() 112 | default_zone_name = self._network_min_to_default_zone_name[network_min] 113 | retval = deque(zone_name for zone_name in self._network_min_to_zone_name_set[network_min] if zone_name != default_zone_name) 114 | retval.appendleft(default_zone_name) 115 | return retval 116 | 117 | def networks_in_zone(self, zone_name): 118 | '''Return a deque containing the network numbers of all networks in the given zone.''' 119 | with self._lock: 120 | zone_name = self._ucased_zone_name_to_zone_name.get(ucase(zone_name)) 121 | if zone_name is None: return deque() 122 | retval = deque() 123 | for network_min in self._zone_name_to_network_min_set[zone_name]: 124 | retval.extend(range(network_min, self._network_min_to_network_max[network_min] + 1)) 125 | return retval 126 | -------------------------------------------------------------------------------- /tashrouter/datagram.py: -------------------------------------------------------------------------------- 1 | '''Datagram class.''' 2 | 3 | import dataclasses 4 | import struct 5 | 6 | 7 | def ddp_checksum(data): 8 | '''Calculate the checksum used in DDP header as well as in determining multicast addresses.''' 9 | retval = 0 10 | for byte in data: 11 | retval += byte 12 | retval = (retval & 0x7FFF) << 1 | (1 if retval & 0x8000 else 0) 13 | return retval or 0xFFFF # because a zero value in the checksum field means one was not calculated 14 | 15 | 16 | @dataclasses.dataclass 17 | class Datagram: 18 | '''DDP datagram.''' 19 | 20 | MAX_DATA_LENGTH = 586 21 | 22 | hop_count: int 23 | destination_network: int 24 | source_network: int 25 | destination_node: int 26 | source_node: int 27 | destination_socket: int 28 | source_socket: int 29 | ddp_type: int 30 | data: bytes 31 | 32 | @classmethod 33 | def from_long_header_bytes(cls, data, verify_checksum=True): 34 | '''Construct a Datagram object from bytes in the long-header format and raise ValueErrors if there are issues.''' 35 | if len(data) < 13: raise ValueError('data too short, must be at least 13 bytes for long-header DDP datagram') 36 | (first, second, checksum, destination_network, source_network, destination_node, source_node, destination_socket, source_socket, 37 | ddp_type) = struct.unpack('>BBHHHBBBBB', data[:13]) 38 | if first & 0xC0: raise ValueError('invalid long DDP header, top two bits of first byte must be zeroes') 39 | hop_count = (first & 0x3C) >> 2 40 | length = (first & 0x3) << 8 | second 41 | if length > 13 + cls.MAX_DATA_LENGTH: 42 | raise ValueError('invalid long DDP header, length %d is greater than %d' % (length, cls.MAX_DATA_LENGTH)) 43 | if length != len(data): 44 | raise ValueError('invalid long DDP header, length field says %d but actual length is %d' % (length, len(data))) 45 | if checksum != 0 and verify_checksum: 46 | calc_checksum = ddp_checksum(data[4:]) 47 | if calc_checksum != checksum: 48 | raise ValueError('invalid long DDP header, checksum is 0x%04X but should be 0x%04X' % (checksum, calc_checksum)) 49 | return cls(hop_count=hop_count, 50 | destination_network=destination_network, 51 | source_network=source_network, 52 | destination_node=destination_node, 53 | source_node=source_node, 54 | destination_socket=destination_socket, 55 | source_socket=source_socket, 56 | ddp_type=ddp_type, 57 | data=data[13:]) 58 | 59 | @classmethod 60 | def from_short_header_bytes(cls, destination_node, source_node, data): 61 | '''Construct a Datagram object from bytes in the short-header format and raise ValueErrors if there are issues.''' 62 | if len(data) < 5: raise ValueError('data too short, must be at least 5 bytes for short-header DDP datagram') 63 | first, second, destination_socket, source_socket, ddp_type = struct.unpack('>BBBBB', data[0:5]) 64 | if first & 0xFC: raise ValueError('invalid short DDP header, top six bits of first byte must be zeroes') 65 | length = (first & 0x3) << 8 | second 66 | if length > 5 + cls.MAX_DATA_LENGTH: 67 | raise ValueError('invalid short DDP header, length %d is greater than %d' % (length, cls.MAX_DATA_LENGTH)) 68 | if length != len(data): 69 | raise ValueError('invalid short DDP header, length field says %d but actual length is %d' % (length, len(data))) 70 | return cls(hop_count=0, 71 | destination_network=0, 72 | source_network=0, 73 | destination_node=destination_node, 74 | source_node=source_node, 75 | destination_socket=destination_socket, 76 | source_socket=source_socket, 77 | ddp_type=ddp_type, 78 | data=data[5:]) 79 | 80 | def _check_ranges(self): 81 | '''Check that the Datagram's parameters are in range, raise ValueError if not.''' 82 | for name, min_value, max_value in (('hop count', 0, 15), 83 | ('destination network', 0, 65534), 84 | ('source network', 0, 65534), 85 | ('destination node', 0, 255), 86 | ('source node', 1, 254), 87 | ('destination socket', 0, 255), 88 | ('source socket', 0, 255), 89 | ('DDP type', 0, 255)): 90 | value = getattr(self, name.lower().replace(' ', '_')) 91 | if not min_value <= value <= max_value: 92 | raise ValueError('invalid %s %d, must be in range %d-%d' % (name, value, min_value, max_value)) 93 | 94 | def as_long_header_bytes(self, calculate_checksum=True): 95 | '''Return this Datagram in long-header format as bytes and raise ValueErrors if there are issues.''' 96 | self._check_ranges() 97 | if len(self.data) > self.MAX_DATA_LENGTH: 98 | raise ValueError('data length %d is greater than max length %d' % (len(self.data), self.MAX_DATA_LENGTH)) 99 | header = struct.pack('>HHBBBBB', 100 | self.destination_network, 101 | self.source_network, 102 | self.destination_node, 103 | self.source_node, 104 | self.destination_socket, 105 | self.source_socket, 106 | self.ddp_type) 107 | data = header + self.data 108 | length = 4 + len(data) 109 | header = struct.pack('>BBH', 110 | (self.hop_count & 0xF) << 2 | (length & 0x300) >> 8, 111 | length & 0xFF, 112 | ddp_checksum(data) if calculate_checksum else 0x0000) 113 | return header + data 114 | 115 | def as_short_header_bytes(self): 116 | '''Return this Datagram in short-header format as bytes and raise ValueErrors if there are issues.''' 117 | if self.hop_count > 0: 118 | raise ValueError('invalid hop count %d, short-header datagrams may not have non-zero hop count' % self.hop_count) 119 | self._check_ranges() 120 | if len(self.data) > self.MAX_DATA_LENGTH: 121 | raise ValueError('data length %d is greater than max length %d' % (len(self.data), self.MAX_DATA_LENGTH)) 122 | length = 5 + len(self.data) 123 | header = struct.pack('>BBBBB', 124 | (length & 0x300) >> 8, 125 | length & 0xFF, 126 | self.destination_socket, 127 | self.source_socket, 128 | self.ddp_type) 129 | return header + self.data 130 | 131 | def copy(self, **kwargs): 132 | '''Return a copy of this Datagram, replacing params specified by kwargs, if any.''' 133 | return dataclasses.replace(self, **kwargs) 134 | 135 | def hop(self): 136 | '''Return a copy of this Datagram with the hop count incremented by one.''' 137 | return self.copy(hop_count=self.hop_count + 1) 138 | -------------------------------------------------------------------------------- /tashrouter/router/routing_table.py: -------------------------------------------------------------------------------- 1 | '''Table of routing information.''' 2 | 3 | import dataclasses 4 | from collections import deque 5 | import logging 6 | from threading import Lock 7 | 8 | from ..port import Port 9 | 10 | 11 | @dataclasses.dataclass(frozen=True) 12 | class RoutingTableEntry: 13 | '''An entry in a routing table for a single network, used to route Datagrams to Ports.''' 14 | 15 | extended_network: bool 16 | network_min: int 17 | network_max: int 18 | distance: int 19 | port: Port 20 | next_network: int 21 | next_node: int 22 | 23 | 24 | class RoutingTable: 25 | '''A Router's routing table.''' 26 | 27 | STATE_GOOD = 1 28 | STATE_SUS = 2 29 | STATE_BAD = 3 30 | STATE_WORST = 4 31 | 32 | def __init__(self, router): 33 | self._router = router 34 | self._entry_by_network = {} 35 | self._state_by_entry = {} 36 | self._lock = Lock() 37 | 38 | def __contains__(self, entry): 39 | with self._lock: 40 | return True if entry in self._state_by_entry else False 41 | 42 | def __iter__(self): 43 | with self._lock: 44 | retval = deque(self._state_by_entry.keys()) 45 | yield from retval 46 | 47 | def get_by_network(self, network): 48 | '''Look up and return an entry in this RoutingTable by network number. Returns (entry, is_bad).''' 49 | with self._lock: 50 | entry = self._entry_by_network.get(network) 51 | if entry is None: return None, None 52 | return entry, True if self._state_by_entry[entry] in (self.STATE_BAD, self.STATE_WORST) else False 53 | 54 | def mark_bad(self, network_min, network_max): 55 | '''If this RoutingTable has an entry with the given network range, mark it bad. Return True if it existed, else False.''' 56 | with self._lock: 57 | cur_entries = set(self._entry_by_network.get(network) for network in range(network_min, network_max + 1)) 58 | if len(cur_entries) != 1: return False 59 | cur_entry = cur_entries.pop() # this is either None or an entry with a coincident range to the new one 60 | if not cur_entry: return False 61 | if self._state_by_entry[cur_entry] != self.STATE_WORST: self._state_by_entry[cur_entry] = self.STATE_BAD 62 | return True 63 | 64 | def consider(self, entry): 65 | '''Consider a new entry for addition to the table. Return True if added, False if not.''' 66 | 67 | with self._lock: 68 | if entry in self._state_by_entry: 69 | self._state_by_entry[entry] = self.STATE_GOOD 70 | return True 71 | cur_entries = set(self._entry_by_network.get(network) for network in range(entry.network_min, entry.network_max + 1)) 72 | if len(cur_entries) != 1: return False # this network range overlaps one that's already defined, can't do anything with it 73 | cur_entry = cur_entries.pop() 74 | 75 | # range currently undefined, add new entry to the table 76 | if cur_entry is None: 77 | pass 78 | # range fully defined by an entry that is either bad or further away, add new entry to the table 79 | elif cur_entry.distance >= entry.distance or self._state_by_entry[cur_entry] in (self.STATE_BAD, self.STATE_WORST): 80 | pass 81 | # range fully defined by an entry representing a route that is now further than we thought, add new entry to the table 82 | elif (cur_entry.next_network, cur_entry.next_node, cur_entry.port) == (entry.next_network, entry.next_node, entry.port): 83 | pass 84 | # range fully defined by a good entry that is closer than the new one, ignore new entry 85 | else: 86 | return False 87 | 88 | if cur_entry: self._state_by_entry.pop(cur_entry) 89 | self._state_by_entry[entry] = self.STATE_GOOD 90 | for network in range(entry.network_min, entry.network_max + 1): self._entry_by_network[network] = entry 91 | logging.debug('%s adding: %s', str(self._router), str(entry)) 92 | return True 93 | 94 | def age(self): 95 | '''Age the RoutingTableEntries in this RoutingTable.''' 96 | entries_to_delete = set() 97 | networks_to_delete = deque() 98 | with self._lock: 99 | for entry in set(self._entry_by_network.values()): 100 | if self._state_by_entry[entry] == self.STATE_WORST: 101 | logging.debug('%s aging out: %s', str(self._router), str(entry)) 102 | entries_to_delete.add(entry) 103 | self._state_by_entry.pop(entry) 104 | try: 105 | self._router.zone_information_table.remove_networks(entry.network_min, entry.network_max) 106 | except ValueError as e: 107 | logging.warning("%s couldn't remove networks from zone information table: %s", str(self._router), e.args[0]) 108 | elif self._state_by_entry[entry] == self.STATE_BAD: 109 | self._state_by_entry[entry] = self.STATE_WORST 110 | elif self._state_by_entry[entry] == self.STATE_SUS: 111 | self._state_by_entry[entry] = self.STATE_BAD 112 | elif self._state_by_entry[entry] == self.STATE_GOOD and entry.distance != 0: 113 | self._state_by_entry[entry] = self.STATE_SUS 114 | for network, entry in self._entry_by_network.items(): 115 | if entry in entries_to_delete: networks_to_delete.append(network) 116 | for network in networks_to_delete: self._entry_by_network.pop(network) 117 | 118 | def entries(self): 119 | '''Yield entries from this RoutingTable along with their badness state.''' 120 | with self._lock: retval = deque(self._state_by_entry.items()) 121 | for entry, state in retval: yield entry, True if state in (self.STATE_BAD, self.STATE_WORST) else False 122 | 123 | def set_port_range(self, port, network_min, network_max): 124 | '''Set the network range for a given port, unsetting any previous entries in the table that defined it.''' 125 | entries_to_delete = set() 126 | networks_to_delete = deque() 127 | with self._lock: 128 | for network, entry in self._entry_by_network.items(): 129 | if entry.port is port and entry.distance == 0: 130 | entries_to_delete.add(entry) 131 | networks_to_delete.append(network) 132 | for entry in entries_to_delete: 133 | logging.debug('%s deleting: %s', str(self._router), str(entry)) 134 | self._state_by_entry.pop(entry) 135 | try: 136 | self._router.zone_information_table.remove_networks(entry.network_min, entry.network_max) 137 | except ValueError as e: 138 | logging.warning("%s couldn't remove networks from zone information table: %s", str(self._router), e.args[0]) 139 | for network in networks_to_delete: self._entry_by_network.pop(network) 140 | entry = RoutingTableEntry(extended_network=port.extended_network, 141 | network_min=network_min, 142 | network_max=network_max, 143 | distance=0, 144 | port=port, 145 | next_network=0, 146 | next_node=0) 147 | logging.debug('%s adding: %s', str(self._router), str(entry)) 148 | for network in range(network_min, network_max + 1): self._entry_by_network[network] = entry 149 | self._state_by_entry[entry] = self.STATE_GOOD 150 | -------------------------------------------------------------------------------- /tashrouter/service/name_information.py: -------------------------------------------------------------------------------- 1 | '''Name Information Service.''' 2 | 3 | from queue import Queue 4 | import struct 5 | from threading import Thread, Event 6 | 7 | from . import Service 8 | from ..datagram import Datagram 9 | 10 | 11 | class NameInformationService(Service): 12 | '''A Service that implements Name Binding Protocol (NBP).''' 13 | 14 | NBP_SAS = 2 15 | NBP_DDP_TYPE = 2 16 | 17 | NBP_CTRL_BRRQ = 1 18 | NBP_CTRL_LKUP = 2 19 | NBP_CTRL_LKUP_REPLY = 3 20 | NBP_CTRL_FWDREQ = 4 21 | 22 | MAX_FIELD_LEN = 32 23 | 24 | def __init__(self): 25 | self.thread = None 26 | self.queue = Queue() 27 | self.stop_flag = object() 28 | self.started_event = Event() 29 | self.stopped_event = Event() 30 | 31 | def start(self, router): 32 | self.thread = Thread(target=self._run, args=(router,)) 33 | self.thread.start() 34 | self.started_event.wait() 35 | 36 | def stop(self): 37 | self.queue.put(self.stop_flag) 38 | self.stopped_event.wait() 39 | 40 | def _run(self, router): 41 | 42 | self.started_event.set() 43 | 44 | while True: 45 | 46 | item = self.queue.get() 47 | if item is self.stop_flag: break 48 | datagram, rx_port = item 49 | 50 | if datagram.ddp_type != self.NBP_DDP_TYPE: continue 51 | if len(datagram.data) < 12: continue 52 | func_tuple_count, nbp_id, req_network, req_node, req_socket, _, object_field = struct.unpack('>BBHBBBB', datagram.data[:8]) 53 | func = func_tuple_count >> 4 54 | tuple_count = func_tuple_count & 0xF 55 | if tuple_count != 1 or func not in (self.NBP_CTRL_BRRQ, self.NBP_CTRL_FWDREQ): continue 56 | if object_field < 1 or object_field > self.MAX_FIELD_LEN: continue 57 | if len(datagram.data) < 8 + object_field: continue 58 | type_field = datagram.data[8 + object_field] 59 | if type_field < 1 or type_field > self.MAX_FIELD_LEN: continue 60 | if len(datagram.data) < 9 + object_field + type_field: continue 61 | zone_field = datagram.data[9 + object_field + type_field] 62 | if zone_field > self.MAX_FIELD_LEN: continue 63 | if len(datagram.data) < 10 + object_field + type_field + zone_field: continue 64 | zone_field = datagram.data[10 + object_field + type_field:10 + object_field + type_field + zone_field] or b'*' 65 | type_field = datagram.data[9 + object_field:9 + object_field + type_field] 66 | object_field = datagram.data[8:8 + object_field] 67 | 68 | common_data = b''.join((struct.pack('>BHBBBB', nbp_id, req_network, req_node, req_socket, 0, len(object_field)), 69 | object_field, 70 | struct.pack('>B', len(type_field)), 71 | type_field, 72 | struct.pack('>B', len(zone_field)), 73 | zone_field)) 74 | lkup_data = struct.pack('>B', (self.NBP_CTRL_LKUP << 4) | 1) + common_data 75 | fwdreq_data = struct.pack('>B', (self.NBP_CTRL_FWDREQ << 4) | 1) + common_data 76 | 77 | if func == self.NBP_CTRL_BRRQ: 78 | 79 | # if zone is *, try to sub in the zone name associated with the nonextended network whence the BrRq comes 80 | if zone_field == b'*': 81 | if rx_port.extended_network: continue # BrRqs from extended networks must provide zone name 82 | if rx_port.network: 83 | entry, _ = router.routing_table.get_by_network(rx_port.network) 84 | if entry: 85 | try: 86 | zones = router.zone_information_table.zones_in_network_range(entry.network_min) 87 | except ValueError: 88 | pass 89 | else: 90 | if len(zones) == 1: zone_field = zones[0] # there should not be more than one zone 91 | 92 | # if zone is still *, just broadcast a LkUp on the requesting network and call it done 93 | if zone_field == b'*': 94 | rx_port.broadcast(Datagram(hop_count=0, 95 | destination_network=0x0000, 96 | source_network=rx_port.network, 97 | destination_node=0xFF, 98 | source_node=rx_port.node, 99 | destination_socket=self.NBP_SAS, 100 | source_socket=self.NBP_SAS, 101 | ddp_type=self.NBP_DDP_TYPE, 102 | data=lkup_data)) 103 | # we know the zone, so multicast LkUps to directly-connected networks and send FwdReqs to non-directly-connected ones 104 | else: 105 | entries = set(router.routing_table.get_by_network(network) 106 | for network in router.zone_information_table.networks_in_zone(zone_field)) 107 | entries.discard((None, None)) 108 | for entry, _ in entries: 109 | if entry.distance == 0: 110 | entry.port.multicast(zone_field, Datagram(hop_count=0, 111 | destination_network=0x0000, 112 | source_network=entry.port.network, 113 | destination_node=0xFF, 114 | source_node=entry.port.node, 115 | destination_socket=self.NBP_SAS, 116 | source_socket=self.NBP_SAS, 117 | ddp_type=self.NBP_DDP_TYPE, 118 | data=lkup_data)) 119 | else: 120 | router.route(Datagram(hop_count=0, 121 | destination_network=entry.network_min, 122 | source_network=0, 123 | destination_node=0x00, 124 | source_node=0, 125 | destination_socket=self.NBP_SAS, 126 | source_socket=self.NBP_SAS, 127 | ddp_type=self.NBP_DDP_TYPE, 128 | data=fwdreq_data)) 129 | 130 | elif func == self.NBP_CTRL_FWDREQ: 131 | 132 | entry, _ = router.routing_table.get_by_network(datagram.destination_network) 133 | if entry is None or entry.distance != 0: continue # FwdReq thinks we're directly connected to this network but we're not 134 | entry.port.multicast(zone_field, Datagram(hop_count=0, 135 | destination_network=0x0000, 136 | source_network=entry.port.network, 137 | destination_node=0xFF, 138 | source_node=entry.port.node, 139 | destination_socket=self.NBP_SAS, 140 | source_socket=self.NBP_SAS, 141 | ddp_type=self.NBP_DDP_TYPE, 142 | data=lkup_data)) 143 | 144 | self.stopped_event.set() 145 | 146 | def inbound(self, datagram, rx_port): 147 | self.queue.put((datagram, rx_port)) 148 | -------------------------------------------------------------------------------- /tashrouter/router/router.py: -------------------------------------------------------------------------------- 1 | '''The heart of this whole affair.''' 2 | 3 | import logging 4 | 5 | from .routing_table import RoutingTable 6 | from .zone_information_table import ZoneInformationTable 7 | from ..datagram import Datagram 8 | from ..service.echo import EchoService 9 | from ..service.name_information import NameInformationService 10 | from ..service.routing_table_aging import RoutingTableAgingService 11 | from ..service.rtmp.responding import RtmpRespondingService 12 | from ..service.rtmp.sending import RtmpSendingService 13 | from ..service.zip.responding import ZipRespondingService 14 | from ..service.zip.sending import ZipSendingService 15 | 16 | 17 | class Router: 18 | '''A router, a device which sends Datagrams to Ports and runs Services.''' 19 | 20 | def __init__(self, short_str, ports): 21 | self._short_str = short_str 22 | self.ports = ports 23 | self._services = ( 24 | (EchoService.ECHO_SAS, EchoService()), 25 | (NameInformationService.NBP_SAS, NameInformationService()), 26 | (None, RoutingTableAgingService()), 27 | (RtmpRespondingService.RTMP_SAS, RtmpRespondingService()), 28 | (None, RtmpSendingService()), 29 | (ZipRespondingService.ZIP_SAS, ZipRespondingService()), 30 | (None, ZipSendingService()), 31 | ) 32 | self.zone_information_table = ZoneInformationTable(self) 33 | self._services_by_sas = {} 34 | for sas, service in self._services: 35 | if sas is not None: self._services_by_sas[sas] = service 36 | self.routing_table = RoutingTable(self) 37 | 38 | def short_str(self): 39 | '''Return a short string representation of this Router.''' 40 | return self._short_str 41 | 42 | __str__ = short_str 43 | __repr__ = short_str 44 | 45 | def _deliver(self, datagram, rx_port): 46 | '''Deliver a datagram locally to the "control plane" of the router.''' 47 | if service := self._services_by_sas.get(datagram.destination_socket): service.inbound(datagram, rx_port) 48 | 49 | def start(self): 50 | '''Start this router.''' 51 | # Ports are responsible for adding their seed entries to routing_table 52 | for port in self.ports: 53 | logging.info('starting %s...', str(port.__class__.__name__)) 54 | port.start(self) 55 | logging.info('all ports started!') 56 | for _, service in self._services: 57 | logging.info('starting %s...', str(service.__class__.__name__)) 58 | service.start(self) 59 | logging.info('all services started!') 60 | 61 | def stop(self): 62 | '''Stop this router.''' 63 | for _, service in self._services: 64 | logging.info('stopping %s...', str(service.__class__.__name__)) 65 | service.stop() 66 | logging.info('all services stopped!') 67 | for port in self.ports: 68 | logging.info('stopping %s...', str(port.__class__.__name__)) 69 | port.stop() 70 | logging.info('all ports stopped!') 71 | 72 | def inbound(self, datagram, rx_port): 73 | '''Called by a Port when a Datagram comes in from that port. The Datagram may be routed, delivered, both, or neither.''' 74 | 75 | # a network number of zero means "this network", but we know what that is from the port, so sub it in 76 | # note that short-header Datagrams always have a network number of zero 77 | if rx_port.network: 78 | if datagram.destination_network == datagram.source_network == 0x0000: 79 | datagram = datagram.copy(destination_network=rx_port.network, source_network=rx_port.network) 80 | elif datagram.destination_network == 0x0000: 81 | datagram = datagram.copy(destination_network=rx_port.network) 82 | elif datagram.source_network == 0x0000: 83 | datagram = datagram.copy(source_network=rx_port.network) 84 | 85 | # if this Datagram's destination network is this port's network, there is no need to route it 86 | if datagram.destination_network in (0x0000, rx_port.network): 87 | # if Datagram is bound for the router via the any-router address, the broadcast address, or its own node address, deliver it 88 | if datagram.destination_node in (0x00, rx_port.node, 0xFF): 89 | self._deliver(datagram, rx_port) 90 | return 91 | 92 | # if this Datagram's destination network is one the router is connected to, we may need to deliver it 93 | entry, _ = self.routing_table.get_by_network(datagram.destination_network) 94 | if entry is not None and entry.distance == 0: 95 | # if this Datagram is addressed to this router's address on another port, deliver and do not route 96 | if datagram.destination_network == entry.port.network and datagram.destination_node == entry.port.node: 97 | self._deliver(datagram, rx_port) 98 | return 99 | # if this Datagram is bound for any router on a network to which this router is directly connected, deliver and do not route 100 | elif datagram.destination_node == 0x00: 101 | self._deliver(datagram, rx_port) 102 | return 103 | # if this Datagram is broadcast to this router's address on another port, deliver but also route 104 | elif datagram.destination_node == 0xFF: 105 | self._deliver(datagram, rx_port) 106 | 107 | self.route(datagram, originating=False) 108 | 109 | def route(self, datagram, originating=True): 110 | '''Route a Datagram to/toward its destination.''' 111 | 112 | # datagrams we originate are the only ones we should raise exceptions for; bad network traffic should never bring us down 113 | if originating: 114 | if datagram.hop_count != 0: raise ValueError('originated datagrams must have hop count of 0') 115 | if datagram.destination_network == 0x0000: raise ValueError('originated datagrams must have nonzero destination network') 116 | # we expect source_network will be zero and we'll fill it in once we know what port we're coming from 117 | 118 | # if we still don't know where we're going, we obviously can't get there; discard the Datagram 119 | if datagram.destination_network == 0x0000: return 120 | 121 | # if the hop count is too high, we can't increment it even if we'd otherwise send the Datagram on; discard the Datagram 122 | if datagram.hop_count >= 15: return 123 | 124 | entry, _ = self.routing_table.get_by_network(datagram.destination_network) 125 | 126 | # you can't get there from here; discard the Datagram 127 | if entry is None: return 128 | 129 | # if we're originating this datagram, we expect that its source network and node will be blank 130 | if originating: 131 | # if for some reason the port is in the routing table but doesn't yet have a network and node, discard the Datagram 132 | if entry.port.network == 0x0000 or entry.port.node == 0x00: return 133 | # else, fill in its source network and node with those of the port it's coming from 134 | datagram = datagram.copy(source_network=entry.port.network, source_node=entry.port.node) 135 | else: 136 | # invalid values for source node, ports will refuse to send it on; discard the Datagram 137 | if datagram.source_node in (0x00, 0xFF): return 138 | # we're not originating this datagram, so bump its hop count 139 | datagram = datagram.hop() 140 | 141 | # here isn't there but we know how to get there; send the Datagram to the next router 142 | if entry.distance != 0: 143 | entry.port.unicast(entry.next_network, entry.next_node, datagram) 144 | # special 'any router' address (see IA page 4-7), control plane's responsibility; discard the Datagram 145 | elif datagram.destination_node == 0x00: 146 | pass 147 | # addressed to another port of this router's, control plane's responsibility; discard the Datagram 148 | elif datagram.destination_network == entry.port.network and datagram.destination_node == entry.port.node: 149 | pass 150 | # the destination is a broadcast to a network to which we are directly connected; broadcast the Datagram there 151 | elif datagram.destination_node == 0xFF: 152 | entry.port.broadcast(datagram) 153 | # the destination is connected to us directly; send the Datagram to its final destination 154 | else: 155 | entry.port.unicast(datagram.destination_network, datagram.destination_node, datagram) 156 | 157 | def reply(self, datagram, rx_port, ddp_type, data): 158 | '''Build and send a reply Datagram to the given Datagram coming in over the given Port with the given data.''' 159 | 160 | if datagram.source_node in (0x00, 0xFF): 161 | pass # invalid as source, don't reply 162 | elif rx_port.node and (datagram.source_network == 0x0000 or 0xFF00 <= datagram.source_network <= 0xFFFE or 163 | datagram.source_network < rx_port.network_min or datagram.source_network > rx_port.network_max): 164 | rx_port.broadcast(Datagram(hop_count=0, 165 | destination_network=0x0000, 166 | source_network=rx_port.network, 167 | destination_node=0xFF, 168 | source_node=rx_port.node, 169 | destination_socket=datagram.source_socket, 170 | source_socket=datagram.destination_socket, 171 | ddp_type=ddp_type, 172 | data=data)) 173 | else: 174 | self.route(Datagram(hop_count=0, 175 | destination_network=datagram.source_network, 176 | source_network=0, # route will fill this in 177 | destination_node=datagram.source_node, 178 | source_node=0, # route will fill this in 179 | destination_socket=datagram.source_socket, 180 | source_socket=datagram.destination_socket, 181 | ddp_type=ddp_type, 182 | data=data)) 183 | -------------------------------------------------------------------------------- /tashrouter/port/localtalk/__init__.py: -------------------------------------------------------------------------------- 1 | '''Superclass for LocalTalk Ports.''' 2 | 3 | import logging 4 | import random 5 | import struct 6 | from threading import Thread, Event, Lock 7 | 8 | from .. import Port 9 | from ...datagram import Datagram 10 | from ...netlog import log_datagram_inbound, log_datagram_unicast, log_datagram_broadcast, log_datagram_multicast 11 | 12 | 13 | class FcsCalculator: 14 | '''Utility class to calculate the FCS (frame check sequence) of an LLAP frame.''' 15 | 16 | LLAP_FCS_LUT = ( 17 | 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF, 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, 18 | 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E, 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876, 19 | 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD, 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, 20 | 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C, 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974, 21 | 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB, 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3, 22 | 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A, 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72, 23 | 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9, 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1, 24 | 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738, 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70, 25 | 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7, 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF, 26 | 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036, 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, 27 | 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5, 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD, 28 | 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134, 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, 29 | 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3, 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB, 30 | 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232, 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, 31 | 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1, 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9, 32 | 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330, 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78, 33 | ) 34 | 35 | def __init__(self): 36 | self.reg = 0 37 | self.reset() 38 | 39 | def reset(self): 40 | '''Reset the FCS calculator as though no data had been fed into it.''' 41 | self.reg = 0xFFFF 42 | 43 | def feed_byte(self, byte): 44 | '''Feed a single byte (an integer between 0 and 255) into the FCS calculator.''' 45 | index = (self.reg & 0xFF) ^ byte 46 | self.reg = self.LLAP_FCS_LUT[index] ^ (self.reg >> 8) 47 | 48 | def feed(self, data): 49 | '''Feed a bytes-like object into the FCS calculator.''' 50 | for byte in data: self.feed_byte(byte) 51 | 52 | def byte1(self): 53 | '''Returns the first byte of the FCS.''' 54 | return (self.reg & 0xFF) ^ 0xFF 55 | 56 | def byte2(self): 57 | '''Returns the second byte of the FCS.''' 58 | return (self.reg >> 8) ^ 0xFF 59 | 60 | def is_okay(self): 61 | '''If the FCS has been fed into the calculator and is correct, this will return True.''' 62 | return True if self.reg == 61624 else False # this is the binary constant on B-22 of Inside Appletalk, but backwards 63 | 64 | 65 | class LocalTalkPort(Port): 66 | '''Superclass for LocalTalk Ports.''' 67 | 68 | ENQ_INTERVAL = 0.25 # seconds 69 | ENQ_ATTEMPTS = 8 70 | 71 | LLAP_APPLETALK_SHORT_HEADER = 0x01 72 | LLAP_APPLETALK_LONG_HEADER = 0x02 73 | LLAP_ENQ = 0x81 74 | LLAP_ACK = 0x82 75 | 76 | def __init__(self, seed_network=0, seed_zone_name=None, respond_to_enq=True, desired_node=0xFE, verify_checksums=True, 77 | calculate_checksums=True): 78 | if seed_network and not seed_zone_name or seed_zone_name and not seed_network: 79 | raise ValueError('seed_network and seed_zone_name must be provided or omitted together') 80 | self.network = self.network_min = self.network_max = seed_network 81 | self.node = 0 82 | self.extended_network = False 83 | self._router = None 84 | self._seed_zone_name = seed_zone_name 85 | self._respond_to_enq = respond_to_enq 86 | self._desired_node = desired_node 87 | self._desired_node_list = list(i for i in range(1, 0xFE + 1) if i != self._desired_node) 88 | random.shuffle(self._desired_node_list) 89 | self._desired_node_attempts = 0 90 | self._verify_checksums = verify_checksums 91 | self._calculate_checksums = calculate_checksums 92 | self._node_thread = None 93 | self._node_lock = Lock() 94 | self._node_started_event = Event() 95 | self._node_stop_event = Event() 96 | self._node_stopped_event = Event() 97 | 98 | def start(self, router): 99 | self._router = router 100 | self._node_thread = Thread(target=self._node_run) 101 | self._node_thread.start() 102 | self._node_started_event.wait() 103 | 104 | def stop(self): 105 | self._node_stop_event.set() 106 | self._node_stopped_event.wait() 107 | 108 | def inbound_frame(self, frame_data): 109 | '''Called by subclass when an inbound LocalTalk frame is received.''' 110 | if len(frame_data) < 3: return # invalid frame, too short 111 | destination_node, source_node, llap_type = struct.unpack('>BBB', frame_data[0:3]) 112 | # short-header data frame 113 | if llap_type == self.LLAP_APPLETALK_SHORT_HEADER: 114 | try: 115 | datagram = Datagram.from_short_header_bytes(destination_node, source_node, frame_data[3:]) 116 | except ValueError as e: 117 | logging.debug('%s failed to parse short-header AppleTalk datagram from LocalTalk frame: %s', str(self), e.args[0]) 118 | else: 119 | log_datagram_inbound(self.network, self.node, datagram, self) 120 | self._router.inbound(datagram, self) 121 | # long-header data frame 122 | elif llap_type == self.LLAP_APPLETALK_LONG_HEADER: 123 | try: 124 | datagram = Datagram.from_long_header_bytes(frame_data[3:], verify_checksum=self._verify_checksums) 125 | except ValueError as e: 126 | logging.debug('%s failed to parse long-header AppleTalk datagram from LocalTalk frame: %s', str(self), e.args[0]) 127 | else: 128 | log_datagram_inbound(self.network, self.node, datagram, self) 129 | self._router.inbound(datagram, self) 130 | # we've settled on a node address and someone else is asking if they can use it, we say no 131 | elif llap_type == self.LLAP_ENQ and self._respond_to_enq and self.node and self.node == destination_node: 132 | self.send_frame(bytes((self.node, self.node, self.LLAP_ACK))) 133 | else: 134 | with self._node_lock: 135 | # someone else has responded that they're on the node address that we want 136 | if llap_type in (self.LLAP_ENQ, self.LLAP_ACK) and not self.node and self._desired_node == destination_node: 137 | self._desired_node_attempts = 0 138 | self._desired_node = self._desired_node_list.pop() 139 | if not self._desired_node_list: 140 | self._desired_node_list = list(range(1, 0xFE + 1)) 141 | random.shuffle(self._desired_node_list) 142 | 143 | def send_frame(self, frame_data): 144 | '''Implemented by subclass to send an outbound LocalTalk frame.''' 145 | raise NotImplementedError('subclass must override "send_frame" method') 146 | 147 | def set_node_id(self, node): 148 | '''Called when a LocalTalk node ID is settled on. May be overridden by subclass.''' 149 | self.node = node 150 | 151 | def unicast(self, network, node, datagram): 152 | if network not in (0, self.network): return 153 | if self.node == 0: return 154 | log_datagram_unicast(network, node, datagram, self) 155 | if datagram.destination_network == datagram.source_network and datagram.destination_network in (0, self.network): 156 | self.send_frame(bytes((node, self.node, self.LLAP_APPLETALK_SHORT_HEADER)) + datagram.as_short_header_bytes()) 157 | else: 158 | self.send_frame(bytes((node, self.node, self.LLAP_APPLETALK_LONG_HEADER)) 159 | + datagram.as_long_header_bytes(calculate_checksum=self._calculate_checksums)) 160 | 161 | def broadcast(self, datagram): 162 | if self.node == 0: return 163 | log_datagram_broadcast(datagram, self) 164 | self.send_frame(bytes((0xFF, self.node, self.LLAP_APPLETALK_SHORT_HEADER)) + datagram.as_short_header_bytes()) 165 | 166 | def multicast(self, zone_name, datagram): 167 | if self.node == 0: return 168 | log_datagram_multicast(zone_name, datagram, self) 169 | self.send_frame(bytes((0xFF, self.node, self.LLAP_APPLETALK_SHORT_HEADER)) + datagram.as_short_header_bytes()) 170 | 171 | def _set_network(self, network): 172 | logging.info('%s assigned network number %d', str(self), network) 173 | self.network = self.network_min = self.network_max = network 174 | self._router.routing_table.set_port_range(self, self.network, self.network) 175 | 176 | def set_network_range(self, network_min, network_max): 177 | if network_min != network_max: raise ValueError('LocalTalk networks are nonextended and cannot be set to a range of networks') 178 | if self.network: raise ValueError('%s assigned network number %d but already has %d' % (str(self), network_min, self.network)) 179 | self._set_network(network_min) 180 | 181 | @staticmethod 182 | def multicast_address(_): 183 | return b'' # multicast is not supported on LocalTalk 184 | 185 | def _node_run(self): 186 | if self.network: 187 | self._set_network(self.network) 188 | self._router.zone_information_table.add_networks_to_zone(self._seed_zone_name, self.network, self.network) 189 | self._node_started_event.set() 190 | while not self._node_stop_event.wait(self.ENQ_INTERVAL): 191 | send_enq = None 192 | with self._node_lock: 193 | if self._desired_node_attempts >= self.ENQ_ATTEMPTS: 194 | logging.info('%s claiming node address %d', str(self), self._desired_node) 195 | self.set_node_id(self._desired_node) 196 | break 197 | else: 198 | send_enq = self._desired_node 199 | self._desired_node_attempts += 1 200 | if send_enq: self.send_frame(bytes((send_enq, send_enq, self.LLAP_ENQ))) 201 | self._node_stopped_event.set() 202 | -------------------------------------------------------------------------------- /tashrouter/service/zip/responding.py: -------------------------------------------------------------------------------- 1 | '''Zone Information Service.''' 2 | 3 | from collections import deque 4 | from itertools import chain 5 | import logging 6 | from queue import Queue 7 | import struct 8 | from threading import Thread, Event 9 | 10 | from . import ZipService 11 | from .. import Service 12 | from ...datagram import Datagram 13 | from ...router.zone_information_table import ucase 14 | 15 | 16 | class ZipRespondingService(Service, ZipService): 17 | '''A Service that implements Zone Information Protocol (ZIP).''' 18 | 19 | def __init__(self): 20 | self.thread = None 21 | self.queue = Queue() 22 | self.stop_flag = object() 23 | self.started_event = Event() 24 | self.stopped_event = Event() 25 | self._pending_network_zone_name_set = {} 26 | 27 | def start(self, router): 28 | self.thread = Thread(target=self._run, args=(router,)) 29 | self.thread.start() 30 | self.started_event.wait() 31 | 32 | def stop(self): 33 | self.queue.put(self.stop_flag) 34 | self.stopped_event.wait() 35 | 36 | def _reply(self, router, datagram): 37 | 38 | if len(datagram.data) < 2: return 39 | func, count = struct.unpack('>BB', datagram.data[:2]) 40 | data = datagram.data[2:] 41 | 42 | networks_and_zone_names = deque() 43 | while len(data) >= 3: 44 | network_min, zone_name_length = struct.unpack('>HB', data[:3]) 45 | zone_name = data[3:3 + zone_name_length] 46 | if len(zone_name) != zone_name_length: break 47 | data = data[3 + zone_name_length:] 48 | if zone_name_length == 0: continue 49 | networks_and_zone_names.append((network_min, zone_name)) 50 | if not networks_and_zone_names: return 51 | 52 | network_min_to_network_max = {} 53 | for entry in router.routing_table: 54 | network_min_to_network_max[entry.network_min] = entry.network_max 55 | 56 | if func == self.ZIP_FUNC_REPLY: 57 | for network_min, zone_name in networks_and_zone_names: 58 | try: 59 | network_max = network_min_to_network_max[network_min] 60 | except KeyError: 61 | logging.warning('%s ZIP reply refers to a network range (starting with %d) with which we are not familiar', str(router), 62 | network_min) 63 | else: 64 | try: 65 | router.zone_information_table.add_networks_to_zone(zone_name, network_min, network_max) 66 | except ValueError as e: 67 | logging.warning("%s ZIP reply couldn't be added to zone information table: %s", str(router), e.args[0]) 68 | elif func == self.ZIP_FUNC_EXT_REPLY: 69 | #TODO this code is fragile and I do not like it 70 | network_min = None 71 | for network_min, zone_name in networks_and_zone_names: 72 | if network_min not in self._pending_network_zone_name_set: self._pending_network_zone_name_set[network_min] = set() 73 | self._pending_network_zone_name_set[network_min].add(zone_name) 74 | if network_min is not None and len(self._pending_network_zone_name_set.get(network_min, ())) >= count and count >= 1: 75 | for zone_name in self._pending_network_zone_name_set.pop(network_min): 76 | try: 77 | network_max = network_min_to_network_max[network_min] 78 | except KeyError: 79 | logging.warning('%s ZIP reply refers to a network range (starting with %d) with which we are not familiar', str(router), 80 | network_min) 81 | else: 82 | try: 83 | router.zone_information_table.add_networks_to_zone(zone_name, network_min, network_max) 84 | except ValueError as e: 85 | logging.warning("%s ZIP reply couldn't be added to zone information table: %s", str(router), e.args[0]) 86 | 87 | @classmethod 88 | def _query(cls, router, datagram, rx_port): 89 | if len(datagram.data) < 4: return 90 | network_count = datagram.data[1] 91 | if len(datagram.data) != (network_count * 2) + 2: return 92 | # in imitation of AppleTalk Internet Router, we only respond with extended replies even if a regular reply would fit 93 | # we also give one list per requested network even if the requested networks are in the same range and the lists are the same; 94 | # that is, if the sender requests zones for networks 3 and 4 and there is a zones list for networks 3-5, we will reply with the 95 | # zone list for network 3 twice... seems silly, but this is how ATIR does it so *shrug* 96 | for network_idx in range(network_count): 97 | requested_network = struct.unpack('>H', datagram.data[(network_idx * 2) + 2:(network_idx * 2) + 4])[0] 98 | entry, _ = router.routing_table.get_by_network(requested_network) 99 | if entry is None: continue 100 | try: 101 | zone_names = router.zone_information_table.zones_in_network_range(entry.network_min) 102 | except ValueError: 103 | continue 104 | datagram_data = deque() 105 | datagram_data_length = 0 106 | for zone_name in chain(zone_names, (None,)): 107 | list_item = None if zone_name is None else struct.pack('>HB', entry.network_min, len(zone_name)) + zone_name 108 | if list_item is None or datagram_data_length + len(list_item) > Datagram.MAX_DATA_LENGTH - 2: 109 | router.reply(datagram, rx_port, cls.ZIP_DDP_TYPE, struct.pack('>BB', cls.ZIP_FUNC_EXT_REPLY, 110 | len(zone_names)) + b''.join(datagram_data)) 111 | datagram_data = deque() 112 | datagram_data_length = 0 113 | if list_item is not None: 114 | datagram_data.append(list_item) 115 | datagram_data_length += len(list_item) 116 | 117 | @classmethod 118 | def _get_net_info(cls, router, datagram, rx_port): 119 | if 0 in (rx_port.network, rx_port.network_min, rx_port.network_max): return 120 | if len(datagram.data) < 7: return 121 | if datagram.data[1:6] != b'\0\0\0\0\0': return 122 | given_zone_name = datagram.data[7:7 + datagram.data[6]] 123 | given_zone_name_ucase = ucase(given_zone_name) 124 | flags = cls.ZIP_GETNETINFO_ZONE_INVALID | cls.ZIP_GETNETINFO_ONLY_ONE_ZONE 125 | default_zone_name = None 126 | number_of_zones = 0 127 | multicast_address = b'' 128 | try: 129 | zone_names = router.zone_information_table.zones_in_network_range(rx_port.network_min, rx_port.network_max) 130 | except ValueError as e: 131 | logging.warning("%s couldn't get zone names in port network range for GetNetInfo: %s", router, e.args[0]) 132 | return 133 | for zone_name in zone_names: 134 | number_of_zones += 1 135 | if default_zone_name is None: 136 | # zones_in_network_range returns the default zone first 137 | default_zone_name = zone_name 138 | multicast_address = rx_port.multicast_address(zone_name) 139 | if ucase(zone_name) == given_zone_name_ucase: 140 | flags &= ~cls.ZIP_GETNETINFO_ZONE_INVALID 141 | multicast_address = rx_port.multicast_address(zone_name) 142 | if number_of_zones > 1: 143 | flags &= ~cls.ZIP_GETNETINFO_ONLY_ONE_ZONE 144 | if not flags & cls.ZIP_GETNETINFO_ZONE_INVALID: break 145 | if number_of_zones == 0: return 146 | if not multicast_address: flags |= cls.ZIP_GETNETINFO_USE_BROADCAST 147 | reply_data = b''.join(( 148 | struct.pack('>BBHHB', cls.ZIP_FUNC_GETNETINFO_REPLY, flags, rx_port.network_min, rx_port.network_max, len(given_zone_name)), 149 | given_zone_name, 150 | struct.pack('>B', len(multicast_address)), 151 | multicast_address, 152 | struct.pack('>B', len(default_zone_name)) if flags & cls.ZIP_GETNETINFO_ZONE_INVALID else b'', 153 | default_zone_name if flags & cls.ZIP_GETNETINFO_ZONE_INVALID else b'')) 154 | router.reply(datagram, rx_port, cls.ZIP_DDP_TYPE, reply_data) 155 | 156 | @classmethod 157 | def _get_my_zone(cls, router, datagram, rx_port): 158 | _, _, tid, _, _, _ = struct.unpack('>BBHBBH', datagram.data) 159 | entry, _ = router.routing_table.get_by_network(datagram.source_network) 160 | if entry is None: return 161 | try: 162 | zone_name = next(iter(router.zone_information_table.zones_in_network_range(entry.network_min)), None) 163 | except ValueError: 164 | return 165 | if not zone_name: return 166 | router.reply(datagram, rx_port, cls.ATP_DDP_TYPE, struct.pack('>BBHBBHB', 167 | cls.ATP_FUNC_TRESP | cls.ATP_EOM, 168 | 0, 169 | tid, 170 | 0, 171 | 0, 172 | 1, 173 | len(zone_name)) + zone_name) 174 | 175 | @classmethod 176 | def _get_zone_list(cls, router, datagram, rx_port, local=False): 177 | _, _, tid, _, _, start_index = struct.unpack('>BBHBBH', datagram.data) 178 | if local: 179 | try: 180 | zone_iter = iter(router.zone_information_table.zones_in_network_range(rx_port.network_min, rx_port.network_max)) 181 | except ValueError as e: 182 | logging.warning("%s couldn't get zone names in port network range for GetLocalZones: %s", router, e.args[0]) 183 | return 184 | else: 185 | zone_iter = iter(router.zone_information_table.zones()) 186 | for _ in range(start_index - 1): next(zone_iter, None) # skip over start_index-1 entries (index is 1-relative) 187 | last_flag = 0 188 | zone_list = deque() 189 | num_zones = 0 190 | data_length = 8 191 | while zone_name := next(zone_iter, None): 192 | if data_length + 1 + len(zone_name) > Datagram.MAX_DATA_LENGTH: break 193 | zone_list.append(struct.pack('>B', len(zone_name))) 194 | zone_list.append(zone_name) 195 | num_zones += 1 196 | data_length += 1 + len(zone_name) 197 | else: 198 | last_flag = 1 199 | router.reply(datagram, rx_port, cls.ATP_DDP_TYPE, struct.pack('>BBHBBH', 200 | cls.ATP_FUNC_TRESP | cls.ATP_EOM, 201 | 0, 202 | tid, 203 | last_flag, 204 | 0, 205 | num_zones) + b''.join(zone_list)) 206 | 207 | def _run(self, router): 208 | self.started_event.set() 209 | while True: 210 | item = self.queue.get() 211 | if item is self.stop_flag: break 212 | datagram, rx_port = item 213 | if datagram.ddp_type == self.ZIP_DDP_TYPE: 214 | if not datagram.data: continue 215 | if datagram.data[0] in (self.ZIP_FUNC_REPLY, self.ZIP_FUNC_EXT_REPLY): 216 | self._reply(router, datagram) 217 | elif datagram.data[0] == self.ZIP_FUNC_QUERY: 218 | self._query(router, datagram, rx_port) 219 | elif datagram.data[0] == self.ZIP_FUNC_GETNETINFO_REQUEST: 220 | self._get_net_info(router, datagram, rx_port) 221 | elif datagram.ddp_type == self.ATP_DDP_TYPE: 222 | if len(datagram.data) != 8: continue 223 | control, bitmap, _, func, zero, _ = struct.unpack('>BBHBBH', datagram.data) 224 | if control != self.ATP_FUNC_TREQ or bitmap != 1 or zero != 0: continue 225 | if func == self.ZIP_ATP_FUNC_GETMYZONE: 226 | self._get_my_zone(router, datagram, rx_port) 227 | elif func == self.ZIP_ATP_FUNC_GETZONELIST: 228 | self._get_zone_list(router, datagram, rx_port, local=False) 229 | elif func == self.ZIP_ATP_FUNC_GETLOCALZONES: 230 | self._get_zone_list(router, datagram, rx_port, local=True) 231 | self.stopped_event.set() 232 | 233 | def inbound(self, datagram, rx_port): 234 | self.queue.put((datagram, rx_port)) 235 | -------------------------------------------------------------------------------- /tashrouter/port/ethertalk/__init__.py: -------------------------------------------------------------------------------- 1 | '''Superclass for EtherTalk Ports.''' 2 | 3 | from collections import deque 4 | import logging 5 | import random 6 | import struct 7 | from threading import Thread, Event, Lock 8 | import time 9 | 10 | from .. import Port 11 | from ...datagram import Datagram, ddp_checksum 12 | from ...netlog import log_datagram_inbound, log_datagram_unicast, log_datagram_broadcast, log_datagram_multicast 13 | from ...netlog import log_ethernet_frame_inbound, log_ethernet_frame_outbound 14 | from ...router.zone_information_table import ucase 15 | 16 | 17 | class EtherTalkPort(Port): 18 | '''Superclass for EtherTalk Ports.''' 19 | 20 | IEEE_802_2_SAP_OTHER = 0xAA 21 | IEEE_802_2_DATAGRAM_SVC_CTRL = 0x03 22 | IEEE_802_2_TYPE_1_HEADER = bytes((IEEE_802_2_SAP_OTHER, IEEE_802_2_SAP_OTHER, IEEE_802_2_DATAGRAM_SVC_CTRL)) 23 | SNAP_HEADER_AARP = bytes((0x00, 0x00, 0x00, 0x80, 0xF3)) 24 | SNAP_HEADER_APPLETALK = bytes((0x08, 0x00, 0x07, 0x80, 0x9B)) 25 | 26 | AARP_ETHERNET = bytes((0x00, 0x01)) 27 | AARP_APPLETALK = bytes((0x80, 0x9B)) 28 | AARP_HW_ADDR_LEN = 6 29 | AARP_PROTOCOL_ADDR_LEN = 4 30 | AARP_LENGTHS = bytes((AARP_HW_ADDR_LEN, AARP_PROTOCOL_ADDR_LEN)) 31 | AARP_HEADER = IEEE_802_2_TYPE_1_HEADER + SNAP_HEADER_AARP + AARP_ETHERNET + AARP_APPLETALK + AARP_LENGTHS 32 | 33 | AARP_REQUEST = 1 34 | AARP_RESPONSE = 2 35 | AARP_PROBE = 3 36 | 37 | AARP_PROBE_TIMEOUT = 0.2 # seconds 38 | AARP_PROBE_RETRIES = 10 39 | 40 | APPLETALK_HEADER = IEEE_802_2_TYPE_1_HEADER + SNAP_HEADER_APPLETALK 41 | 42 | ELAP_BROADCAST_ADDR = bytes((0x09, 0x00, 0x07, 0xFF, 0xFF, 0xFF)) 43 | ELAP_MULTICAST_PREFIX = bytes((0x09, 0x00, 0x07, 0x00, 0x00)) 44 | ELAP_MULTICAST_ADDR_MAX = 0xFC 45 | ELAP_MULTICAST_ADDRS = tuple(bytes((0x09, 0x00, 0x07, 0x00, 0x00, i)) for i in range(ELAP_MULTICAST_ADDR_MAX + 1)) 46 | 47 | AMT_MAX_AGE = 10 # seconds 48 | AMT_AGE_INTERVAL = 1 # seconds 49 | HELD_DATAGRAM_MAX_AGE = 10 # seconds 50 | HELD_DATAGRAM_AGE_INTERVAL = 1 # seconds 51 | HELD_DATAGRAM_AARP_REQUEST_INTERVAL = 0.25 # seconds 52 | 53 | def __init__(self, hw_addr, seed_network_min=0, seed_network_max=0, seed_zone_names=(), desired_network=0, desired_node=0, 54 | verify_checksums=True, calculate_checksums=True): 55 | if seed_network_min and not seed_network_max or seed_network_max and not seed_network_min: 56 | raise ValueError('seed_network_min and seed_network_max must be provided or omitted together') 57 | if seed_network_min and not seed_zone_names or seed_zone_names and not seed_network_min: 58 | raise ValueError('seed_network_min/max and seed_zone_names must be provided or omitted together') 59 | self.network_min = seed_network_min 60 | self.network_max = seed_network_max 61 | self.network = 0 62 | self.node = 0 63 | self.extended_network = True 64 | self._hw_addr = hw_addr 65 | self._seed_zone_names = seed_zone_names 66 | self._desired_network = 0 67 | self._desired_node = 0 68 | if self.network_min: 69 | self._desired_network_list = [desired_network] if self.network_min <= desired_network <= self.network_max else [] 70 | self._desired_node_list = [desired_node] if 1 <= desired_node <= 0xFD else [] 71 | self._reroll_desired_network_and_node() 72 | else: 73 | self._desired_network_list = [] 74 | self._desired_node_list = [] 75 | self._verify_checksums = verify_checksums 76 | self._calculate_checksums = calculate_checksums 77 | self._aarp_probe_attempts = 0 78 | self._aarp_probe_lock = Lock() 79 | self._router = None 80 | self._address_mapping_table = {} # (network, node) -> (ethernet address [bytes], time.monotonic() value when last used) 81 | self._held_datagrams = {} # (network, node) -> deque((Datagram, time.monotonic() value when inserted)) 82 | self._tables_lock = Lock() 83 | self._age_held_datagrams_thread = None 84 | self._age_held_datagrams_started_event = Event() 85 | self._age_held_datagrams_stop_event = Event() 86 | self._age_held_datagrams_stopped_event = Event() 87 | self._send_aarp_requests_thread = None 88 | self._send_aarp_requests_started_event = Event() 89 | self._send_aarp_requests_stop_event = Event() 90 | self._send_aarp_requests_stopped_event = Event() 91 | self._age_address_mapping_table_thread = None 92 | self._age_address_mapping_table_started_event = Event() 93 | self._age_address_mapping_table_stop_event = Event() 94 | self._age_address_mapping_table_stopped_event = Event() 95 | self._acquire_network_and_node_thread = None 96 | self._acquire_network_and_node_started_event = Event() 97 | self._acquire_network_and_node_stop_event = Event() 98 | self._acquire_network_and_node_stopped_event = Event() 99 | 100 | def _reroll_desired_network_and_node(self): 101 | '''Reroll the network and node number.''' 102 | if not self._desired_node_list: 103 | if not self._desired_network_list: 104 | self._desired_network_list = list(range(self.network_min, self.network_max + 1)) 105 | random.shuffle(self._desired_network_list) 106 | self._desired_network = self._desired_network_list.pop() 107 | self._desired_node_list = list(range(1, 0xFD + 1)) 108 | random.shuffle(self._desired_node_list) 109 | self._desired_node = self._desired_node_list.pop() 110 | self._aarp_probe_attempts = 0 111 | 112 | def _send_frame(self, hw_addr, payload): 113 | '''Send a payload to an Ethernet address, padding if necessary.''' 114 | pad = b'\0' * (46 - len(payload)) if len(payload) < 46 else b'' 115 | frame_data = b''.join((hw_addr, self._hw_addr, struct.pack('>H', len(payload)), payload, pad)) 116 | log_ethernet_frame_outbound(frame_data, self) 117 | self.send_frame(frame_data) 118 | 119 | def _send_datagram(self, hw_addr, datagram): 120 | '''Turn a Datagram into an Ethernet frame and send it to the given address.''' 121 | self._send_frame(hw_addr, b''.join((self.APPLETALK_HEADER, 122 | datagram.as_long_header_bytes(calculate_checksum=self._calculate_checksums)))) 123 | 124 | def _send_aarp_request(self, network, node): 125 | '''Create an AARP request for the given network and node and broadcast it to all AppleTalk nodes.''' 126 | if not self.network or not self.node: return 127 | self._send_frame(self.ELAP_BROADCAST_ADDR, b''.join((self.AARP_HEADER, struct.pack('>H', self.AARP_REQUEST), 128 | self._hw_addr, 129 | struct.pack('>BHBHLBHB', 130 | 0, self.network, self.node, 131 | 0, 0, 132 | 0, network, node)))) 133 | 134 | def _send_aarp_response(self, destination_hw_addr, destination_network, destination_node): 135 | '''Create an AARP response containing our address and send it to the given destination.''' 136 | if not self.network or not self.node: return 137 | self._send_frame(destination_hw_addr, b''.join((self.AARP_HEADER, struct.pack('>H', self.AARP_RESPONSE), 138 | self._hw_addr, 139 | struct.pack('>BHB', 0, self.network, self.node), 140 | destination_hw_addr, 141 | struct.pack('>BHB', 0, destination_network, destination_node)))) 142 | 143 | def _send_aarp_probe(self, network, node): 144 | '''Create an AARP probe for the given network and node and broadcast it to all AppleTalk nodes.''' 145 | self._send_frame(self.ELAP_BROADCAST_ADDR, b''.join((self.AARP_HEADER, struct.pack('>H', self.AARP_PROBE), 146 | self._hw_addr, 147 | struct.pack('>BHBHLBHB', 148 | 0, network, node, 149 | 0, 0, 150 | 0, network, node)))) 151 | 152 | def _add_address_mapping(self, network, node, mapped_hw_addr): 153 | '''Add an address mapping for the given network, node, and Ethernet address and release any held Datagrams waiting on it.''' 154 | datagrams_to_send = deque() 155 | with self._tables_lock: 156 | self._address_mapping_table[(network, node)] = (mapped_hw_addr, time.monotonic()) 157 | if (network, node) in self._held_datagrams: 158 | for datagram, _ in self._held_datagrams[(network, node)]: datagrams_to_send.append((mapped_hw_addr, datagram)) 159 | self._held_datagrams.pop((network, node)) 160 | for hw_addr, datagram in datagrams_to_send: self._send_datagram(hw_addr, datagram) 161 | 162 | def _send_aarp_requests_run(self): 163 | '''Thread for sending AARP requests for held Datagrams.''' 164 | self._send_aarp_requests_started_event.set() 165 | while not self._send_aarp_requests_stop_event.wait(timeout=self.HELD_DATAGRAM_AARP_REQUEST_INTERVAL): 166 | with self._tables_lock: aarp_requests = deque(self._held_datagrams.keys()) 167 | for network, node in aarp_requests: self._send_aarp_request(network, node) 168 | self._send_aarp_requests_stopped_event.set() 169 | 170 | def _age_held_datagrams_run(self): 171 | '''Thread for aging held Datagrams.''' 172 | self._age_held_datagrams_started_event.set() 173 | while not self._age_held_datagrams_stop_event.wait(timeout=self.HELD_DATAGRAM_AGE_INTERVAL): 174 | with self._tables_lock: 175 | now = time.monotonic() 176 | new_held_datagrams = {} 177 | for network_node, datagram_hold_times in self._held_datagrams.items(): 178 | new_datagram_hold_times = deque() 179 | for datagram, hold_time in datagram_hold_times: 180 | if now - hold_time < self.HELD_DATAGRAM_MAX_AGE: new_datagram_hold_times.append((datagram, hold_time)) 181 | if new_datagram_hold_times: 182 | new_held_datagrams[network_node] = new_datagram_hold_times 183 | self._held_datagrams = new_held_datagrams 184 | self._age_held_datagrams_stopped_event.set() 185 | 186 | def _age_address_mapping_table_run(self): 187 | '''Thread for aging entries in the Address Mapping Table.''' 188 | self._age_address_mapping_table_started_event.set() 189 | while not self._age_address_mapping_table_stop_event.wait(timeout=self.AMT_AGE_INTERVAL): 190 | with self._tables_lock: 191 | now = time.monotonic() 192 | entries_to_remove = deque(network_node for network_node, address_last_used_time in self._address_mapping_table.items() 193 | if now - address_last_used_time[1] >= self.AMT_MAX_AGE) 194 | for entry_to_remove in entries_to_remove: self._address_mapping_table.pop(entry_to_remove) 195 | self._age_address_mapping_table_stopped_event.set() 196 | 197 | def _acquire_network_and_node_run(self): 198 | '''Thread for acquiring a network and node number.''' 199 | if self.network_min and self.network_max: 200 | self._set_network_range(self.network_min, self.network_max) 201 | for zone_name in self._seed_zone_names: 202 | self._router.zone_information_table.add_networks_to_zone(zone_name, self.network_min, self.network_max) 203 | self._acquire_network_and_node_started_event.set() 204 | while not self._acquire_network_and_node_stop_event.wait(timeout=self.AARP_PROBE_TIMEOUT): 205 | send_aarp_probe = None 206 | with self._aarp_probe_lock: 207 | if self._aarp_probe_attempts >= self.AARP_PROBE_RETRIES: 208 | logging.info('%s claiming address %d.%d', str(self), self._desired_network, self._desired_node) 209 | self.network = self._desired_network 210 | self.node = self._desired_node 211 | break 212 | if self._desired_network and self._desired_node: 213 | send_aarp_probe = (self._desired_network, self._desired_node) 214 | self._aarp_probe_attempts += 1 215 | if send_aarp_probe: 216 | desired_network, desired_node = send_aarp_probe 217 | self._send_aarp_probe(desired_network, desired_node) 218 | self._acquire_network_and_node_stopped_event.set() 219 | 220 | def _process_aarp_frame(self, func, source_hw_addr, source_network, source_node): 221 | '''Process and act on an inbound AARP frame.''' 222 | if func in (self.AARP_REQUEST, self.AARP_PROBE): 223 | self._send_aarp_response(source_hw_addr, source_network, source_node) 224 | elif func == self.AARP_RESPONSE: 225 | self._add_address_mapping(source_network, source_node, source_hw_addr) 226 | with self._aarp_probe_lock: 227 | if self.network == self.node == 0 and source_network == self._desired_network and source_node == self._desired_node: 228 | self._reroll_desired_network_and_node() 229 | 230 | def inbound_frame(self, frame_data): 231 | '''Called by subclass with inbound Ethernet frames.''' 232 | 233 | if frame_data[14:17] != self.IEEE_802_2_TYPE_1_HEADER: return 234 | length = struct.unpack('>H', frame_data[12:14])[0] 235 | if length > len(frame_data) + 14: return # probably an ethertype 236 | 237 | if frame_data[17:22] == self.SNAP_HEADER_AARP and length == 36: 238 | 239 | if frame_data[22:28] != b''.join((self.AARP_ETHERNET, self.AARP_APPLETALK, self.AARP_LENGTHS)): return 240 | 241 | log_ethernet_frame_inbound(frame_data, self) 242 | 243 | func, source_hw_addr, _, source_network, source_node = struct.unpack('>H6sBHB', frame_data[28:40]) 244 | 245 | if frame_data.startswith(self._hw_addr) or (func == self.AARP_REQUEST and frame_data.startswith(self.ELAP_BROADCAST_ADDR)): 246 | self._process_aarp_frame(func, source_hw_addr, source_network, source_node) 247 | elif func == self.AARP_RESPONSE: 248 | self._add_address_mapping(source_network, source_node, source_hw_addr) 249 | 250 | elif frame_data[17:22] == self.SNAP_HEADER_APPLETALK: 251 | 252 | log_ethernet_frame_inbound(frame_data, self) 253 | 254 | try: 255 | datagram = Datagram.from_long_header_bytes(frame_data[22:14 + length], verify_checksum=self._verify_checksums) 256 | except ValueError as e: 257 | logging.debug('%s failed to parse AppleTalk datagram from EtherTalk frame: %s', str(self), e.args[0]) 258 | else: 259 | if datagram.hop_count == 0: self._add_address_mapping(datagram.source_network, datagram.source_node, frame_data[6:12]) 260 | if (frame_data.startswith((self._hw_addr, self.ELAP_BROADCAST_ADDR)) or 261 | (frame_data.startswith(self.ELAP_MULTICAST_PREFIX) and frame_data[5] <= self.ELAP_MULTICAST_ADDR_MAX)): 262 | log_datagram_inbound(self.network, self.node, datagram, self) 263 | self._router.inbound(datagram, self) 264 | 265 | def send_frame(self, frame_data): 266 | '''Implemented by subclass to send Ethernet frames.''' 267 | raise NotImplementedError('subclass must override "send_frame" method') 268 | 269 | def start(self, router): 270 | '''Start this Port with the given Router. Subclass should call this and add its own threads in its implementation.''' 271 | self._router = router 272 | self._age_held_datagrams_thread = Thread(target=self._age_held_datagrams_run) 273 | self._age_held_datagrams_thread.start() 274 | self._send_aarp_requests_thread = Thread(target=self._send_aarp_requests_run) 275 | self._send_aarp_requests_thread.start() 276 | self._age_address_mapping_table_thread = Thread(target=self._age_address_mapping_table_run) 277 | self._age_address_mapping_table_thread.start() 278 | self._acquire_network_and_node_thread = Thread(target=self._acquire_network_and_node_run) 279 | self._acquire_network_and_node_thread.start() 280 | self._age_held_datagrams_started_event.wait() 281 | self._send_aarp_requests_started_event.wait() 282 | self._age_address_mapping_table_started_event.wait() 283 | self._acquire_network_and_node_started_event.wait() 284 | 285 | def stop(self): 286 | '''Stop this Port. Subclass should call this and add its own threads in its implementation.''' 287 | self._age_held_datagrams_stop_event.set() 288 | self._send_aarp_requests_stop_event.set() 289 | self._age_address_mapping_table_stop_event.set() 290 | self._acquire_network_and_node_stop_event.set() 291 | self._age_held_datagrams_stopped_event.wait() 292 | self._send_aarp_requests_stopped_event.wait() 293 | self._age_address_mapping_table_stopped_event.wait() 294 | self._acquire_network_and_node_stopped_event.wait() 295 | 296 | def unicast(self, network, node, datagram): 297 | log_datagram_unicast(network, node, datagram, self) 298 | send_datagram = None 299 | send_aarp_request = None 300 | with self._tables_lock: 301 | if (network, node) in self._address_mapping_table: 302 | hw_addr, _ = self._address_mapping_table[(network, node)] 303 | send_datagram = (hw_addr, datagram) 304 | elif (network, node) in self._held_datagrams: 305 | self._held_datagrams[(network, node)].append((datagram, time.monotonic())) 306 | else: 307 | self._held_datagrams[(network, node)] = deque(((datagram, time.monotonic()),)) 308 | send_aarp_request = (network, node) 309 | if send_datagram: 310 | hw_addr, datagram = send_datagram 311 | self._send_datagram(hw_addr, datagram) 312 | if send_aarp_request: 313 | network, node = send_aarp_request 314 | self._send_aarp_request(network, node) 315 | 316 | def broadcast(self, datagram): 317 | log_datagram_broadcast(datagram, self) 318 | if (datagram.destination_network, datagram.destination_node) != (0x0000, 0xFF): 319 | datagram = datagram.copy(destination_network=0x0000, destination_node=0xFF) 320 | self._send_datagram(self.ELAP_BROADCAST_ADDR, datagram) 321 | 322 | def multicast(self, zone_name, datagram): 323 | log_datagram_multicast(zone_name, datagram, self) 324 | self._send_datagram(self.multicast_address(zone_name), datagram) 325 | 326 | def _set_network_range(self, network_min, network_max): 327 | logging.info('%s assigned network number range %d-%d', str(self), network_min, network_max) 328 | self.network_min = network_min 329 | self.network_max = network_max 330 | self._router.routing_table.set_port_range(self, self.network_min, self.network_max) 331 | self.network = 0 332 | self.node = 0 333 | with self._aarp_probe_lock: 334 | self._desired_network_list = [] 335 | self._desired_node_list = [] 336 | self._reroll_desired_network_and_node() 337 | 338 | def set_network_range(self, network_min, network_max): 339 | '''Called by RTMP responding service when we don't have a network range but an RTMP datagram tells us what ours is.''' 340 | if self.network_min or self.network_max: 341 | raise ValueError('%s assigned network number range %d-%d but already has %d-%d' % (str(self), network_min, network_max, 342 | self.network_min, self.network_max)) 343 | self._set_network_range(network_min, network_max) 344 | 345 | @classmethod 346 | def multicast_address(cls, zone_name): 347 | '''Return the ELAP multicast address for the named zone.''' 348 | return cls.ELAP_MULTICAST_ADDRS[ddp_checksum(ucase(zone_name)) % len(cls.ELAP_MULTICAST_ADDRS)] 349 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------