Skip to content

Commit aba5dc5

Browse files
committed
remote: workaround potential nested eventloops
1 parent b4daf12 commit aba5dc5

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

pwnlib/tubes/remote.py

+16-6
Original file line numberDiff line numberDiff line change
@@ -110,19 +110,29 @@ 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(*info_args):
125+
loop = asyncio.get_event_loop()
126+
if loop.is_running():
127+
# If an event loop is already running, use it to run the async function
128+
future = asyncio.run_coroutine_threadsafe(async_getaddrinfo(*info_args), loop)
129+
return future.result()
130+
else:
131+
# If no event loop is running, create a new one
132+
return asyncio.run(async_getaddrinfo(*info_args))
133+
121134
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))
135+
hostnames = sync_getaddrinfo(self.rhost, self.rport, fam, typ, 0, socket.AI_PASSIVE)
126136
for res in hostnames:
127137
self.family, self.type, self.proto, _canonname, sockaddr = res
128138

0 commit comments

Comments
 (0)