__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. #!/usr/bin/env python3.5
  2. # Copyright 2017 Digital
  3. #
  4. # This file is part of DigiLib.
  5. #
  6. # DigiLib is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # DigiLib is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with DigiLib. If not, see <http://www.gnu.org/licenses/>.
  18. import atexit
  19. import logging
  20. import logging.handlers
  21. import os
  22. import queue
  23. import select
  24. import socket
  25. import sys
  26. import threading
  27. import time
  28. import traceback
  29. import blinker
  30. import curio
  31. import digilib.misc
  32. lclient = logging.getLogger(__name__+".client")
  33. lserver = logging.getLogger(__name__+".server")
  34. lschat = logging.getLogger(__name__+".server.chat")
  35. lcchat = logging.getLogger(__name__+".client.chat")
  36. _tasks = []
  37. class ConnHandlerBase(object):
  38. def __init__(self, socket, addr, server):
  39. self.status = "init"
  40. super(ConnHandlerBase, self).__init__()
  41. self.socket = socket
  42. self.addr = addr
  43. self.server = server
  44. self.block_size = 1024
  45. # self.welcome_client()
  46. self.status="connected"
  47. async def welcome_client(self):
  48. pass
  49. async def handle(self, data):
  50. return
  51. async def recv(self):
  52. data_received = await self.socket.recv(self.block_size)
  53. data_decoded = data_received.decode("utf-8")
  54. return data_decoded
  55. async def send(self, msg, log_msg=False):
  56. msg_encoded = bytes(msg, "utf-8")
  57. if log_msg:
  58. lschat.info("server:"+log_msg)
  59. else:
  60. lschat.info("Server:"+msg)
  61. try:
  62. await self.socket.send(msg_encoded)
  63. return True
  64. except Exception as e:
  65. lserver.error(e, exc_info=True)
  66. return False
  67. async def close(self):
  68. self.status = "closed"
  69. try:
  70. await self.socket.shutdown(0)
  71. except:
  72. lserver.debug("error during socket shutdown")
  73. try:
  74. await self.socket.close()
  75. except:
  76. lserver.debug("error closing socket")
  77. class ConnHandlerEcho(ConnHandlerBase):
  78. def __init__(self, socket, addr, server):
  79. self.status = "init"
  80. self.super_class = super(ConnHandlerEcho, self)
  81. self.super_class.__init__(socket, addr, server)
  82. self.server = server
  83. def welcome_client(self):
  84. self.send("welcome to the client")
  85. def handle(self, data):
  86. lschat.info("Client:"+data)
  87. for h in list(set(self.server.connection_handler)-{self}):
  88. h.send(data)
  89. class Server(object):
  90. """
  91. Server opens either an unix or an inet connection. for every client which connects a new ClientHandler class is created.
  92. """
  93. def __init__(self,
  94. host,
  95. port=None,
  96. af_family="AF_INET",
  97. log_ip=False,
  98. max_allowed_clients=5,
  99. handler_class=None,
  100. handler_kwargs={},
  101. ):
  102. super(Server, self).__init__()
  103. # set to true when the server shuts down, for instance after a
  104. # fatal exception
  105. self.exit_event = False
  106. # on which hostname or ip address the connection will be opened
  107. self.host = host
  108. # on which port the connection will be opened
  109. self.port = port
  110. # what AF_INET family to use, either AF_INET or AF_UNIX (file socket)
  111. self.af_family = af_family
  112. # whether ip addresses will be logged
  113. self.log_ip = log_ip
  114. # number of maximum client connection at a time
  115. self.max_allowed_clients = max_allowed_clients
  116. # this handler class will be used when creating a new handler
  117. self.handler_class = handler_class
  118. # the kwargs passed to the handler's __init__ function
  119. self.handler_kwargs = handler_kwargs
  120. # don't make the socket yet, we don't need right now. will be created
  121. # when the start method is called
  122. # self.socket = self.make_socket()
  123. self.socket = None
  124. # create a task group for handlers, so we can easily cancel/terminate
  125. # them all at once
  126. self.handle_tasks = curio.TaskGroup(name="tg_handle_clients")
  127. # list of all active connection handlers
  128. self.connection_handler = []
  129. # these aren't actually used, I will remove them soon
  130. # self.conn_to_addr = {}
  131. # self.addr_to_conn = {}
  132. # self.conn_to_handler ={}
  133. # self.handler_to_conn = {}
  134. # this was used for the select.select approach. we use the async approach now, let's remove it
  135. # self.read_sockets_expected = [self.socket]
  136. # register our cleanup method to be executed when the program exits.
  137. # the cleanup function unregisters itself, so it won't get executed twice when the user called it befor the program exites
  138. atexit.register(self.shutdown)
  139. def make_socket(self):
  140. """
  141. factory method for sockets.
  142. this method makes a normal socket and wraps it in a curi.io.Socket wrapper
  143. """
  144. lserver.debug("making a {} socket".format(self.af_family))
  145. if self.af_family == "AF_INET":
  146. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  147. elif self.af_family == "AF_UNIX":
  148. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  149. else:
  150. raise ValueError(
  151. "AF_FAMILY '{}' not supported!".format(
  152. self.af_family
  153. )
  154. )
  155. s = curio.io.Socket(s)
  156. return s
  157. def make_handler(self, conn, addr):
  158. """
  159. factory method for handlers.
  160. this method creates a handler object from self.handler_class and self.handler_kwargs
  161. """
  162. return self.handler_class(conn, addr, self, **self.handler_kwargs)
  163. # DEPRECATED
  164. # def register_conn(self, conn, addr):
  165. # # if self.log_ip:
  166. # # lserver.info("New connection from {} on port {}".format(*addr))
  167. # self.read_sockets_expected.append(conn)
  168. # if addr:
  169. # self.conn_to_addr[conn] = addr
  170. # self.addr_to_conn[addr] = conn
  171. #
  172. # def unregister_conn(self, conn):
  173. # self.read_sockets_expected.remove(conn)
  174. # addr = self.conn_to_addr.get(conn, False)
  175. # if addr:
  176. # del self.addr_to_conn[addr]
  177. # del self.conn_to_addr[conn]
  178. #
  179. # def register_handler(self, handler, conn):
  180. # self.connection_handler.append(handler)
  181. # self.conn_to_handler[conn] = handler
  182. # self.handler_to_conn[handler] = conn
  183. #
  184. # def unregister_handler(self, handler, conn):
  185. # self.connection_handler.remove(handler)
  186. # del self.conn_to_handler[conn]
  187. # del self.handler_to_conn[handler]
  188. def setup(self):
  189. """
  190. opens the connection and starts listening for clients. this method
  191. does not block, it returns after starting to listen.
  192. """
  193. lserver.info("setting up socket")
  194. if self.af_family == "AF_INET":
  195. self.socket.bind((self.host, self.port))
  196. elif self.af_family == "AF_UNIX":
  197. if os.path.exists(self.host):
  198. lserver.debug("file already exists")
  199. lserver.debug("attempting to remove it")
  200. os.remove(self.host)
  201. self.socket.bind(self.host)
  202. self.socket.listen(self.max_allowed_clients)
  203. # self.socket.settimeout(1)
  204. def shutdown(self):
  205. """
  206. This method properly shuts down the sockets and closes them.
  207. it unregisters itself from atexit, so it doesn't get executed twice
  208. when it was manually called before to program exits.
  209. """
  210. def error_handler(func,*args,log_text="error",**kwargs):
  211. try:
  212. func(*args,**kwargs)
  213. except Exception as exc:
  214. lserver.debug("error occured during "+log_text,exc_info=exc)
  215. atexit.unregister(self.shutdown)
  216. lserver.info("shutting down server")
  217. error_handler(
  218. self.handle_tasks.cancel_remaining,log_text="handler cancel")
  219. # check if there is actually a socket. if the shutdown method is
  220. # executed before the start method, there is no socket.
  221. if self.socket:
  222. error_handler(self.socket.shutdown,log_text="socket shutdown")
  223. error_handler(self.socket.close,log_text="socket close")
  224. def start(self):
  225. """
  226. this method starts the server. it is blocking.
  227. """
  228. self.setup()
  229. curio.run(self.run)
  230. async def run(self):
  231. """
  232. this method is the main loop of the Server. it waits for new client
  233. connections and creates a handle task for each of them. it does not
  234. receive or send anything.
  235. """
  236. lserver.debug("entering main loop")
  237. while ( not self.exit_event ):
  238. lserver.debug("waiting for client to connect")
  239. # wait for a client to connect
  240. conn,addr = await self.socket.accept()
  241. if self.log_ip:
  242. lserver.info(
  243. "new client connection, {}:{}!".format(*addr))
  244. else:
  245. lserver.info("a new client connected, let's handle it")
  246. handler = self.make_handler(conn, addr)
  247. # self.register_conn(conn, addr)
  248. # self.register_handler(handler, conn)
  249. await self.handle_tasks.spawn(self.handle_client(conn,handler))
  250. async def handle_client(self,socket,handler):
  251. """
  252. This method waits for the client to send something and calls the
  253. ClientHandler's handle method. there is a handle_client method running for each client connected.
  254. """
  255. while True:
  256. try:
  257. if self.log_ip:
  258. lserver.debug("waiting for {} to send something"
  259. .format(socket.getsockname()))
  260. else:
  261. lserver.debug("waiting for the client to send something")
  262. # wait for the client to send something
  263. data = await handler.recv()
  264. # if there is no data the client disconnected. this is a
  265. # tcp protocoll specification.
  266. if not data:
  267. if self.log_ip:
  268. lserver.info("the connection to {} was closed"
  269. .format(socket.getsockname()))
  270. else:
  271. lserver.info("the connection to the client was closed")
  272. # self.unregister_handler(handler, socket)
  273. # self.unregister_conn(socket)
  274. await handler.close()
  275. # break out of the loop. don't return because we need to
  276. # do cleanup
  277. break
  278. else:
  279. # don't strip the data of its whitespaces, since they may
  280. # be important.
  281. lschat.info("Client:"+data.rstrip())
  282. coro = handler.handle(data)
  283. task = await curio.spawn(coro)
  284. except Exception as e:
  285. lserver.error(e, exc_info=True)
  286. # let's sleep a bit, in case something is broken and the
  287. # loop throws an exception every time
  288. await curio.sleep(0.01)
  289. # if a task exits and hasn't been joined, curio prints a warning.
  290. # we don't want the warning, so let's join the current task for 0
  291. # seconds. instead of task.join() we use task.wait(). the only
  292. # difference is that wait doesn't throw a exception if the task was
  293. # stopped or crashed
  294. cur_task = await curio.current_task()
  295. await curio.ignore_after(0,cur_task.wait)
  296. class Client(threading.Thread):
  297. """docstring for Client"""
  298. is_connecting = False
  299. is_connected = False
  300. status = "uninitialized"
  301. def __init__(self,
  302. host,
  303. port=None,
  304. af_family="AF_INET",
  305. handle_data_func=None,
  306. error_handler=None,
  307. block_size=1024,
  308. ):
  309. self.super_class = super(Client, self)
  310. self.super_class.__init__()
  311. self.name = "Client"
  312. self.exit_event = False
  313. self.host = host
  314. self.port = port
  315. self.af_family = af_family
  316. self.block_size = block_size
  317. self.handle_data_func = handle_data_func
  318. self.is_connected = False
  319. self.error_handler = error_handler
  320. # self.socket = self.make_socket()
  321. self.socket = None
  322. self.status = "disconnected"
  323. def connect(self):
  324. self.status = "connecting"
  325. self.socket = self.make_socket()
  326. lclient.info(
  327. "connecting to socket '{}' of type {}".format(
  328. self.host,
  329. self.af_family
  330. )
  331. )
  332. try:
  333. if self.af_family == "AF_INET":
  334. self.socket.connect((self.host, self.port))
  335. elif self.af_family == "AF_UNIX":
  336. if os.path.exists(self.host):
  337. self.socket.connect(self.host)
  338. else:
  339. lclient.warn("File not found. Aborting.")
  340. return
  341. self.is_connected = True
  342. self.status = "connected"
  343. lclient.info("connected")
  344. return True
  345. except Exception as e:
  346. lclient.debug(e, exc_info=True)
  347. if type(e) is ConnectionRefusedError:
  348. lclient.info("failed to connect to socket '{}'".format(self.host))
  349. self.disconnect()
  350. return False
  351. def disconnect(self):
  352. lclient.info("disconnecting from socket '{}'".format(self.host))
  353. self.is_connected = False
  354. self.status = "disconnected"
  355. if self.socket:
  356. try:
  357. self.socket.shutdown(socket.SHUT_RDWR)
  358. except Exception as e:
  359. lclient.error(e)
  360. try:
  361. self.socket.close()
  362. except Exception as e:
  363. lclient.error("error occured while closing the socket, " +
  364. "maybe it is already closed",exc_info=e)
  365. del self.socket
  366. self.socket = None
  367. def handle_data(self, data_received):
  368. data_decoded = data_received.decode("utf-8")
  369. lcchat.info("Server: "+data_decoded)
  370. if self.handle_data_func:
  371. try:
  372. self.handle_data_func(data_decoded)
  373. except Exception as e:
  374. lclient.error(e, exc_info=True)
  375. def is_running(self):
  376. return (self in threading.enumerate())
  377. def make_socket(self):
  378. lclient.info("creating a {} socket".format(self.af_family))
  379. if self.af_family == "AF_INET":
  380. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  381. elif self.af_family == "AF_UNIX":
  382. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  383. else:
  384. raise ValueError(
  385. "AF_FAMILY '{}' not supported!".format(
  386. self.af_family
  387. )
  388. )
  389. return s
  390. def main_loop(self):
  391. lclient.debug("starting main loop")
  392. while ( not self.exit_event ):
  393. if not self.status in ["connected"]:
  394. time.sleep(0.1)
  395. continue
  396. # print(0)
  397. read_confirmed, write_confirmed, exc_confirmed \
  398. = select.select(
  399. [self.socket],
  400. [],
  401. [self.socket],
  402. 1
  403. )
  404. if self.socket in exc_confirmed:
  405. self.is_connected = False
  406. lclient.warning("socket is expected to corrupt, exiting")
  407. self.disconnect()
  408. # self.stop()
  409. break
  410. elif self.socket in read_confirmed:
  411. try:
  412. data_received = self.read_from_socket()
  413. if data_received == b'':
  414. lclient.info("connection is broken, closing socket exiting")
  415. self.disconnect()
  416. # self.stop()
  417. # break
  418. else:
  419. try:
  420. self.handle_data(data_received)
  421. except Exception as e:
  422. lserver.error(
  423. "Error while handling data",
  424. exc_info=e
  425. )
  426. except Exception as e:
  427. lclient.error(e, exc_info=True)
  428. if type(e) is OSError:
  429. self.is_connected = False
  430. lclient.warn("connection broken, exiting")
  431. self.disconnect()
  432. # self.stop()
  433. # break
  434. else:
  435. raise
  436. else:
  437. time.sleep(0.1)
  438. def read_from_socket(self):
  439. data_received = self.socket.recv(self.block_size)
  440. return data_received
  441. def run(self):
  442. # self.connect()
  443. if self.error_handler:
  444. self.error_handler(self.main_loop)
  445. else:
  446. self.main_loop()
  447. def send(self, msg):
  448. msg = msg.rstrip()
  449. msg_encoded = bytes(msg+"\r\n", "utf-8")
  450. try:
  451. lcchat.info("Client: "+msg)
  452. self.socket.send(msg_encoded)
  453. except Exception as e:
  454. self.is_connected = False
  455. lclient.error(e, exc_info=True)
  456. self.status = "shutdown"
  457. def setup(self):
  458. pass
  459. def stop(self,reason=None):
  460. self.disconnect()
  461. self.exit_event = True
  462. if reason:
  463. print(reason)
  464. class AsyncClient(object):
  465. """docstring for Client"""
  466. is_connecting = False
  467. is_connected = False
  468. status = "uninitialized"
  469. def __init__(self,
  470. host,
  471. port=None,
  472. af_family="AF_INET",
  473. handle_data_func=None,
  474. error_handler=None,
  475. block_size=1024,
  476. ):
  477. self.super_class = super(AsyncClient, self)
  478. self.super_class.__init__()
  479. self.name = "Client"
  480. self.exit_event = False
  481. self.host = host
  482. self.port = port
  483. self.af_family = af_family
  484. self.block_size = block_size
  485. self.handle_data_func = handle_data_func
  486. self.is_connected = False
  487. self.error_handler = error_handler
  488. self.socket = None
  489. self.status = "disconnected"
  490. def connect(self):
  491. self.status = "connecting"
  492. self.socket = self.make_socket()
  493. lclient.info("connecting to socket '{}' of type {}".format(
  494. self.host,self.af_family))
  495. try:
  496. if self.af_family == "AF_INET":
  497. self.socket.connect((self.host, self.port))
  498. elif self.af_family == "AF_UNIX":
  499. self.socket.connect(self.host)
  500. self.is_connected = True
  501. self.status = "connected"
  502. lclient.info("connected")
  503. return True
  504. except Exception as e:
  505. lclient.debug(e, exc_info=True)
  506. if type(e) is ConnectionRefusedError:
  507. lclient.info("failed to connect to socket '{}'".format(self.host))
  508. self.disconnect()
  509. return False
  510. def disconnect(self):
  511. lclient.info("disconnecting from socket '{}'".format(self.host))
  512. self.is_connected = False
  513. self.status = "disconnected"
  514. if self.socket:
  515. try:
  516. self.socket.shutdown(socket.SHUT_RDWR)
  517. except Exception as e:
  518. lclient.error(e)
  519. try:
  520. self.socket.close()
  521. except Exception as e:
  522. lclient.error("error occured while closing the socket, " +
  523. "maybe it is already closed",exc_info=e)
  524. del self.socket
  525. self.socket = None
  526. def handle_data(self, data_received):
  527. data_decoded = data_received.decode("utf-8")
  528. lcchat.info("Server: "+data_decoded)
  529. if self.handle_data_func:
  530. try:
  531. self.handle_data_func(data_decoded)
  532. except Exception as e:
  533. lclient.error(e, exc_info=True)
  534. def is_running(self):
  535. return (self in threading.enumerate())
  536. def make_socket(self):
  537. lclient.info("creating a {} socket".format(self.af_family))
  538. if self.af_family == "AF_INET":
  539. s = trio.socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  540. elif self.af_family == "AF_UNIX":
  541. s = trio.socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  542. else:
  543. raise ValueError(
  544. "AF_FAMILY '{}' not supported!".format(
  545. self.af_family
  546. )
  547. )
  548. return s
  549. async def read_from_socket(self):
  550. data_received = await self.socket.recv(self.block_size)
  551. return data_received
  552. async def recv(self):
  553. data_received = await self.socket.recv(self.block_size)
  554. data_decoded = data_received.decode("utf-8")
  555. return data_decoded
  556. async def run(self):
  557. lclient.debug("starting main loop")
  558. while ( not self.exit_event ):
  559. if not self.status in ["connected"]:
  560. time.sleep(0.1)
  561. continue
  562. # if self.socket in exc_confirmed:
  563. # self.is_connected = False
  564. # lclient.warning("socket is expected to corrupt, exiting")
  565. # self.disconnect()
  566. # # self.stop()
  567. # break
  568. # elif self.socket in read_confirmed:
  569. try:
  570. data = await self.read_from_socket()
  571. if not data:
  572. lclient.info("connection closed")
  573. self.disconnect()
  574. else:
  575. self.handle_data(data)
  576. except Exception as e:
  577. lclient.error(e, exc_info=True)
  578. if type(e) is OSError:
  579. self.is_connected = False
  580. lclient.warn("connection broken, exiting")
  581. self.disconnect()
  582. else:
  583. raise
  584. async def start(self,connect=False):
  585. if connect:
  586. self.connect()
  587. if self.error_handler:
  588. self.error_handler(self.run)
  589. else:
  590. self.run()
  591. def send(self, msg):
  592. msg = msg.rstrip()
  593. msg_encoded = bytes(msg+"\r\n", "utf-8")
  594. try:
  595. lcchat.info("Client: "+msg)
  596. self.socket.send(msg_encoded)
  597. except Exception as e:
  598. self.is_connected = False
  599. lclient.error(e, exc_info=True)
  600. self.disconnect()
  601. # self.exit_event = True
  602. # self.status = "shutdown"
  603. def setup(self):
  604. pass
  605. def stop(self,reason=None):
  606. self.disconnect()
  607. self.exit_event = True
  608. if reason:
  609. print(reason)
  610. #