Skip to content

Commit

Permalink
network: add tcp_connect
Browse files Browse the repository at this point in the history
  • Loading branch information
doronz88 committed Feb 4, 2022
1 parent fc8860c commit 8fe1060
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/pyzshell/pyzshell/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,15 @@ def symbol(self, symbol: int):
""" at a symbol object from a given address """
return Symbol.create(symbol, self)

@property
def errno(self):
""" get info about the last occurred error """
errno = self.symbols.errno[0]
if not errno:
return
err_str = self.symbols.strerror(errno).peek_str()
return f'[{errno}] {err_str}'

@property
def environ(self) -> typing.List[str]:
result = []
Expand Down
22 changes: 22 additions & 0 deletions src/pyzshell/pyzshell/network.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
import socket as pysock

from pyzshell.exceptions import ZShellError
from pyzshell.structs.generic import sockaddr_in


class Network:
def __init__(self, client):
self._client = client

def socket(self, family=pysock.AF_INET, type=pysock.SOCK_STREAM, proto=0) -> int:
result = self._client.symbols.socket(family, type, proto).c_int64
if 0 == result:
raise ZShellError(f'failed to create socket: {result}')
return result

def tcp_connect(self, address: str, port: int):
sockfd = self.socket(family=pysock.AF_INET, type=pysock.SOCK_STREAM, proto=0)
servaddr = sockaddr_in.build(
{'sin_addr': pysock.inet_aton(address), 'sin_port': pysock.htons(port)})
self._client.symbols.errno[0] = 0
self._client.symbols.connect(sockfd, servaddr, len(servaddr))
if self._client.errno:
raise ZShellError(f'failed connecting to: {address}:{port} ({self._client.errno})')
return sockfd
21 changes: 19 additions & 2 deletions src/pyzshell/pyzshell/structs/generic.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
from construct import Int32ul, Int64ul, Int16ul
from construct import Int32ul, Int16ul, Struct, Int16sl, Bytes, Default, Int64sl, Const, PaddedString

UNIX_PATH_MAX = 108
AF_UNIX = 1
AF_INET = 2

uid_t = Int32ul
gid_t = Int32ul
time_t = Int32ul
long = Int64ul
long = Int64sl
mode_t = Int16ul
in_addr = Bytes(4)

sockaddr_in = Struct(
'sin_family' / Const(AF_INET, Int16sl),
'sin_port' / Int16ul,
'sin_addr' / in_addr,
'sin_zero' / Default(Bytes(8), b'\x00' * 8),
)

sockaddr_un = Struct(
'sun_family' / Const(AF_UNIX, Int16sl),
'sun_path' / PaddedString(UNIX_PATH_MAX, 'utf8'),
)

0 comments on commit 8fe1060

Please sign in to comment.