def bind_unix_listener(self):
# http://0pointer.de/blog/projects/systemd.html (search "file
# descriptor 3")
try:
socket_fd = 3
self.sock = socket.fromfd(socket_fd, socket.AF_UNIX,
socket.SOCK_STREAM)
self.sock.listen(50)
return self.sock
except (TypeError, BlockingIOError, socket.error, ValueError):
pass
try:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if os.path.exists(MESSAGE_SOCK_PATH):
os.remove(MESSAGE_SOCK_PATH)
self.sock.bind(MESSAGE_SOCK_PATH)
self.sock.listen(50)
return self.sock
except Exception as ex:
exc_type, exc_value, exc_tb = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_tb,
file=sys.stderr)
raise ex
python类fromfd()的实例源码
def NewConnection(self, path, fd, properties):
address = str(path)
address = address[len(address) - 17:len(address)]
address = address.replace("_", ":")
print_info("Connected: {}\n".format(address))
blue_socket = socket.fromfd(
fd.take(), socket.AF_UNIX, socket.SOCK_STREAM)
socket_sink = SocketSink(sock=blue_socket)
self.bridge = TCPBridge(
sink=socket_sink,
port_in=self.tcp_port_in,
port_out=self.tcp_port_out)
try:
self.bridge.start(in_background=False)
except TCPBridgeError as error:
print_error(str(error) + "\n")
self.bridge.stop()
blue_socket.close()
print_info("Disconnected: {}\n".format(address))
Bluetooth().disconnect(address)
def NewConnection(self, path, fd, properties):
self.fd = fd.take()
print("NewConnection(%s, %d)" % (path, self.fd))
server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
server_sock.setblocking(1)
server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n")
myfifo.openFifo()
print('enter recv loop\n')
try:
while True:
data = server_sock.recv(1024)
print("received: %s" % data)
myfifo.writeFifo(data)
#server_sock.send("looping back: %s\n" % data)
except IOError as err:
print (err)
pass
server_sock.close()
print("all done")
def NewConnection(self, path, fd, properties):
self.fd = fd.take()
print("NewConnection(%s, %d)" % (path, self.fd))
server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
server_sock.setblocking(1)
server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n")
try:
while True:
data = server_sock.recv(1024)
print("received: %s" % data)
server_sock.send("looping back: %s\n" % data)
except IOError:
pass
server_sock.close()
print("all done")
def NewConnection(self, path, fd, properties):
self.fd = fd.take()
device_path = os.path.basename(path)
print("\nConnected to %s\nPress [ENTER] to continue" % device_path)
server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
server_sock.settimeout(1)
server_sock.send("Hello, this is Edison!")
try:
while True:
try:
data = server_sock.recv(1024)
gardening_system.function(data)
if data == 'b':
server_sock.send(gardening_system.requestData())
except socket.timeout:
pass
gardening_system.myProgram()
except IOError:
pass
server_sock.close()
print("\nYour device is now disconnected\nPress [ENTER] to continue")
def processSockets(fd):
data = ""
server_sock = socket.fromfd(fd,
socket.AF_UNIX,
socket.SOCK_STREAM)
server_sock.settimeout(1)
server_sock.send("Hello, this is Edison!")
try:
while not closing:
try:
data = server_sock.recv(1024)
print ("Here's data %s" % data)
result = ha.callFunction(data)
if result:
server_sock.send(result)
except socket.timeout:
pass
except IOError:
pass
server_sock.close()
# Agent class
def NewConnection(self, path, fd, properties):
self.fd = fd.take()
device_path = os.path.basename(path)
print("\nConnected to %s\nPress [ENTER] to continue" % device_path)
server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
server_sock.settimeout(1)
server_sock.send("Hello, this is Edison!")
try:
while True:
try:
data = server_sock.recv(1024)
temperature_monitor.function(data)
if data == 'get':
server_sock.send(temperature_monitor.requestData())
except socket.timeout:
pass
temperature_monitor.myProgram()
except IOError:
pass
server_sock.close()
print("\nYour device is now disconnected\nPress [ENTER] to continue")
def get_high_socket_fd(self):
if WIN32:
# The child process will not have any socket handles, so
# calling socket.fromfd() should produce WSAENOTSOCK even
# if there is a handle of the same number.
return socket.socket().detach()
else:
# We want to produce a socket with an fd high enough that a
# freshly created child process will not have any fds as high.
fd = socket.socket().detach()
to_close = []
while fd < 50:
to_close.append(fd)
fd = os.dup(fd)
for x in to_close:
os.close(x)
return fd
def recvfd(socketfd):
"""
Receive a file descriptor from a L{sendmsg} message on the given C{AF_UNIX}
socket.
@param socketfd: An C{AF_UNIX} socket, attached to another process waiting
to send sockets via the ancillary data mechanism in L{send1msg}.
@param fd: C{int}
@return: a 2-tuple of (new file descriptor, description).
@rtype: 2-tuple of (C{int}, C{bytes})
"""
ourSocket = socket.fromfd(socketfd, socket.AF_UNIX, socket.SOCK_STREAM)
data, ancillary, flags = recvmsg(ourSocket)
[(cmsgLevel, cmsgType, packedFD)] = ancillary
# cmsgLevel and cmsgType really need to be SOL_SOCKET / SCM_RIGHTS, but
# since those are the *only* standard values, there's not much point in
# checking.
[unpackedFD] = unpack("i", packedFD)
return (unpackedFD, data)
def _fromListeningDescriptor(cls, reactor, fd, addressFamily, factory):
"""
Create a new L{Port} based on an existing listening I{SOCK_STREAM}
socket.
Arguments are the same as to L{Port.__init__}, except where noted.
@param fd: An integer file descriptor associated with a listening
socket. The socket must be in non-blocking mode. Any additional
attributes desired, such as I{FD_CLOEXEC}, must also be set already.
@param addressFamily: The address family (sometimes called I{domain}) of
the existing socket. For example, L{socket.AF_INET}.
@return: A new instance of C{cls} wrapping the socket given by C{fd}.
"""
port = socket.fromfd(fd, addressFamily, cls.socketType)
interface = port.getsockname()[0]
self = cls(None, factory, None, interface, reactor)
self._preexistingSocket = port
return self
def killSocket(self):
if not self.currentResponse:
return
try:
socket.fromfd(self.currentResponse.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM).shutdown(socket.SHUT_RDWR)
return
except AttributeError:
pass
except Exception, e:
util.ERROR(err=e)
try:
self.currentResponse.raw._fp.fp._sock.shutdown(socket.SHUT_RDWR)
except AttributeError:
pass
except Exception, e:
util.ERROR(err=e)
def get_high_socket_fd(self):
if WIN32:
# The child process will not have any socket handles, so
# calling socket.fromfd() should produce WSAENOTSOCK even
# if there is a handle of the same number.
return socket.socket().detach()
else:
# We want to produce a socket with an fd high enough that a
# freshly created child process will not have any fds as high.
fd = socket.socket().detach()
to_close = []
while fd < 50:
to_close.append(fd)
fd = os.dup(fd)
for x in to_close:
os.close(x)
return fd
def fromfd(fd, family, type_, proto=0):
s = socket.fromfd(fd, family, type_, proto)
if s.__class__ is not socket.socket:
s = socket.socket(_sock=s)
return s
def rebuild_socket(reduced_handle, family, type_, proto):
fd = rebuild_handle(reduced_handle)
_sock = fromfd(fd, family, type_, proto)
close(fd)
return _sock
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
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = port
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = port
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def adopt_sessions(self):
if not self.fdtx_path:
return
fdtx = FdTx(None)
fdtx.connect(self.fdtx_path, 5)
# receive open file descriptors together with their associated authkeys
while True:
try: # future safety: double the needed message length, two fd's
authkey, fd = fdtx.get(AUTHKEY_LENGTH*2, 2)
except ConnectionClosed:
break # other end sent all it had
if authkey not in self.adoption:
continue # session died during handover
self.adoption[authkey]['fd'] = fd[0] # just one fd per message
for authkey in self.adoption:
if 'fd' not in self.adoption[authkey]:
continue # session died during handover
# reconnect the session
fd = self.adoption[authkey]['fd']
pid = self.adoption[authkey]['pid']
address = tuple(self.adoption[authkey]['address'])
# represent the adopted session by an AdoptedSession instance that
# only implements .pid and .terminate()
local = AdoptedSession(pid)
sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
remote = RemoteSession(address, authkey, timeout=1, sock=sock)
self.add_connection(remote._connection, authkey)
self.sessions[authkey] = (local, remote)
# recreate the allocation records
alloc = self.adoption[authkey]['allocations']
for a in alloc:
resource = a['profile']
collateral = a['collateral']
self.allocators['local'].allocate(resource, remote, collateral)
def adopt_sessions(self):
if not self.fdtx_path:
return
fdtx = FdTx(None)
fdtx.connect(self.fdtx_path, 5)
# receive open file descriptors together with their associated authkeys
while True:
try: # future safety: double the needed message length, two fd's
authkey, fd = fdtx.get(AUTHKEY_LENGTH*2, 2)
except ConnectionClosed:
break # other end sent all it had
if authkey not in self.adoption:
continue # session died during handover
self.adoption[authkey]['fd'] = fd[0] # just one fd per message
for authkey in self.adoption:
if 'fd' not in self.adoption[authkey]:
continue # session died during handover
# reconnect the session
fd = self.adoption[authkey]['fd']
pid = self.adoption[authkey]['pid']
address = tuple(self.adoption[authkey]['address'])
# represent the adopted session by an AdoptedSession instance that
# only implements .pid and .terminate()
local = AdoptedSession(pid)
sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
remote = RemoteSession(address, authkey, timeout=1, sock=sock)
self.add_connection(remote._connection, authkey)
self.sessions[authkey] = (local, remote)
# recreate the allocation records
alloc = self.adoption[authkey]['allocations']
for a in alloc:
resource = a['profile']
collateral = a['collateral']
self.allocators['local'].allocate(resource, remote, collateral)
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, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = port
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def fromfd(fd, family, type_, proto=0):
s = socket.fromfd(fd, family, type_, proto)
if s.__class__ is not socket.socket:
s = socket.socket(_sock=s)
return s
def rebuild_socket(reduced_handle, family, type_, proto):
fd = rebuild_handle(reduced_handle)
_sock = fromfd(fd, family, type_, proto)
close(fd)
return _sock
def stop(self):
try:
if six.PY2:
self._response.raw._fp.close()
else:
s = socket.fromfd(self._response.raw._fp.fileno(),
socket.AF_INET,
socket.SOCK_STREAM)
s.shutdown(socket.SHUT_RDWR)
s.close()
except Exception:
pass
self._response.connection.close()
self._executor.shutdown(wait=False)
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = self.socket.getsockname()[1]
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = self.socket.getsockname()[1]
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = port
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = port
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
# If we are on Python 2 the return value from socket.fromfd
# is an internal socket object but what we need for ssl wrap
# is the wrapper around it :(
sock = self.socket
if PY2 and not isinstance(sock, socket.socket):
sock = socket.socket(sock.family, sock.type, sock.proto, sock)
self.socket = ssl_context.wrap_socket(sock, server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = None
def __init__(self, host, port, app, handler=None,
passthrough_errors=False, ssl_context=None, fd=None):
if handler is None:
handler = WSGIRequestHandler
self.address_family = select_ip_version(host, port)
if fd is not None:
real_sock = socket.fromfd(fd, self.address_family,
socket.SOCK_STREAM)
port = 0
HTTPServer.__init__(self, (host, int(port)), handler)
self.app = app
self.passthrough_errors = passthrough_errors
self.shutdown_signal = False
self.host = host
self.port = port
# Patch in the original socket.
if fd is not None:
self.socket.close()
self.socket = real_sock
self.server_address = self.socket.getsockname()
if ssl_context is not None:
if isinstance(ssl_context, tuple):
ssl_context = load_ssl_context(*ssl_context)
if ssl_context == 'adhoc':
ssl_context = generate_adhoc_ssl_context()
self.socket = ssl_context.wrap_socket(self.socket,
server_side=True)
self.ssl_context = ssl_context
else:
self.ssl_context = 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?')