aboutsummaryrefslogtreecommitdiffstats
path: root/termcast_server/__init__.py
blob: 6896b0484151e3acff2cef7a8032e0a652865781 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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

def main():
    server = Server(sys.argv[1])
    server.listen()