basic_protocols.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. #!/usr/bin/python3
  2. #
  3. import socket
  4. import struct
  5. import logging
  6. import time
  7. import enum
  8. import select
  9. import os
  10. #
  11. import accelerated_functions
  12. #
  13. class ProtocolException(Exception):
  14. pass
  15. #
  16. class ProtocolHelper():
  17. def __init__(self):
  18. self._buffer = b''
  19. #
  20. def set_buffer(self, data):
  21. """
  22. Set the buffer contents to the data that you wish to send.
  23. """
  24. #
  25. self._buffer = data
  26. #
  27. def get_buffer(self):
  28. return self._buffer
  29. #
  30. def recv(self, socket, num_bytes):
  31. """
  32. Try to fill up the buffer to a max of 'num_bytes'. If the buffer is filled,
  33. return True, otherwise return False.
  34. """
  35. #
  36. data = socket.recv(num_bytes-len(self._buffer))
  37. #
  38. if len(data) == 0:
  39. raise ProtocolException('The socket was closed.')
  40. #
  41. self._buffer += data
  42. if len(self._buffer) == num_bytes:
  43. return True
  44. #
  45. return False
  46. #
  47. def send(self, socket):
  48. """
  49. Try to send the remainder of the buffer. If the entire buffer has been sent,
  50. return True, otherwise return False.
  51. """
  52. #
  53. n = socket.send(self._buffer)
  54. self._buffer = self._buffer[n:]
  55. if len(self._buffer) == 0:
  56. return True
  57. #
  58. return False
  59. #
  60. #
  61. class Protocol():
  62. def _run_iteration(self):
  63. """
  64. This function should be overridden. It runs a single iteration of the protocol.
  65. """
  66. #
  67. pass
  68. #
  69. def run(self):
  70. while True:
  71. finished = self._run_iteration()
  72. #
  73. if finished:
  74. # protocol is done
  75. return True
  76. #
  77. #
  78. #
  79. #
  80. class ChainedProtocol(Protocol):
  81. def __init__(self, protocols):
  82. self.protocols = protocols
  83. self.current_protocol = 0
  84. #
  85. self.states = enum.Enum('CHAIN_STATES', 'READY_TO_BEGIN RUNNING DONE')
  86. self.state = self.states.READY_TO_BEGIN
  87. #
  88. def _run_iteration(self):
  89. if self.state is self.states.READY_TO_BEGIN:
  90. self.state = self.states.RUNNING
  91. #
  92. if self.state is self.states.RUNNING:
  93. if self.protocols[self.current_protocol] is None or self.protocols[self.current_protocol].run():
  94. self.current_protocol += 1
  95. #
  96. if self.current_protocol >= len(self.protocols):
  97. self.state = self.states.DONE
  98. #
  99. #
  100. if self.state is self.states.DONE:
  101. return True
  102. #
  103. return False
  104. #
  105. #
  106. class Socks4Protocol(Protocol):
  107. def __init__(self, socket, addr_port, username=None):
  108. self.socket = socket
  109. self.addr_port = addr_port
  110. self.username = username
  111. #
  112. self.states = enum.Enum('SOCKS_4_STATES', 'READY_TO_BEGIN CONNECTING_TO_PROXY WAITING_FOR_PROXY DONE')
  113. self.state = self.states.READY_TO_BEGIN
  114. #
  115. self.protocol_helper = None
  116. #
  117. def _run_iteration(self):
  118. if self.state is self.states.READY_TO_BEGIN:
  119. self.protocol_helper = ProtocolHelper()
  120. self.protocol_helper.set_buffer(self.socks_cmd(self.addr_port, self.username))
  121. self.state = self.states.CONNECTING_TO_PROXY
  122. #
  123. if self.state is self.states.CONNECTING_TO_PROXY:
  124. if self.protocol_helper.send(self.socket):
  125. self.protocol_helper = ProtocolHelper()
  126. self.state = self.states.WAITING_FOR_PROXY
  127. #logging.debug('Waiting for reply from proxy')
  128. #
  129. #
  130. if self.state is self.states.WAITING_FOR_PROXY:
  131. response_size = 8
  132. if self.protocol_helper.recv(self.socket, response_size):
  133. response = self.protocol_helper.get_buffer()
  134. if response[1] != 0x5a:
  135. raise ProtocolException('Could not connect to SOCKS proxy, msg: %x'%(response[1],))
  136. #
  137. self.state = self.states.DONE
  138. #
  139. #
  140. if self.state is self.states.DONE:
  141. return True
  142. #
  143. return False
  144. #
  145. def socks_cmd(self, addr_port, username=None):
  146. socks_version = 4
  147. command = 1
  148. dnsname = b''
  149. host, port = addr_port
  150. #
  151. try:
  152. username = bytes(username, 'utf8')
  153. except TypeError:
  154. pass
  155. #
  156. if username is None:
  157. username = b''
  158. elif b'\x00' in username:
  159. raise ProtocolException('Username cannot contain a NUL character.')
  160. #
  161. username = username+b'\x00'
  162. #
  163. try:
  164. addr = socket.inet_aton(host)
  165. except socket.error:
  166. addr = b'\x00\x00\x00\x01'
  167. dnsname = bytes(host, 'utf8')+b'\x00'
  168. #
  169. return struct.pack('!BBH', socks_version, command, port) + addr + username + dnsname
  170. #
  171. #
  172. class PushDataProtocol(Protocol):
  173. def __init__(self, socket, total_bytes, send_buffer_len=None, use_acceleration=None):
  174. if send_buffer_len is None:
  175. send_buffer_len = 1024*512
  176. #
  177. if use_acceleration is None:
  178. use_acceleration = True
  179. #
  180. self.socket = socket
  181. self.total_bytes = total_bytes
  182. self.use_acceleration = use_acceleration
  183. #
  184. self.states = enum.Enum('PUSH_DATA_STATES', 'READY_TO_BEGIN SEND_INFO PUSH_DATA RECV_CONFIRMATION DONE')
  185. self.state = self.states.READY_TO_BEGIN
  186. #
  187. self.byte_buffer = os.urandom(send_buffer_len)
  188. self.bytes_written = 0
  189. self.protocol_helper = None
  190. #
  191. def _run_iteration(self):
  192. if self.state is self.states.READY_TO_BEGIN:
  193. info = self.total_bytes.to_bytes(8, byteorder='big', signed=False)
  194. info += len(self.byte_buffer).to_bytes(8, byteorder='big', signed=False)
  195. self.protocol_helper = ProtocolHelper()
  196. self.protocol_helper.set_buffer(info)
  197. self.state = self.states.SEND_INFO
  198. #
  199. if self.state is self.states.SEND_INFO:
  200. if self.protocol_helper.send(self.socket):
  201. self.state = self.states.PUSH_DATA
  202. #
  203. #
  204. if self.state is self.states.PUSH_DATA:
  205. if self.use_acceleration:
  206. ret_val = accelerated_functions.push_data(self.socket.fileno(), self.total_bytes, self.byte_buffer)
  207. if ret_val < 0:
  208. raise ProtocolException('Error while pushing data.')
  209. #
  210. self.bytes_written = self.total_bytes
  211. else:
  212. bytes_remaining = self.total_bytes-self.bytes_written
  213. data_size = min(len(self.byte_buffer), bytes_remaining)
  214. if data_size != len(self.byte_buffer):
  215. data = self.byte_buffer[:data_size]
  216. else:
  217. data = self.byte_buffer
  218. # don't make a copy of the byte string each time if we don't need to
  219. #
  220. n = self.socket.send(data)
  221. self.bytes_written += n
  222. #
  223. if self.bytes_written == self.total_bytes:
  224. # finished sending the data
  225. logging.debug('Finished sending the data (%d bytes).', self.bytes_written)
  226. self.protocol_helper = ProtocolHelper()
  227. self.state = self.states.RECV_CONFIRMATION
  228. #
  229. #
  230. if self.state is self.states.RECV_CONFIRMATION:
  231. response_size = 8
  232. if self.protocol_helper.recv(self.socket, response_size):
  233. response = self.protocol_helper.get_buffer()
  234. if response != b'RECEIVED':
  235. raise ProtocolException('Did not receive the expected message: {}'.format(response))
  236. #
  237. self.state = self.states.DONE
  238. #
  239. #
  240. if self.state is self.states.DONE:
  241. return True
  242. #
  243. return False
  244. #
  245. #
  246. class PullDataProtocol(Protocol):
  247. def __init__(self, socket, use_acceleration=None):
  248. if use_acceleration is None:
  249. use_acceleration = True
  250. #
  251. self.socket = socket
  252. self.use_acceleration = use_acceleration
  253. #
  254. self.states = enum.Enum('PULL_DATA_STATES', 'READY_TO_BEGIN RECV_INFO PULL_DATA SEND_CONFIRMATION DONE')
  255. self.state = self.states.READY_TO_BEGIN
  256. #
  257. self.data_size = None
  258. self.recv_buffer_len = None
  259. self.bytes_read = 0
  260. self.protocol_helper = None
  261. self._time_of_first_byte = None
  262. self.elapsed_time = None
  263. #
  264. def _run_iteration(self):
  265. if self.state is self.states.READY_TO_BEGIN:
  266. self.protocol_helper = ProtocolHelper()
  267. self.state = self.states.RECV_INFO
  268. #
  269. if self.state is self.states.RECV_INFO:
  270. info_size = 16
  271. if self.protocol_helper.recv(self.socket, info_size):
  272. response = self.protocol_helper.get_buffer()
  273. self.data_size = int.from_bytes(response[0:8], byteorder='big', signed=False)
  274. self.recv_buffer_len = int.from_bytes(response[8:16], byteorder='big', signed=False)
  275. self.state = self.states.PULL_DATA
  276. #
  277. #
  278. if self.state is self.states.PULL_DATA:
  279. if self.use_acceleration:
  280. (ret_val, elapsed_time) = accelerated_functions.pull_data(self.socket.fileno(), self.data_size, self.recv_buffer_len)
  281. if ret_val < 0:
  282. raise ProtocolException('Error while pulling data.')
  283. #
  284. self.bytes_read = self.data_size
  285. self.elapsed_time = elapsed_time
  286. else:
  287. bytes_remaining = self.data_size-self.bytes_read
  288. block_size = min(self.recv_buffer_len, bytes_remaining)
  289. #
  290. data = self.socket.recv(block_size)
  291. #
  292. if len(data) == 0:
  293. raise ProtocolException('The socket was closed.')
  294. #
  295. self.bytes_read += len(data)
  296. #
  297. if self.bytes_read != 0 and self._time_of_first_byte is None:
  298. self._time_of_first_byte = time.time()
  299. #
  300. if self.bytes_read == self.data_size and self.elapsed_time is None:
  301. self.elapsed_time = time.time()-self._time_of_first_byte
  302. #
  303. #
  304. if self.bytes_read == self.data_size:
  305. # finished receiving the data
  306. logging.debug('Finished receiving the data.')
  307. self.protocol_helper = ProtocolHelper()
  308. self.protocol_helper.set_buffer(b'RECEIVED')
  309. self.state = self.states.SEND_CONFIRMATION
  310. #
  311. #
  312. if self.state is self.states.SEND_CONFIRMATION:
  313. if self.protocol_helper.send(self.socket):
  314. self.state = self.states.DONE
  315. #
  316. #
  317. if self.state is self.states.DONE:
  318. return True
  319. #
  320. return False
  321. #
  322. def calc_transfer_rate(self):
  323. """ Returns bytes/s. """
  324. assert self.data_size is not None and self.elapsed_time is not None
  325. return self.data_size/self.elapsed_time
  326. #
  327. #
  328. class SendDataProtocol(Protocol):
  329. def __init__(self, socket, data):
  330. self.socket = socket
  331. self.send_data = data
  332. #
  333. self.states = enum.Enum('SEND_DATA_STATES', 'READY_TO_BEGIN SEND_INFO SEND_DATA RECV_CONFIRMATION DONE')
  334. self.state = self.states.READY_TO_BEGIN
  335. #
  336. self.protocol_helper = None
  337. #
  338. def _run_iteration(self):
  339. if self.state is self.states.READY_TO_BEGIN:
  340. info_size = 20
  341. info = len(self.send_data).to_bytes(info_size, byteorder='big', signed=False)
  342. self.protocol_helper = ProtocolHelper()
  343. self.protocol_helper.set_buffer(info)
  344. self.state = self.states.SEND_INFO
  345. #
  346. if self.state is self.states.SEND_INFO:
  347. if self.protocol_helper.send(self.socket):
  348. self.protocol_helper = ProtocolHelper()
  349. self.protocol_helper.set_buffer(self.send_data)
  350. self.state = self.states.SEND_DATA
  351. #
  352. #
  353. if self.state is self.states.SEND_DATA:
  354. if self.protocol_helper.send(self.socket):
  355. self.protocol_helper = ProtocolHelper()
  356. self.state = self.states.RECV_CONFIRMATION
  357. #
  358. #
  359. if self.state is self.states.RECV_CONFIRMATION:
  360. response_size = 8
  361. if self.protocol_helper.recv(self.socket, response_size):
  362. response = self.protocol_helper.get_buffer()
  363. if response != b'RECEIVED':
  364. raise ProtocolException('Did not receive the expected message: {}'.format(response))
  365. #
  366. self.state = self.states.DONE
  367. #
  368. #
  369. if self.state is self.states.DONE:
  370. return True
  371. #
  372. return False
  373. #
  374. #
  375. class ReceiveDataProtocol(Protocol):
  376. def __init__(self, socket):
  377. self.socket = socket
  378. #
  379. self.states = enum.Enum('RECV_DATA_STATES', 'READY_TO_BEGIN RECV_INFO RECV_DATA SEND_CONFIRMATION DONE')
  380. self.state = self.states.READY_TO_BEGIN
  381. #
  382. self.protocol_helper = None
  383. self.data_size = None
  384. self.received_data = None
  385. #
  386. def _run_iteration(self):
  387. if self.state is self.states.READY_TO_BEGIN:
  388. self.protocol_helper = ProtocolHelper()
  389. self.state = self.states.RECV_INFO
  390. #
  391. if self.state is self.states.RECV_INFO:
  392. info_size = 20
  393. if self.protocol_helper.recv(self.socket, info_size):
  394. response = self.protocol_helper.get_buffer()
  395. self.data_size = int.from_bytes(response, byteorder='big', signed=False)
  396. self.protocol_helper = ProtocolHelper()
  397. self.state = self.states.RECV_DATA
  398. #
  399. #
  400. if self.state is self.states.RECV_DATA:
  401. if self.protocol_helper.recv(self.socket, self.data_size):
  402. response = self.protocol_helper.get_buffer()
  403. self.received_data = response
  404. self.protocol_helper = ProtocolHelper()
  405. self.protocol_helper.set_buffer(b'RECEIVED')
  406. self.state = self.states.SEND_CONFIRMATION
  407. #
  408. #
  409. if self.state is self.states.SEND_CONFIRMATION:
  410. if self.protocol_helper.send(self.socket):
  411. self.state = self.states.DONE
  412. #
  413. #
  414. if self.state is self.states.DONE:
  415. return True
  416. #
  417. return False
  418. #
  419. #
  420. class ServerListener():
  421. def __init__(self, endpoint, accept_callback):
  422. self.callback = accept_callback
  423. #
  424. self.s = socket.socket()
  425. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  426. self.s.bind(endpoint)
  427. self.s.listen(0)
  428. #
  429. def accept(self):
  430. newsock, endpoint = self.s.accept()
  431. logging.debug("New client from %s:%d (fd=%d)",
  432. endpoint[0], endpoint[1], newsock.fileno())
  433. self.callback(newsock)
  434. #
  435. #
  436. class SimpleClientConnectionProtocol(Protocol):
  437. def __init__(self, endpoint, total_bytes, data_generator=None, proxy=None, username=None):
  438. self.endpoint = endpoint
  439. self.data_generator = data_generator
  440. self.total_bytes = total_bytes
  441. self.proxy = proxy
  442. self.username = username
  443. #
  444. self.states = enum.Enum('CLIENT_CONN_STATES', 'READY_TO_BEGIN CONNECT_TO_PROXY PUSH_DATA DONE')
  445. self.state = self.states.READY_TO_BEGIN
  446. #
  447. self.socket = socket.socket()
  448. self.sub_protocol = None
  449. #
  450. if self.proxy is None:
  451. logging.debug('Socket %d connecting to endpoint %r...', self.socket.fileno(), self.endpoint)
  452. self.socket.connect(self.endpoint)
  453. else:
  454. logging.debug('Socket %d connecting to proxy %r...', self.socket.fileno(), self.proxy)
  455. self.socket.connect(self.proxy)
  456. #
  457. #
  458. def _run_iteration(self):
  459. if self.state is self.states.READY_TO_BEGIN:
  460. if self.proxy is None:
  461. self.sub_protocol = PushDataProtocol(self.socket, self.total_bytes, self.data_generator)
  462. self.state = self.states.PUSH_DATA
  463. else:
  464. self.sub_protocol = Socks4Protocol(self.socket, self.endpoint, username=self.username)
  465. self.state = self.states.CONNECT_TO_PROXY
  466. #
  467. #
  468. if self.state is self.states.CONNECT_TO_PROXY:
  469. if self.sub_protocol.run():
  470. self.sub_protocol = PushDataProtocol(self.socket, self.total_bytes, self.data_generator)
  471. self.state = self.states.PUSH_DATA
  472. #
  473. #
  474. if self.state is self.states.PUSH_DATA:
  475. if self.sub_protocol.run():
  476. self.state = self.states.DONE
  477. #
  478. #
  479. if self.state is self.states.DONE:
  480. return True
  481. #
  482. return False
  483. #
  484. #
  485. class SimpleServerConnectionProtocol(Protocol):
  486. def __init__(self, socket, conn_id, bandwidth_callback=None):
  487. self.socket = socket
  488. self.conn_id = conn_id
  489. self.bandwidth_callback = bandwidth_callback
  490. #
  491. self.states = enum.Enum('SERVER_CONN_STATES', 'READY_TO_BEGIN PULL_DATA DONE')
  492. self.state = self.states.READY_TO_BEGIN
  493. #
  494. self.sub_protocol = None
  495. #
  496. def _run_iteration(self):
  497. if self.state is self.states.READY_TO_BEGIN:
  498. self.sub_protocol = PullDataProtocol(self.socket)
  499. self.state = self.states.PULL_DATA
  500. #
  501. if self.state is self.states.PULL_DATA:
  502. if self.sub_protocol.run():
  503. if self.bandwidth_callback:
  504. self.bandwidth_callback(self.conn_id, self.sub_protocol.data_size, self.sub_protocol.calc_transfer_rate())
  505. #
  506. self.state = self.states.DONE
  507. #
  508. #
  509. if self.state is self.states.DONE:
  510. return True
  511. #
  512. return False
  513. #
  514. #
  515. if __name__ == '__main__':
  516. import sys
  517. logging.basicConfig(level=logging.DEBUG)
  518. #
  519. if sys.argv[1] == 'client':
  520. endpoint = ('127.0.0.1', 4747)
  521. proxy = ('127.0.0.1', 9003)
  522. #proxy = None
  523. username = bytes([x for x in os.urandom(12) if x != 0])
  524. #username = None
  525. data_MB = 40
  526. #
  527. client = SimpleClientConnectionProtocol(endpoint, data_MB*2**20, proxy=proxy, username=username)
  528. client.run()
  529. elif sys.argv[1] == 'server':
  530. import multiprocessing
  531. import queue
  532. #
  533. endpoint = ('127.0.0.1', 4747)
  534. processes = []
  535. conn_counter = [0]
  536. #
  537. def bw_callback(conn_id, data_size, transfer_rate):
  538. logging.info('Avg Transferred (MB): %.4f', data_size/(1024**2))
  539. logging.info('Avg Transfer rate (MB/s): %.4f', transfer_rate/(1024**2))
  540. #
  541. def start_server_conn(socket, conn_id):
  542. server = SimpleServerConnectionProtocol(socket, conn_id, bandwidth_callback=bw_callback)
  543. try:
  544. server.run()
  545. except KeyboardInterrupt:
  546. socket.close()
  547. #
  548. #
  549. def accept_callback(socket):
  550. conn_id = conn_counter[0]
  551. conn_counter[0] += 1
  552. #
  553. p = multiprocessing.Process(target=start_server_conn, args=(socket, conn_id))
  554. processes.append(p)
  555. p.start()
  556. #
  557. l = ServerListener(endpoint, accept_callback)
  558. #
  559. try:
  560. while True:
  561. l.accept()
  562. #
  563. except KeyboardInterrupt:
  564. print()
  565. #
  566. for p in processes:
  567. p.join()
  568. #
  569. #
  570. #