Advertisement
NaroxEG

Untitled

Jul 21st, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.45 KB | None | 0 0
  1. import os
  2. import socket
  3. import threading
  4. from Crypto.Cipher import AES
  5. import requests
  6.  
  7. # Define AES encryption parameters
  8. key = b"TheNeuralNineKey"
  9. nonce = b"TheNeuralNineNce"
  10. cipher = AES.new(key, AES.MODE_EAX, nonce)
  11.  
  12. PORT = 4466
  13. SIZE = 4096
  14. FORMAT = "utf-8"
  15. DATA_PATH = "device_data"
  16.  
  17. def get_public_ip():
  18. try:
  19. response = requests.get('https://api.ipify.org')
  20. return response.text
  21. except:
  22. return None
  23.  
  24. PUBLIC_IP = get_public_ip()
  25.  
  26. def handle_connection(conn, addr):
  27. print(f"[New connection] {addr} connected")
  28. conn.send("ok@Welcome to the file transfer system".encode(FORMAT))
  29.  
  30. while True:
  31. data = conn.recv(SIZE).decode(FORMAT)
  32. cmd, *cmd_data = data.split("@")
  33.  
  34. if cmd == "HELP":
  35. send_data = "ok@"
  36. send_data += "LIST: List all files\n"
  37. send_data += "SEND <filename>: Send a file\n"
  38. send_data += "RECEIVE <filename>: Receive a file\n"
  39. send_data += "DISCONNECT: Disconnect from the system\n"
  40. send_data += "HELP: List all commands"
  41. conn.send(send_data.encode(FORMAT))
  42.  
  43. elif cmd == "DISCONNECT":
  44. break
  45.  
  46. elif cmd == "LIST":
  47. files = os.listdir(DATA_PATH)
  48. send_data = "ok@"
  49. if not files:
  50. send_data += "The directory is empty"
  51. else:
  52. send_data += "\n".join(files)
  53. conn.send(send_data.encode(FORMAT))
  54.  
  55. elif cmd == "SEND":
  56. filename = cmd_data[0]
  57. filepath = os.path.join(DATA_PATH, filename)
  58.  
  59. if not os.path.exists(filepath):
  60. conn.send("ERROR@File not found".encode(FORMAT))
  61. continue
  62.  
  63. with open(filepath, "rb") as f:
  64. file_data = f.read()
  65.  
  66. encrypted_data = cipher.encrypt(file_data)
  67. file_size = len(encrypted_data)
  68.  
  69. conn.send(f"READY@{file_size}".encode(FORMAT))
  70. conn.recv(SIZE) # Wait for receiver's acknowledgment
  71.  
  72. conn.sendall(encrypted_data)
  73.  
  74. conn.recv(SIZE) # Wait for receiver's confirmation
  75.  
  76. elif cmd == "RECEIVE":
  77. filename = cmd_data[0]
  78. file_size = int(cmd_data[1])
  79.  
  80. filepath = os.path.join(DATA_PATH, filename)
  81.  
  82. conn.send("READY".encode(FORMAT))
  83.  
  84. encrypted_data = b""
  85. remaining = file_size
  86. while remaining:
  87. chunk = conn.recv(min(SIZE, remaining))
  88. encrypted_data += chunk
  89. remaining -= len(chunk)
  90.  
  91. decrypted_data = cipher.decrypt(encrypted_data)
  92.  
  93. with open(filepath, "wb") as f:
  94. f.write(decrypted_data)
  95.  
  96. send_data = "ok@File received successfully"
  97. conn.send(send_data.encode(FORMAT))
  98.  
  99. print(f"[Disconnected] {addr} disconnected")
  100.  
  101. def start_server():
  102. print("[Starting] Server is starting")
  103. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  104. server.bind(('0.0.0.0', PORT))
  105. server.listen()
  106. print(f"[Listening] Server is listening on {PUBLIC_IP}:{PORT}")
  107. print("Make sure to configure port forwarding on your router for port", PORT)
  108.  
  109. while True:
  110. conn, addr = server.accept()
  111. thread = threading.Thread(target=handle_connection, args=(conn, addr))
  112. thread.start()
  113.  
  114. def connect_to_peer():
  115. peer_ip = input("Enter peer IP address: ")
  116. peer_port = int(input("Enter peer port: "))
  117. peer_addr = (peer_ip, peer_port)
  118.  
  119. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  120. client.connect(peer_addr)
  121.  
  122. while True:
  123. data = client.recv(SIZE).decode(FORMAT)
  124. cmd, msg = data.split("@", 1)
  125.  
  126. if cmd == "ok":
  127. print(f"{msg}")
  128. elif cmd == "ERROR":
  129. print(f"Error: {msg}")
  130. elif cmd == "READY":
  131. file_size = int(msg)
  132. client.send("ACK".encode(FORMAT))
  133.  
  134. encrypted_data = b""
  135. remaining = file_size
  136. while remaining:
  137. chunk = client.recv(min(SIZE, remaining))
  138. encrypted_data += chunk
  139. remaining -= len(chunk)
  140.  
  141. decrypted_data = cipher.decrypt(encrypted_data)
  142. filename = input("Enter the filename to save: ")
  143. filepath = os.path.join(DATA_PATH, filename)
  144. with open(filepath, "wb") as f:
  145. f.write(decrypted_data)
  146. print(f"File {filename} received successfully.")
  147. client.send("DONE".encode(FORMAT))
  148.  
  149. user_input = input("> ")
  150. user_data = user_input.split(" ")
  151. cmd = user_data[0]
  152.  
  153. if cmd == "HELP":
  154. client.send(cmd.encode(FORMAT))
  155.  
  156. elif cmd == "DISCONNECT":
  157. client.send(cmd.encode(FORMAT))
  158. break
  159.  
  160. elif cmd == "LIST":
  161. client.send(cmd.encode(FORMAT))
  162.  
  163. elif cmd == "SEND":
  164. filename = user_data[1]
  165. filepath = os.path.join(DATA_PATH, filename)
  166.  
  167. if not os.path.exists(filepath):
  168. print("Error: File not found")
  169. continue
  170.  
  171. with open(filepath, "rb") as f:
  172. file_data = f.read()
  173.  
  174. encrypted_data = cipher.encrypt(file_data)
  175. file_size = len(encrypted_data)
  176.  
  177. client.send(f"RECEIVE@{filename}@{file_size}".encode(FORMAT))
  178. client.recv(SIZE) # Wait for peer's READY signal
  179.  
  180. client.sendall(encrypted_data)
  181.  
  182. elif cmd == "RECEIVE":
  183. filename = user_data[1]
  184. client.send(f"SEND@{filename}".encode(FORMAT))
  185.  
  186. print("Disconnected from the peer")
  187. client.close()
  188.  
  189. def main():
  190. os.makedirs(DATA_PATH, exist_ok=True)
  191. print(f"Your public IP address is: {PUBLIC_IP}")
  192. mode = input("Enter 's' for server mode or 'c' for client mode: ")
  193. if mode.lower() == 's':
  194. start_server()
  195. elif mode.lower() == 'c':
  196. connect_to_peer()
  197. else:
  198. print("Invalid mode. Exiting.")
  199.  
  200. if __name__ == "__main__":
  201. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement