basic_protocols.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. def get_desc(self):
  80. """
  81. This function can be overridden.
  82. """
  83. #
  84. return None
  85. #
  86. #
  87. class FakeProxyProtocol(Protocol):
  88. def __init__(self, socket, addr_port):
  89. self.socket = socket
  90. self.addr_port = addr_port
  91. #
  92. self.states = enum.Enum('PROXY_STATES', 'READY_TO_BEGIN CONNECTING_TO_PROXY DONE')
  93. self.state = self.states.READY_TO_BEGIN
  94. #
  95. self.protocol_helper = None
  96. #
  97. def _run_iteration(self):
  98. if self.state is self.states.READY_TO_BEGIN:
  99. self.protocol_helper = ProtocolHelper()
  100. host, port = self.addr_port
  101. addr = socket.inet_aton(host)[::-1]
  102. self.protocol_helper.set_buffer(addr+struct.pack('!H', port))
  103. self.state = self.states.CONNECTING_TO_PROXY
  104. #
  105. if self.state is self.states.CONNECTING_TO_PROXY:
  106. if self.protocol_helper.send(self.socket):
  107. self.protocol_helper = ProtocolHelper()
  108. self.state = self.states.DONE
  109. #
  110. #
  111. if self.state is self.states.DONE:
  112. return True
  113. #
  114. return False
  115. #
  116. #
  117. class ChainedProtocol(Protocol):
  118. def __init__(self, protocols):
  119. self.protocols = protocols
  120. self.current_protocol = 0
  121. #
  122. self.states = enum.Enum('CHAIN_STATES', 'READY_TO_BEGIN RUNNING DONE')
  123. self.state = self.states.READY_TO_BEGIN
  124. #
  125. def _run_iteration(self):
  126. if self.state is self.states.READY_TO_BEGIN:
  127. self.state = self.states.RUNNING
  128. #
  129. if self.state is self.states.RUNNING:
  130. if self.protocols[self.current_protocol] is None or self.protocols[self.current_protocol].run():
  131. self.current_protocol += 1
  132. #
  133. if self.current_protocol >= len(self.protocols):
  134. self.state = self.states.DONE
  135. #
  136. #
  137. if self.state is self.states.DONE:
  138. return True
  139. #
  140. return False
  141. #
  142. #
  143. class Socks4Protocol(Protocol):
  144. def __init__(self, socket, addr_port, username=None):
  145. self.socket = socket
  146. self.addr_port = addr_port
  147. self.username = username
  148. #
  149. self.states = enum.Enum('SOCKS_4_STATES', 'READY_TO_BEGIN CONNECTING_TO_PROXY WAITING_FOR_PROXY DONE')
  150. self.state = self.states.READY_TO_BEGIN
  151. #
  152. self.protocol_helper = None
  153. #
  154. def _run_iteration(self):
  155. if self.state is self.states.READY_TO_BEGIN:
  156. self.protocol_helper = ProtocolHelper()
  157. self.protocol_helper.set_buffer(self.socks_cmd(self.addr_port, self.username))
  158. self.state = self.states.CONNECTING_TO_PROXY
  159. #
  160. if self.state is self.states.CONNECTING_TO_PROXY:
  161. if self.protocol_helper.send(self.socket):
  162. self.protocol_helper = ProtocolHelper()
  163. self.state = self.states.WAITING_FOR_PROXY
  164. #logging.debug('Waiting for reply from proxy')
  165. #
  166. #
  167. if self.state is self.states.WAITING_FOR_PROXY:
  168. response_size = 8
  169. if self.protocol_helper.recv(self.socket, response_size):
  170. response = self.protocol_helper.get_buffer()
  171. if response[1] != 0x5a:
  172. raise ProtocolException('Could not connect to SOCKS proxy, msg: %x'%(response[1],))
  173. #
  174. self.state = self.states.DONE
  175. #
  176. #
  177. if self.state is self.states.DONE:
  178. return True
  179. #
  180. return False
  181. #
  182. def socks_cmd(self, addr_port, username=None):
  183. socks_version = 4
  184. command = 1
  185. dnsname = b''
  186. host, port = addr_port
  187. #
  188. try:
  189. username = bytes(username, 'utf8')
  190. except TypeError:
  191. pass
  192. #
  193. if username is None:
  194. username = b''
  195. elif b'\x00' in username:
  196. raise ProtocolException('Username cannot contain a NUL character.')
  197. #
  198. username = username+b'\x00'
  199. #
  200. try:
  201. addr = socket.inet_aton(host)
  202. except socket.error:
  203. addr = b'\x00\x00\x00\x01'
  204. dnsname = bytes(host, 'utf8')+b'\x00'
  205. #
  206. return struct.pack('!BBH', socks_version, command, port) + addr + username + dnsname
  207. #
  208. #
  209. class PushDataProtocol(Protocol):
  210. def __init__(self, socket, total_bytes, send_buffer_len=None, use_acceleration=None, push_start_cb=None, push_done_cb=None):
  211. if send_buffer_len is None:
  212. send_buffer_len = 1024*512
  213. #
  214. if use_acceleration is None:
  215. use_acceleration = True
  216. #
  217. self.socket = socket
  218. self.total_bytes = total_bytes
  219. self.use_acceleration = use_acceleration
  220. self.push_start_cb = push_start_cb
  221. self.push_done_cb = push_done_cb
  222. #
  223. self.states = enum.Enum('PUSH_DATA_STATES', 'READY_TO_BEGIN SEND_INFO START_CALLBACK PUSH_DATA RECV_CONFIRMATION DONE_CALLBACK DONE')
  224. self.state = self.states.READY_TO_BEGIN
  225. #
  226. self.byte_buffer = os.urandom(send_buffer_len)
  227. self.bytes_written = 0
  228. self.protocol_helper = None
  229. #
  230. def _run_iteration(self):
  231. if self.state is self.states.READY_TO_BEGIN:
  232. info = self.total_bytes.to_bytes(8, byteorder='big', signed=False)
  233. info += len(self.byte_buffer).to_bytes(8, byteorder='big', signed=False)
  234. self.protocol_helper = ProtocolHelper()
  235. self.protocol_helper.set_buffer(info)
  236. self.state = self.states.SEND_INFO
  237. #
  238. if self.state is self.states.SEND_INFO:
  239. if self.protocol_helper.send(self.socket):
  240. self.state = self.states.START_CALLBACK
  241. #
  242. #
  243. if self.state is self.states.START_CALLBACK:
  244. if self.push_start_cb is not None:
  245. self.push_start_cb()
  246. #
  247. self.state = self.states.PUSH_DATA
  248. #
  249. if self.state is self.states.PUSH_DATA:
  250. if self.use_acceleration:
  251. ret_val = accelerated_functions.push_data(self.socket.fileno(), self.total_bytes, self.byte_buffer)
  252. if ret_val < 0:
  253. raise ProtocolException('Error while pushing data.')
  254. #
  255. self.bytes_written = self.total_bytes
  256. else:
  257. bytes_remaining = self.total_bytes-self.bytes_written
  258. data_size = min(len(self.byte_buffer), bytes_remaining)
  259. if data_size != len(self.byte_buffer):
  260. data = self.byte_buffer[:data_size]
  261. else:
  262. data = self.byte_buffer
  263. # don't make a copy of the byte string each time if we don't need to
  264. #
  265. n = self.socket.send(data)
  266. self.bytes_written += n
  267. #
  268. if self.bytes_written == self.total_bytes:
  269. # finished sending the data
  270. logging.debug('Finished sending the data (%d bytes).', self.bytes_written)
  271. self.protocol_helper = ProtocolHelper()
  272. self.state = self.states.RECV_CONFIRMATION
  273. #
  274. #
  275. if self.state is self.states.RECV_CONFIRMATION:
  276. response_size = 8
  277. if self.protocol_helper.recv(self.socket, response_size):
  278. response = self.protocol_helper.get_buffer()
  279. if response != b'RECEIVED':
  280. raise ProtocolException('Did not receive the expected message: {}'.format(response))
  281. #
  282. self.state = self.states.DONE_CALLBACK
  283. #
  284. #
  285. if self.state is self.states.DONE_CALLBACK:
  286. if self.push_done_cb is not None:
  287. self.push_done_cb()
  288. #
  289. self.state = self.states.DONE
  290. #
  291. if self.state is self.states.DONE:
  292. return True
  293. #
  294. return False
  295. #
  296. #
  297. class PullDataProtocol(Protocol):
  298. def __init__(self, socket, use_acceleration=None):
  299. if use_acceleration is None:
  300. use_acceleration = True
  301. #
  302. self.socket = socket
  303. self.use_acceleration = use_acceleration
  304. #
  305. self.states = enum.Enum('PULL_DATA_STATES', 'READY_TO_BEGIN RECV_INFO PULL_DATA SEND_CONFIRMATION DONE')
  306. self.state = self.states.READY_TO_BEGIN
  307. #
  308. self.data_size = None
  309. self.recv_buffer_len = None
  310. self.bytes_read = 0
  311. self.protocol_helper = None
  312. self.time_of_first_byte = None
  313. self.time_of_last_byte = None
  314. #self.byte_counter = None
  315. #self.byte_counter_start_time = None
  316. self.deltas = None
  317. #
  318. def _run_iteration(self):
  319. if self.state is self.states.READY_TO_BEGIN:
  320. self.protocol_helper = ProtocolHelper()
  321. self.state = self.states.RECV_INFO
  322. #
  323. if self.state is self.states.RECV_INFO:
  324. info_size = 16
  325. if self.protocol_helper.recv(self.socket, info_size):
  326. response = self.protocol_helper.get_buffer()
  327. self.data_size = int.from_bytes(response[0:8], byteorder='big', signed=False)
  328. self.recv_buffer_len = int.from_bytes(response[8:16], byteorder='big', signed=False)
  329. assert(self.recv_buffer_len <= 10*1024*1024)
  330. # don't use a buffer size larget than 10 MiB to avoid using up all memory
  331. self.state = self.states.PULL_DATA
  332. #
  333. #
  334. if self.state is self.states.PULL_DATA:
  335. if self.use_acceleration:
  336. #(ret_val, time_of_first_byte, time_of_last_byte, byte_counter, byte_counter_start_time) = accelerated_functions.pull_data(self.socket.fileno(), self.data_size, self.recv_buffer_len)
  337. (ret_val, time_of_first_byte, time_of_last_byte, deltas) = accelerated_functions.pull_data(self.socket.fileno(), self.data_size, self.recv_buffer_len)
  338. if ret_val < 0:
  339. raise ProtocolException('Error while pulling data.')
  340. #
  341. #if sum(byte_counter) != self.data_size:
  342. if sum(deltas['bytes']) != self.data_size:
  343. logging.warning('Lost some history data ({} != {}).'.format(sum(deltas['bytes']), self.data_size))
  344. #
  345. self.bytes_read = self.data_size
  346. self.time_of_first_byte = time_of_first_byte
  347. self.time_of_last_byte = time_of_last_byte
  348. #self.byte_counter = byte_counter
  349. #self.byte_counter_start_time = byte_counter_start_time
  350. self.deltas = deltas
  351. else:
  352. bytes_remaining = self.data_size-self.bytes_read
  353. block_size = min(self.recv_buffer_len, bytes_remaining)
  354. #
  355. data = self.socket.recv(block_size)
  356. #
  357. if len(data) == 0:
  358. raise ProtocolException('The socket was closed.')
  359. #
  360. self.bytes_read += len(data)
  361. #
  362. if self.bytes_read != 0 and self.time_of_first_byte is None:
  363. self.time_of_first_byte = time.time()
  364. #
  365. if self.bytes_read == self.data_size and self.time_of_last_byte is None:
  366. self.time_of_last_byte = time.time()
  367. #
  368. #
  369. if self.bytes_read == self.data_size:
  370. # finished receiving the data
  371. logging.debug('Finished receiving the data.')
  372. self.protocol_helper = ProtocolHelper()
  373. self.protocol_helper.set_buffer(b'RECEIVED')
  374. self.state = self.states.SEND_CONFIRMATION
  375. #
  376. #
  377. if self.state is self.states.SEND_CONFIRMATION:
  378. if self.protocol_helper.send(self.socket):
  379. self.state = self.states.DONE
  380. #
  381. #
  382. if self.state is self.states.DONE:
  383. return True
  384. #
  385. return False
  386. #
  387. def calc_transfer_rate(self):
  388. """ Returns bytes/s. """
  389. assert self.data_size is not None and self.time_of_first_byte is not None and self.time_of_last_byte is not None
  390. try:
  391. return self.data_size/(self.time_of_last_byte-self.time_of_first_byte)
  392. except ZeroDivisionError:
  393. return float('nan')
  394. #
  395. #
  396. #
  397. class SendDataProtocol(Protocol):
  398. def __init__(self, socket, data):
  399. self.socket = socket
  400. self.send_data = data
  401. #
  402. self.states = enum.Enum('SEND_DATA_STATES', 'READY_TO_BEGIN SEND_INFO SEND_DATA RECV_CONFIRMATION DONE')
  403. self.state = self.states.READY_TO_BEGIN
  404. #
  405. self.protocol_helper = None
  406. #
  407. def _run_iteration(self):
  408. if self.state is self.states.READY_TO_BEGIN:
  409. info_size = 20
  410. info = len(self.send_data).to_bytes(info_size, byteorder='big', signed=False)
  411. self.protocol_helper = ProtocolHelper()
  412. self.protocol_helper.set_buffer(info)
  413. self.state = self.states.SEND_INFO
  414. #
  415. if self.state is self.states.SEND_INFO:
  416. if self.protocol_helper.send(self.socket):
  417. self.protocol_helper = ProtocolHelper()
  418. if len(self.send_data) > 0:
  419. self.protocol_helper.set_buffer(self.send_data)
  420. self.state = self.states.SEND_DATA
  421. else:
  422. self.state = self.states.RECV_CONFIRMATION
  423. #
  424. #
  425. #
  426. if self.state is self.states.SEND_DATA:
  427. if self.protocol_helper.send(self.socket):
  428. self.protocol_helper = ProtocolHelper()
  429. self.state = self.states.RECV_CONFIRMATION
  430. #
  431. #
  432. if self.state is self.states.RECV_CONFIRMATION:
  433. response_size = 8
  434. if self.protocol_helper.recv(self.socket, response_size):
  435. response = self.protocol_helper.get_buffer()
  436. if response != b'RECEIVED':
  437. raise ProtocolException('Did not receive the expected message: {}'.format(response))
  438. #
  439. self.state = self.states.DONE
  440. #
  441. #
  442. if self.state is self.states.DONE:
  443. return True
  444. #
  445. return False
  446. #
  447. #
  448. class ReceiveDataProtocol(Protocol):
  449. def __init__(self, socket):
  450. self.socket = socket
  451. #
  452. self.states = enum.Enum('RECV_DATA_STATES', 'READY_TO_BEGIN RECV_INFO RECV_DATA SEND_CONFIRMATION DONE')
  453. self.state = self.states.READY_TO_BEGIN
  454. #
  455. self.protocol_helper = None
  456. self.data_size = None
  457. self.received_data = None
  458. #
  459. def _run_iteration(self):
  460. if self.state is self.states.READY_TO_BEGIN:
  461. self.protocol_helper = ProtocolHelper()
  462. self.state = self.states.RECV_INFO
  463. #
  464. if self.state is self.states.RECV_INFO:
  465. info_size = 20
  466. if self.protocol_helper.recv(self.socket, info_size):
  467. response = self.protocol_helper.get_buffer()
  468. self.data_size = int.from_bytes(response, byteorder='big', signed=False)
  469. self.protocol_helper = ProtocolHelper()
  470. if self.data_size > 0:
  471. self.state = self.states.RECV_DATA
  472. else:
  473. self.received_data = b''
  474. self.protocol_helper.set_buffer(b'RECEIVED')
  475. self.state = self.states.SEND_CONFIRMATION
  476. #
  477. #
  478. #
  479. if self.state is self.states.RECV_DATA:
  480. if self.protocol_helper.recv(self.socket, self.data_size):
  481. response = self.protocol_helper.get_buffer()
  482. self.received_data = response
  483. self.protocol_helper = ProtocolHelper()
  484. self.protocol_helper.set_buffer(b'RECEIVED')
  485. self.state = self.states.SEND_CONFIRMATION
  486. #
  487. #
  488. if self.state is self.states.SEND_CONFIRMATION:
  489. if self.protocol_helper.send(self.socket):
  490. self.state = self.states.DONE
  491. #
  492. #
  493. if self.state is self.states.DONE:
  494. return True
  495. #
  496. return False
  497. #
  498. #
  499. class ServerListener():
  500. def __init__(self, bind_endpoint, accept_callback):
  501. self.callback = accept_callback
  502. #
  503. self.s = socket.socket()
  504. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  505. self.s.setblocking(0)
  506. self.s.bind(bind_endpoint)
  507. self.s.listen(1000)
  508. #
  509. def accept(self, block=True):
  510. if block:
  511. (readable, _, _) = select.select([self.s], [], [])
  512. else:
  513. readable = [self.s]
  514. #
  515. try:
  516. (newsock, endpoint) = self.s.accept()
  517. logging.debug("New client from %s:%d (fd=%d)",
  518. endpoint[0], endpoint[1], newsock.fileno())
  519. self.callback(newsock)
  520. return True
  521. except BlockingIOError:
  522. return False
  523. #
  524. #
  525. def stop(self):
  526. self.s.shutdown(socket.SHUT_RDWR)
  527. # use 'shutdown' rather than 'close' since 'close' won't stop a blocking 'accept' call
  528. #
  529. #
  530. class SimpleClientConnectionProtocol(Protocol):
  531. def __init__(self, endpoint, total_bytes, data_generator=None, proxy=None, username=None):
  532. self.endpoint = endpoint
  533. self.data_generator = data_generator
  534. self.total_bytes = total_bytes
  535. self.proxy = proxy
  536. self.username = username
  537. #
  538. self.states = enum.Enum('CLIENT_CONN_STATES', 'READY_TO_BEGIN CONNECT_TO_PROXY PUSH_DATA DONE')
  539. self.state = self.states.READY_TO_BEGIN
  540. #
  541. self.socket = socket.socket()
  542. self.sub_protocol = None
  543. #
  544. if self.proxy is None:
  545. logging.debug('Socket %d connecting to endpoint %r...', self.socket.fileno(), self.endpoint)
  546. self.socket.connect(self.endpoint)
  547. else:
  548. logging.debug('Socket %d connecting to proxy %r...', self.socket.fileno(), self.proxy)
  549. self.socket.connect(self.proxy)
  550. #
  551. #
  552. def _run_iteration(self):
  553. if self.state is self.states.READY_TO_BEGIN:
  554. if self.proxy is None:
  555. self.sub_protocol = PushDataProtocol(self.socket, self.total_bytes, self.data_generator)
  556. self.state = self.states.PUSH_DATA
  557. else:
  558. self.sub_protocol = Socks4Protocol(self.socket, self.endpoint, username=self.username)
  559. self.state = self.states.CONNECT_TO_PROXY
  560. #
  561. #
  562. if self.state is self.states.CONNECT_TO_PROXY:
  563. if self.sub_protocol.run():
  564. self.sub_protocol = PushDataProtocol(self.socket, self.total_bytes, self.data_generator)
  565. self.state = self.states.PUSH_DATA
  566. #
  567. #
  568. if self.state is self.states.PUSH_DATA:
  569. if self.sub_protocol.run():
  570. self.state = self.states.DONE
  571. #
  572. #
  573. if self.state is self.states.DONE:
  574. return True
  575. #
  576. return False
  577. #
  578. #
  579. class SimpleServerConnectionProtocol(Protocol):
  580. def __init__(self, socket, conn_id, bandwidth_callback=None):
  581. self.socket = socket
  582. self.conn_id = conn_id
  583. self.bandwidth_callback = bandwidth_callback
  584. #
  585. self.states = enum.Enum('SERVER_CONN_STATES', 'READY_TO_BEGIN PULL_DATA DONE')
  586. self.state = self.states.READY_TO_BEGIN
  587. #
  588. self.sub_protocol = None
  589. #
  590. def _run_iteration(self):
  591. if self.state is self.states.READY_TO_BEGIN:
  592. self.sub_protocol = PullDataProtocol(self.socket)
  593. self.state = self.states.PULL_DATA
  594. #
  595. if self.state is self.states.PULL_DATA:
  596. if self.sub_protocol.run():
  597. if self.bandwidth_callback:
  598. self.bandwidth_callback(self.conn_id, self.sub_protocol.data_size, self.sub_protocol.calc_transfer_rate())
  599. #
  600. self.state = self.states.DONE
  601. #
  602. #
  603. if self.state is self.states.DONE:
  604. return True
  605. #
  606. return False
  607. #
  608. #
  609. if __name__ == '__main__':
  610. import sys
  611. logging.basicConfig(level=logging.DEBUG)
  612. #
  613. if sys.argv[1] == 'client':
  614. endpoint = ('127.0.0.1', 4747)
  615. #proxy = ('127.0.0.1', 9003)
  616. proxy = None
  617. username = bytes([x for x in os.urandom(12) if x != 0])
  618. #username = None
  619. data_MB = 4000
  620. #
  621. client = SimpleClientConnectionProtocol(endpoint, data_MB*2**20, proxy=proxy, username=username)
  622. client.run()
  623. elif sys.argv[1] == 'server':
  624. import multiprocessing
  625. import queue
  626. #
  627. endpoint = ('127.0.0.1', 4747)
  628. processes = []
  629. conn_counter = [0]
  630. #
  631. def bw_callback(conn_id, data_size, transfer_rate):
  632. logging.info('Avg Transferred (MB): %.4f', data_size/(1024**2))
  633. logging.info('Avg Transfer rate (MB/s): %.4f', transfer_rate/(1024**2))
  634. #
  635. def start_server_conn(socket, conn_id):
  636. server = SimpleServerConnectionProtocol(socket, conn_id, bandwidth_callback=bw_callback)
  637. try:
  638. server.run()
  639. except KeyboardInterrupt:
  640. socket.close()
  641. #
  642. #
  643. def accept_callback(socket):
  644. conn_id = conn_counter[0]
  645. conn_counter[0] += 1
  646. #
  647. p = multiprocessing.Process(target=start_server_conn, args=(socket, conn_id))
  648. processes.append(p)
  649. p.start()
  650. #
  651. l = ServerListener(endpoint, accept_callback)
  652. #
  653. try:
  654. while True:
  655. l.accept()
  656. #
  657. except KeyboardInterrupt:
  658. print()
  659. #
  660. for p in processes:
  661. p.join()
  662. #
  663. #
  664. #