2016-06-03 17:02:02 +00:00
|
|
|
from Interface import Interface
|
|
|
|
import SocketServer
|
|
|
|
import threading
|
|
|
|
import socket
|
2018-04-25 20:08:17 +00:00
|
|
|
import time
|
2016-06-03 17:02:02 +00:00
|
|
|
import sys
|
2018-04-04 12:14:22 +00:00
|
|
|
import RNS
|
2016-06-03 17:02:02 +00:00
|
|
|
|
|
|
|
class UdpInterface(Interface):
|
|
|
|
|
2018-04-05 17:12:21 +00:00
|
|
|
def __init__(self, owner, name, bindip=None, bindport=None, forwardip=None, forwardport=None):
|
2016-06-03 17:02:02 +00:00
|
|
|
self.IN = True
|
|
|
|
self.OUT = False
|
2018-04-25 20:08:17 +00:00
|
|
|
self.transmit_delay = 0.001
|
2016-06-03 17:02:02 +00:00
|
|
|
|
2018-04-05 17:12:21 +00:00
|
|
|
self.name = name
|
|
|
|
|
2016-06-03 17:02:02 +00:00
|
|
|
if (bindip != None and bindport != None):
|
|
|
|
self.receives = True
|
|
|
|
self.bind_ip = bindip
|
|
|
|
self.bind_port = bindport
|
|
|
|
|
2020-03-01 15:56:49 +00:00
|
|
|
def handlerFactory(callback):
|
|
|
|
def createHandler(*args, **keys):
|
|
|
|
return UdpInterfaceHandler(callback, *args, **keys)
|
|
|
|
return createHandler
|
|
|
|
|
2016-06-03 17:02:02 +00:00
|
|
|
self.owner = owner
|
|
|
|
address = (self.bind_ip, self.bind_port)
|
2020-03-01 15:56:49 +00:00
|
|
|
self.server = SocketServer.UDPServer(address, handlerFactory(self.processIncoming))
|
2016-06-03 17:02:02 +00:00
|
|
|
|
|
|
|
thread = threading.Thread(target=self.server.serve_forever)
|
|
|
|
thread.setDaemon(True)
|
|
|
|
thread.start()
|
|
|
|
|
|
|
|
if (forwardip != None and forwardport != None):
|
|
|
|
self.forwards = True
|
|
|
|
self.forward_ip = forwardip
|
|
|
|
self.forward_port = forwardport
|
|
|
|
|
|
|
|
|
|
|
|
def processIncoming(self, data):
|
2018-04-04 12:14:22 +00:00
|
|
|
self.owner.inbound(data, self)
|
2016-06-03 17:02:02 +00:00
|
|
|
|
|
|
|
def processOutgoing(self,data):
|
2018-04-25 20:08:17 +00:00
|
|
|
time.sleep(self.transmit_delay)
|
2016-06-03 17:02:02 +00:00
|
|
|
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
|
|
udp_socket.sendto(data, (self.forward_ip, self.forward_port))
|
|
|
|
|
|
|
|
|
|
|
|
def __str__(self):
|
2018-04-04 12:14:22 +00:00
|
|
|
return "UdpInterface["+self.name+"/"+self.bind_ip+":"+str(self.bind_port)+"]"
|
2016-06-03 17:02:02 +00:00
|
|
|
|
|
|
|
class UdpInterfaceHandler(SocketServer.BaseRequestHandler):
|
2020-03-01 15:56:49 +00:00
|
|
|
def __init__(self, callback, *args, **keys):
|
|
|
|
self.callback = callback
|
|
|
|
SocketServer.BaseRequestHandler.__init__(self, *args, **keys)
|
2016-06-03 17:02:02 +00:00
|
|
|
|
|
|
|
def handle(self):
|
2020-03-01 15:56:49 +00:00
|
|
|
data = self.request[0]
|
|
|
|
self.callback(data)
|