def main(use_stream=True): ssl_ctx = ssl.SSLContext() 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_ctx.wrap_socket(s) print(s) if use_stream: # Both CPython and Pycopy SSLSocket objects support read() and # write() methods. s.write(b"GET / HTTP/1.0\r\n\r\n") print(s.read(4096)) else: # Pycopy SSLSocket objects implement only stream interface, not # socket interface s.send(b"GET / HTTP/1.0\r\n\r\n") print(s.recv(4096)) s.close()
def open_connection(host, port, ssl=False, server_hostname=None): 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: s.close() raise if DEBUG and __debug__: log.debug("open_connection: After connect") yield IOWrite(s) if DEBUG and __debug__: log.debug("open_connection: After iowait: %s", s) s2 = s if ssl: if ssl is True: import ussl ssl = ussl.SSLContext() s2 = ssl.wrap_socket(s, server_hostname=server_hostname, do_handshake=False) s2.setblocking(False) return StreamReader(s, s2), StreamWriter(s, s2)
def instance1(): multitest.next() ctx = ssl.SSLContext() s = socket.socket() s.connect(socket.getaddrinfo(IP, PORT)[0][-1]) s = ctx.wrap_socket(s) s.write(b"client to server") print(s.read(16)) s.close()
def main(use_stream=True): ssl_ctx = ssl.SSLContext() ssl_ctx.set_cert_key(cert, key) 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_ctx.wrap_socket(client_s, server_side=True) print(client_s) print("Request:") if use_stream: # Both CPython and Pycopy 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:", repr(e)) else: print(client_s.recv(4096)) client_s.send(CONTENT % counter) client_s.close() counter += 1 print()
def instance0(): ctx = ssl.SSLContext() ctx.set_cert_key(cert, key) multitest.globals(IP=multitest.get_network_ip()) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1]) s.listen(1) multitest.next() s2, _ = s.accept() s2 = ctx.wrap_socket(s2, server_side=True) print(s2.read(16)) s2.write(b"server to client") s.close()
def request(method, url, data=None, json=None, headers={}, stream=None, parse_headers=True): redir_cnt = 1 if json is not None: assert data is None import ujson data = ujson.dumps(json) while True: 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, 0, usocket.SOCK_STREAM) ai = ai[0] resp_d = None if parse_headers is not False: resp_d = {} s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) if proto == "https:": ctx = ussl.SSLContext() s = ctx.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: s.write(b"Content-Type: application/json\r\n") if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"Connection: close\r\n\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.decode()) elif l.startswith(b"Location:") and 300 <= status <= 399: if not redir_cnt: raise ValueError("Too many redirects") redir_cnt -= 1 url = l[9:].decode().strip() #print("redir to:", url) status = 300 break if parse_headers is False: pass elif parse_headers is True: l = l.decode() k, v = l.split(":", 1) resp_d[k] = v.strip() else: parse_headers(l, resp_d) except OSError: s.close() raise if status != 300: break resp = Response(s) resp.status_code = status resp.reason = reason if resp_d is not None: resp.headers = resp_d return resp
try: import usocket as _socket except: import _socket try: import ussl as ssl except: import ssl # CPython only supports server_hostname with SSLContext ssl = ssl.SSLContext() 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:
# Calculate gzip dictionary size to use global gzdict_sz, gzdict_buf if gzdict_buf: return sz = gc.mem_free() + gc.mem_alloc() if sz <= 65536: gzdict_sz = 16 + 12 gzdict_buf = bytearray(4096) else: gzdict_buf = bytearray(32768) import ussl import usocket warn_ussl = True ssl_ctx = ussl.SSLContext() def url_open(url): global warn_ussl if debug: print(url) proto, _, host, urlpath = url.split('/', 3) try: ai = usocket.getaddrinfo(host, 443, 0, usocket.SOCK_STREAM) except OSError as e: fatal("Unable to resolve %s (no Internet?)" % host, e) #print("Address infos:", ai) ai = ai[0]
try: import usocket as _socket except: import _socket try: import ussl as ssl except: import ssl if hasattr(ssl, "SSLContext"): # CPython and Pycopy support SSLContext, and Python API supports # server_hostname only on SSLContext. ctx = ssl.SSLContext() else: # Original MicroPython API doesn't have SSLContext, but supports # server_hostname param to module-global wrap_socket(). ctx = ssl 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 = ctx.wrap_socket(s, server_hostname=opts["host"]) else:
def get(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, 0, usocket.SOCK_STREAM) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) if proto == "https:": ctx = ussl.SSLContext() s = ctx.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() l = l.split(None, 2) #print(l) status = int(l[1]) 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") except OSError: s.close() raise return s
def __init__(self, protocol=PROTOCOL_TLS): self._ctx = _ussl.SSLContext(protocol)