Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 1 | # Copyright (C) 2008 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | """Common SSH management logic.""" |
| 16 | |
| 17 | import functools |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 18 | import multiprocessing |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 19 | import os |
| 20 | import re |
| 21 | import signal |
| 22 | import subprocess |
| 23 | import sys |
| 24 | import tempfile |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 25 | import time |
| 26 | |
| 27 | import platform_utils |
| 28 | from repo_trace import Trace |
| 29 | |
| 30 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 31 | PROXY_PATH = os.path.join(os.path.dirname(__file__), "git_ssh") |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 32 | |
| 33 | |
| 34 | def _run_ssh_version(): |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 35 | """run ssh -V to display the version number""" |
| 36 | return subprocess.check_output( |
| 37 | ["ssh", "-V"], stderr=subprocess.STDOUT |
| 38 | ).decode() |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 39 | |
| 40 | |
| 41 | def _parse_ssh_version(ver_str=None): |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 42 | """parse a ssh version string into a tuple""" |
| 43 | if ver_str is None: |
| 44 | ver_str = _run_ssh_version() |
Saagar Jha | 90f574f | 2023-05-04 13:50:00 -0700 | [diff] [blame] | 45 | m = re.match(r"^OpenSSH_([0-9.]+)(p[0-9]+)?[\s,]", ver_str) |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 46 | if m: |
| 47 | return tuple(int(x) for x in m.group(1).split(".")) |
| 48 | else: |
| 49 | return () |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 50 | |
| 51 | |
| 52 | @functools.lru_cache(maxsize=None) |
| 53 | def version(): |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 54 | """return ssh version as a tuple""" |
| 55 | try: |
| 56 | return _parse_ssh_version() |
| 57 | except FileNotFoundError: |
| 58 | print("fatal: ssh not installed", file=sys.stderr) |
| 59 | sys.exit(1) |
Sebastian Schuberth | fff1d2d | 2023-11-15 15:51:33 +0100 | [diff] [blame^] | 60 | except subprocess.CalledProcessError as e: |
| 61 | print( |
| 62 | "fatal: unable to detect ssh version" |
| 63 | f" (code={e.returncode}, output={e.stdout})", |
| 64 | file=sys.stderr, |
| 65 | ) |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 66 | sys.exit(1) |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 67 | |
| 68 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 69 | URI_SCP = re.compile(r"^([^@:]*@?[^:/]{1,}):") |
| 70 | URI_ALL = re.compile(r"^([a-z][a-z+-]*)://([^@/]*@?[^/]*)/") |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 71 | |
| 72 | |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 73 | class ProxyManager: |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 74 | """Manage various ssh clients & masters that we spawn. |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 75 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 76 | This will take care of sharing state between multiprocessing children, and |
| 77 | make sure that if we crash, we don't leak any of the ssh sessions. |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 78 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 79 | The code should work with a single-process scenario too, and not add too |
| 80 | much overhead due to the manager. |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 81 | """ |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 82 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 83 | # Path to the ssh program to run which will pass our master settings along. |
| 84 | # Set here more as a convenience API. |
| 85 | proxy = PROXY_PATH |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 86 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 87 | def __init__(self, manager): |
| 88 | # Protect access to the list of active masters. |
| 89 | self._lock = multiprocessing.Lock() |
| 90 | # List of active masters (pid). These will be spawned on demand, and we |
| 91 | # are responsible for shutting them all down at the end. |
| 92 | self._masters = manager.list() |
| 93 | # Set of active masters indexed by "host:port" information. |
| 94 | # The value isn't used, but multiprocessing doesn't provide a set class. |
| 95 | self._master_keys = manager.dict() |
| 96 | # Whether ssh masters are known to be broken, so we give up entirely. |
| 97 | self._master_broken = manager.Value("b", False) |
| 98 | # List of active ssh sesssions. Clients will be added & removed as |
| 99 | # connections finish, so this list is just for safety & cleanup if we |
| 100 | # crash. |
| 101 | self._clients = manager.list() |
| 102 | # Path to directory for holding master sockets. |
| 103 | self._sock_path = None |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 104 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 105 | def __enter__(self): |
| 106 | """Enter a new context.""" |
| 107 | return self |
Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 108 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 109 | def __exit__(self, exc_type, exc_value, traceback): |
| 110 | """Exit a context & clean up all resources.""" |
| 111 | self.close() |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 112 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 113 | def add_client(self, proc): |
| 114 | """Track a new ssh session.""" |
| 115 | self._clients.append(proc.pid) |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 116 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 117 | def remove_client(self, proc): |
| 118 | """Remove a completed ssh session.""" |
| 119 | try: |
| 120 | self._clients.remove(proc.pid) |
| 121 | except ValueError: |
| 122 | pass |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 123 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 124 | def add_master(self, proc): |
| 125 | """Track a new master connection.""" |
| 126 | self._masters.append(proc.pid) |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 127 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 128 | def _terminate(self, procs): |
| 129 | """Kill all |procs|.""" |
| 130 | for pid in procs: |
| 131 | try: |
| 132 | os.kill(pid, signal.SIGTERM) |
| 133 | os.waitpid(pid, 0) |
| 134 | except OSError: |
| 135 | pass |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 136 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 137 | # The multiprocessing.list() API doesn't provide many standard list() |
| 138 | # methods, so we have to manually clear the list. |
| 139 | while True: |
| 140 | try: |
| 141 | procs.pop(0) |
| 142 | except: # noqa: E722 |
| 143 | break |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 144 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 145 | def close(self): |
| 146 | """Close this active ssh session. |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 147 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 148 | Kill all ssh clients & masters we created, and nuke the socket dir. |
| 149 | """ |
| 150 | self._terminate(self._clients) |
| 151 | self._terminate(self._masters) |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 152 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 153 | d = self.sock(create=False) |
| 154 | if d: |
| 155 | try: |
| 156 | platform_utils.rmdir(os.path.dirname(d)) |
| 157 | except OSError: |
| 158 | pass |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 159 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 160 | def _open_unlocked(self, host, port=None): |
| 161 | """Make sure a ssh master session exists for |host| & |port|. |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 162 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 163 | If one doesn't exist already, we'll create it. |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 164 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 165 | We won't grab any locks, so the caller has to do that. This helps keep |
| 166 | the business logic of actually creating the master separate from |
| 167 | grabbing locks. |
| 168 | """ |
| 169 | # Check to see whether we already think that the master is running; if |
| 170 | # we think it's already running, return right away. |
| 171 | if port is not None: |
Jason R. Coombs | b32ccbb | 2023-09-29 11:04:49 -0400 | [diff] [blame] | 172 | key = f"{host}:{port}" |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 173 | else: |
| 174 | key = host |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 175 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 176 | if key in self._master_keys: |
| 177 | return True |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 178 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 179 | if self._master_broken.value or "GIT_SSH" in os.environ: |
| 180 | # Failed earlier, so don't retry. |
| 181 | return False |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 182 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 183 | # We will make two calls to ssh; this is the common part of both calls. |
| 184 | command_base = ["ssh", "-o", "ControlPath %s" % self.sock(), host] |
| 185 | if port is not None: |
| 186 | command_base[1:1] = ["-p", str(port)] |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 187 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 188 | # Since the key wasn't in _master_keys, we think that master isn't |
| 189 | # running... but before actually starting a master, we'll double-check. |
| 190 | # This can be important because we can't tell that that 'git@myhost.com' |
| 191 | # is the same as 'myhost.com' where "User git" is setup in the user's |
| 192 | # ~/.ssh/config file. |
| 193 | check_command = command_base + ["-O", "check"] |
| 194 | with Trace("Call to ssh (check call): %s", " ".join(check_command)): |
| 195 | try: |
| 196 | check_process = subprocess.Popen( |
| 197 | check_command, |
| 198 | stdout=subprocess.PIPE, |
| 199 | stderr=subprocess.PIPE, |
| 200 | ) |
| 201 | check_process.communicate() # read output, but ignore it... |
| 202 | isnt_running = check_process.wait() |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 203 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 204 | if not isnt_running: |
| 205 | # Our double-check found that the master _was_ infact |
| 206 | # running. Add to the list of keys. |
| 207 | self._master_keys[key] = True |
| 208 | return True |
| 209 | except Exception: |
| 210 | # Ignore excpetions. We we will fall back to the normal command |
| 211 | # and print to the log there. |
| 212 | pass |
Mike Frysinger | 5291eaf | 2021-05-05 15:53:03 -0400 | [diff] [blame] | 213 | |
Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 214 | command = command_base[:1] + ["-M", "-N"] + command_base[1:] |
| 215 | p = None |
| 216 | try: |
| 217 | with Trace("Call to ssh: %s", " ".join(command)): |
| 218 | p = subprocess.Popen(command) |
| 219 | except Exception as e: |
| 220 | self._master_broken.value = True |
| 221 | print( |
| 222 | "\nwarn: cannot enable ssh control master for %s:%s\n%s" |
| 223 | % (host, port, str(e)), |
| 224 | file=sys.stderr, |
| 225 | ) |
| 226 | return False |
| 227 | |
| 228 | time.sleep(1) |
| 229 | ssh_died = p.poll() is not None |
| 230 | if ssh_died: |
| 231 | return False |
| 232 | |
| 233 | self.add_master(p) |
| 234 | self._master_keys[key] = True |
| 235 | return True |
| 236 | |
| 237 | def _open(self, host, port=None): |
| 238 | """Make sure a ssh master session exists for |host| & |port|. |
| 239 | |
| 240 | If one doesn't exist already, we'll create it. |
| 241 | |
| 242 | This will obtain any necessary locks to avoid inter-process races. |
| 243 | """ |
| 244 | # Bail before grabbing the lock if we already know that we aren't going |
| 245 | # to try creating new masters below. |
| 246 | if sys.platform in ("win32", "cygwin"): |
| 247 | return False |
| 248 | |
| 249 | # Acquire the lock. This is needed to prevent opening multiple masters |
| 250 | # for the same host when we're running "repo sync -jN" (for N > 1) _and_ |
| 251 | # the manifest <remote fetch="ssh://xyz"> specifies a different host |
| 252 | # from the one that was passed to repo init. |
| 253 | with self._lock: |
| 254 | return self._open_unlocked(host, port) |
| 255 | |
| 256 | def preconnect(self, url): |
| 257 | """If |uri| will create a ssh connection, setup the ssh master for it.""" # noqa: E501 |
| 258 | m = URI_ALL.match(url) |
| 259 | if m: |
| 260 | scheme = m.group(1) |
| 261 | host = m.group(2) |
| 262 | if ":" in host: |
| 263 | host, port = host.split(":") |
| 264 | else: |
| 265 | port = None |
| 266 | if scheme in ("ssh", "git+ssh", "ssh+git"): |
| 267 | return self._open(host, port) |
| 268 | return False |
| 269 | |
| 270 | m = URI_SCP.match(url) |
| 271 | if m: |
| 272 | host = m.group(1) |
| 273 | return self._open(host) |
| 274 | |
| 275 | return False |
| 276 | |
| 277 | def sock(self, create=True): |
| 278 | """Return the path to the ssh socket dir. |
| 279 | |
| 280 | This has all the master sockets so clients can talk to them. |
| 281 | """ |
| 282 | if self._sock_path is None: |
| 283 | if not create: |
| 284 | return None |
| 285 | tmp_dir = "/tmp" |
| 286 | if not os.path.exists(tmp_dir): |
| 287 | tmp_dir = tempfile.gettempdir() |
| 288 | if version() < (6, 7): |
| 289 | tokens = "%r@%h:%p" |
| 290 | else: |
| 291 | tokens = "%C" # hash of %l%h%p%r |
| 292 | self._sock_path = os.path.join( |
| 293 | tempfile.mkdtemp("", "ssh-", tmp_dir), "master-" + tokens |
| 294 | ) |
| 295 | return self._sock_path |