1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import time
import socket
import threading
import libs.threadmanager
import tunnels.base
from libs.events import broadcast
from libs.packets import make_packet
from libs.construct import *
connections = {}
class Tunnel(tunnels.base.Tunnel):
'''UDP Tunnel class. No difference because UDP is simple.'''
def __init__(self, node):
self.connection = Connection(node)
def connect(self):
pass # No need to SYN with UDP
def disconnect(self):
self.connection.disconnect()
def send(self, message):
self.connection.send(message)
class Connection(tunnels.base.Connection):
'''UDP "connection" to a peer'''
def __init__(self, node): # TODO switch to a global node class
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.connect((node.ip, node.port))
self.data = ""
self.packages = {}
#handshake is ended in friends.handle_packets
def send(self, message):
broadcast('logthis', 'Sending: ' + message, level = 0)
self.sock.send(message)
def disconnect(self):
'''Do nothing, UDP does not need to close any connections.'''
pass
class Listener(libs.threadmanager.Thread):
'''Listen for UDP connections on our port'''
def __init__(self, port=1337):
super(Listener, self).__init__()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(('', port)) # TODO: bind other addresses
self.sock.setblocking(False)
def run(self):
while not self._stop.isSet():
try:
data = self.sock.recvfrom(4096)
ip = data[1][0]
friend = libs.friends.get_friend_by_ip(ip)
friend.connection = self.sock
friend.data += data[0] # Send data to the Friend object
broadcast('logthis', 'UDP recv: %s' % data[0], level = 0)
friend.parse_packets()
friend.connection = self.sock
except socket.error as error:
if error.errno == 11: # No new messages
time.sleep(1)
except AttributeError as error:
broadcast('logthis', 'Got message from an unknown IP address.')
# TODO: how to handle this - maybe they are using a dynamic IP
# address and they really are a friend.
def start():
listener = Listener()
listener.start()
libs.threadmanager.register(listener)
|