__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. """
  39. ConnectionHandlerBase is the base class for all connection handlers.
  40. It provides basic methodes. Consider inheriting form ConnectionHandler
  41. instead, as it provides better functionality.
  42. """
  43. addr = None
  44. block_size = 1024
  45. server = None
  46. def __init__(self, socket, addr, server):
  47. super(ConnHandlerBase, self).__init__()
  48. self.socket = socket
  49. self.addr = addr
  50. self.server = server
  51. async def disconnect(self):
  52. """
  53. disconenct explicitely disconnects the client, shuts the socket down
  54. and closes it.
  55. """
  56. try:
  57. await self.send(bytes())
  58. except:
  59. lserver.debug("error during disconenct")
  60. try:
  61. await self.socket.shutdown(0)
  62. except:
  63. lserver.debug("error during socket shutdown")
  64. try:
  65. await self.socket.close()
  66. except:
  67. lserver.debug("error closing socket")
  68. async def handle(self, data):
  69. """
  70. This method is called for every message the server receives from the
  71. client. It should handle the data. Performing asynchronous blocking
  72. actions is ok, as the client loop does not wait for this method to
  73. finish. therefore, this method can be called multiple times at once,
  74. use curio locks if appropriate.
  75. """
  76. raise NotImplemented()
  77. async def recv(self):
  78. """
  79. This method waits for the client to send something and returns bytes!
  80. """
  81. data_received = await self.socket.recv(self.block_size)
  82. return data_received
  83. async def send(self, data, log_msg=None):
  84. """
  85. This method sends bytes to the client. Returns False if an exception
  86. was raised during sending, otherwise True.
  87. """
  88. if log_msg:
  89. lschat.info("server:"+str(log_msg))
  90. else:
  91. lschat.info("Server:"+str(data))
  92. try:
  93. await self.socket.send(data)
  94. return True
  95. except Exception as e:
  96. lserver.error(e, exc_info=True)
  97. return False
  98. class ConnHandler(object):
  99. """
  100. More advanced connection handler than ConnectionHandlerBase. For
  101. instance, sends() takes a string and encodes it, recv() decodes
  102. the client's and returns a string and welcome_client is called after
  103. the ConnHandler is initialized (Not after the inheriting class is
  104. initialized though!)
  105. """
  106. def __init__(self, socket, addr, server):
  107. super(ConnHandler, self).__init__(socket,addr,server)
  108. async def disconnect(self):
  109. """
  110. disconenct() explicitely disconnects the client, performes a proper
  111. the shutdow on the socket and closes it.
  112. """
  113. try:
  114. await self.send("")
  115. except:
  116. lserver.debug("error during disconenct")
  117. try:
  118. await self.socket.shutdown(0)
  119. except:
  120. lserver.debug("error during socket shutdown")
  121. try:
  122. await self.socket.close()
  123. except:
  124. lserver.debug("error closing socket")
  125. async def handle(self, data):
  126. return
  127. async def on_welcome(self):
  128. """
  129. This method can be used to send a welcome message to the client.
  130. """
  131. self.send("Welcome client, this is the server sending!")
  132. async def recv(self):
  133. """
  134. This method waits for the client to send something, decodes it and
  135. returns a string.
  136. """
  137. data_received = await self.socket.recv(self.block_size)
  138. data_decoded = data_received.decode("utf-8")
  139. return data_decoded
  140. async def send(self, data, log_msg=False):
  141. """
  142. This method takes a string, encodes it and sends it to the client.
  143. Returns False if an exception was raised during sending, otherwise True.
  144. """
  145. if log_msg:
  146. lschat.info("server:"+log_msg)
  147. else:
  148. lschat.info("Server:"+data)
  149. data_encoded = bytes(data, "utf-8")
  150. try:
  151. await self.socket.send(data_encoded)
  152. return True
  153. except Exception as e:
  154. lserver.error(e, exc_info=True)
  155. return False
  156. class ConnHandlerEcho(ConnHandler):
  157. """
  158. A Conn handler which sends everything it receives to every other client
  159. connected to the server
  160. """
  161. def __init__(self, socket, addr, server):
  162. super(ConnHandlerEcho, self).__init__(socket, addr, server)
  163. def handle(self, data):
  164. for h in self.server.connection_handler:
  165. if not h is self:
  166. h.send(data)
  167. class Server(object):
  168. """
  169. Server opens either an unix or an inet connection. for every client which connects a new ClientHandler class is created.
  170. """
  171. def __init__(self,
  172. host,
  173. port=None,
  174. af_family="AF_INET",
  175. log_ip=False,
  176. max_allowed_clients=5,
  177. handler_class=None,
  178. handler_kwargs={},
  179. ):
  180. super(Server, self).__init__()
  181. # set to true when the server shuts down, for instance after a
  182. # fatal exception
  183. self.exit_event = False
  184. # on which hostname or ip address the connection will be opened
  185. self.host = host
  186. # on which port the connection will be opened
  187. self.port = port
  188. # what AF_INET family to use, either AF_INET or AF_UNIX (file socket)
  189. self.af_family = af_family
  190. # whether ip addresses will be logged
  191. self.log_ip = log_ip
  192. # number of maximum client connection at a time
  193. self.max_allowed_clients = max_allowed_clients
  194. # this handler class will be used when creating a new handler
  195. self.handler_class = handler_class
  196. # the kwargs passed to the handler's __init__ function
  197. self.handler_kwargs = handler_kwargs
  198. # don't make the socket yet, we don't need right now. will be created
  199. # when the start method is called
  200. # self.socket = self.make_socket()
  201. self.socket = None
  202. # create a task group for handlers, so we can easily cancel/terminate
  203. # them all at once
  204. self.handle_tasks = curio.TaskGroup(name="tg_handle_clients")
  205. # list of all active connection handlers
  206. self.connection_handler = []
  207. # register our cleanup method to be executed when the program exits.
  208. # the cleanup function unregisters itself, so it won't get executed twice when the user called it befor the program exites
  209. atexit.register(self.shutdown)
  210. def make_socket(self):
  211. """
  212. factory method for sockets.
  213. this method makes a normal socket and wraps it in a curi.io.Socket wrapper
  214. """
  215. lserver.debug("making a {} socket".format(self.af_family))
  216. if self.af_family == "AF_INET":
  217. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  218. elif self.af_family == "AF_UNIX":
  219. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  220. else:
  221. raise ValueError(
  222. "AF_FAMILY '{}' not supported!".format(
  223. self.af_family
  224. )
  225. )
  226. s = curio.io.Socket(s)
  227. return s
  228. def make_handler(self, conn, addr):
  229. """
  230. factory method for handlers.
  231. this method creates a handler object from self.handler_class and self.handler_kwargs
  232. """
  233. return self.handler_class(conn, addr, self, **self.handler_kwargs)
  234. def setup(self):
  235. """
  236. creates a scoket, opens the connection and starts listening for
  237. clients. this method does not block, it returns after starting to
  238. listen.
  239. """
  240. lserver.info("setting up server")
  241. self.socket = self.make_socket()
  242. if self.af_family == "AF_INET":
  243. self.socket.bind((self.host, self.port))
  244. elif self.af_family == "AF_UNIX":
  245. if os.path.exists(self.host):
  246. lserver.debug("file already exists")
  247. lserver.debug("attempting to remove it")
  248. os.remove(self.host)
  249. self.socket.bind(self.host)
  250. self.socket.listen(self.max_allowed_clients)
  251. def shutdown(self):
  252. """
  253. This method properly shuts down the sockets and closes them.
  254. it unregisters itself from atexit, so it doesn't get executed twice
  255. when it was manually called before to program exits.
  256. """
  257. def error_handler(func,*args,log_text="error",async_=False,**kwargs):
  258. try:
  259. if async_:
  260. coro = func(*args,**kwargs)
  261. lserver.debug("{} {}".format(func,coro))
  262. else:
  263. func(*args,**kwargs)
  264. except Exception as exc:
  265. lserver.debug("error occured during "+log_text,exc_info=exc)
  266. atexit.unregister(self.shutdown)
  267. lserver.info("shutting down server")
  268. error_handler(
  269. self.handle_tasks.cancel_remaining,log_text="handler cancel",async_=True)
  270. # check if there is actually a socket. if the shutdown method is
  271. # executed before the start method, there is no socket.
  272. if self.socket:
  273. error_handler(self.socket.shutdown,log_text="socket shutdown")
  274. error_handler(self.socket.close,log_text="socket close")
  275. def start(self):
  276. """
  277. this method starts the server. it is blocking.
  278. """
  279. self.setup()
  280. curio.run(self.run)
  281. async def run(self):
  282. """
  283. this method is the main loop of the Server. it waits for new client
  284. connections and creates a handle task for each of them. it does not
  285. receive or send anything.
  286. """
  287. lserver.debug("entering main loop")
  288. while ( not self.exit_event ):
  289. lserver.debug("waiting for client to connect")
  290. # wait for a client to connect
  291. conn,addr = await self.socket.accept()
  292. if self.log_ip:
  293. lserver.info(
  294. "new client connection, {}:{}!".format(*addr))
  295. else:
  296. lserver.info("a new client connected, let's handle it")
  297. handler = self.make_handler(conn, addr)
  298. # self.register_conn(conn, addr)
  299. # self.register_handler(handler, conn)
  300. await self.handle_tasks.spawn(self.handle_client(conn,handler))
  301. async def handle_client(self,socket,handler):
  302. """
  303. This method waits for the client to send something and calls the
  304. ClientHandler's handle method. there is a handle_client method running for each client connected.
  305. """
  306. if hasattr(handler,"on_welcome"):
  307. await handler.on_welcome()
  308. while True:
  309. try:
  310. if self.log_ip:
  311. lserver.debug("waiting for {} to send something"
  312. .format(socket.getsockname()))
  313. else:
  314. lserver.debug("waiting for the client to send something")
  315. # wait for the client to send something
  316. data = await handler.recv()
  317. # if there is no data the client disconnected. this is a
  318. # tcp protocoll specification.
  319. if not data:
  320. if self.log_ip:
  321. lserver.info("the connection to {} was closed"
  322. .format(socket.getsockname()))
  323. else:
  324. lserver.info("the connection to the client was closed")
  325. # self.unregister_handler(handler, socket)
  326. # self.unregister_conn(socket)
  327. await handler.close()
  328. # break out of the loop. don't return because we need to
  329. # do cleanup
  330. break
  331. else:
  332. # don't strip the data of its whitespaces, since they may
  333. # be important.
  334. lschat.info("Client:"+data.rstrip())
  335. coro = handler.handle(data)
  336. task = await curio.spawn(coro)
  337. except Exception as e:
  338. lserver.error(e, exc_info=True)
  339. # let's sleep a bit, in case something is broken and the
  340. # loop throws an exception every time
  341. await curio.sleep(0.01)
  342. # if a task exits and hasn't been joined, curio prints a warning.
  343. # we don't want the warning, so let's join the current task for 0
  344. # seconds. instead of task.join() we use task.wait(). the only
  345. # difference is that wait doesn't throw a exception if the task was
  346. # stopped or crashed
  347. cur_task = await curio.current_task()
  348. await curio.ignore_after(0,cur_task.wait)
  349. class Client(threading.Thread):
  350. """docstring for Client"""
  351. is_connecting = False
  352. is_connected = False
  353. status = "uninitialized"
  354. def __init__(self,
  355. host,
  356. port=None,
  357. af_family="AF_INET",
  358. handle_data_func=None,
  359. error_handler=None,
  360. block_size=1024,
  361. ):
  362. self.super_class = super(Client, self)
  363. self.super_class.__init__()
  364. self.name = "Client"
  365. self.exit_event = False
  366. self.host = host
  367. self.port = port
  368. self.af_family = af_family
  369. self.block_size = block_size
  370. self.handle_data_func = handle_data_func
  371. self.is_connected = False
  372. self.error_handler = error_handler
  373. # self.socket = self.make_socket()
  374. self.socket = None
  375. self.status = "disconnected"
  376. def connect(self):
  377. self.status = "connecting"
  378. self.socket = self.make_socket()
  379. lclient.info(
  380. "connecting to socket '{}' of type {}".format(
  381. self.host,
  382. self.af_family
  383. )
  384. )
  385. try:
  386. if self.af_family == "AF_INET":
  387. self.socket.connect((self.host, self.port))
  388. elif self.af_family == "AF_UNIX":
  389. if os.path.exists(self.host):
  390. self.socket.connect(self.host)
  391. else:
  392. lclient.warn("File not found. Aborting.")
  393. return
  394. self.is_connected = True
  395. self.status = "connected"
  396. lclient.info("connected")
  397. return True
  398. except Exception as e:
  399. lclient.debug(e, exc_info=True)
  400. if type(e) is ConnectionRefusedError:
  401. lclient.info("failed to connect to socket '{}'".format(self.host))
  402. self.disconnect()
  403. return False
  404. def disconnect(self):
  405. lclient.info("disconnecting from socket '{}'".format(self.host))
  406. self.is_connected = False
  407. self.status = "disconnected"
  408. if self.socket:
  409. try:
  410. self.socket.shutdown(socket.SHUT_RDWR)
  411. except Exception as e:
  412. lclient.error(e)
  413. try:
  414. self.socket.close()
  415. except Exception as e:
  416. lclient.error("error occured while closing the socket, " +
  417. "maybe it is already closed",exc_info=e)
  418. del self.socket
  419. self.socket = None
  420. def handle_data(self, data_received):
  421. data_decoded = data_received.decode("utf-8")
  422. lcchat.info("Server: "+data_decoded)
  423. if self.handle_data_func:
  424. try:
  425. self.handle_data_func(data_decoded)
  426. except Exception as e:
  427. lclient.error(e, exc_info=True)
  428. def is_running(self):
  429. return (self in threading.enumerate())
  430. def make_socket(self):
  431. lclient.info("creating a {} socket".format(self.af_family))
  432. if self.af_family == "AF_INET":
  433. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  434. elif self.af_family == "AF_UNIX":
  435. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  436. else:
  437. raise ValueError(
  438. "AF_FAMILY '{}' not supported!".format(
  439. self.af_family
  440. )
  441. )
  442. return s
  443. def main_loop(self):
  444. lclient.debug("starting main loop")
  445. while ( not self.exit_event ):
  446. if not self.status in ["connected"]:
  447. time.sleep(0.1)
  448. continue
  449. # print(0)
  450. read_confirmed, write_confirmed, exc_confirmed \
  451. = select.select(
  452. [self.socket],
  453. [],
  454. [self.socket],
  455. 1
  456. )
  457. if self.socket in exc_confirmed:
  458. self.is_connected = False
  459. lclient.warning("socket is expected to corrupt, exiting")
  460. self.disconnect()
  461. # self.stop()
  462. break
  463. elif self.socket in read_confirmed:
  464. try:
  465. data_received = self.read_from_socket()
  466. if data_received == b'':
  467. lclient.info("connection is broken, closing socket exiting")
  468. self.disconnect()
  469. # self.stop()
  470. # break
  471. else:
  472. try:
  473. self.handle_data(data_received)
  474. except Exception as e:
  475. lserver.error(
  476. "Error while handling data",
  477. exc_info=e
  478. )
  479. except Exception as e:
  480. lclient.error(e, exc_info=True)
  481. if type(e) is OSError:
  482. self.is_connected = False
  483. lclient.warn("connection broken, exiting")
  484. self.disconnect()
  485. # self.stop()
  486. # break
  487. else:
  488. raise
  489. else:
  490. time.sleep(0.1)
  491. def read_from_socket(self):
  492. data_received = self.socket.recv(self.block_size)
  493. return data_received
  494. def run(self):
  495. # self.connect()
  496. if self.error_handler:
  497. self.error_handler(self.main_loop)
  498. else:
  499. self.main_loop()
  500. def send(self, msg):
  501. msg = msg.rstrip()
  502. msg_encoded = bytes(msg+"\r\n", "utf-8")
  503. try:
  504. lcchat.info("Client: "+msg)
  505. self.socket.send(msg_encoded)
  506. except Exception as e:
  507. self.is_connected = False
  508. lclient.error(e, exc_info=True)
  509. self.status = "shutdown"
  510. def setup(self):
  511. pass
  512. def stop(self,reason=None):
  513. self.disconnect()
  514. self.exit_event = True
  515. if reason:
  516. print(reason)
  517. class AsyncClient(object):
  518. """docstring for Client"""
  519. is_connecting = False
  520. is_connected = False
  521. status = "uninitialized"
  522. def __init__(self,
  523. host,
  524. port=None,
  525. af_family="AF_INET",
  526. handle_data_func=None,
  527. error_handler=None,
  528. block_size=1024,
  529. ):
  530. self.super_class = super(AsyncClient, self)
  531. self.super_class.__init__()
  532. self.name = "Client"
  533. self.exit_event = False
  534. self.host = host
  535. self.port = port
  536. self.af_family = af_family
  537. self.block_size = block_size
  538. self.handle_data_func = handle_data_func
  539. self.is_connected = False
  540. self.error_handler = error_handler
  541. self.socket = None
  542. self.status = "disconnected"
  543. def connect(self):
  544. self.status = "connecting"
  545. self.socket = self.make_socket()
  546. lclient.info("connecting to socket '{}' of type {}".format(
  547. self.host,self.af_family))
  548. try:
  549. if self.af_family == "AF_INET":
  550. self.socket.connect((self.host, self.port))
  551. elif self.af_family == "AF_UNIX":
  552. self.socket.connect(self.host)
  553. self.is_connected = True
  554. self.status = "connected"
  555. lclient.info("connected")
  556. return True
  557. except Exception as e:
  558. lclient.debug(e, exc_info=True)
  559. if type(e) is ConnectionRefusedError:
  560. lclient.info("failed to connect to socket '{}'".format(self.host))
  561. self.disconnect()
  562. return False
  563. def disconnect(self):
  564. lclient.info("disconnecting from socket '{}'".format(self.host))
  565. self.is_connected = False
  566. self.status = "disconnected"
  567. if self.socket:
  568. try:
  569. self.socket.shutdown(socket.SHUT_RDWR)
  570. except Exception as e:
  571. lclient.error(e)
  572. try:
  573. self.socket.close()
  574. except Exception as e:
  575. lclient.error("error occured while closing the socket, " +
  576. "maybe it is already closed",exc_info=e)
  577. del self.socket
  578. self.socket = None
  579. def handle_data(self, data_received):
  580. data_decoded = data_received.decode("utf-8")
  581. lcchat.info("Server: "+data_decoded)
  582. if self.handle_data_func:
  583. try:
  584. self.handle_data_func(data_decoded)
  585. except Exception as e:
  586. lclient.error(e, exc_info=True)
  587. def is_running(self):
  588. return (self in threading.enumerate())
  589. def make_socket(self):
  590. lclient.info("creating a {} socket".format(self.af_family))
  591. if self.af_family == "AF_INET":
  592. s = trio.socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  593. elif self.af_family == "AF_UNIX":
  594. s = trio.socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  595. else:
  596. raise ValueError(
  597. "AF_FAMILY '{}' not supported!".format(
  598. self.af_family
  599. )
  600. )
  601. return s
  602. async def read_from_socket(self):
  603. data_received = await self.socket.recv(self.block_size)
  604. return data_received
  605. async def recv(self):
  606. data_received = await self.socket.recv(self.block_size)
  607. data_decoded = data_received.decode("utf-8")
  608. return data_decoded
  609. async def run(self):
  610. lclient.debug("starting main loop")
  611. while ( not self.exit_event ):
  612. if not self.status in ["connected"]:
  613. time.sleep(0.1)
  614. continue
  615. # if self.socket in exc_confirmed:
  616. # self.is_connected = False
  617. # lclient.warning("socket is expected to corrupt, exiting")
  618. # self.disconnect()
  619. # # self.stop()
  620. # break
  621. # elif self.socket in read_confirmed:
  622. try:
  623. data = await self.read_from_socket()
  624. if not data:
  625. lclient.info("connection closed")
  626. self.disconnect()
  627. else:
  628. self.handle_data(data)
  629. except Exception as e:
  630. lclient.error(e, exc_info=True)
  631. if type(e) is OSError:
  632. self.is_connected = False
  633. lclient.warn("connection broken, exiting")
  634. self.disconnect()
  635. else:
  636. raise
  637. async def start(self,connect=False):
  638. if connect:
  639. self.connect()
  640. if self.error_handler:
  641. self.error_handler(self.run)
  642. else:
  643. self.run()
  644. def send(self, msg):
  645. msg = msg.rstrip()
  646. msg_encoded = bytes(msg+"\r\n", "utf-8")
  647. try:
  648. lcchat.info("Client: "+msg)
  649. self.socket.send(msg_encoded)
  650. except Exception as e:
  651. self.is_connected = False
  652. lclient.error(e, exc_info=True)
  653. self.disconnect()
  654. # self.exit_event = True
  655. # self.status = "shutdown"
  656. def setup(self):
  657. pass
  658. def stop(self,reason=None):
  659. self.disconnect()
  660. self.exit_event = True
  661. if reason:
  662. print(reason)
  663. #