socket.py (1546B)
1 # standard imports 2 import os 3 import logging 4 import socket 5 import stat 6 7 # local imports 8 from funga.error import SignerError 9 from .handle import SignRequestHandler 10 11 logg = logging.getLogger(__name__) 12 13 14 class SocketHandler: 15 16 def __init__(self): 17 self.handler = SignRequestHandler() 18 19 20 def process(self, csock): 21 d = csock.recv(4096) 22 23 r = None 24 try: 25 r = self.handler.handle_jsonrpc(d) 26 except SignerError as e: 27 r = e.to_jsonrpc() 28 29 csock.send(r) 30 31 32 def start_server_socket(s): 33 s.listen(10) 34 logg.debug('server started') 35 handler = SocketHandler() 36 while True: 37 (csock, caddr) = s.accept() 38 handler.process(csock) 39 csock.close() 40 s.close() 41 os.unlink(socket_path) 42 43 44 def start_server_tcp(spec): 45 s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 46 s.bind(spec) 47 logg.debug('created tcp socket {}'.format(spec)) 48 start_server_socket(s) 49 50 51 def start_server_unix(socket_path): 52 socket_dir = os.path.dirname(socket_path) 53 try: 54 fi = os.stat(socket_dir) 55 if not stat.S_ISDIR: 56 RuntimeError('socket path {} is not a directory'.format(socket_dir)) 57 except FileNotFoundError: 58 os.mkdir(socket_dir) 59 60 try: 61 os.unlink(socket_path) 62 except FileNotFoundError: 63 pass 64 s = socket.socket(family = socket.AF_UNIX, type = socket.SOCK_STREAM) 65 s.bind(socket_path) 66 logg.debug('created unix ipc socket {}'.format(socket_path)) 67 start_server_socket(s)