17 def __init__(d, pid, debug=None):
20 d._stderr = tempfile.TemporaryFile(mode='w+')
23 d._sp = subprocess.Popen(
24 preexec_fn = _shuffle_fd3,
25 stdin = subprocess.PIPE,
26 stdout = subprocess.PIPE,
29 args = ['gdb', '-p', str(pid), '-batch', '-ex',
30 'python import fishdescriptor.indonor as id;'+
31 ' id.DonorImplementation().eval_loop()'
35 def _eval_integer(d, expr):
37 l = d._sp.stdout.readline()
38 if l != b'!\n': raise RuntimeError("indonor said %s" % repr(l))
39 d._sp.stdin.write(expr.encode('utf-8') + b'\n')
41 l = d._sp.stdout.readline().rstrip(b'\n')
43 except Exception as e:
44 if d._stderr is not None:
46 shutil.copyfileobj(d._stderr, sys.stderr)
51 def _eval_success(d, expr):
52 r = d._eval_integer(expr)
53 if r != 1: raise RuntimeError("eval of %s gave %d" % (expr, r))
56 return d._eval_integer('di.geteuid()')
58 def _ancilmsg(d, fds):
63 my $fds = pack "i*", @ARGV;
64 my $m = Socket::MsgHdr::pack_cmsghdr SOL_SOCKET, SCM_RIGHTS, $fds;
65 print join ", ", unpack "C*", $m;
67 ap = subprocess.Popen(
68 stdin = subprocess.DEVNULL,
69 stdout = subprocess.PIPE,
70 args = ['perl','-we',perl_script] + [str(x) for x in fds]
72 (output, dummy) = ap.communicate()
73 return output.decode('utf-8')
75 def donate(d, path, fds):
76 ancil = d._ancilmsg(fds)
77 d._eval_success('di.donate(%s, [ %s ])'
78 % (repr(path), ancil))
79 return len(ancil.split(','))
82 d._eval_integer('di.mkdir(%s)'
90 if oe.errno != os.errno.ENOENT: raise oe
93 def _sock_dir(d, target_euid):
94 run_dir = '/run/user/%d' % target_euid
95 if d._exists(run_dir):
96 return run_dir + '/fishdescriptor'
99 pw = pwd.getpwuid(target_euid)
100 return pw.pw_dir + '/.fishdescriptor'
105 'cannot find good socket path - no /run/user/UID nor pw entry for target process euid %d'
110 # -> list of fds in our process
113 sockdir = d._sock_dir(euid)
116 sockname = '%s/%s,%d' % (sockdir, os.uname().nodename, d.pid)
118 target_root = '/proc/%d/root' % d.pid
119 if not d._exists(target_root):
122 our_sockname = target_root + sockname
128 try: os.remove(our_sockname)
129 except FileNotFoundError: pass
131 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
135 ancil_len = d.donate(our_sockname, fds)
136 (s2, dummy) = s.accept()
137 (msg, ancil, flags, sender) = s2.recvmsg(1, ancil_len)
140 unpack_fmt = '%di' % len(fds)
142 for clvl, ctype, cdata in ancil:
143 if clvl == socket.SOL_SOCKET and ctype == socket.SCM_RIGHTS:
144 assert(got_fds is None)
145 got_fds = struct.unpack_from(unpack_fmt, cdata)
148 if s is not None: s.close()
149 if s2 is not None: s2.close()
151 try: os.remove(our_sockname)
152 except FileNotFoundError: pass