4 import fishdescriptor.fish
13 usage = '''fishdescriptor [-p|--pid] <pid> <action>... [-p|--pid <pid> <action>...]
16 [<here-0fd>=]<there-fd>
17 fish the openfile referenced by descriptor <there-fd> in
18 (the most recent) <pid> and keep a descriptor onto it;
19 and, optionally, give it the number <here-fd> for exec
20 exec <program> [<arg>...]
21 execute a process with each specified <here>
24 calls getsockname/getpeername on the most recent
28 now attach to <pid>, detaching from previous pid
32 # list of (nominal, there) where nominal might be None
35 # fdmap[nominal] = (actual, Donor, there)
37 def implement_pending():
38 try: actuals = donor.fish([pend[1] for pend in pending])
39 except fishdescriptor.fish.Error as e:
40 print('fishdescriptor error: %s' % e, file=sys.stderr)
42 assert(len(actuals) == len(pending))
43 for (nominal, there), actual in zip(pending, actuals):
44 overwriting_info = fdmap.get(nominal)
45 if overwriting_info is not None: os.close(overwriting_info[0])
46 fdmap[nominal] = (actual, donor, there)
48 def implement_sockinfo(nominal):
49 (actual, tdonor, there) = fdmap[nominal]
50 # socket.fromfd requires the AF. But of course we don't know the AF.
51 # There isn't a sane way to get it in Python:
52 # https://utcc.utoronto.ca/~cks/space/blog/python/SocketFromFdMistake
54 # https://github.com/tiran/socketfromfd
55 # adds a dependency, not portable due to reliance on SO_DOMAIN
56 # call getsockname using ctypes
57 # no sane way to discover how to unpack sa_family_t
62 my $sa = getsockname STDIN;
63 exit 0 if !defined $sa and $!==ENOTSOCK;
64 my $family = sockaddr_family $sa;
65 print $family, "\n" or die $!;
67 famp = subprocess.Popen(
69 stdout = subprocess.PIPE,
70 args = ['perl','-we',perl_script]
72 (output, dummy) = famp.communicate()
75 sock = socket.fromfd(actual, family, 0)
77 print("[%s] %d sockinfo" % (tdonor.pid, there), end='')
78 for f in (lambda: socket.AddressFamily(family).name,
79 lambda: repr(sock.getsockname()),
80 lambda: repr(sock.getpeername())):
82 except Exception as e: info = repr(e)
83 print("\t", info, sep='', end='')
88 def permute_fds_for_exec():
89 actual2intended = { info[0]: nominal for nominal, info in fdmap.items() }
90 # invariant at the start of each loop iteration:
91 # for each intended (aka `nominal') we have processed:
92 # relevant open-file is only held in fd intended
93 # (unless `nominal' is None in which case it is closed)
94 # for each intended (aka `nominal') we have NOT processed:
95 # relevant open-file is only held in actual
96 # where actual = fdmap[nominal][0]
97 # and where actual2intended[actual] = nominal
98 # we can rely on processing each intended only once,
99 # since they're hash keys
100 # the post-condition is not really a valid state (fdmap
101 # is nonsense) but we call this function just before exec
102 for intended, (actual, tdonor, there) in fdmap.items():
103 if intended == actual:
105 if intended is not None:
106 inway_intended = actual2intended.get(intended)
107 if inway_intended is not None:
108 inway_moved = os.dup(intended)
109 actual2intended[inway_moved] = inway_intended
110 fdmap[inway_intented][0] = inway_moved
111 os.dup2(actual, intended)
114 def implement_exec(argl):
115 if donor is not None: donor.detach()
117 permute_fds_for_exec()
118 os.execvp(argl[0], argl)
122 if donor is not None: donor.detach()
123 donor = fishdescriptor.fish.Donor(pid, debug=ov.debug)
125 def ocb_set_donor(option, opt, value, parser):
128 ov = optparse.Values()
135 def arg_matches(regexp):
137 m = re.search(regexp, arg)
140 op = optparse.OptionParser(usage=usage)
142 op.disable_interspersed_args()
143 op.add_option('-p','--pid', type='int', action='callback',
144 callback=ocb_set_donor)
145 op.add_option('-D','--debug', action='store_const',
146 dest='debug', const=sys.stderr)
150 last_nominal = None # None or (nominal,) ie None or (None,) or (int,)
153 (ov, args) = op.parse_args(args=args, values=ov)
154 if not len(args): break
160 elif arg_matches(r'^(?:(\d+)=)?(\d+)?$'):
161 (nominal, there) = m.groups()
162 nominal = None if nominal is None else int(nominal)
164 pending.append((nominal,there))
165 last_nominal = (nominal,)
168 op.error("exec needs command to run")
171 elif arg == 'sockinfo':
172 if last_nominal is None:
173 op.error('sockinfo needs a prior fd spec')
175 implement_sockinfo(last_nominal[0])
177 op.error("unknown argument/option `%s'" % arg)