示例#1
0
    def _accept_conn(self):
        cl, remote_addr = self._listen_s.accept()
        print("Client connection from:", remote_addr)

        if len(self._clients) >= self._max_connections:
            # Maximum connections limit reached
            cl.setblocking(True)
            self._generate_static_page(cl, 503, '503 Too Many Connections')
            return

        data = cl.recv(64).decode()
        if data and 'Upgrade: websocket' not in data.split(
                '\r\n') and 'GET' == data.split(' ')[0]:
            # data should looks like GET /index.html HTTP/1.1\r\nHost: 19'
            # requested file is on second position in data, ignore all get parameters after question mark
            requested_file = data.split(' ')[1].split('?')[0]
            requested_file = "/index.html" if requested_file in [
                None, '/'
            ] else requested_file

            cl.setblocking(True)
            self._serve_file(requested_file, cl)
            return

        try:
            websocket_helper.server_handshake(cl)
            self._clients.append(
                self._make_client(
                    WebSocketConnection(remote_addr, cl,
                                        self.remove_connection)))
        except OSError:
            self._generate_static_page(cl, 500,
                                       '500 Internal Server Error [2]')
示例#2
0
def accept_conn(listen_sock):
    global client_s, key, cert, websslrepl
    cl, remote_addr = listen_sock.accept()
    prev = uos.dupterm(None)
    uos.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    if websslrepl:
        if hasattr(uos, 'dupterm_notify'):
            cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
        cl = ssl.wrap_socket(cl, server_side=True, key=key, cert=cert)
        wss_helper.server_handshake(cl, ssl=True)
    else:
        websocket_helper.server_handshake(cl)
    ws = uwebsocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data (ESP32/ESP8266-only)
    if not websslrepl:
        if hasattr(uos, 'dupterm_notify'):
            cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#3
0
    def _accept_conn(self, listen_sock):
        cl, remote_addr = self._listen_s.accept()
        print("Client connection from:", remote_addr)

        if len(self._clients) >= self._max_connections:
            # Maximum connections limit reached
            cl.setblocking(True)
            self._generate_static_page(cl, 503, "503 Too Many Connections")
            return

        requested_file = None
        data = cl.recv(64).decode()
        if data and "Upgrade: websocket" not in data.split(
                "\r\n") and "GET" == data.split(" ")[0]:
            # data should looks like GET /index.html HTTP/1.1\r\nHost: 19"
            # requested file is on second position in data, ignore all get parameters after question mark
            requested_file = data.split(" ")[1].split("?")[0]
            requested_file = self._page if requested_file in [
                None, "/"
            ] else requested_file

        try:
            websocket_helper.server_handshake(cl)
            self._clients.append(
                self._make_client(
                    WebSocketConnection(remote_addr, cl,
                                        self.remove_connection)))
        except OSError:
            if requested_file:
                cl.setblocking(True)
                self._serve_file(requested_file, cl)
            else:
                self._generate_static_page(cl, 500,
                                           "500 Internal Server Error [2]")
示例#4
0
文件: uremi.py 项目: pfalcon/uremi
 def http_handler(self, s, req):
     meth, path, proto = req.split()
     if path == b"/":
         server.skip_headers(s)
         s.write("HTTP/1.0 200 OK\r\n\r\n")
         render(self.w, s)
     elif path == b"/res/style.css":
         server.skip_headers(s)
         s.write("HTTP/1.0 200 OK\r\n\r\n")
         with open(path[1:], "rb") as f:
             data = f.read()
             s.write(data)
     elif path == b"/ws":
         websocket_helper.server_handshake(s)
         s = websocket.websocket(s)
         print("websock connected")
         while 1:
             data = s.readline()
             data = data.decode("ascii").rstrip().split()
             print(data)
             global CONN
             CONN = s
             EVENT_MAP[(int(data[0]), data[1])]()
     else:
         s.write("HTTP/1.0 404 NAK\r\n\r\n")
示例#5
0
 def accept_conn(self, listen_sock):
     cl, remote_addr = listen_sock.accept()
     print("\nWebSocket connection from:", remote_addr)
     websocket_helper.server_handshake(cl)
     self.ws = websocket.websocket(cl, True)
     self.ws.ioctl(9, 2)  # change to data frame
     cl.setblocking(False)
     self.client_s = cl
     self.connected = True
示例#6
0
def accept_ws(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    client_s.append(cl)

    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    cl.setblocking(False)
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#7
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
    print("WebREPL connected\n>>> ", end="")
示例#8
0
    def _accept(self, self_s):
        # handler for new incoming connections
        collect()
        sock, addr = self_s.accept(
        )  # client socket, client address (self_s == self._s, passed as param)

        if self._c_ip_max is not None:
            ip_conns = 0  # connections from this IP
            for c in self._c:
                if c.address[0] == addr[0]:
                    ip_conns += 1

            if ip_conns >= self._c_ip_max:  # too many from this IP
                sock.setblocking(True)
                self._serve_static(sock, 503)
                return

        if len(self._c) >= self._c_max:  # too many connections in general
            sock.setblocking(True)
            self._serve_static(sock, 503)
            return

        file_req = None  # path of requested file; set to index page if HTTP GET does not specify
        data = sock.recv(64).decode()
        if data and "Upgrade: websocket" not in data.split(
                '\r\n') and 'GET' == data.split(' ')[0]:
            # data should looks like GET /index.html HTTP/1.1\r\nHost: 19"
            # requested file is on second position in data, ignore all get parameters after question mark
            file_req = data.split(' ')[1].split('?')[0]
            if not file_req or file_req == '/':
                file_req = '/' + self._index_page  # eg "/index.html"

        try:
            websocket_helper.server_handshake(sock)
        except OSError:  # handshake failed (no websocket connection) -> file was required or serve default file
            if file_req:
                sock.setblocking(True)
                self._serve_file(sock, file_req)
            else:
                self._serve_static(sock, 500)
        else:
            c = self._Client()

            def remove(client):
                if client in self._c:
                    self._c.remove(client)

            c.setup(sock, addr, remove)

            self._c.append(c)
示例#9
0
def handle_conn(listen_sock):
    cl, remote_addr = listen_sock.accept()

    print("""

First-time WebREPL connection has been received. WebREPL initial setup
will now start over this connection. During setup, UART REPL will be
non-responsive. After setup finishes, the board will be rebooted. In
case of error during setup, current session will continue.

If you receive this message unexpectedly, it may mean that your WebREPL
connection is being hacked (power off board if unsure).
""")

    websocket_helper.server_handshake(cl)
    ws = websocket(cl)

    ws.write("""\
Welcome to MicroPython WebREPL!\r
\r
This is the first time you connect to WebREPL, so please set a password\r
to use for the following WebREPL sessions. Once you enter the password\r
twice, your board will reboot with WebREPL running in active mode. On\r
some boards, you may need to press reset button or reconnect power.\r
\r
""")

    while 1:
        passwd1 = getpass(ws, "New password: "******"Password too short\r\n")
            continue
        elif len(passwd1) > 9:
            ws.write("Password too long\r\n")
            continue
        passwd2 = getpass(ws, "Confirm password: "******"Passwords do not match\r\n")

    with open("port_config.py", "w") as f:
        f.write("WEBREPL_PASS = %r\n" % passwd1.decode("ascii"))

    ws.write("Password successfully set, restarting...\r\n")
    cl.close()
    time.sleep(2)
    import machine
    machine.reset()
示例#10
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    if uos.dupterm():
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#11
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    if uos.dupterm():
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#12
0
文件: webrepl.py 项目: ccldaout/esp32
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    prev = uos.dupterm(None)
    uos.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    uos.dupterm(ws)
示例#13
0
def handle_conn(listen_sock):
    cl, remote_addr = listen_sock.accept()

    print("""

First-time WebREPL connection has been received. WebREPL initial setup
will now start over this connection. During setup, UART REPL will be
non-responsive. After setup finishes, the board will be rebooted. In
case of error during setup, current session will continue.

If you receive this message unexpectedly, it may mean that your WebREPL
connection is being hacked (power off board if unsure).
""")

    websocket_helper.server_handshake(cl)
    ws = websocket(cl)

    ws.write("""\
Welcome to MicroPython WebREPL!\r
\r
This is the first time you connect to WebREPL, so please set a password\r
to use for the following WebREPL sessions. Once you enter the password\r
twice, your board will reboot with WebREPL running in active mode. On\r
some boards, you may need to press reset button or reconnect power.\r
\r
""")

    while 1:
        passwd1 = getpass(ws, "New password: "******"Password too short\r\n")
            continue
        passwd2 = getpass(ws, "Confirm password: "******"Passwords do not match\r\n")

    with open("port_config.py", "w") as f:
        f.write("WEBREPL_PASS = %r\n" % passwd1.decode("ascii"))

    ws.write("Password successfully set, restarting...\r\n")
    cl.close()
    time.sleep(2)
    import machine
    machine.reset()
示例#14
0
    def _accept_conn(self, list):
        cl, addr = self.sock.accept()

        self.close_prev_conn()  # Close any previous connections
        print("\nTotal Clients: %s" % len(self.clients))
        print(addr[0])
        print("Mem: %s" % gc.mem_free())

        if len(self.clients) >= self.max_conn:
            cl.setblocking(True)
            create_static_page(cl, 503, "503 Too Many Connections")
            return

        requested_file = None
        self.sock.settimeout(3)  # Timeout after n seconds

        # Catch timeouts, don't continue if timeout occurs
        try:
            data = cl.recv(
                64).decode()  # Get first 64 chars of browser response
        except OSError:
            print("TIMEOUT for: %s" % addr[0])
            if len(self.clients):
                self.clients[0].connection.close()
            return

        self.sock.settimeout(None)  # Remove timeout

        if data and "Upgrade: websocket" not in data.split(
                "\r\n") and "GET" == data.split(" ")[0]:
            requested_file = data.split(" ")[1].split("?")[0]
            requested_file = self.index_pg if requested_file in [
                None, "/"
            ] else requested_file

        try:
            websocket_helper.server_handshake(cl)
            self.clients.append(
                self.create_socket(
                    SocketConnection(addr, cl, self.remove_connection)))
        except OSError:
            if requested_file:
                self._serve_file(requested_file, cl)
            else:
                create_static_page(cl, 500, "500 Internal Server Error [2]")
示例#15
0
    def acceptConn(self, listenSock):
        cl, remote_addr = self.listenSock.accept()
        print("\nOtto WS connection from:", remote_addr)

        if self.clientSock is not None:
            try:
                self.webSock.close()
                self.clientSock.close()
            except:
                pass
            self.webSock = None
            self.clientSock = None

        self.clientSock = cl
        websocket_helper.server_handshake(self.clientSock)
        self.webSock = uwebsocket.websocket(self.clientSock, True)
        self.clientSock.setblocking(False)
        self.clientSock.setsockopt(socket.SOL_SOCKET, 20, self.wsRemoteCommand)
示例#16
0
 def _accept_handler(self, sock):
     (client_sock, client_addr) = sock.accept()
     callback = self.do_accept(client_addr)
     if callback is None:  # connection is rejected
         client_sock.close()
         return
     # Use the web REPL socket stuff to handle the connection
     websocket_helper.server_handshake(client_sock)
     websock = uwebsocket.websocket(client_sock, True)  # Blocking writes
     webreplsock = _webrepl._webrepl(websock)
     client_sock.setblocking(False)
     # Create a WSReader to read characters one by one and process lines
     websock_reader = WSReader(webreplsock, self, callback)
     # Update the list of connected clients
     self._clients.append((client_addr, websock_reader))
     # Let the WSReader callback handle incoming data
     client_sock.setsockopt(socket.SOL_SOCKET, 20,
                            websock_reader._client_cbk)
示例#17
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    prev = uos.dupterm(None)
    uos.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = uwebsocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data (ESP32/ESP8266-only)
    if hasattr(uos, "dupterm_notify"):
        cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#18
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = uwebsocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)

    # attach new
    prev = uos.dupterm(ws)

    # notify REPL on socket incoming data (ESP32/ESP8266-only)
    if hasattr(uos, "dupterm_notify"):
        cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)

    # last: close old, in case it errors out
    if prev:
        prev.close()
示例#19
0
    def accept_conn(cls, listen_sock):

        cl, remote_addr = listen_sock.accept()
        prev = uos.dupterm(None)
        uos.dupterm(prev)
        if prev:
            print("\nConcurrent WebREPL connection from", remote_addr,
                  "rejected")
            cl.close()
            return
        print("\nWebREPL connection from:", remote_addr)
        WebREPL().client_s = cl
        websocket_helper.server_handshake(cl)
        WebREPL().ws = websocket.websocket(cl, True)

        WebREPL().wr = _webrepl._webrepl(WebREPL().ws)
        type(WebREPL().wr)
        cl.setblocking(False)
        # notify REPL on socket incoming data
        cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
        uos.dupterm(WebREPL().wr)
示例#20
0
	def _process_conn(self, client):
		resp = client.conn.recv(64).decode()
		conn = client.conn
		
		conn.setblocking(True)
		
		# Process any websocket connections
		try:
			# If this is a websocket signal
			websocket_helper.server_handshake(conn)
			print("Websocket A")
			OpenSockets(conn, client.addr, client.s, None)  # Add this connect to the open sockets list
			print("Websocket B")
		except OSError:
			# If no websocket connection, run the page request
			# Get the requested page
			if resp:
				if "GET" == resp.split(" ")[0]:  # If this is a GET request
					get_file = resp.split(" ")[1].split("?")[0]
					print("Get file: %s" % get_file)
					self._serve_file(client, get_file)
示例#21
0
    def _accept_conn(self, listen_sock):
        cl, remote_addr = listen_sock.accept()
        print("Client connection from:", remote_addr)

        if len(self._clients) >= self._max_connections:
            # Maximum connections limit reached
            cl.setblocking(True)
            cl.sendall("HTTP/1.1 503 Too many connections\n\n")
            cl.sendall("\n")
            #TODO: Make sure the data is sent before closing
            sleep(0.1)
            cl.close()
            return

        try:
            websocket_helper.server_handshake(cl)
        except OSError:
            # Not a websocket connection, do nothing
            return

        self._clients.append(self._make_client(WebSocketConnection(remote_addr, cl, self.remove_connection)))
示例#22
0
def accept_conn(listen_s):
    """Accept socket connection & transform to WS
    
    Acceptes connection, makes it a WS and
    sets ws_inc_handler as the msg handler for the connection
    
    Arguments:
        listen_s {socket} -- The socket that is listened 
                             for connections on
    
    Returns:
        websocket -- The websocket connection
    """
    connection, remote_addr = listen_s.accept()
    print(remote_addr)
    websocket_helper.server_handshake(connection)
    print("Connection: ", connection)
    global ws
    ws = uwebsocket.websocket(connection, True)
    connection.setblocking(False)
    connection.setsockopt(socket.SOL_SOCKET, 20, ws_inc_handler)
    return ws
示例#23
0
    def _accept_conn(self, listen_sock):
        cl, remote_addr = listen_sock.accept()
        print("Client connection from:", remote_addr)

        if len(self._clients) >= self._max_connections:
            # Maximum connections limit reached
            cl.setblocking(True)
            cl.sendall("HTTP/1.1 503 Too many connections\n\n")
            cl.sendall("\n")
            #TODO: Make sure the data is sent before closing
            sleep(0.1)
            cl.close()
            return

        try:
            websocket_helper.server_handshake(cl)
        except OSError:
            # Not a websocket connection, serve webpage
            self._serve_page(cl)
            return

        self._clients.append(self._make_client(WebSocketConnection(remote_addr, cl, self.remove_connection)))