diff options
author | Jesse Luehrs <doy@tozt.net> | 2014-09-23 14:01:46 -0400 |
---|---|---|
committer | Jesse Luehrs <doy@tozt.net> | 2014-09-23 14:01:46 -0400 |
commit | 70cd632270083acc2bb835069d6e00f07a728cb3 (patch) | |
tree | 37298ef15ceed88a147ec668ce6977a9f1a5b942 /termcast_server/__init__.py | |
parent | f44c44324c24aa667bfd56bb7b9ee2e96ac93bd4 (diff) | |
download | python-termcast-server-70cd632270083acc2bb835069d6e00f07a728cb3.tar.gz python-termcast-server-70cd632270083acc2bb835069d6e00f07a728cb3.zip |
reorganize
Diffstat (limited to 'termcast_server/__init__.py')
-rw-r--r-- | termcast_server/__init__.py | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/termcast_server/__init__.py b/termcast_server/__init__.py new file mode 100644 index 0000000..3a8dfee --- /dev/null +++ b/termcast_server/__init__.py @@ -0,0 +1,78 @@ +import signal +import socket +import sys +import threading +import uuid + +from . import pubsub +from . import ssh +from . import termcast + +class Server(object): + def __init__(self, keyfile): + self.publisher = pubsub.Publisher() + self.keyfile = keyfile + + def listen(self): + ssh_sock = self._open_socket(2200) + termcast_sock = self._open_socket(2201) + + threading.Thread( + target=lambda: self.wait_for_ssh_connection(ssh_sock) + ).start() + threading.Thread( + target=lambda: self.wait_for_termcast_connection(termcast_sock) + ).start() + + def wait_for_ssh_connection(self, sock): + self._wait_for_connection( + sock, + lambda client: self.handle_ssh_connection(client) + ) + + def wait_for_termcast_connection(self, sock): + self._wait_for_connection( + sock, + lambda client: self.handle_termcast_connection(client) + ) + + def handle_ssh_connection(self, client): + self._handle_connection( + client, + lambda client, connection_id: ssh.Connection( + client, connection_id, self.publisher, self.keyfile + ) + ) + + def handle_termcast_connection(self, client): + self._handle_connection( + client, + lambda client, connection_id: termcast.Connection( + client, connection_id, self.publisher + ) + ) + + def _wait_for_connection(self, sock, cb): + while True: + try: + sock.listen(100) + client, addr = sock.accept() + except Exception as e: + print('*** Listen/accept failed: ' + str(e)) + traceback.print_exc() + continue + + threading.Thread(target=cb, args=(client,)).start() + + def _handle_connection(self, client, cb): + connection_id = uuid.uuid4().hex + connection = cb(client, connection_id) + self.publisher.subscribe(connection) + connection.run() + self.publisher.unsubscribe(connection) + + def _open_socket(self, port): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(('', port)) + return sock |