16 d._sp = subprocess.Popen(
17 preexec_fn = _shuffle_fd3,
18 stdin = subprocess.PIPE,
19 stdout = subprocess.PIPE,
21 args = ['gdb', '-p', str(pid), '-batch', '-ex',
22 'python import fishdescriptor.indonor as id;'+
23 ' id.DonorImplementation().eval_loop()'
27 def _eval_integer(d, expr):
28 l = d._sp.stdout.readline()
29 if l != b'!\n': raise RuntimeError("indonor said %s" % repr(l))
30 d._sp.stdin.write(expr.encode('utf-8') + b'\n')
32 l = d._sp.stdout.readline().rstrip(b'\n')
35 def _eval_success(d, expr):
36 r = d._eval_integer(expr)
37 if r != 1: raise RuntimeError("eval of %s gave %d" % (expr, r))
40 return d._eval_integer('di.geteuid()')
42 def _ancilmsg(d, fds):
47 my $fds = pack "i*", @ARGV;
48 my $m = Socket::MsgHdr::pack_cmsghdr SOL_SOCKET, SCM_RIGHTS, $fds;
49 print join ", ", unpack "C*", $m;
51 ap = subprocess.Popen(
52 stdin = subprocess.DEVNULL,
53 stdout = subprocess.PIPE,
54 args = ['perl','-we',perl_script] + [str(x) for x in fds]
56 (output, dummy) = ap.communicate()
57 return output.decode('utf-8')
59 def donate(d, path, fds):
60 ancil = d._ancilmsg(fds)
61 d._eval_success('di.donate(%s, [ %s ])'
62 % (repr(path), ancil))
63 return len(ancil.split(','))
66 d._eval_integer('di.mkdir(%s)'
74 if oe.errno != os.errno.ENOENT: raise oe
77 def _sock_dir(d, target_euid):
78 run_dir = '/run/user/%d' % target_euid
79 if d._exists(run_dir):
80 return run_dir + '/fishdescriptor'
83 pw = pwd.getpwuid(target_euid)
84 return pw.pw_dir + '/.fishdescriptor'
89 'cannot find good socket path - no /run/user/UID nor pw entry for target process euid %d'
94 # -> list of fds in our process
97 sockdir = d._sock_dir(euid)
100 sockname = '%s/%s,%d' % (sockdir, os.uname().nodename, d._pid)
102 target_root = '/proc/%d/root' % d._pid
103 if not d._exists(target_root):
106 our_sockname = target_root + sockname
112 try: os.remove(our_sockname)
113 except FileNotFoundError: pass
115 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
119 ancil_len = d.donate(our_sockname, fds)
120 (s2, dummy) = s.accept()
121 (msg, ancil, flags, sender) = s2.recvmsg(1, ancil_len)
124 unpack_fmt = '%di' % len(fds)
126 for clvl, ctype, cdata in ancil:
127 if clvl == socket.SOL_SOCKET and ctype == socket.SCM_RIGHTS:
128 assert(got_fds is None)
129 got_fds = struct.unpack_from(unpack_fmt, cdata)
132 if s is not None: s.close()
133 if s2 is not None: s2.close()
135 try: os.remove(our_sockname)
136 except FileNotFoundError: pass