Skip to content

Commit b9976b6

Browse files
committed
remote: workaround potential nested eventloops
Require python 3.7+ for `asyncio.get_running_loop()`
1 parent b4daf12 commit b9976b6

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

pwnlib/tubes/remote.py

+17-6
Original file line numberDiff line numberDiff line change
@@ -110,19 +110,30 @@ def _connect(self, fam, typ):
110110
sock = None
111111
timeout = self.timeout
112112

113-
async def resolve_hostname(host, port, fam=0, typ=0, proto=0, flags=0):
114-
loop = asyncio.get_event_loop()
113+
async def async_getaddrinfo(host, port, fam=0, typ=0, proto=0, flags=0):
114+
loop = asyncio.get_running_loop()
115115
try:
116116
result = await loop.getaddrinfo(host, port, family=fam, type=typ, proto=proto, flags=flags)
117117
except asyncio.exceptions.CancelledError:
118118
result = []
119119
return result
120120

121+
# Using asyncio to avoid blocking when DNS resolution fail. It's probably better
122+
# to use async all the ways to `sock.connect`. However, let's keep the changes
123+
# small until we have the needs.
124+
def sync_getaddrinfo(*args):
125+
loop = asyncio.get_event_loop()
126+
coro = async_getaddrinfo(*args)
127+
if loop.is_running():
128+
# If an event loop is already running, use it to run the async function
129+
future = asyncio.run_coroutine_threadsafe(coro, loop)
130+
return future.result()
131+
else:
132+
# If no event loop is running, create a new one
133+
return asyncio.run(coro)
134+
121135
with self.waitfor('Opening connection to %s on port %s' % (self.rhost, self.rport)) as h:
122-
# Using asyncio to avoid blocking when DNS resolution fail. It's probably better
123-
# to use async all the ways to `sock.connect`. However, let's keep the changes
124-
# small until we have the needs.
125-
hostnames = asyncio.run(resolve_hostname(self.rhost, self.rport, fam, typ, 0, socket.AI_PASSIVE))
136+
hostnames = sync_getaddrinfo(self.rhost, self.rport, fam, typ, 0, socket.AI_PASSIVE)
126137
for res in hostnames:
127138
self.family, self.type, self.proto, _canonname, sockaddr = res
128139

0 commit comments

Comments
 (0)