-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp2p.py
141 lines (112 loc) · 4.27 KB
/
p2p.py
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import sys, textwrap, socketserver, string, readline, threading
from time import *
import getpass, os, subprocess
from pwn import *
from random import randrange
import json
class Service(socketserver.BaseRequestHandler):
def handle(self):
while True:
command = self.receive('Cmd: ').decode("utf-8")
#p = subprocess.Popen(command,
# shell=True, stdout=(subprocess.PIPE), stderr=(subprocess.PIPE))
#self.send(p.stdout.read())
if command != "":
to_send=command.split(",")
recive_message(myself,neighbors,to_send[1],to_send[0])
def send(self, string, newline=True):
if newline:
string = str(string) + '\n'
try:
self.request.sendall(bytes(string, 'utf-8'))
except:
pass
def receive(self, prompt='> '):
self.send(prompt, newline=False)
return self.request.recv(4096).strip()
class ThreadedService(socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler):
pass
###########################################################
def get_neighbors(neighbors):
return list(neighbors.keys())
def is_neighbor(neighbors,destination):
if destination in get_neighbors(neighbors):
return True
return False
def is_destination(myself,destination):
if myself == destination:
return True
return False
def send_message(neighbors,destination, msg="test"):
if is_neighbor(neighbors,destination):
#print("Si es vecino :D")
#print("Enviando paquete a",destination,"con IP:",neighbors[destination][0])
conn = remote(neighbors[destination][0], neighbors[destination][1])
conn.send(msg+","+destination)
conn.close()
else:
#print("Pues no es su vecino :c")
n_neighbors=len(get_neighbors(neighbors))
#print(list(get_neighbors(neighbors)))
forward = get_neighbors(neighbors)[randrange(n_neighbors)]
#print("Se eligió a",forward, "con IP", neighbors[forward][0], "Pero el destinatario sigue siendo", destination)
conn = remote(neighbors[forward][0], neighbors[forward][1])
conn.send(msg+","+destination)
conn.close()
def recive_message(myself,neighbors,destination,msg="test"):
if is_destination(myself,destination):
#print("Yo soy, recibido manito uwu")
print("-"*20)
print("Mensaje recibido")
print("-"*20)
print("| "+msg)
print("-"*20)
else:
#print("No soy yo, enviando mensaje a otro")
send_message(neighbors,destination,msg)
def import_profile(file):
neighbors_t={}
f = open(file+".pf", "r")
linea = f.read()
result = json.loads(linea, strict=False)
myself_t = result["myself"]
port_t = int(result["port"])
name_n = list(result["neighbors"].keys())
for i in name_n:
neighbors_t[i]=tuple(result["neighbors"][i])
return myself_t,neighbors_t,port_t
###########################################################
def main():
global myself,neighbors
#file=input("Enter file profile: ")
if len(sys.argv) != 2:
print("Uso: python script.py <nombre_del_archivo>")
sys.exit(1)
nombre_del_archivo = sys.argv[1]
myself,neighbors,port = import_profile('profiles/'+nombre_del_archivo)
host = '0.0.0.0'
print('Starting server...')
service = Service
server = ThreadedService((host, port), service)
server.allow_reuse_address = True
server_thread = threading.Thread(target=(server.serve_forever))
server_thread.daemon = True
server_thread.start()
print('Server started on ' + str(server.server_address) + '!')
print("I am",myself)
for i in neighbors.keys():
print("My neighbor is", i)
while True:
print("-"*20)
print("¿Que desea hacer?")
print("1) Enviar Un mensaje")
print("0) Exit")
r=input("> ")
if r == '1':
dst=input("Para quien?: ")
txt=input("Que le quieres decir?: ")
send_message(neighbors,dst, msg=txt)
elif r == '0':
break
if __name__ == '__main__':
main()