3 # This file is part of chiark-utils, a collection of useful programs
4 # used on chiark.greenend.org.uk.
7 # Copyright 2018 Citrix Systems Ltd
9 # This is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 3, or (at your option) any later version.
13 # This is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 # You should have received a copy of the GNU General Public License along
19 # with this program; if not, consult the Free Software Foundation's
20 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
38 class Error(Exception): pass
41 def __init__(d, pid, debug=None):
44 d._stderr = tempfile.TemporaryFile(mode='w+')
47 d._sp = subprocess.Popen(
48 preexec_fn = _shuffle_fd3,
49 stdin = subprocess.PIPE,
50 stdout = subprocess.PIPE,
53 args = ['gdb', '-p', str(pid), '-batch', '-ex',
54 'python import fishdescriptor.indonor as id;'+
55 ' id.DonorImplementation().eval_loop()'
59 def _eval_integer(d, expr):
61 l = d._sp.stdout.readline()
62 if not len(l): raise Error('gdb process donor python repl quit')
63 if l != b'!\n': raise RuntimeError("indonor said %s" % repr(l))
64 d._sp.stdin.write(expr.encode('utf-8') + b'\n')
66 l = d._sp.stdout.readline().rstrip(b'\n')
68 except Exception as e:
69 if d._stderr is not None:
71 shutil.copyfileobj(d._stderr, sys.stderr)
76 def _eval_success(d, expr):
77 r = d._eval_integer(expr)
78 if r != 1: raise RuntimeError("eval of %s gave %d" % (expr, r))
81 return d._eval_integer('di.geteuid()')
83 def _ancilmsg(d, fds):
88 my $fds = pack "i*", @ARGV;
89 my $m = Socket::MsgHdr::pack_cmsghdr SOL_SOCKET, SCM_RIGHTS, $fds;
90 print join ", ", unpack "C*", $m;
92 ap = subprocess.Popen(
93 stdin = subprocess.DEVNULL,
94 stdout = subprocess.PIPE,
95 args = ['perl','-we',perl_script] + [str(x) for x in fds]
97 (output, dummy) = ap.communicate()
98 return output.decode('utf-8')
100 def donate(d, path, fds):
101 ancil = d._ancilmsg(fds)
102 d._eval_success('di.donate(%s, [ %s ])'
103 % (repr(path), ancil))
104 return len(ancil.split(','))
107 d._eval_integer('di.mkdir(%s)'
110 def _exists(d, path):
114 except OSError as oe:
115 if oe.errno != errno.ENOENT: raise oe
118 def _sock_dir(d, target_euid, target_root):
119 run_dir = '/run/user/%d' % target_euid
120 if d._exists(target_root + run_dir):
121 return run_dir + '/fishdescriptor'
124 pw = pwd.getpwuid(target_euid)
125 return pw.pw_dir + '/.fishdescriptor'
130 'cannot find good socket path - no /run/user/UID nor pw entry for target process euid %d'
135 # -> list of fds in our process
137 target_root = '/proc/%d/root' % d.pid
138 if not d._exists(target_root):
142 sockdir = d._sock_dir(euid, target_root)
145 sockname = '%s/%s,%d' % (sockdir, os.uname().nodename, d.pid)
147 our_sockname = target_root + sockname
153 try: os.remove(our_sockname)
154 except FileNotFoundError: pass
156 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
158 os.chmod(our_sockname, 666)
161 ancil_len = d.donate(sockname, fds)
162 (s2, dummy) = s.accept()
163 (msg, ancil, flags, sender) = s2.recvmsg(1, ancil_len)
166 unpack_fmt = '%di' % len(fds)
168 for clvl, ctype, cdata in ancil:
169 if clvl == socket.SOL_SOCKET and ctype == socket.SCM_RIGHTS:
170 assert(got_fds is None)
171 got_fds = struct.unpack_from(unpack_fmt, cdata)
174 if s is not None: s.close()
175 if s2 is not None: s2.close()
177 try: os.remove(our_sockname)
178 except FileNotFoundError: pass