def request(method, url, json=None, timeout=None, headers=None):
    urlparts = url.split('/', 3)
    proto = urlparts[0]
    host = urlparts[2]
    urlpath = '' if len(urlparts) < 4 else urlparts[3]

    if proto == 'http:':
        port = 80
    elif proto == 'https:':
        port = 443
    else:
        raise OSError('Unsupported protocol: %s' % proto[:-1])

    if ':' in host:
        host, port = host.split(':')
        port = int(port)

    if json is not None:
        content = ujson.dumps(json)
        content_type = CONTENT_TYPE_JSON
    else:
        content = None

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][4]

    sock = usocket.socket()

    if timeout is not None:
        assert SUPPORT_TIMEOUT, 'Socket does not support timeout'
        sock.settimeout(timeout)

    sock.connect(addr)

    if proto == 'https:':
        assert SUPPORT_SSL, 'HTTPS not supported: could not find ussl'
        sock = ussl.wrap_socket(sock)

    sock.write('%s /%s HTTP/1.0\r\nHost: %s\r\n' % (method, urlpath, host))

    if headers is not None:
        for header in headers.items():
            sock.write('%s: %s\r\n' % header)

    if content is not None:
        sock.write('content-length: %s\r\n' % len(content))
        sock.write('content-type: %s\r\n' % content_type)
        sock.write('\r\n')
        sock.write(content)
    else:
        sock.write('\r\n')

    l = sock.readline()
    protover, status, msg = l.split(None, 2)

    # Skip headers
    while sock.readline() != b'\r\n':
        pass

    return Response(int(status), sock)
Beispiel #2
0
def test(peer_addr):
    s = socket.socket()
    s.connect(peer_addr)
    s = ssl.wrap_socket(s)
    cert = s.getpeercert(True)
    print(type(cert), len(cert) > 100)
    s.close()
Beispiel #3
0
 def __init__(self, url, post_data={}):
     self.code = 0
     self.headers = {}
     self.body = ""
     self.url = url
     [scheme, host, path, data] = urlparse(self.url)
     if scheme == 'http':
         addr = socket.getaddrinfo(host, 80)[0][-1]
         s = socket.socket()
         s.settimeout(5)
         s.connect(addr)
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC)
         sock.settimeout(5)
         s = ssl.wrap_socket(sock)
         s.connect(socket.getaddrinfo(host, 443)[0][4])
     if post_data:
         data = urlencode(post_data)
         #print('POST %s HTTP/1.0\r\nHost: %s\r\n\r\n%s\r\n' % (path or '/', host, data.strip()))
         s.send(b'POST %s HTTP/1.0\r\nHost: %s\r\n\r\n%s\r\n' % (path or '/', host, data.strip()))
     else:
         #print('GET %s%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path or '/', '?'+data.strip(), host))
         s.send(b'GET %s%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path or '/', '?'+data.strip(), host))
     while 1:
         recv = s.recv(1024)
         if len(recv) == 0: break
         self.body += recv.decode()
     s.close()
     self._parse_result()
Beispiel #4
0
def url_open(url):
    global warn_ussl
    proto, _, host, urlpath = url.split('/', 3)
    ai = usocket.getaddrinfo(host, 443)
    #print("Address infos:", ai)
    addr = ai[0][4]

    s = usocket.socket(ai[0][0])
    #print("Connect address:", addr)
    s.connect(addr)

    if proto == "https:":
        s = ussl.wrap_socket(s)
        if warn_ussl:
            print("Warning: %s SSL certificate is not validated" % host)
            warn_ussl = False

    # MicroPython rawsocket module supports file interface directly
    s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
    l = s.readline()
    protover, status, msg = l.split(None, 2)
    if status != b"200":
        if status == b"404":
            print("Package not found")
        raise ValueError(status)
    while 1:
        l = s.readline()
        if not l:
            raise ValueError("Unexpected EOF")
        if l == b'\r\n':
            break

    return s
Beispiel #5
0
 def connect(self, clean_session=True):
     self.sock = socket.socket()
     self.sock.connect(self.addr)
     if self.ssl:
         import ussl
         self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
     msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
     msg[1] = 10 + 2 + len(self.client_id)
     msg[9] = clean_session << 1
     if self.user is not None:
         msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
         msg[9] |= 0xC0
     if self.keepalive:
         assert self.keepalive < 65536
         msg[10] |= self.keepalive >> 8
         msg[11] |= self.keepalive & 0x00FF
     if self.lw_topic:
         msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
         msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
         msg[9] |= self.lw_retain << 5
     self.sock.write(msg)
     #print(hex(len(msg)), hexlify(msg, ":"))
     self._send_str(self.client_id)
     if self.lw_topic:
         self._send_str(self.lw_topic)
         self._send_str(self.lw_msg)
     if self.user is not None:
         self._send_str(self.user)
         self._send_str(self.pswd)
     resp = self.sock.read(4)
     assert resp[0] == 0x20 and resp[1] == 0x02
     if resp[3] != 0:
         raise MQTTException(resp[3])
     return resp[2] & 1
def open_connection(host, port, ssl=False):
    if DEBUG and __debug__:
        log.debug("open_connection(%s, %s)", host, port)
    ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
    ai = ai[0]
    s = _socket.socket(ai[0], ai[1], ai[2])
    s.setblocking(False)
    try:
        s.connect(ai[-1])
    except OSError as e:
        if e.args[0] != uerrno.EINPROGRESS:
            raise
    if DEBUG and __debug__:
        log.debug("open_connection: After connect")
    yield IOWrite(s)
#    if __debug__:
#        assert s2.fileno() == s.fileno()
    if DEBUG and __debug__:
        log.debug("open_connection: After iowait: %s", s)
    if ssl:
        print("Warning: uasyncio SSL support is alpha")
        import ussl
        s.setblocking(True)
        s2 = ussl.wrap_socket(s)
        s.setblocking(False)
        return StreamReader(s, s2), StreamWriter(s2, {})
    return StreamReader(s), StreamWriter(s, {})
def main(use_stream=True):
    s = _socket.socket()

    ai = _socket.getaddrinfo("google.com", 443)
    print("Address infos:", ai)
    addr = ai[0][-1]

    print("Connect address:", addr)
    s.connect(addr)

    s = ssl.wrap_socket(s)
    print(s)

    if use_stream:
        # Both CPython and MicroPython SSLSocket objects support read() and
        # write() methods.
        s.write(b"GET / HTTP/1.0\n\n")
        print(s.read(4096))
    else:
        # MicroPython SSLSocket objects implement only stream interface, not
        # socket interface
        s.send(b"GET / HTTP/1.0\n\n")
        print(s.recv(4096))

    s.close()
Beispiel #8
0
    def download(url, local_name):
        proto, _, host, urlpath = url.split('/', 3)
        ai = usocket.getaddrinfo(host, 443)
        #print("Address infos:", ai)
        addr = ai[0][4]

        s = usocket.socket()
        #print("Connect address:", addr)
        s.connect(addr)

        if proto == "https:":
            s = ussl.wrap_socket(s)

        # MicroPython rawsocket module supports file interface directly
        s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
        l = s.readline()
        protover, status, msg = l.split(None, 2)
        if status != b"200":
            raise OSError()
        while 1:
            l = s.readline()
            if not l:
                raise OSError()
            if l == b'\r\n':
                break
        with open(local_name, "wb") as f:
            while 1:
                l = s.read(1024)
                if not l:
                    break
                f.write(l)
Beispiel #9
0
def urlopen(url, data=None, method="GET"):
    if data is not None and method == "GET":
        method = "POST"
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][4]
    s = usocket.socket()
    s.connect(addr)
    if proto == "https:":
        s = ussl.wrap_socket(s, server_hostname=host)

    s.write(method)
    s.write(b" /")
    s.write(path)
    s.write(b" HTTP/1.0\r\nHost: ")
    s.write(host)
    s.write(b"\r\n")

    if data:
        s.write(b"Content-Length: ")
        s.write(str(len(data)))
        s.write(b"\r\n")
    s.write(b"\r\n")
    if data:
        s.write(data)

    l = s.readline()
    protover, status, msg = l.split(None, 2)
    status = int(status)
    #print(protover, status, msg)
    while True:
        l = s.readline()
        if not l or l == b"\r\n":
            break
        #print(l)
        if l.startswith(b"Transfer-Encoding:"):
            if b"chunked" in l:
                raise ValueError("Unsupported " + l)
        elif l.startswith(b"Location:"):
            raise NotImplementedError("Redirects not yet supported")

    return s
def request(method, url, data=None, json=None, headers={}, stream=None):
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][4]
    s = usocket.socket()
    s.connect(addr)
    if proto == "https:":
        s = ussl.wrap_socket(s)
    s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
    if not "Host" in headers:
        s.write(b"Host: %s\r\n" % host)
    if json is not None:
        assert data is None
        import ujson
        data = ujson.dumps(json)
    if data:
        s.write(b"Content-Length: %d\r\n" % len(data))
    s.write(b"\r\n")
    if data:
        s.write(data)

    l = s.readline()
    protover, status, msg = l.split(None, 2)
    status = int(status)
    #print(protover, status, msg)
    while True:
        l = s.readline()
        if not l or l == b"\r\n":
            break
        #print(line)
        if l.startswith(b"Transfer-Encoding:"):
            if b"chunked" in line:
                raise ValueError("Unsupported " + l)
        elif l.startswith(b"Location:"):
            raise NotImplementedError("Redirects not yet supported")

    resp = Response(s)
    resp.status_code = status
    resp.reason = msg.rstrip()
    return resp
Beispiel #11
0
def test_one(site, opts):
    ai = _socket.getaddrinfo(site, 443)
    addr = ai[0][-1]

    s = _socket.socket()

    try:
        s.connect(addr)

        if "sni" in opts:
            s = ssl.wrap_socket(s, server_hostname=opts["host"])
        else:
            s = ssl.wrap_socket(s)

        s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, 'latin'))
        resp = s.read(4096)
#        print(resp)

    finally:
        s.close()
Beispiel #12
0
def main(use_stream=True):
    s = socket.socket()

    # Binding to all interfaces - server will be accessible to other hosts!
    ai = socket.getaddrinfo("0.0.0.0", 8443)
    print("Bind address info:", ai)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to https://<this_host>:8443/")

    counter = 0
    while True:
        res = s.accept()
        client_s = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_s)
        client_s = ssl.wrap_socket(client_s, server_side=True)
        print(client_s)
        print("Request:")
        if use_stream:
            # Both CPython and MicroPython SSLSocket objects support read() and
            # write() methods.
            # Browsers are prone to terminate SSL connection abruptly if they
            # see unknown certificate, etc. We must continue in such case -
            # next request they issue will likely be more well-behaving and
            # will succeed.
            try:
                req = client_s.readline()
                print(req)
                while True:
                    h = client_s.readline()
                    if h == b"" or h == b"\r\n":
                        break
                    print(h)
                if req:
                    client_s.write(CONTENT % counter)
            except Exception as e:
                print("Exception serving request:", e)
        else:
            print(client_s.recv(4096))
            client_s.send(CONTENT % counter)
        client_s.close()
        counter += 1
        print()
def connect(uri):
    """
    Connect a websocket.
    """

    uri = urlparse(uri)
    assert uri

    if __debug__:
        LOGGER.debug("open connection %s:%s", uri.hostname, uri.port)

    sock = socket.socket()
    addr = socket.getaddrinfo(uri.hostname, uri.port)
    sock.connect(addr[0][4])
    if uri.protocol == "wss":
        sock = ussl.wrap_socket(sock)

    def send_header(header, *args):
        if __debug__:
            LOGGER.debug(str(header), *args)
        sock.write(header % args + "\r\n")

    # Sec-WebSocket-Key is 16 bytes of random base64 encoded
    key = binascii.b2a_base64(bytes(random.getrandbits(8) for _ in range(16)))[:-1]

    send_header(b"GET %s HTTP/1.1", uri.path or "/")
    send_header(b"Host: %s:%s", uri.hostname, uri.port)
    send_header(b"Connection: Upgrade")
    send_header(b"Upgrade: websocket")
    send_header(b"Sec-WebSocket-Key: %s", key)
    send_header(b"Sec-WebSocket-Version: 13")
    send_header(
        b"Origin: http://{hostname}:{port}".format(hostname=uri.hostname, port=uri.port)
    )
    send_header(b"")

    header = sock.readline()[:-2]
    assert header.startswith(b"HTTP/1.1 101 "), header

    # We don't (currently) need these headers
    # FIXME: should we check the return key?
    while header:
        if __debug__:
            LOGGER.debug(str(header))
        header = sock.readline()[:-2]

    return WebsocketClient(sock)
Beispiel #14
0
    def connect(self, clean_session=True):
        self.sock = socket.socket()
        addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        self.sock.connect(addr)
        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        premsg = bytearray(b"\x10\0\0\0\0\0")
        msg = bytearray(b"\x04MQTT\x04\x02\0\0")

        sz = 10 + 2 + len(self.client_id)
        msg[6] = clean_session << 1
        if self.user is not None:
            sz += 2 + len(self.user) + 2 + len(self.pswd)
            msg[6] |= 0xC0
        if self.keepalive:
            assert self.keepalive < 65536
            msg[7] |= self.keepalive >> 8
            msg[8] |= self.keepalive & 0x00FF
        if self.lw_topic:
            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
            msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
            msg[6] |= self.lw_retain << 5

        i = 1
        while sz > 0x7f:
            premsg[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        premsg[i] = sz

        self.sock.write(premsg, i + 2)
        self.sock.write(msg)
        #print(hex(len(msg)), hexlify(msg, ":"))
        self._send_str(self.client_id)
        if self.lw_topic:
            self._send_str(self.lw_topic)
            self._send_str(self.lw_msg)
        if self.user is not None:
            self._send_str(self.user)
            self._send_str(self.pswd)
        resp = self.sock.read(4)

        assert resp[0] == 0x20 and resp[1] == 0x02
        if resp[3] != 0:
            raise MQTTException(resp[3])
        return resp[2] & 1
Beispiel #15
0
    def connect(self, clean_session=True):

        if not self.sock:
            self.sock_connect()

        try:
            self.sock.connect(self.addr)
        except OSError as e:
            return None

        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
        msg[1] = 10 + 2 + len(self.client_id)
        msg[9] = clean_session << 1
        if self.user is not None:
            msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
            msg[9] |= 0xC0
        if self.keepalive:
            if self.keepalive > 65536:
                return None
            msg[10] |= self.keepalive >> 8
            msg[11] |= self.keepalive & 0x00FF
        # if self.lw_topic:
        #     msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
        #     msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
        #     msg[9] |= self.lw_retain << 5

        self.write(msg)

        self._send_str(self.client_id)

        # if self.lw_topic:
        #     self._send_str(self.lw_topic)
        #     self._send_str(self.lw_msg)

        if self.user is not None:
            self._send_str(self.user)
            self._send_str(self.pswd)

        resp = None
        try:
            resp = self.sock.read(4)
        except OSError as e:
            # print(e)
            return None
Beispiel #16
0
    def connect(self, clean_session=True):
        self.sock = socket.socket()
        addr = None
        addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        self.sock.connect(addr)
        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        premsg = bytearray(b"\x10\0\0\0\0\0")
        msg = bytearray(b"\x04MQTT\x04\x02\0\0")

        sz = 10 + 2 + len(self.client_id)
        msg[6] = clean_session << 1
        if self.user is not None:
            sz += 2 + len(self.user) + 2 + len(self.pswd)
            msg[6] |= 0xC0
        if self.keepalive:
            assert self.keepalive < 65536
            msg[7] |= self.keepalive >> 8
            msg[8] |= self.keepalive & 0x00FF
        if self.lw_topic:
            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
            msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
            msg[6] |= self.lw_retain << 5

        i = 1
        while sz > 0x7f:
            premsg[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        premsg[i] = sz

        self.sock.send(premsg[0:i + 2])
        self.sock.send(msg)
        #print(hex(len(msg)), hexlify(msg, ":"))
        self._send_str(self.client_id)
        if self.lw_topic:
            self._send_str(self.lw_topic)
            self._send_str(self.lw_msg)
        if self.user is not None:
            self._send_str(self.user)
            self._send_str(self.pswd)
        resp = self.sock.recv(4)
        assert resp[0] == 0x20 and resp[1] == 0x02
        if resp[3] != 0:
            raise MQTTException(resp[3])
        return resp[2] & 1
Beispiel #17
0
def getMessages(messages):

    if (connect.do_connect()):

        s = _socket.socket()

        ai = _socket.getaddrinfo(const.TELEGRAM_API, const.TELEGRAM_PORT)
        #print("Address infos:", ai)
        addr = ai[0][-1]

        print("Connect address Telegram:", addr)
        s.connect(addr)

        s.settimeout(const.TELEGRAM_TIMEOUT)

        s = ssl.wrap_socket(s)
        #print(s)
        print("\r\n")

        getRequest = "GET /bot"
        getRequest += const.TELEGRAM_TOKEN
        getRequest += messages
        getRequest += " HTTP/1.0\r\n\r\n"

        s.write(getRequest)
        quote = s.read(4096)
        #print(quote)
        quote = quote.decode("ascii")
        #print(quote)
        #print("\r\n")
        if (len(quote) > 0):
            #print(quote)

            ind = quote.find("\r\n\r\n")
            quote = quote[ind:]
            quote = json.loads(quote)
            try:
                quote = quote["result"][0]
            except:
                quote = quote["result"]
        else:
            quote = "No Message"

        #print("\r\n")
        s.close()

        return quote
Beispiel #18
0
 def connect(self, clean_session=True):
     self.sock = socket.socket()
     self.sock.connect(self.addr)
     if self.ssl:
         import ussl
         self.sock = ussl.wrap_socket(self.sock)
     msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
     msg[1] = 10 + 2 + len(self.client_id)
     msg[9] = clean_session << 1
     self.sock.write(msg)
     #print(hex(len(msg)), hexlify(msg, ":"))
     self._send_str(self.client_id)
     resp = self.sock.read(4)
     assert resp[0] == 0x20 and resp[1] == 0x02
     if resp[3] != 0:
         raise MQTTException(resp[3])
     return resp[2] & 1
Beispiel #19
0
def connect(uri):
    """
    Connect a websocket.
    """

    uri = urlparse(uri)
    assert uri

    if __debug__: LOGGER.debug("open connection %s:%s", uri.hostname, uri.port)

    sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    addr = socket.getaddrinfo(uri.hostname, uri.port)
    sock.connect(addr[0][4])
    if uri.protocol == 'wss':
        sock = ussl.wrap_socket(sock)

    def send_header(header, *args):
        if __debug__: LOGGER.debug(str(header), *args)
        sock.write(header % args + '\r\n')

    # Sec-WebSocket-Key is 16 bytes of random base64 encoded
    key = binascii.b2a_base64(bytes(random.getrandbits(8)
                                    for _ in range(16)))[:-1]

    send_header(b'GET %s HTTP/1.1', uri.path or '/')
    send_header(b'Host: %s:%s', uri.hostname, uri.port)
    send_header(b'Connection: Upgrade')
    send_header(b'Upgrade: websocket')
    send_header(b'Sec-WebSocket-Key: %s', key)
    send_header(b'Sec-WebSocket-Version: 13')
    send_header(b'Origin: http://localhost')
    send_header(b'')

    header = sock.readline()[:-2]
    assert header.startswith(b'HTTP/1.1 101 '), header

    # We don't (currently) need these headers
    # FIXME: should we check the return key?
    print("Header: {}".format(header))
    while header:
        if __debug__: LOGGER.debug(str(header))
        header = sock.readline()[:-2]
        print("Header: {}".format(header))

    return WebsocketClient(sock)
Beispiel #20
0
def updateGame():
    import usocket
    import ussl
    port = 443
    path = 'firstcaress/SimPortugal/master/game.py'
    host = 'raw.githubusercontent.com'
    proto = 'https:'
    method = 'GET'
    ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
    ai = ai[0]
    s = usocket.socket(ai[0], ai[1], ai[2])
    try:
        antonio = 3
        s.connect(ai[-1])
        if proto == "https:":
            s = ussl.wrap_socket(s, server_hostname=host)

        s.write(method)
        s.write(b" /")
        s.write(path)
        s.write(b" HTTP/1.0\r\nHost: ")
        s.write(host)
        s.write(b"\r\n")
        s.write(b"\r\n")
        l = s.readline()
        l = l.split(None, 2)
        status = int(l[1])
        actualizar = open('/flash/game.py', 'w')
        while True:
            l = s.readline()
            m = l.decode('utf-8')[:-2]

            if str(m) == "#comecar":
                antonio = 5
            if str(m) == "#acabar aqui":
                print("End Of File")
                Menu.load = "1.1"
                actualizar.close()
                machine.reset()
                break
            if antonio == 5:
                actualizar.write(m + '\n')
            print(m)
    except:
        print('error')
        Menu.load = "1.1"
Beispiel #21
0
def connect(uri):
    """
    Connect a websocket.
    """

    uri = urlparse(uri)
    assert uri

    if __DEBUG:
        print("open connection %s:%s" % (uri.hostname, uri.port))

    sock = socket.socket()
    addr = socket.getaddrinfo(uri.hostname, uri.port)
    sock.connect(addr[0][4])
    if uri.protocol == 'wss':
        sock = ussl.wrap_socket(sock)

    def send_header(header, *args):
        if __DEBUG:
            print(str(header), *args)
        sock.write(header % args + '\r\n')

    # Sec-WebSocket-Key is 16 bytes of random base64 encoded
    key = binascii.b2a_base64(ucrypto.getrandbits(16 * 8)).strip()

    send_header(b'GET %s HTTP/1.1', uri.path or '/')
    send_header(b'Host: %s:%s', uri.hostname, uri.port)
    send_header(b'Connection: Upgrade')
    send_header(b'Upgrade: websocket')
    send_header(b'Sec-WebSocket-Key: %s', key)
    send_header(b'Sec-WebSocket-Version: 13')
    send_header(b'Origin: http://localhost')
    send_header(b'')

    header = sock.readline()[:-2]
    assert header.startswith(b'HTTP/1.1 101 '), header

    # We don't (currently) need these headers
    # FIXME: should we check the return key?
    while header:
        if __DEBUG:
            print(str(header))
        header = sock.readline()[:-2]

    return WebsocketClient(sock)
Beispiel #22
0
 def connect(self, timeout=1, clean_session=True):
     assert len(self.alt_settings)
     serv, port, user, pswd, ssl, ca_certs, keepalive = self.alt_settings[
         self.alt_index].split(',')
     if serv.endswith('.local'):
         serv = get_localserver(serv, timeout=timeout)
         assert serv is not None
     addr_info = socket.getaddrinfo(serv, int(port))[0][-1]
     self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self._sock.setblocking(True)
     self._sock.connect(addr_info)
     if ssl:
         self._sock = ussl.wrap_socket(self._sock)
     msg = bytearray(b'\x10\x00\x00\x04MQTT\x04\x02\x00\x00')
     msg[1] = 10 + 2 + len(self.name)
     msg[9] = clean_session << 1
     if user:
         msg[1] += 2 + len(user) + 2 + len(pswd)
         msg[9] |= (0x03) << 6
     if keepalive:
         keepalive = int(keepalive)
         assert keepalive < 65536
         msg[10] |= keepalive >> 8
         msg[11] |= keepalive & 0x00FF
     if self._lw_topic:
         msg[1] += 2 + len(self._lw_topic) + 2 + len(self._lw_msg)
         msg[9] |= 0x4 | (self._lw_qos & 0x1) << 3 | (self._lw_qos
                                                      & 0x2) << 3
         msg[9] |= self._lw_retain << 5
     self._sock.write(msg)
     self._send_str(self.name)
     if self._lw_topic:
         self._send_str(self._lw_topic)
         self._send_str(self._lw_msg)
     if user:
         self._send_str(user)
         self._send_str(pswd)
     resp = self._sock.read(4)
     if resp is None or not len(resp):
         raise OSError(-1)
     assert resp[0] == 0x20 and resp[1] == 0x02
     if resp[3] != 0:
         raise OSError(resp[3])
     if self.connected_cb:
         self.connected_cb(resp[2] & 0x01, addr_info)
Beispiel #23
0
 def connect(A, clean_session=True, socket_timeout=-1):
     E = clean_session
     A.sock = socket.socket()
     G = socket.getaddrinfo(A.server, A.port)[0][-1]
     A.sock.connect(G)
     A._sock_timeout(socket_timeout)
     if A.ssl:
         import ussl
         A.sock = ussl.wrap_socket(A.sock, **A.ssl_params)
     F = bytearray(b'\x10\x00\x00\x00\x00\x00')
     B = bytearray(b'\x00\x04MQTT\x04\x00\x00\x00')
     D = 10 + 2 + len(A.client_id)
     B[7] = bool(E) << 1
     if bool(E): A.rcv_pids.clear()
     if A.user is not None:
         D += 2 + len(A.user)
         B[7] |= 1 << 7
         if A.pswd is not None:
             D += 2 + len(A.pswd)
             B[7] |= 1 << 6
     if A.keepalive:
         assert A.keepalive < 65536
         B[8] |= A.keepalive >> 8
         B[9] |= A.keepalive & 255
     if A.lw_topic:
         D += 2 + len(A.lw_topic) + 2 + len(A.lw_msg)
         B[7] |= 4 | (A.lw_qos & 1) << 3 | (A.lw_qos & 2) << 3
         B[7] |= A.lw_retain << 5
     H = A._varlen_encode(D, F, 1)
     A._write(F, H)
     A._write(B)
     A._send_str(A.client_id)
     if A.lw_topic:
         A._send_str(A.lw_topic)
         A._send_str(A.lw_msg)
     if A.user is not None:
         A._send_str(A.user)
         if A.pswd is not None: A._send_str(A.pswd)
     C = A._read(4)
     if not (C[0] == 32 and C[1] == 2): raise MQTTException(29)
     if C[3] != 0:
         if 1 <= C[3] <= 5: raise MQTTException(20 + C[3])
         else: raise MQTTException(20, C[3])
     A.last_cpacket = ticks_ms()
     return C[2] & 1
Beispiel #24
0
    def connect(self, clean_session=True):
        self.sock = socket.socket()
        addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        _ = self.sock.connect(
            addr)  #Added dummy variable to avoid print in stdout
        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        premsg = bytearray(b"\x10\0\0\0\0")
        msg = bytearray(b"\0\x04MQTT\x04\0\0\0")

        sz = 10 + 2 + len(self.client_id)
        msg[7] = clean_session << 1
        if self.user is not None:
            sz += 2 + len(self.user)
            msg[7] |= 1 << 7
            if self.pswd is not None:
                sz += 2 + len(self.pswd)
                msg[7] |= 1 << 6
        if self.keepalive:
            assert self.keepalive < 65536
            msg[8] |= self.keepalive >> 8
            msg[9] |= self.keepalive & 0x00FF
        if self.lw_topic:
            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
            msg[7] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
            msg[7] |= self.lw_retain << 5

        plen = self._varlen_encode(sz, premsg, 1)
        self.sock.write(premsg, plen)
        self.sock.write(msg)
        self._send_str(self.client_id)
        if self.lw_topic:
            self._send_str(self.lw_topic)
            self._send_str(self.lw_msg)
        if self.user is not None:
            self._send_str(self.user)
            if self.pswd is not None:
                self._send_str(self.pswd)
        resp = self.sock.read(4)
        assert resp[0] == 0x20 and resp[1] == 0x02
        if resp[3] != 0:
            raise MQTTException(resp[3])
        return resp[2] & 1
Beispiel #25
0
def url_open(url):
    global warn_ussl

    if debug:
        print(url)

    proto, _, host, urlpath = url.split('/', 3)
    try:
        ai = usocket.getaddrinfo(host, 443)
    except OSError as e:
        fatal("Unable to resolve %s (no Internet?)" % host, e)
    #print("Address infos:", ai)
    addr = ai[0][4]

    s = usocket.socket(ai[0][0])
    try:
        #print("Connect address:", addr)
        s.connect(addr)

        if proto == "https:":
            s = ussl.wrap_socket(s, server_hostname=host)
            if warn_ussl:
                print("Warning: %s SSL certificate is not validated" % host)
                warn_ussl = False

        # MicroPython rawsocket module supports file interface directly
        s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
        l = s.readline()
        protover, status, msg = l.split(None, 2)
        if status != b"200":
            if status == b"404" or status == b"301":
                raise NotFoundError("Package not found")
            raise ValueError(status)
        while 1:
            l = s.readline()
            if not l:
                raise ValueError("Unexpected EOF in HTTP headers")
            if l == b'\r\n':
                break
    except Exception as e:
        s.close()
        raise e

    return s
Beispiel #26
0
def url_open(url):
    global warn_ussl

    if debug:
        print(url)

    proto, _, host, urlpath = url.split('/', 3)
    try:
        ai = usocket.getaddrinfo(host, 443)
    except OSError as e:
        fatal("Unable to resolve %s (no Internet?)" % host, e)
    #print("Address infos:", ai)
    addr = ai[0][4]

    s = usocket.socket(ai[0][0])
    try:
        #print("Connect address:", addr)
        s.connect(addr)

        if proto == "https:":
            s = ussl.wrap_socket(s)
            if warn_ussl:
                print("Warning: %s SSL certificate is not validated" % host)
                warn_ussl = False

        # MicroPython rawsocket module supports file interface directly
        s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
        l = s.readline()
        protover, status, msg = l.split(None, 2)
        if status != b"200":
            if status == b"404" or status == b"301":
                raise NotFoundError("Package not found")
            raise ValueError(status)
        while 1:
            l = s.readline()
            if not l:
                raise ValueError("Unexpected EOF in HTTP headers")
            if l == b'\r\n':
                break
    except Exception as e:
        s.close()
        raise e

    return s
def main():
    underlying_socket = usocket.socket()

    ai = usocket.getaddrinfo("google.com", 443)
    print("Address infos:", ai)
    addr = ai[0][-1]

    print("Connect address:", addr)
    underlying_socket.connect(addr)

    wrapper_socket = ussl.wrap_socket(underlying_socket, do_handshake=False)
    wrapper_socket.setblocking(False)
    print(wrapper_socket)

    write_all(wrapper_socket, underlying_socket, b"GET / HTTP/1.0\r\n\r\n")
    print(read_all(wrapper_socket, underlying_socket, -1))

    wrapper_socket.close()
    underlying_socket.close()
Beispiel #28
0
def wrap_socket(sock, keyfile=None, certfile=None, server_side=False,
                cert_reqs=CERT_NONE, *, ca_certs=None, server_hostname=None):
    # TODO: More arguments accepted by CPython could also be handled here.
    # That would allow us to accept ca_certs as a positional argument, which
    # we should.
    kw = {}
    if keyfile is not None:
        kw["keyfile"] = keyfile
    if certfile is not None:
        kw["certfile"] = certfile
    if server_side is not False:
        kw["server_side"] = server_side
    if cert_reqs is not CERT_NONE:
        kw["cert_reqs"] = cert_reqs
    if ca_certs is not None:
        kw["ca_certs"] = ca_certs
    if server_hostname is not None:
        kw["server_hostname"] = server_hostname
    return _ussl.wrap_socket(sock, **kw)
Beispiel #29
0
def httpGetTest():
    s = _socket.socket()

    ai = _socket.getaddrinfo("api.trya.space", 443)
    print("Address infos:", ai)
    addr = ai[0][-1]

    print("Connect address:", addr)
    s.connect(addr)

    s = ssl.wrap_socket(s)
    print(s)

    # Both CPython and MicroPython SSLSocket objects support read() and
    # write() methods.
    s.write(b"GET / HTTP/1.0\r\n\r\n")
    print(s.read(4096))

    s.close()
Beispiel #30
0
def https_test(hostname=aws_endpoint, sslp=ssl_params):
    s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM,
                       usocket.IPPROTO_SEC)
    s.setblocking(False)
    w = ussl.wrap_socket(s, **ssl_params)
    print("connecting...")
    w.connect((hostname, 8443))
    print("connected")
    print("sending request")
    w.write(b'GET /things/%s/shadow HTTP/1.0\r\nHost: %s\r\n\r\n' %
            (thing_name, hostname))
    print("waiting for data...")
    while True:
        data = w.read(1024)
        if data:
            print(str(data, 'utf-8'))
            break
    w.close()
    print("DONE")
Beispiel #31
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    cl = ssl.wrap_socket(cl, server_side=True)
    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)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
def main(use_stream=True):
    s = socket.socket()

    # Binding to all interfaces - server will be accessible to other hosts!
    ai = socket.getaddrinfo("0.0.0.0", 8443)
    print("Bind address info:", ai)
    addr = ai[0][4]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to https://<this_host>:8443/")

    counter = 0
    while True:
        res = s.accept()
        client_s = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_s)
        client_s = ssl.wrap_socket(client_s, server_side=True)
        print(client_s)
        print("Request:")
        if use_stream:
            # Both CPython and MicroPython SSLSocket objects support read() and
            # write() methods.
            # Browsers are prone to terminate SSL connection abruptly if they
            # see unknown certificate, etc. We must continue in such case -
            # next request they issue will likely be more well-behaving and
            # will succeed.
            try:
                req = client_s.read(4096)
                print(req)
                if req:
                    client_s.write(CONTENT % counter)
            except Exception as e:
                print("Exception serving request:", e)
        else:
            print(client_s.recv(4096))
            client_s.send(CONTENT % counter)
        client_s.close()
        counter += 1
        print()
Beispiel #33
0
def http_get(url):
    proto, _, host, path = url.split('/', 3)
    port = 80
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC)
    if proto == "https:":
        import ussl
        s = ussl.wrap_socket(s)
        port = 443
    addr = socket.getaddrinfo(host, port)[0][-1]
    s.connect(addr)
    print(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host),
                 'utf8'))
    while True:
        data = s.recv(100)
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
Beispiel #34
0
def connect(protocol, address, timeout):

    if protocol == 'https:':
        sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM,
                              usocket.IPPROTO_SEC)
    else:
        sock = usocket.socket()

    if timeout is not None:
        assert SUPPORT_TIMEOUT, 'Socket does not support timeout'
        sock.settimeout(timeout)

    if protocol == 'https:':
        assert SUPPORT_SSL, 'HTTPS not supported: could not find ussl'
        #        sock = ussl.wrap_socket(sock, ssl_version=ussl.PROTOCOL_TLSv1)
        sock = ussl.wrap_socket(sock)

    sock.connect(address)

    return sock
def main(use_stream=True):
    s = _socket.socket()
    s.settimeout(1)
    host = "www.baidu.com"
    ai = _socket.getaddrinfo(host, 443)
    print("Address infos:", ai)
    addr = ai[0][-1]
    for i in range(5):
        try:
            print("Connect address:", addr)
            s.connect(addr)

            tmp = ssl.wrap_socket(s, server_hostname=host)

            tmp.write(b"GET / HTTP/1.1\r\n\r\n")
            print(tmp.readline('\r\n'))
        except Exception as e:
            print(e)

    s.close()
Beispiel #36
0
def open_connection(host, port, ssl=False):
    ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
    ai = ai[0]
    s = _socket.socket(ai[0], ai[1], ai[2])
    s.setblocking(False)
    try:
        s.connect(ai[-1])
    except OSError as e:
        if e.args[0] != uerrno.EINPROGRESS:
            raise
    yield IOWrite(s)
#    if __debug__:
#        assert s2.fileno() == s.fileno()
    if ssl:
        import ussl
        s.setblocking(True)
        s2 = ussl.wrap_socket(s)
        s.setblocking(False)
        return StreamReader(s, s2), StreamWriter(s2, {})
    return StreamReader(s), StreamWriter(s, {})
	def connect(A,clean_session=True):
		E=clean_session;A.sock=socket.socket();A.poller_r=uselect.poll();A.poller_r.register(A.sock,uselect.POLLIN);A.poller_w=uselect.poll();A.poller_w.register(A.sock,uselect.POLLOUT);G=socket.getaddrinfo(A.server,A.port)[0][-1];A.sock.connect(G)
		if A.ssl:import ussl;A.sock=ussl.wrap_socket(A.sock,**A.ssl_params)
		F=bytearray(b'\x10\x00\x00\x00\x00\x00');B=bytearray(b'\x00\x04MQTT\x04\x00\x00\x00');D=10+2+len(A.client_id);B[7]=bool(E)<<1
		if bool(E):A.rcv_pids.clear()
		if A.user is not None:
			D+=2+len(A.user);B[7]|=1<<7
			if A.pswd is not None:D+=2+len(A.pswd);B[7]|=1<<6
		if A.keepalive:assert A.keepalive<65536;B[8]|=A.keepalive>>8;B[9]|=A.keepalive&255
		if A.lw_topic:D+=2+len(A.lw_topic)+2+len(A.lw_msg);B[7]|=4|(A.lw_qos&1)<<3|(A.lw_qos&2)<<3;B[7]|=A.lw_retain<<5
		H=A._varlen_encode(D,F,1);A._write(F,H);A._write(B);A._send_str(A.client_id)
		if A.lw_topic:A._send_str(A.lw_topic);A._send_str(A.lw_msg)
		if A.user is not None:
			A._send_str(A.user)
			if A.pswd is not None:A._send_str(A.pswd)
		C=A._read(4)
		if not(C[0]==32 and C[1]==2):raise MQTTException(29)
		if C[3]!=0:
			if 1<=C[3]<=5:raise MQTTException(20+C[3])
			else:raise MQTTException(20,C[3])
		A.last_cpacket=ticks_ms();return C[2]&1
Beispiel #38
0
def main(use_stream=True):
    while True:
        d.measure()
        data = b"api_key=" + API_KEY + "&field1=" + str(
            d.temperature()) + "&field2=" + str(d.humidity())

        s = _socket.socket()
        ai = _socket.getaddrinfo(HOST, 443)
        addr = ai[0][-1]
        s.connect(addr)

        s = ssl.wrap_socket(s)

        s.write("POST /update HTTP/1.0\r\n")
        s.write("Host: " + HOST + "\r\n")
        s.write("Content-Length: " + str(len(data)) + "\r\n\r\n")
        s.write(data)
        print(s.read(128))

        s.close()
        time.sleep(60)
Beispiel #39
0
 def connect(self, clean_session=True):
     self.sock = socket.socket()
     try:
         self.sock.settimeout(30)
         self.sock.connect(self.addr)
         self.sock.settimeout(None)
     except Exception as e:
         print('MQTT connect error', e.args[0])
         return -1
     if self.ssl:
         import ussl
         self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
     msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
     msg[1] = 10 + 2 + len(self.client_id)
     msg[9] = clean_session << 1
     if self.user is not None:
         msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
         msg[9] |= 0xC0
     if self.keepalive:
         assert self.keepalive < 65536
         msg[10] |= self.keepalive >> 8
         msg[11] |= self.keepalive & 0x00FF
     if self.lw_topic:
         msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
         msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
         msg[9] |= self.lw_retain << 5
     self.sock.write(msg)
     #print(hex(len(msg)), hexlify(msg, ":"))
     self._send_str(self.client_id)
     if self.lw_topic:
         self._send_str(self.lw_topic)
         self._send_str(self.lw_msg)
     if self.user is not None:
         self._send_str(self.user)
         self._send_str(self.pswd)
     resp = self.sock.read(4)
     assert resp[0] == 0x20 and resp[1] == 0x02
     if resp[3] != 0:
         raise MQTTException(resp[3])
     return resp[2] & 1
Beispiel #40
0
def connect(uri):
    """
    Connect a websocket.
    """

    uri = urlparse(uri)
    assert uri

    sock = socket.socket()
    addr = socket.getaddrinfo(uri.hostname, uri.port)
    sock.connect(addr[0][4])
    if uri.protocol == 'wss':
        sock = ussl.wrap_socket(sock)

    def send_header(header, *args):
        sock.write(header % args + '\r\n')

    # Sec-WebSocket-Key is 16 bytes of random base64 encoded
    key = binascii.b2a_base64(bytes(random.getrandbits(8)
                                    for _ in range(16)))[:-1]

    send_header(b'GET %s HTTP/1.1', uri.path or '/')
    send_header(b'Host: %s:%s', uri.hostname, uri.port)
    send_header(b'Connection: Upgrade')
    send_header(b'Upgrade: websocket')
    send_header(b'Sec-WebSocket-Key: %s', key)
    send_header(b'Sec-WebSocket-Version: 13')
    send_header(b'Origin: http://{hostname}:{port}'.format(
        hostname=uri.hostname, port=uri.port))
    send_header(b'')

    header = sock.readline()[:-2]
    assert header.startswith(b'HTTP/1.1 101 '), header

    # We don't (currently) need these headers
    # FIXME: should we check the return key?
    while header:
        header = sock.readline()[:-2]

    return WebsocketClient(sock)
Beispiel #41
0
    def makeRequest(self):
        ai = usocket.getaddrinfo(self.host, self.port)
        addr = ai[0][-1]
        s = usocket.socket()
        s.connect(addr)
        if self.proto == "https:":
            import ussl
            s = ussl.wrap_socket(s)
        s.write(b"%s /%s HTTP/1.0\r\n" % (self.method, self.path))
        if "Host" not in self.headers:
            s.write(b"Host: %s\r\n" % self.host)
        # Iterate over keys to avoid tuple alloc
        for k in self.headers:
            s.write(k)
            s.write(b": ")
            s.write(self.headers[k])
            s.write(b"\r\n")
        if self.data:
            s.write(b"Content-Length: %d\r\n" % len(self.data))
        s.write(b"\r\n")
        if self.data:
            s.write(self.data)

        l = s.readline()
        protover, status, msg = l.split(None, 2)
        status = int(status)
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                print(status)
                raise NotImplementedError("Redirects not yet supported")
        s.close()
        self.status_code = status
        self.status_reason = msg.rstrip()
Beispiel #42
0
 def connect(self, clean_session=True):
     if self.ssl:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                   socket.IPPROTO_SEC)
     else:
         self.sock = socket.socket()
     self.sock.connect(self.addr)
     if self.ssl:
         import ussl
         self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
     msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
     msg[1] = 10 + 2 + len(self.client_id)
     msg[9] = clean_session << 1
     if self.user is not None:
         msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
         msg[9] |= 0xC0
     if self.keepalive:
         assert self.keepalive < 65536
         msg[10] |= self.keepalive >> 8
         msg[11] |= self.keepalive & 0x00FF
     if self.lw_topic:
         msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
         msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
         msg[9] |= self.lw_retain << 5
     self.sock.write(msg)
     #print(hex(len(msg)), hexlify(msg, ":"))
     self._send_str(self.client_id)
     if self.lw_topic:
         self._send_str(self.lw_topic)
         self._send_str(self.lw_msg)
     if self.user is not None:
         self._send_str(self.user)
         self._send_str(self.pswd)
     resp = self.sock.read(4)
     #print(hex(len(resp)), hexlify(resp, ":"))
     assert resp[0] == 0x20 and resp[1] == 0x02
     if resp[3] != 0:
         raise MQTTException(resp[3])
     return resp[2] & 1
Beispiel #43
0
 async def sock_connect_stream(uPK,
                               addr,
                               ssl_wrap=False,
                               timeouts=(20, 300)):
     if uPK.trace:
         uPK.trace('>>connect(%s, ssl_wrap=%s)' % (addr, ssl_wrap))
     s = socket.socket()
     try:
         s.settimeout(timeouts[0])
         await fuzzy_sleep_ms()
         s.connect(addr)
         s.settimeout(timeouts[1])
         await fuzzy_sleep_ms()
         if ssl_wrap:
             uPK.GC_COLLECT()
             await fuzzy_sleep_ms(30)
             return (s, ssl.wrap_socket(s))
         await fuzzy_sleep_ms()
         return (s, s)
     except:
         s.close()
         raise
Beispiel #44
0
def trigger(event, key, value1='', value2='', value3=''):  
    path = '/trigger/%s/with/key/%s' % (make_safe(event), make_safe(key))  
    data =  '{'+value1+':"",'+value2+':"",'+value3+':""}'
             
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(10)
    s = ssl.wrap_socket(sock)
    s.connect(socket.getaddrinfo(IFTTT_HOST, IFTTT_PORT)[0][4])
    
    request = '%s %s HTTP/1.0\r\n' % ('POST', path)
    request += 'Host: %s\r\n' % IFTTT_HOST
    request += 'Content-Type: application/json\r\n'
    request += 'Content-Length: %s\r\n\r\n%s\r\n\r\n' % (len(data), data)
    
    s.send(request)
    response = ''
    while 1:
        recv = s.readline()
        if len(recv) == 0: break
        response += recv.decode()
    s.close()
    return response
Beispiel #45
0
def _req(method="GET", path="/", data=None):
    if data != None:
        data = ujson.dumps(data)
    s = usocket.socket()

    ai = usocket.getaddrinfo(_host, 443)
    s.connect(ai[0][-1])
    s = ussl.wrap_socket(s, server_hostname=_host)

    s.write(b"{} {}.json?auth={} HTTP/1.1\r\n".format(method, path, _token))
    s.write(b"Host: {}\r\n".format(_host))
    s.write(b"Content-Type: application/json\r\n")
    if data != None:
        s.write(b"Content-Length: {}\r\n".format(len(data)))
    s.write(b"Connection: close\r\n")
    s.write(b"\r\n")
    if data:
        s.write(data)
    ros = s.read()
    print(ros)
    s.close()
    return ros
Beispiel #46
0
def trigger(event, key, value1='', value2='', value3=''):  
    path = '/trigger/%s/with/key/%s' % (make_safe(event), make_safe(key))  
    data =  '{"value1":"","value2":"","value3":""}'
             
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC)
    sock.settimeout(10)
    s = ssl.wrap_socket(sock)
    s.connect(socket.getaddrinfo(IFTTT_HOST, IFTTT_PORT)[0][4])
    
    request = '%s %s HTTP/1.0\r\n' % ('POST', path)
    request += 'Host: %s\r\n' % IFTTT_HOST
    request += 'Content-Type: application/json\r\n'
    request += 'Content-Length: %s\r\n\r\n%s\r\n\r\n' % (len(data), data)
    
    s.send(request)
    response = ''
    while 1:
        recv = s.readline()
        if len(recv) == 0: break
        response += recv.decode()
    s.close()
    return response
Beispiel #47
0
def post_msg(host, port, message):
    """Sings and posts the message to specified host and port"""
    global last_ticket

    # attach the last known ticket and the signature
    msg_and_ticket = '{0} {1}'.format(message, last_ticket)
    body = '{0} {1}'.format(msg_and_ticket,
                            simple_sign(msg_and_ticket,
                                        DEVICE_SECRET)).encode()

    # connect WIFI if required
    if not connect_wifi(WIFI_AP, WIFI_PASSWORD):
        # skip this measurement
        return

    # establish connection
    s = socket.socket()
    s.settimeout(2.0)
    s.connect(socket.getaddrinfo(host, port)[0][-1])
    s = ussl.wrap_socket(s)

    # Example of a request
    # POST / HTTP/1.1
    # Content-Length: 5
    #
    # <message> <last_ticket> <signature>
    s.write(b'POST / HTTP/1.1\r\n')
    s.write('Content-Length: {0}\r\n'.format(len(body)).encode())
    s.write(b'\r\n')
    s.write(body)

    # read response to find X-Ticket header
    rsp = s.read(1024)
    s.close()
    lines = rsp.decode('utf-8').split('\r\n')
    for l in lines:
        if l.startswith('X-Ticket:'):
            last_ticket = l.split(': ')[-1]
Beispiel #48
0
# very basic test of ssl module, just to test the methods exist

try:
    import uio as io
    import ussl as ssl
except ImportError:
    print("SKIP")
    raise SystemExit

# create in client mode
try:
    ss = ssl.wrap_socket(io.BytesIO())
except OSError as er:
    print('wrap_socket:', repr(er))

# create in server mode (can use this object for further tests)
socket = io.BytesIO()
ss = ssl.wrap_socket(socket, server_side=1)

# print
print(repr(ss)[:12])

# setblocking
try:
    ss.setblocking(False)
except NotImplementedError:
    print('setblocking: NotImplementedError')
ss.setblocking(True)

# write
print(ss.write(b'aaaa'))
def request(method, url, data=None, json=None, headers={}, stream=None):
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)
    s = usocket.socket()
    try:
        s.connect(usocket.getaddrinfo(host, port)[0][-1])
        if proto == "https:":
            s = ussl.wrap_socket(s, server_hostname=host)
        s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)
        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")
        if json is not None:
            assert data is None
            import ujson
            data = ujson.dumps(json)
            s.write(b"Content-Type: application/json\r\n")
        if data:
            s.write(b"Content-Length: %d\r\n" % len(data))
        s.write(b"\r\n")
        if data:
            s.write(data)

        l = s.readline()
        #print(l)
        l = l.split(None, 2)
        status = int(l[1])
        reason = ""
        if len(l) > 2:
            reason = l[2].rstrip()
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            #print(l)
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")
    except OSError:
        s.close()
        raise
    s.close()
    resp = Response(s)
    resp.status_code = status
    resp.reason = reason
    return resp
Beispiel #50
0
def request(method, url, json=None, timeout=None, headers=None):
    urlparts = url.split('/', 3)
    proto = urlparts[0]
    host = urlparts[2]
    urlpath = '' if len(urlparts) < 4 else urlparts[3]

    if proto == 'http:':
        port = 80
    elif proto == 'https:':
        port = 443
    else:
        raise OSError('Unsupported protocol: %s' % proto[:-1])

    if ':' in host:
        host, port = host.split(':')
        port = int(port)

    if json is not None:
        content = ujson.dumps(json)
        content_type = CONTENT_TYPE_JSON
    else:
        content = None

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][-1]

    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.IPPROTO_SEC)

    if timeout is not None:
        assert SUPPORT_TIMEOUT, 'Socket does not support timeout'
        sock.settimeout(timeout)

    if proto == 'https:':
        assert SUPPORT_SSL, 'HTTPS not supported: could not find ussl'
        sock = ussl.wrap_socket(sock)

    sock.connect(addr)

    sock.write('%s /%s HTTP/1.1\r\nHost: %s\r\n' % (method, urlpath, host))

    if headers is not None:
        for header in headers.items():
            sock.write('%s: %s\r\n' % header)

    if content is not None:
        # sock.write('authorization: %s\r\n' % 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NjYXBob2xkLmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHw1NzkwNGRlY2NjZjI5ZjAyMmQwZTk0MTEiLCJhdWQiOiJKdGdmeVpJUTJwSmo5ckk4RTllNjE3aFFjazBSbnhBbiIsImV4cCI6MTQ3MTY2NjkyNSwiaWF0IjoxNDY5MDc0OTI1fQ.WQiyNMzkL7djIj8g2-LgrWIsut68pbGp1c9dJ7i_JPc')
        sock.write('content-length: %s\r\n' % len(content))
        sock.write('content-type: %s\r\n' % content_type)
        sock.write('\r\n')
        sock.write(content)
    else:
        sock.write('\r\n')

    l = sock.readline()
    protover, status, msg = l.split(None, 2)

    # Skip headers
    while sock.readline() != b'\r\n':
        pass

    return Response(int(status), sock)