def socketpair():
s1, s2 = eunuchs.socketpair.socketpair()
p, c = (socket.fromfd(s1, socket.AF_UNIX, socket.SOCK_STREAM),
socket.fromfd(s2, socket.AF_UNIX, socket.SOCK_STREAM))
os.close(s1)
os.close(s2)
return p, c
python类AF_UNIX的实例源码
def __init__(self, addr, certfile, keyfile,
requestHandler=SSLRequestHandler,
logRequests=False, encoding=None, bind_and_activate=True,
address_family=socket.AF_INET):
self.logRequests = logRequests
StratumJSONRPCDispatcher.__init__(self, encoding)
# TCPServer.__init__ has an extra parameter on 2.6+, so
# check Python version and decide on how to call it
vi = sys.version_info
self.address_family = address_family
if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
# Unix sockets can't be bound if they already exist in the
# filesystem. The convention of e.g. X11 is to unlink
# before binding again.
if os.path.exists(addr):
try:
os.unlink(addr)
except OSError:
logging.warning("Could not unlink socket %s", addr)
SSLTCPServer.__init__(self, addr, certfile, keyfile, requestHandler, bind_and_activate)
if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def _start_worker(self):
env = dict(os.environ)
env["ABUSEHELPER_SUBPROCESS"] = ""
# Find out the full package & module name. Don't refer to the
# variable __loader__ directly to keep flake8 (version 2.5.0)
# linter happy.
fullname = globals()["__loader__"].fullname
own_conn, other_conn = native_socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
try:
process = subprocess.Popen(
[sys.executable, "-m", fullname],
preexec_fn=os.setpgrp,
stdin=other_conn.fileno(),
close_fds=True,
env=env
)
try:
conn = socket.fromfd(own_conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM)
except:
process.terminate()
process.wait()
raise
finally:
own_conn.close()
other_conn.close()
return process, conn
def __init__(self):
tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
self.tmap = {
"all": (tcp4, tcp6, udp4, udp6, unix),
"tcp": (tcp4, tcp6),
"tcp4": (tcp4,),
"tcp6": (tcp6,),
"udp": (udp4, udp6),
"udp4": (udp4,),
"udp6": (udp6,),
"unix": (unix,),
"inet": (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
self._procfs_path = None
def __init__(self):
self.handle = nfq.nfq_open()
self.fileno = nfq.nfq_fd(self.handle)
self.socket = socket.fromfd(self.fileno, socket.AF_UNIX, socket.SOCK_RAW)
if nfq.nfq_unbind_pf(self.handle, socket.AF_INET) < 0:
raise OSError('nfq_unbind_pf() failed. Are you root?')
if nfq.nfq_bind_pf(self.handle, socket.AF_INET) < 0:
raise OSError('nfq_bind_pf() failed. Are you root?')
def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler,
logRequests=False, encoding=None, bind_and_activate=True,
address_family=socket.AF_INET):
self.logRequests = logRequests
StratumJSONRPCDispatcher.__init__(self, encoding)
# TCPServer.__init__ has an extra parameter on 2.6+, so
# check Python version and decide on how to call it
vi = sys.version_info
self.address_family = address_family
if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
# Unix sockets can't be bound if they already exist in the
# filesystem. The convention of e.g. X11 is to unlink
# before binding again.
if os.path.exists(addr):
try:
os.unlink(addr)
except OSError:
logging.warning("Could not unlink socket %s", addr)
SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, addr, certfile, keyfile,
requestHandler=SSLRequestHandler,
logRequests=False, encoding=None, bind_and_activate=True,
address_family=socket.AF_INET):
self.logRequests = logRequests
StratumJSONRPCDispatcher.__init__(self, encoding)
# TCPServer.__init__ has an extra parameter on 2.6+, so
# check Python version and decide on how to call it
vi = sys.version_info
self.address_family = address_family
if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
# Unix sockets can't be bound if they already exist in the
# filesystem. The convention of e.g. X11 is to unlink
# before binding again.
if os.path.exists(addr):
try:
os.unlink(addr)
except OSError:
logging.warning("Could not unlink socket %s", addr)
SSLTCPServer.__init__(self, addr, certfile, keyfile, requestHandler, bind_and_activate)
if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def _compiler_build(compiler, code,
time_limit_ns, memory_limit_bytes, process_limit):
loop = get_event_loop()
sandbox = await _sandbox_pool.get()
try:
await compiler.prepare(sandbox, code.encode())
output_file = path.join(sandbox.in_dir, 'output')
mkfifo(output_file)
with socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK) as cgroup_sock:
cgroup_sock.bind(path.join(sandbox.in_dir, 'cgroup'))
cgroup_sock.listen()
build_task = loop.create_task(compiler.build(
sandbox,
output_file='/in/output',
cgroup_file='/in/cgroup'))
others_task = gather(read_pipe(output_file, _MAX_OUTPUT),
wait_cgroup(cgroup_sock,
build_task,
time_limit_ns,
memory_limit_bytes,
process_limit))
package, status = await build_task
output, (time_usage_ns, memory_usage_bytes) = await others_task
return package, output.decode(encoding='utf-8', errors='replace'), \
time_usage_ns, memory_usage_bytes
finally:
_sandbox_pool.put_nowait(sandbox)
def enter_cgroup(socket_path):
with socket(AF_UNIX, SOCK_STREAM) as sock:
sock.connect(socket_path)
sock.recv(1)
def __init__(self, interfaces: Iterable[VPPInterface], listen_socket: socket.socket, marks: Iterable[str] = None):
"""
Initialise VPP listener.
:param interfaces: The interfaces we listen to and their information
:param listen_socket: The socket we are listening on, may be a unicast or multicast socket
:param marks: Marks attached to this listener
"""
self.interfaces = interfaces
self.listen_socket = listen_socket
self.marks = list(marks or [])
# Check that we have Unix Domain sockets
if self.listen_socket.family != socket.AF_UNIX or self.listen_socket.type != socket.SOCK_DGRAM:
raise ListeningSocketError("Listen socket has to be Unix domain datagram socket")
def __init__(self):
tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
self.tmap = {
"all": (tcp4, tcp6, udp4, udp6, unix),
"tcp": (tcp4, tcp6),
"tcp4": (tcp4,),
"tcp6": (tcp6,),
"udp": (udp4, udp6),
"udp4": (udp4,),
"udp6": (udp6,),
"unix": (unix,),
"inet": (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
self._procfs_path = None
def process_inet(self, file, family, type_, inodes, filter_pid=None):
"""Parse /proc/net/tcp* and /proc/net/udp* files."""
if file.endswith('6') and not os.path.exists(file):
# IPv6 not supported
return
with open_text(file, buffering=BIGGER_FILE_BUFFERING) as f:
f.readline() # skip the first line
for lineno, line in enumerate(f, 1):
try:
_, laddr, raddr, status, _, _, _, _, _, inode = \
line.split()[:10]
except ValueError:
raise RuntimeError(
"error while parsing %s; malformed line %s %r" % (
file, lineno, line))
if inode in inodes:
# # We assume inet sockets are unique, so we error
# # out if there are multiple references to the
# # same inode. We won't do this for UNIX sockets.
# if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
# raise ValueError("ambiguos inode with multiple "
# "PIDs references")
pid, fd = inodes[inode][0]
else:
pid, fd = None, -1
if filter_pid is not None and filter_pid != pid:
continue
else:
if type_ == socket.SOCK_STREAM:
status = TCP_STATUSES[status]
else:
status = _common.CONN_NONE
try:
laddr = self.decode_address(laddr, family)
raddr = self.decode_address(raddr, family)
except _Ipv6UnsupportedError:
continue
yield (fd, family, type_, laddr, raddr, status, pid)
def _get_unix_sockets(self, pid):
"""Get UNIX sockets used by process by parsing 'pfiles' output."""
# TODO: rewrite this in C (...but the damn netstat source code
# does not include this part! Argh!!)
cmd = "pfiles %s" % pid
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if PY3:
stdout, stderr = [x.decode(sys.stdout.encoding)
for x in (stdout, stderr)]
if p.returncode != 0:
if 'permission denied' in stderr.lower():
raise AccessDenied(self.pid, self._name)
if 'no such process' in stderr.lower():
raise NoSuchProcess(self.pid, self._name)
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
lines = stdout.split('\n')[2:]
for i, line in enumerate(lines):
line = line.lstrip()
if line.startswith('sockname: AF_UNIX'):
path = line.split(' ', 2)[2]
type = lines[i - 2].strip()
if type == 'SOCK_STREAM':
type = socket.SOCK_STREAM
elif type == 'SOCK_DGRAM':
type = socket.SOCK_DGRAM
else:
type = -1
yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
def __init__(self):
tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
self.tmap = {
"all": (tcp4, tcp6, udp4, udp6, unix),
"tcp": (tcp4, tcp6),
"tcp4": (tcp4,),
"tcp6": (tcp6,),
"udp": (udp4, udp6),
"udp4": (udp4,),
"udp6": (udp6,),
"unix": (unix,),
"inet": (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
self._procfs_path = None
def process_inet(self, file, family, type_, inodes, filter_pid=None):
"""Parse /proc/net/tcp* and /proc/net/udp* files."""
if file.endswith('6') and not os.path.exists(file):
# IPv6 not supported
return
with open_text(file, buffering=BIGGER_FILE_BUFFERING) as f:
f.readline() # skip the first line
for lineno, line in enumerate(f, 1):
try:
_, laddr, raddr, status, _, _, _, _, _, inode = \
line.split()[:10]
except ValueError:
raise RuntimeError(
"error while parsing %s; malformed line %s %r" % (
file, lineno, line))
if inode in inodes:
# # We assume inet sockets are unique, so we error
# # out if there are multiple references to the
# # same inode. We won't do this for UNIX sockets.
# if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
# raise ValueError("ambiguos inode with multiple "
# "PIDs references")
pid, fd = inodes[inode][0]
else:
pid, fd = None, -1
if filter_pid is not None and filter_pid != pid:
continue
else:
if type_ == socket.SOCK_STREAM:
status = TCP_STATUSES[status]
else:
status = _common.CONN_NONE
try:
laddr = self.decode_address(laddr, family)
raddr = self.decode_address(raddr, family)
except _Ipv6UnsupportedError:
continue
yield (fd, family, type_, laddr, raddr, status, pid)
def cmd(id, args, socket_path, per_cmd_connection):
from socket import socket, AF_UNIX, SOCK_STREAM
sock = socket(AF_UNIX, SOCK_STREAM)
sock.connect(socket)
try:
msg = '%s %s' % (id, args)
sock.send(msg.encode())
resp = sock.recv(4096)
print(resp)
finally:
sock.close()
def read_ha_proxy_stats(haproxy_stats_socket):
conn = socket(AF_UNIX, SOCK_STREAM)
try:
conn.connect(haproxy_stats_socket)
conn.sendall(b'show stat\r\n')
data = conn.recv(BUFFER_SIZE)
while len(data) % BUFFER_SIZE == 0:
try:
data += conn.recv(BUFFER_SIZE, MSG_DONTWAIT)
except socket.error:
break
return data
finally:
conn.close()
def __get_sock(self):
if isinstance(self.__address, tuple):
family = socket.AF_INET
else:
family = socket.AF_UNIX
return socket.socket(family, socket.SOCK_STREAM)
def shutdown(self):
if self.local_end_type in ConnectionBased:
server_kill = self.socket_plinko(self.lhost,self.local_end_type)
if server_kill.type != socket.AF_UNIX:
server_kill.connect((self.lhost,self.lport))
server_kill.close()
elif "unix" in self.local_end_type:
try:
remove(self.lhost)
except:
output("[?.?] Unable to delete Unix Socket: %s"%self.lhost,YELLOW)
output("[^.^] Thanks for using Decept!")
sys.exit()