def _send_request(self, method, url, body=None, headers=None, timeout=None): p = urlparse(url) if p.hostname and p.hostname != self._host \ or p.scheme == "http" and self._secure \ or p.scheme == "https" and not self._secure \ or p.port and p.port != self._port: self.fire(NotConnected()) return resource = p.path if p.query: resource += "?" + p.query if headers is None: headers = Headers([]) else: headers = Headers([(k, v) for k, v in headers.items()]) # Clients MUST include Host header in HTTP/1.1 requests (RFC 2616) if not headers.has_key("Host"): headers["Host"] = self._host \ + (":" + str(self._port)) if self._port else "" command = "%s %s HTTP/1.1" % (method, resource) if body is not None: headers["Content-Length"] = len(body) message = "%s\r\n%s" % (command, headers) self._outstanding += 1 if timeout is not None: self._timer = Timer(timeout, SocketError(ETIMEDOUT), self.channel) \ .register(self) self.fire(write(message.encode('utf-8')), self._transport) if body is not None: self.fire(write(body), self._transport)
def _send_request(self, method, url, body=None, headers={}, timeout=None): p = urlparse(url) if p.hostname and p.hostname != self._host \ or p.scheme == "http" and self._secure \ or p.scheme == "https" and not self._secure \ or p.port and p.port != self._port: self.fire(NotConnected()) return resource = p.path if p.query: resource += "?" + p.query headers = Headers([(k, v) for k, v in list(headers.items())]) # Clients MUST include Host header in HTTP/1.1 requests (RFC 2616) if "Host" not in headers: headers["Host"] = self._host \ + (":" + str(self._port)) if self._port else "" command = "%s %s HTTP/1.1" % (method, resource) if body is not None: headers["Content-Length"] = len(body) message = "%s\r\n%s" % (command, headers) self._outstanding += 1 if timeout is not None: self._timer = Timer(timeout, SocketError(ETIMEDOUT), self.channel) \ .register(self) self.fire(write(message.encode('utf-8')), self._transport) if body is not None: self.fire(write(body), self._transport)
def test(manager, watcher, webapp, chunksize): echo = Echo().register(webapp) assert watcher.wait("registered", channel="wsserver") f = urlopen(webapp.server.http.base) s = f.read() assert s == b"Hello World!" watcher.clear() WebSocketsDispatcher("/websocket").register(webapp) assert watcher.wait("registered", channel="web") uri = "ws://{0:s}:{1:d}/websocket".format( webapp.server.host, webapp.server.port) WebSocketClient(uri).register(manager) client = Client().register(manager) assert watcher.wait("registered", channel="wsclient") assert watcher.wait("connected", channel="wsclient") assert watcher.wait("connect", channel="wsserver") assert len(echo.clients) == 1 assert watcher.wait("read", channel="ws") assert client.response.startswith("Welcome") watcher.clear() client.fire(write("Hello!"), "ws") assert watcher.wait("read", channel="ws") assert client.response == "Received: Hello!" watcher.clear() client.fire(write("World!"), "ws") assert watcher.wait("read", channel="ws") assert client.response == "Received: World!" watcher.clear() data = "A" * (chunksize + 1) client.fire(write(data), "ws") assert watcher.wait("read", channel="ws") assert client.response == "Received: %s" % (data,) f = urlopen(webapp.server.http.base) s = f.read() assert s == b"Hello World!" assert len(echo.clients) == 1 client.fire(close(), "ws") assert watcher.wait("disconnect", channel="wsserver") assert len(echo.clients) == 0 client.unregister() assert watcher.wait("unregistered")
def test(manager, watcher, webapp): echo = Echo().register(webapp) assert watcher.wait("registered", channel="wsserver") f = urlopen(webapp.server.http.base) s = f.read() assert s == b"Hello World!" watcher.clear() WebSocketsDispatcher("/websocket").register(webapp) assert watcher.wait("registered", channel="web") uri = "ws://{0:s}:{1:d}/websocket".format(webapp.server.host, webapp.server.port) WebSocketClient(uri).register(manager) client = Client().register(manager) assert watcher.wait("registered", channel="wsclient") assert watcher.wait("connected", channel="wsclient") assert watcher.wait("connect", channel="wsserver") assert len(echo.clients) == 1 assert watcher.wait("read", channel="ws") assert client.response.startswith("Welcome") watcher.clear() client.fire(write("Hello!"), "ws") assert watcher.wait("read", channel="ws") assert client.response == "Received: Hello!" for size in (BUFSIZE, BUFSIZE + 1, BUFSZIE * 2): data = "A" * (size + 1) client.fire(write(data), "ws") assert watcher.wait("read", channel="ws") assert client.response == "Received: %s" % (data, ) f = urlopen(webapp.server.http.base) s = f.read() assert s == b"Hello World!" assert len(echo.clients) == 1 client.fire(close(), "ws") assert watcher.wait("disconnect", channel="wsserver") assert len(echo.clients) == 0 client.unregister() assert watcher.wait("unregistered")
def _do_code_servkey(self, message): plainsymkey = Random.get_random_bytes(RANDBYTELEN) self.symkey = SHA256.new(str(plainsymkey).encode()).digest() pubkey = RSA.importKey(message) self.pubkey = PKCS1_OAEP.new(pubkey) ciphertext = self.pubkey.encrypt(self.symkey) self.fire(sockets.write(B_SYMKEY+ciphertext))
def test_unix(tmpfile, Poller): m = Manager() + Poller() server = Server() + UNIXServer(tmpfile) client = Client() + UNIXClient() server.register(m) client.register(m) m.start() try: assert pytest.wait_for(server, "ready") assert pytest.wait_for(client, "ready") client.fire(connect(tmpfile)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") client.fire(close()) assert pytest.wait_for(client, "disconnected") assert pytest.wait_for(server, "disconnected") server.fire(close()) assert pytest.wait_for(server, "closed") finally: m.stop()
def test_unix(tmpdir, Poller): m = Manager() + Poller() sockpath = tmpdir.ensure("test.sock") filename = str(sockpath) server = Server() + UNIXServer(filename) client = Client() + UNIXClient() server.register(m) client.register(m) m.start() try: assert pytest.wait_for(server, "ready") assert pytest.wait_for(client, "ready") client.fire(connect(filename)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") client.fire(close()) assert pytest.wait_for(client, "disconnected") assert pytest.wait_for(server, "disconnected") server.fire(close()) assert pytest.wait_for(server, "closed") finally: m.stop() os.remove(filename)
def _do_code_chalng(self, message): self.waiting = True self.challenger = decrypt_AES(self.symkey, message) print("{} is challenging you!\nAccept or deny?".format(self.challenger)) response = None while not response: r = input("> ").lower() if r in self.chalng_replies['accept']: response = 'accept' elif r in self.chalng_replies['deny']: response = 'deny' else: print("Invalid input. Accept or deny?") ciphertext = encrypt_AES(self.symkey, (self.username+','+self.challenger).encode()) self.first_listen_input = True if response == 'accept': self.fire(sockets.write(B_CHALNGACCEPT+ciphertext)) #self.fire(GameSessionInit(challenger)) elif response == 'deny': self.fire(sockets.write(B_CHALNGDENY+ciphertext)) self.challenger = None self.waiting = False self.fire(Listen())
def NewUser(self): while True: username = input("> ") if username in self.reserved: print("Username contains a reserved word. Try again.") elif not re.match('^[\w-]+$', username): print("Username may only contain alphanumeric characters. Try again.") elif len(username) > MAXNAMELEN: print("Name too long. Try again.") else: self.username = username ciphertext = encrypt_AES(self.symkey, self.username.encode()) self.fire(sockets.write(B_NEWUSER+ciphertext)) break
def GameSession(self, opponent): user_input = None while not user_input: if self.first_game_input: self.first_game_input = False user_input = read_game_input('['+self.username+']: ', self.my_turn) else: user_input = read_game_input('', self.my_turn) if self.my_turn: self.my_turn = False time_input_received = str(round(time.time(), 3)).encode() time_len = str(len(time_input_received)).encode() if user_input == ' ': message = B_GAMESLAP+encrypt_AES(self.symkey, time_input_received) elif user_input == 'n': message = B_GAMENEXT+encrypt_AES(self.symkey, time_input_received) elif user_input == 'q': message = B_GAMEQUIT+encrypt_AES(self.symkey, str(self.gameid).encode()) self.fire(GameSessionEnd()) else: print("Invalid user input for game session: '{}'".format(user_input), file=sys.stderr) self.fire(sockets.write(message))
def read(self, sock, data): self.fire(write(sock, "Received: " + data))
def connect(self, sock, host, port): self.clients.append(sock) print("WebSocket Client Connected:", host, port) self.fire(write(sock, "Welcome {0:s}:{1:d}".format(host, port)))
def Challenge(self, to_challenge): self.challenged = to_challenge print("Challenging {}...".format(to_challenge)) ciphertext = encrypt_AES(self.symkey, to_challenge.encode()) self.fire(sockets.write(B_CHALNG+ciphertext))
def send_json(self, msg, receiver = None): msg = simplejson.dumps(msg) for s in [receiver] if receiver else self.knownSockets: self.fireEvent(write(s, msg))
def _do_cmd_list(self): self.fire(sockets.write(B_USERLIST)) self.waiting = True