Run Python language bindings and example code through a linter and formatter

This commit is contained in:
Joseph Henry
2021-03-07 21:11:21 -08:00
parent e1d0f92d61
commit dd6cf48d61
2 changed files with 526 additions and 467 deletions

View File

@@ -1,159 +1,157 @@
import time, sys '''Example low-level socket usage'''
import time
import sys
import libzt import libzt
# Where identity files are stored
keyPath = "."
# Network to join
networkId = 0
# Port used by ZeroTier to send encpryted UDP traffic
# NOTE: Should be different from other instances of ZeroTier
# running on the same machine
ztServicePort = 9997
remoteIP = None
# A port your app logic may use
serverPort = 8080
# Flags to keep state
is_joined = False
is_online = False
mode = None
def print_usage(): def print_usage():
print("\nUsage: <server|client> <id_path> <nwid> <ztServicePort> <remoteIP> <serverPort>\n") '''print help'''
print(" Ex: python3 example.py server . 0123456789abcdef 9994 8080") print(
print(" Ex: python3 example.py client . 0123456789abcdef 9994 192.168.22.1 8080\n") "\nUsage: <server|client> <id_path> <nwid> <zt_service_port> <remote_ip> <remote_port>\n"
if (len(sys.argv) < 6): )
print('Too few arguments') print("Ex: python3 demo.py server . 0123456789abcdef 9994 8080")
if (len(sys.argv) > 7): print("Ex: python3 demo.py client . 0123456789abcdef 9994 192.168.22.1 8080\n")
print('Too many arguments') if len(sys.argv) < 6:
exit(0) print("Too few arguments")
# if len(sys.argv) > 7:
if (len(sys.argv) < 6 or len(sys.argv) > 7): print("Too many arguments")
print_usage() sys.exit(0)
if (sys.argv[1] == 'server' and len(sys.argv) == 6):
mode = sys.argv[1]
keyPath = sys.argv[2]
networkId = int(sys.argv[3],16)
ztServicePort = int(sys.argv[4])
serverPort = int(sys.argv[5])
if (sys.argv[1] == 'client' and len(sys.argv) == 7):
mode = sys.argv[1]
keyPath = sys.argv[2]
networkId = int(sys.argv[3],16)
ztServicePort = int(sys.argv[4])
remoteIP = sys.argv[5]
serverPort = int(sys.argv[6])
if (mode is None):
print_usage()
print('mode = ', mode)
print('path = ', keyPath)
print('networkId = ', networkId)
print('ztServicePort = ', ztServicePort)
print('remoteIP = ', remoteIP)
print('serverPort = ', serverPort)
is_joined = False # Flags to keep state
is_online = False # Flags to keep state
# #
# Event handler # Event handler
# #
class MyEventCallbackClass(libzt.EventCallbackClass): class MyEventCallbackClass(libzt.EventCallbackClass):
def on_zerotier_event(self, msg): def on_zerotier_event(self, msg):
global is_online global is_online
global is_joined global is_joined
print("eventCode=", msg.eventCode) print("eventCode=", msg.eventCode)
if (msg.eventCode == libzt.ZTS_EVENT_NODE_ONLINE): if msg.eventCode == libzt.ZTS_EVENT_NODE_ONLINE:
print("ZTS_EVENT_NODE_ONLINE") print("ZTS_EVENT_NODE_ONLINE")
print("nodeId="+hex(msg.node.address)) print("nodeId=" + hex(msg.node.address))
# The node is now online, you can join/leave networks # The node is now online, you can join/leave networks
is_online = True is_online = True
if (msg.eventCode == libzt.ZTS_EVENT_NODE_OFFLINE): if msg.eventCode == libzt.ZTS_EVENT_NODE_OFFLINE:
print("ZTS_EVENT_NODE_OFFLINE") print("ZTS_EVENT_NODE_OFFLINE")
if (msg.eventCode == libzt.ZTS_EVENT_NETWORK_READY_IP4): if msg.eventCode == libzt.ZTS_EVENT_NETWORK_READY_IP4:
print("ZTS_EVENT_NETWORK_READY_IP4") print("ZTS_EVENT_NETWORK_READY_IP4")
is_joined = True is_joined = True
# The node has successfully joined a network and has an address # The node has successfully joined a network and has an address
# you can perform network calls now # you can perform network calls now
if (msg.eventCode == libzt.ZTS_EVENT_PEER_DIRECT): if msg.eventCode == libzt.ZTS_EVENT_PEER_DIRECT:
print("ZTS_EVENT_PEER_DIRECT") print("ZTS_EVENT_PEER_DIRECT")
if (msg.eventCode == libzt.ZTS_EVENT_PEER_RELAY): if msg.eventCode == libzt.ZTS_EVENT_PEER_RELAY:
print("ZTS_EVENT_PEER_RELAY") print("ZTS_EVENT_PEER_RELAY")
# #
# Example start and join logic # Main
# #
print("Starting ZeroTier..."); def main():
eventCallback = MyEventCallbackClass() global is_online
libzt.start(keyPath, eventCallback, ztServicePort) global is_joined
print("Waiting for node to come online...")
while (not is_online):
time.sleep(1)
print("Joining network:", hex(networkId));
libzt.join(networkId)
while (not is_joined):
time.sleep(1) # You can ping this app at this point
print('Joined network')
key_file_path = "." # Where identity files are stored
network_id = 0 # Network to join
# Port used by ZeroTier to send encpryted UDP traffic
# NOTE: Should be different from other instances of ZeroTier
# running on the same machine
zt_service_port = 9997
remote_ip = None # ZeroTier IP of remote node
remote_port = 8080 # ZeroTier port your app logic may use
mode = None # client|server
if len(sys.argv) < 6 or len(sys.argv) > 7:
print_usage()
if sys.argv[1] == "server" and len(sys.argv) == 6:
mode = sys.argv[1]
key_file_path = sys.argv[2]
network_id = int(sys.argv[3], 16)
zt_service_port = int(sys.argv[4])
remote_port = int(sys.argv[5])
if sys.argv[1] == "client" and len(sys.argv) == 7:
mode = sys.argv[1]
key_file_path = sys.argv[2]
network_id = int(sys.argv[3], 16)
zt_service_port = int(sys.argv[4])
remote_ip = sys.argv[5]
remote_port = int(sys.argv[6])
if mode is None:
print_usage()
print("mode = ", mode)
print("path = ", key_file_path)
print("network_id = ", network_id)
print("zt_service_port = ", zt_service_port)
print("remote_ip = ", remote_ip)
print("remote_port = ", remote_port)
# #
# Example server # Example start and join logic
# #
if (mode == 'server'): print("Starting ZeroTier...")
print("Starting server...") event_callback = MyEventCallbackClass()
serv = libzt.socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0) libzt.start(key_file_path, event_callback, zt_service_port)
try: print("Waiting for node to come online...")
#serv.setblocking(True) while not is_online:
serv.bind(('::', serverPort)) time.sleep(1)
serv.listen(5) print("Joining network:", hex(network_id))
while True: libzt.join(network_id)
conn, addr = serv.accept() while not is_joined:
print('Accepted connection from: ', addr) time.sleep(1) # You can ping this app at this point
while True: print("Joined network")
print('recv:')
data = conn.recv(4096)
if data:
print('data = ', data)
#print(type(b'what'))
#exit(0)
if not data: break
print('send:')
#bytes(data, 'ascii') + b'\x00'
n_bytes = conn.send(data) # echo back to the server
print('sent ' + str(n_bytes) + ' byte(s)')
conn.close()
print('client disconnected')
except Exception as e:
print(e)
print('errno=',libzt.errno()) # See include/ZeroTierSockets.h for codes
#
# Example server
#
if mode == "server":
print("Starting server...")
serv = libzt.socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0)
try:
# serv.setblocking(True)
serv.bind(("0.0.0.0", remote_port))
serv.listen(5)
while True:
conn, addr = serv.accept()
print("Accepted connection from: ", addr)
while True:
print("recv:")
data = conn.recv(4096)
if data:
print("data = ", data)
# print(type(b'what'))
# exit(0)
if not data:
break
print("send:")
# bytes(data, 'ascii') + b'\x00'
n_bytes = conn.send(data) # echo back to the server
print("sent " + str(n_bytes) + " byte(s)")
conn.close()
print("client disconnected")
except Exception as ex:
print(ex)
print("errno=", libzt.errno()) # See include/ZeroTierSockets.h for codes
# #
# Example client # Example client
# #
if (mode == 'client'): if mode == "client":
print("Starting client...") print("Starting client...")
client = libzt.socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0) client = libzt.socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0)
try: try:
print("connecting...") print("connecting...")
client.connect((remoteIP, serverPort)) client.connect((remote_ip, remote_port))
print("send:") print("send:")
data = 'Hello, world!' data = "Hello, world!"
client.send(data) client.send(data)
data = client.recv(1024) data = client.recv(1024)
print('Received', repr(data)) print("Received", repr(data))
except Exception as e: except Exception as ex:
print(e) print(ex)
print('errno=',libzt.errno()) print("errno=", libzt.errno())
if __name__ == "__main__":
main()

View File

@@ -1,347 +1,408 @@
"""ZeroTier low-level socket interface"""
import libzt import libzt
class EventCallbackClass(libzt.PythonDirectorCallbackClass): class EventCallbackClass(libzt.PythonDirectorCallbackClass):
pass """ZeroTier event callback class"""
pass
# Convert libzt error code to exception
def handle_error(err): def handle_error(err):
if (err == libzt.ZTS_ERR_SOCKET): """Convert libzt error code to exception"""
raise Exception('ZTS_ERR_SOCKET (' + str(err) + ')') if err == libzt.ZTS_ERR_SOCKET:
if (err == libzt.ZTS_ERR_SERVICE): raise Exception("ZTS_ERR_SOCKET (" + str(err) + ")")
raise Exception('ZTS_ERR_SERVICE (' + str(err) + ')') if err == libzt.ZTS_ERR_SERVICE:
if (err == libzt.ZTS_ERR_ARG): raise Exception("ZTS_ERR_SERVICE (" + str(err) + ")")
raise Exception('ZTS_ERR_ARG (' + str(err) + ')') if err == libzt.ZTS_ERR_ARG:
# ZTS_ERR_NO_RESULT isn't strictly an error raise Exception("ZTS_ERR_ARG (" + str(err) + ")")
#if (err == libzt.ZTS_ERR_NO_RESULT): # ZTS_ERR_NO_RESULT isn't strictly an error
# raise Exception('ZTS_ERR_NO_RESULT (' + err + ')') # if (err == libzt.ZTS_ERR_NO_RESULT):
if (err == libzt.ZTS_ERR_GENERAL): # raise Exception('ZTS_ERR_NO_RESULT (' + err + ')')
raise Exception('ZTS_ERR_GENERAL (' + str(err) + ')') if err == libzt.ZTS_ERR_GENERAL:
raise Exception("ZTS_ERR_GENERAL (" + str(err) + ")")
# This implementation of errno is NOT thread safe # This implementation of errno is NOT thread safe
# That is, this value is shared among all lower-level socket calls # That is, this value is shared among all lower-level socket calls
# and may change for any reason at any time if you have multiple # and may change for any reason at any time if you have multiple
# threads making socket calls. # threads making socket calls.
def errno(): def errno():
return libzt.cvar.zts_errno """Return errno value of low-level socket layer"""
return libzt.cvar.zts_errno
# Start the ZeroTier service
def start(path, callback, port): def start(path, callback, port):
libzt.zts_start(path, callback, port) """Start the ZeroTier service"""
libzt.zts_start(path, callback, port)
# Stop the ZeroTier service
def stop(): def stop():
libzt.zts_stop() """Stop the ZeroTier service"""
libzt.zts_stop()
# [debug] Restarts the ZeroTier service and network stack
def restart(): def restart():
libzt.zts_restart() """[debug] Restarts the ZeroTier service and network stack"""
libzt.zts_restart()
# Permenantly shuts down the network stack.
def free(): def free():
libzt.zts_free() """Permenantly shuts down the network stack"""
libzt.zts_free()
# Join a ZeroTier network
def join(networkId): def join(network_id):
libzt.zts_join(networkId) """Join a ZeroTier network"""
libzt.zts_join(network_id)
# Leave a ZeroTier network
def leave(networkId): def leave(network_id):
libzt.zts_leave(networkId) """Leave a ZeroTier network"""
libzt.zts_leave(network_id)
# Orbit a moon
def zts_orbit(moonWorldId, moonSeed): def zts_orbit(moon_world_id, moon_seed):
return libzt.zts_orbit(moonWorldId, moonSeed) """Orbit a moon"""
return libzt.zts_orbit(moon_world_id, moon_seed)
# De-orbit a moon
def zts_deorbit(moonWorldId): def zts_deorbit(moon_world_id):
return libzt.zts_deorbit(moonWorldId) """De-orbit a moon"""
return libzt.zts_deorbit(moon_world_id)
# Pythonic class that wraps low-level sockets
class socket():
class socket:
_fd = -1 # native layer file descriptor """Pythonic class that wraps low-level sockets"""
_family = -1 _fd = -1 # native layer file descriptor
_type = -1 _family = -1
_proto = -1 _type = -1
_connected = False _proto = -1
_closed = True _connected = False
_bound = False _closed = True
_bound = False
def __init__(self, sock_family=-1, sock_type=-1, sock_proto=-1, sock_fd=None):
self._fd = sock_fd def __init__(self, sock_family=-1, sock_type=-1, sock_proto=-1, sock_fd=None):
self._family = sock_family self._fd = sock_fd
self._type = sock_type self._family = sock_family
self._family = sock_family self._type = sock_type
# Only create native socket if no fd was provided. We may have self._family = sock_family
# accepted a connection # Only create native socket if no fd was provided. We may have
if (sock_fd == None): # accepted a connection
self._fd = libzt.zts_socket(sock_family, sock_type, sock_proto) if sock_fd is None:
self._fd = libzt.zts_socket(sock_family, sock_type, sock_proto)
def has_dualstack_ipv6():
return True def has_dualstack_ipv6(self):
"""Return whether libzt supports dual stack sockets: yes"""
@property return True
def family(self):
return _family @property
def family(self):
@property """Return family of socket"""
def type(self): return self._family
return _type
@property
@property def type(self):
def proto(self): """Return type of socket"""
return _proto return self._type
# Intentionally not supported @property
def socketpair(self, family, type, proto): def proto(self):
raise NotImplementedError("socketpair(): libzt does not support AF_UNIX sockets") """Return protocol of socket"""
return self._proto
# Convenience function to create a connection to a remote host
def create_connection(self, remote_address): def socketpair(self, sock_family, sock_type, sock_proto):
# TODO: implement timeout """Intentionally not supported"""
conn = socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0) raise NotImplementedError(
conn.connect(remote_address) "socketpair(): libzt does not support AF_UNIX sockets"
return conn )
# Convenience function to create a listening socket def create_connection(self, remote_address):
def create_server(self, local_address, family=libzt.ZTS_AF_INET, backlog=None): """Convenience function to create a connection to a remote host"""
# TODO: implement reuse_port # TODO: implement timeout
conn = socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0) conn = socket(libzt.ZTS_AF_INET, libzt.ZTS_SOCK_STREAM, 0)
conn.bind(local_address) conn.connect(remote_address)
conn.listen(backlog) return conn
return conn
def create_server(self, local_address, sock_family=libzt.ZTS_AF_INET, backlog=None):
def fromfd(self, fd, family, type, proto=0): """Convenience function to create a listening socket"""
raise NotImplementedError("fromfd(): Not supported. OS File descriptors aren't used in libzt.") # TODO: implement reuse_port
conn = socket(sock_family, libzt.ZTS_SOCK_STREAM, 0)
def fromshare(self, data): conn.bind(local_address)
raise NotImplementedError("libzt does not support this (yet?)") conn.listen(backlog)
return conn
def close(self, fd):
raise NotImplementedError("close(fd): Not supported OS File descriptors aren't used in libzt.") def fromfd(self, fd, sock_family, sock_type, sock_proto=0):
"""libzt does not support this (yet)"""
def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): raise NotImplementedError(
raise NotImplementedError("libzt does not support this (yet?)") "fromfd(): Not supported. OS File descriptors aren't used in libzt."
)
def getfqdn(self, name):
raise NotImplementedError("libzt does not support this (yet?)") def fromshare(self, data):
"""libzt does not support this (yet)"""
def gethostbyname(self, hostname): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def getaddrinfo(self, host, port, sock_family=0, sock_type=0, sock_proto=0, flags=0):
def gethostbyname_ex(self, hostname): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def gethostname(self): def getfqdn(self, name):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def gethostbyaddr(self, ip_address):
raise NotImplementedError("libzt does not support this (yet?)") def gethostbyname(self, hostname):
"""libzt does not support this (yet)"""
def getnameinfo(self, sockaddr, flags): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def gethostbyname_ex(self, hostname):
def getprotobyname(self, protocolname): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def getservbyname(self, servicename, protocolname): def gethostname(self):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def getservbyport(self, port, protocolname):
raise NotImplementedError("libzt does not support this (yet?)") def gethostbyaddr(self, ip_address):
"""libzt does not support this (yet)"""
def ntohl(x): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def getnameinfo(self, sockaddr, flags):
def ntohs(x): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def htonl(x): def getprotobyname(self, protocolname):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def htons(x):
raise NotImplementedError("libzt does not support this (yet?)") def getservbyname(self, servicename, protocolname):
"""libzt does not support this (yet)"""
def inet_aton(ip_string): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def getservbyport(self, port, protocolname):
def inet_ntoa(packed_ip): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def inet_pton(address_family, ip_string): def ntohl(x):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def inet_ntop(address_family, packed_ip):
raise NotImplementedError("libzt does not support this (yet?)") def ntohs(x):
"""libzt does not support this (yet)"""
def CMSG_LEN(length): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def htonl(x):
def CMSG_SPACE(length): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def getdefaulttimeout(self): def htons(x):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def setdefaulttimeout(self, timeout):
raise NotImplementedError("libzt does not support this (yet?)") def inet_aton(ip_string):
"""libzt does not support this (yet)"""
def sethostname(self, name): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def inet_ntoa(packed_ip):
def if_nameindex(self): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def if_nametoindex(self, if_name): def inet_pton(address_family, ip_string):
raise NotImplementedError("if_nametoindex(): libzt does not name interfaces.") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def if_indextoname(self, if_index):
raise NotImplementedError("if_indextoname(): libzt does not name interfaces.") def inet_ntop(address_family, packed_ip):
"""libzt does not support this (yet)"""
# Accept connection on the socket raise NotImplementedError("libzt does not support this (yet?)")
def accept(self):
new_conn_fd, addr, port = libzt.zts_py_accept(self._fd) def CMSG_LEN(length):
if (new_conn_fd < 0): """libzt does not support this (yet)"""
handle_error(new_conn_fd) raise NotImplementedError("libzt does not support this (yet?)")
return None
return ztsocket(self._family, self._type, self._proto, new_conn_fd), addr def CMSG_SPACE(length):
"""libzt does not support this (yet)"""
# Bind the socket to a local interface address raise NotImplementedError("libzt does not support this (yet?)")
def bind(self, local_address):
err = libzt.zts_py_bind(self._fd, self._family, self._type, local_address) def getdefaulttimeout(self):
if (err < 0): """libzt does not support this (yet)"""
handle_error(err) raise NotImplementedError("libzt does not support this (yet?)")
# Close the socket def setdefaulttimeout(self, timeout):
def close(self): """libzt does not support this (yet)"""
err = libzt.zts_py_close(self._fd) raise NotImplementedError("libzt does not support this (yet?)")
if (err < 0):
handle_error(err) def sethostname(self, name):
"""libzt does not support this (yet)"""
# Connect the socket to a remote address raise NotImplementedError("libzt does not support this (yet?)")
def connect(self, remote_address):
err = libzt.zts_py_connect(self._fd, self._family, self._type, remote_address) def if_nameindex(self):
if (err < 0): """libzt does not support this"""
handle_error(err) raise NotImplementedError("if_nameindex(): libzt does not name interfaces.")
# Connect to remote host but return low-level result code, and errno on failure def if_nametoindex(self, if_name):
# This uses a non-thread-safe implementation of errno """libzt does not support this"""
def connect_ex(self, remote_address): raise NotImplementedError("if_nametoindex(): libzt does not name interfaces.")
err = libzt.zts_py_connect(self._fd, self._family, self._type, remote_address)
if (err < 0): def if_indextoname(self, if_index):
return errno() """libzt does not support this"""
return err raise NotImplementedError("if_indextoname(): libzt does not name interfaces.")
def detach(self): def accept(self):
raise NotImplementedError("detach(): Not supported. OS File descriptors aren't used in libzt.") """Accept connection on the socket"""
new_conn_fd, addr, port = libzt.zts_py_accept(self._fd)
def dup(self): if new_conn_fd < 0:
raise NotImplementedError("libzt does not support this (yet?)") handle_error(new_conn_fd)
return None
def fileno(self): return socket(self._family, self._type, self._proto, new_conn_fd), addr
raise NotImplementedError("libzt does not support this (yet?)")
def bind(self, local_address):
def get_inheritable(self): """Bind the socket to a local interface address"""
raise NotImplementedError("libzt does not support this (yet?)") err = libzt.zts_py_bind(self._fd, self._family, self._type, local_address)
if err < 0:
def getpeername(self): handle_error(err)
raise NotImplementedError("libzt does not support this (yet?)")
def close(self):
def getsockname(self): """Close the socket"""
raise NotImplementedError("libzt does not support this (yet?)") err = libzt.zts_py_close(self._fd)
if err < 0:
def getsockopt(self, level, optname, buflen): handle_error(err)
raise NotImplementedError("libzt does not support this (yet?)")
def connect(self, remote_address):
# Get whether this socket is in blocking or non-blocking mode """Connect the socket to a remote address"""
def getblocking(self): err = libzt.zts_py_connect(self._fd, self._family, self._type, remote_address)
return libzt.zts_py_getblocking(self._fd) if err < 0:
handle_error(err)
def gettimeout(self):
raise NotImplementedError("libzt does not support this (yet?)") def connect_ex(self, remote_address):
"""Connect to remote host but return low-level result code, and errno on failure
def ioctl(self, control, option): This uses a non-thread-safe implementation of errno
raise NotImplementedError("libzt does not support this (yet?)") """
err = libzt.zts_py_connect(self._fd, self._family, self._type, remote_address)
# Put the socket in a listening state (with an optional backlog argument) if err < 0:
def listen(self, backlog): return errno()
err = libzt.zts_py_listen(self._fd, backlog) return err
if (err < 0):
handle_error(err) def detach(self):
"""libzt does not support this"""
def makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None): raise NotImplementedError(
raise NotImplementedError("libzt does not support this (yet?)") "detach(): Not supported. OS File descriptors aren't used in libzt.")
# Read data from the socket def dup(self):
def recv(self, n_bytes, flags=0): """libzt does not support this"""
err, data = libzt.zts_py_recv(self._fd, n_bytes, flags) raise NotImplementedError("libzt does not support this (yet?)")
if (err < 0):
handle_error(err) def fileno(self):
return None """libzt does not support this"""
return data raise NotImplementedError("libzt does not support this (yet?)")
def recvfrom(self, bufsize, flags): def get_inheritable(self):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def recvmsg(self, bufsize, ancbufsize, flags):
raise NotImplementedError("libzt does not support this (yet?)") def getpeername(self):
"""libzt does not support this (yet)"""
def recvmsg_into(self, buffers, ancbufsize, flags): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def getsockname(self):
def recvfrom_into(self, buffer, nbytes, flags): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def recv_into(self, buffer, nbytes, flags): def getsockopt(self, level, optname, buflen):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
# Write data to the socket
def send(self, data, flags=0): def getblocking(self):
err = libzt.zts_py_send(self._fd, data, len(data), flags) """Get whether this socket is in blocking or non-blocking mode"""
if (err < 0): return libzt.zts_py_getblocking(self._fd)
handle_error(err)
return err def gettimeout(self):
"""libzt does not support this (yet)"""
def sendall(self, bytes, flags): raise NotImplementedError("libzt does not support this (yet?)")
raise NotImplementedError("libzt does not support this (yet?)")
def ioctl(self, control, option):
def sendto(self, bytes, address): """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
def sendto(self, bytes, flags, address): def listen(self, backlog):
raise NotImplementedError("libzt does not support this (yet?)") """Put the socket in a listening state (with an optional backlog argument)"""
err = libzt.zts_py_listen(self._fd, backlog)
def sendmsg(self, buffers, ancdata, flags, address): if err < 0:
raise NotImplementedError("libzt does not support this (yet?)") handle_error(err)
def sendmsg_afalg(self, msg, *, op, iv, assoclen, flags): def makefile(mode="r", buffering=None, *, encoding=None, errors=None, newline=None):
raise NotImplementedError("sendmsg_afalg(): libzt does not support AF_ALG") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def send_fds(self, sock, buffers, fds, flags, address):
raise NotImplementedError("libzt does not support this (yet?)") def recv(self, n_bytes, flags=0):
"""Read data from the socket"""
def recv_fds(self, sock, bufsize, maxfds, flags): err, data = libzt.zts_py_recv(self._fd, n_bytes, flags)
raise NotImplementedError("libzt does not support this (yet?)") if err < 0:
handle_error(err)
def sendfile(self, file, offset=0, count=None): return None
raise NotImplementedError("libzt does not support this (yet?)") return data
def set_inheritable(self, inheritable): def recvfrom(self, bufsize, flags):
raise NotImplementedError("libzt does not support this (yet?)") """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
# Set whether this socket is in blocking or non-blocking mode
def setblocking(self, flag): def recvmsg(self, bufsize, ancbufsize, flags):
libzt.zts_py_setblocking(self._fd, flag) """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def settimeout(self, value):
raise NotImplementedError("libzt does not support this (yet?)") def recvmsg_into(self, buffers, ancbufsize, flags):
"""libzt does not support this (yet)"""
def setsockopt(self, level, optname, value): raise NotImplementedError("libzt does not support this (yet?)")
# TODO: value: buffer
# TODO: value: int def recvfrom_into(self, buffer, n_bytes, flags):
# TODO: value: None -> optlen required """libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") raise NotImplementedError("libzt does not support this (yet?)")
# Shut down one or more aspects (rx/tx) of the socket def recv_into(self, buffer, n_bytes, flags):
def shutdown(self, how): """libzt does not support this (yet)"""
libzt.shutdown(self._fd, how) raise NotImplementedError("libzt does not support this (yet?)")
def send(self, data, flags=0):
"""Write data to the socket"""
err = libzt.zts_py_send(self._fd, data, len(data), flags)
if err < 0:
handle_error(err)
return err
def sendall(self, n_bytes, flags):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def sendto(self, n_bytes, flags, address):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def sendmsg(self, buffers, ancdata, flags, address):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def sendmsg_afalg(self, msg, *, op, iv, assoclen, flags):
"""libzt does not support this (yet)"""
raise NotImplementedError("sendmsg_afalg(): libzt does not support AF_ALG")
def send_fds(self, sock, buffers, fds, flags, address):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def recv_fds(self, sock, bufsize, maxfds, flags):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def sendfile(self, file, offset=0, count=None):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def set_inheritable(self, inheritable):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def setblocking(self, flag):
"""Set whether this socket is in blocking or non-blocking mode"""
libzt.zts_py_setblocking(self._fd, flag)
def settimeout(self, value):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
# TODO: value: buffer
# TODO: value: int
# TODO: value: None -> optlen required
def setsockopt(self, level, optname, value):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)")
def shutdown(self, how):
"""Shut down one or more aspects (rx/tx) of the socket"""
libzt.zts_shutdown(self._fd, how)