4 import fishdescriptor.fish
12 usage = '''fishdescriptor [-p|--pid] <pid> <action>... [-p|--pid <pid> <action>...]
15 [<here-0fd>=]<there-fd>
16 fish the openfile referenced by descriptor <there-fd> in
17 (the most recent) <pid> and keep a descriptor onto it;
18 and, optionally, give it the number <here-fd> for exec
19 exec <program> [<arg>...]
20 execute a process with each specified <here>
23 calls getsockname/getpeername on the most recent
27 now attach to <pid>, detaching from previous pid
31 # list of (nominal, there) where nominal might be None
34 # fdmap[nominal] = (actual, Donor, there)
36 def implement_pending():
37 actuals = donor.fish([pend[1] for pend in pending])
38 assert(len(actuals) == len(pending))
39 for (nominal, there), actual in zip(pending, actuals):
40 overwriting_info = fdmap.get(nominal)
41 if overwriting_info is not None: os.close(overwriting_info[0])
42 fdmap[nominal] = (actual, donor, there)
44 def implement_sockinfo(nominal):
45 (actual, tdonor, there) = fdmap[nominal]
46 # socket.fromfd requires the AF. But of course we don't know the AF.
47 # There isn't a sane way to get it in Python:
48 # https://utcc.utoronto.ca/~cks/space/blog/python/SocketFromFdMistake
50 # https://github.com/tiran/socketfromfd
51 # adds a dependency, not portable due to reliance on SO_DOMAIN
52 # call getsockname using ctypes
53 # no sane way to discover how to unpack sa_family_t
58 my $sa = getsockname STDIN;
59 exit 0 if !defined $sa and $!==ENOTSOCK;
60 my $family = sockaddr_family $sa;
61 print $family, "\n" or die $!;
63 famp = subprocess.Popen(
65 stdout = subprocess.PIPE,
66 args = ['perl','-we',perl_script]
68 (output, dummy) = famp.communicate()
71 sock = socket.fromfd(actual, family, 0)
73 print("[%s] %d sockinfo" % (tdonor.pid, there), end='')
74 for f in (lambda: socket.AddressFamily(family).name,
75 lambda: repr(sock.getsockname()),
76 lambda: repr(sock.getpeername())):
78 except Exception as e: info = repr(e)
79 print("\t", info, sep='', end='')
84 def permute_fds_for_exec():
85 actual2intended = { info[0]: nominal for nominal, info in fdmap.items }
86 # invariant at the start of each loop iteration:
87 # for each intended (aka `nominal') we have processed:
88 # relevant open-file is only held in fd intended
89 # (unless `nominal' is None in which case it is closed)
90 # for each intended (aka `nominal') we have NOT processed:
91 # relevant open-file is only held in actual
92 # where actual = fdmap[nominal][0]
93 # and where actual2intended[actual] = nominal
94 # we can rely on processing each intended only once,
95 # since they're hash keys
96 # the post-condition is not really a valid state (fdmap
97 # is nonsense) but we call this function just before exec
98 for intended, (actual, tdonor, there) in fdmap.items():
99 if intended == actual:
101 if intended is not None:
102 inway_intended = actual2intended.get(intended)
103 if inway_intended is not None:
104 inway_moved = os.dup(intended)
105 actual2intended[inway_moved] = inway_intended
106 fdmap[inway_intented][0] = inway_moved
107 os.dup2(actual, intended)
110 def implement_exec(argl):
111 if donor is not None: donor.detach()
113 permut_fds_for_exec()
114 os.execvp(argl[0], argl)
118 if donor is not None: donor.detach()
119 donor = fishdescriptor.fish.Donor(pid)
121 def ocb_set_donor(option, opt, value, parser):
124 ov = optparse.Values()
131 def arg_matches(regexp):
133 m = re.search(regexp, arg)
136 op = optparse.OptionParser(usage=usage)
138 op.disable_interspersed_args()
139 op.add_option('-p','--pid', type='int', action='callback',
140 callback=ocb_set_donor)
143 last_nominal = None # None or (nominal,) ie None or (None,) or (int,)
146 (ov, args) = op.parse_args(args=args, values=ov)
147 if not len(args): break
150 print("ARG %s" % arg, file=sys.stderr)
153 print("SET_DONOR", file=sys.stderr)
155 elif arg_matches(r'^(?:(\d+)=)?(\d+)?$'):
156 (nominal, there) = m.groups()
157 nominal = None if nominal is None else int(nominal)
159 pending.append((nominal,there))
160 last_nominal = (nominal,)
163 op.error("exec needs command to run")
166 elif arg == 'sockinfo':
167 if last_nominal is None:
168 op.error('sockinfo needs a prior fd spec')
170 implement_sockinfo(last_nominal[0])
172 op.error("unknown argument/option `%s'" % arg)