xref: /openbsd-src/usr.bin/tmux/spawn.c (revision 29ebed3733c53f26b45edd4bc4795dfaa9d323c8)
1 /* $OpenBSD: spawn.c,v 1.17 2020/03/19 14:03:49 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2019 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include <errno.h>
22 #include <paths.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <util.h>
28 
29 #include "tmux.h"
30 
31 /*
32  * Set up the environment and create a new window and pane or a new pane.
33  *
34  * We need to set up the following items:
35  *
36  * - history limit, comes from the session;
37  *
38  * - base index, comes from the session;
39  *
40  * - current working directory, may be specified - if it isn't it comes from
41  *   either the client or the session;
42  *
43  * - PATH variable, comes from the client if any, otherwise from the session
44  *   environment;
45  *
46  * - shell, comes from default-shell;
47  *
48  * - termios, comes from the session;
49  *
50  * - remaining environment, comes from the session.
51  */
52 
53 static void
54 spawn_log(const char *from, struct spawn_context *sc)
55 {
56 	struct session		*s = sc->s;
57 	struct winlink		*wl = sc->wl;
58 	struct window_pane	*wp0 = sc->wp0;
59 	char			 tmp[128];
60 	const char		*name;
61 
62 	log_debug("%s: %s, flags=%#x", from, sc->item->name, sc->flags);
63 
64 	if (wl != NULL && wp0 != NULL)
65 		xsnprintf(tmp, sizeof tmp, "wl=%d wp0=%%%u", wl->idx, wp0->id);
66 	else if (wl != NULL)
67 		xsnprintf(tmp, sizeof tmp, "wl=%d wp0=none", wl->idx);
68 	else if (wp0 != NULL)
69 		xsnprintf(tmp, sizeof tmp, "wl=none wp0=%%%u", wp0->id);
70 	else
71 		xsnprintf(tmp, sizeof tmp, "wl=none wp0=none");
72 	log_debug("%s: s=$%u %s idx=%d", from, s->id, tmp, sc->idx);
73 
74 	name = sc->name;
75 	if (name == NULL)
76 		name = "none";
77 	log_debug("%s: name=%s", from, name);
78 }
79 
80 struct winlink *
81 spawn_window(struct spawn_context *sc, char **cause)
82 {
83 	struct cmdq_item	*item = sc->item;
84 	struct client		*c = item->client;
85 	struct session		*s = sc->s;
86 	struct window		*w;
87 	struct window_pane	*wp;
88 	struct winlink		*wl;
89 	int			 idx = sc->idx;
90 	u_int			 sx, sy, xpixel, ypixel;
91 
92 	spawn_log(__func__, sc);
93 
94 	/*
95 	 * If the window already exists, we are respawning, so destroy all the
96 	 * panes except one.
97 	 */
98 	if (sc->flags & SPAWN_RESPAWN) {
99 		w = sc->wl->window;
100 		if (~sc->flags & SPAWN_KILL) {
101 			TAILQ_FOREACH(wp, &w->panes, entry) {
102 				if (wp->fd != -1)
103 					break;
104 			}
105 			if (wp != NULL) {
106 				xasprintf(cause, "window %s:%d still active",
107 				    s->name, sc->wl->idx);
108 				return (NULL);
109 			}
110 		}
111 
112 		sc->wp0 = TAILQ_FIRST(&w->panes);
113 		TAILQ_REMOVE(&w->panes, sc->wp0, entry);
114 
115 		layout_free(w);
116 		window_destroy_panes(w);
117 
118 		TAILQ_INSERT_HEAD(&w->panes, sc->wp0, entry);
119 		window_pane_resize(sc->wp0, w->sx, w->sy);
120 
121 		layout_init(w, sc->wp0);
122 		window_set_active_pane(w, sc->wp0, 0);
123 	}
124 
125 	/*
126 	 * Otherwise we have no window so we will need to create one. First
127 	 * check if the given index already exists and destroy it if so.
128 	 */
129 	if ((~sc->flags & SPAWN_RESPAWN) && idx != -1) {
130 		wl = winlink_find_by_index(&s->windows, idx);
131 		if (wl != NULL && (~sc->flags & SPAWN_KILL)) {
132 			xasprintf(cause, "index %d in use", idx);
133 			return (NULL);
134 		}
135 		if (wl != NULL) {
136 			/*
137 			 * Can't use session_detach as it will destroy session
138 			 * if this makes it empty.
139 			 */
140 			wl->flags &= ~WINLINK_ALERTFLAGS;
141 			notify_session_window("window-unlinked", s, wl->window);
142 			winlink_stack_remove(&s->lastw, wl);
143 			winlink_remove(&s->windows, wl);
144 
145 			if (s->curw == wl) {
146 				s->curw = NULL;
147 				sc->flags &= ~SPAWN_DETACHED;
148 			}
149 		}
150 	}
151 
152 	/* Then create a window if needed. */
153 	if (~sc->flags & SPAWN_RESPAWN) {
154 		if (idx == -1)
155 			idx = -1 - options_get_number(s->options, "base-index");
156 		if ((sc->wl = winlink_add(&s->windows, idx)) == NULL) {
157 			xasprintf(cause, "couldn't add window %d", idx);
158 			return (NULL);
159 		}
160 		default_window_size(sc->c, s, NULL, &sx, &sy, &xpixel, &ypixel,
161 		    -1);
162 		if ((w = window_create(sx, sy, xpixel, ypixel)) == NULL) {
163 			winlink_remove(&s->windows, sc->wl);
164 			xasprintf(cause, "couldn't create window %d", idx);
165 			return (NULL);
166 		}
167 		if (s->curw == NULL)
168 			s->curw = sc->wl;
169 		sc->wl->session = s;
170 		w->latest = sc->c;
171 		winlink_set_window(sc->wl, w);
172 	} else
173 		w = NULL;
174 	sc->flags |= SPAWN_NONOTIFY;
175 
176 	/* Spawn the pane. */
177 	wp = spawn_pane(sc, cause);
178 	if (wp == NULL) {
179 		if (~sc->flags & SPAWN_RESPAWN)
180 			winlink_remove(&s->windows, sc->wl);
181 		return (NULL);
182 	}
183 
184 	/* Set the name of the new window. */
185 	if (~sc->flags & SPAWN_RESPAWN) {
186 		if (sc->name != NULL) {
187 			w->name = format_single(item, sc->name, c, s, NULL,
188 			    NULL);
189 			options_set_number(w->options, "automatic-rename", 0);
190 		} else
191 			w->name = xstrdup(default_window_name(w));
192 	}
193 
194 	/* Switch to the new window if required. */
195 	if (~sc->flags & SPAWN_DETACHED)
196 		session_select(s, sc->wl->idx);
197 
198 	/* Fire notification if new window. */
199 	if (~sc->flags & SPAWN_RESPAWN)
200 		notify_session_window("window-linked", s, w);
201 
202 	session_group_synchronize_from(s);
203 	return (sc->wl);
204 }
205 
206 struct window_pane *
207 spawn_pane(struct spawn_context *sc, char **cause)
208 {
209 	struct cmdq_item	 *item = sc->item;
210 	struct client		 *c = item->client;
211 	struct session		 *s = sc->s;
212 	struct window		 *w = sc->wl->window;
213 	struct window_pane	 *new_wp;
214 	struct environ		 *child;
215 	struct environ_entry	 *ee;
216 	char			**argv, *cp, **argvp, *argv0, *cwd;
217 	const char		 *cmd, *tmp;
218 	int			  argc;
219 	u_int			  idx;
220 	struct termios		  now;
221 	u_int			  hlimit;
222 	struct winsize		  ws;
223 	sigset_t		  set, oldset;
224 	key_code		  key;
225 
226 	spawn_log(__func__, sc);
227 
228 	/*
229 	 * Work out the current working directory. If respawning, use
230 	 * the pane's stored one unless specified.
231 	 */
232 	if (sc->cwd != NULL)
233 		cwd = format_single(item, sc->cwd, c, item->target.s, NULL, NULL);
234 	else if (~sc->flags & SPAWN_RESPAWN)
235 		cwd = xstrdup(server_client_get_cwd(c, item->target.s));
236 	else
237 		cwd = NULL;
238 
239 	/*
240 	 * If we are respawning then get rid of the old process. Otherwise
241 	 * either create a new cell or assign to the one we are given.
242 	 */
243 	hlimit = options_get_number(s->options, "history-limit");
244 	if (sc->flags & SPAWN_RESPAWN) {
245 		if (sc->wp0->fd != -1 && (~sc->flags & SPAWN_KILL)) {
246 			window_pane_index(sc->wp0, &idx);
247 			xasprintf(cause, "pane %s:%d.%u still active",
248 			    s->name, sc->wl->idx, idx);
249 			free(cwd);
250 			return (NULL);
251 		}
252 		if (sc->wp0->fd != -1) {
253 			bufferevent_free(sc->wp0->event);
254 			close(sc->wp0->fd);
255 		}
256 		window_pane_reset_mode_all(sc->wp0);
257 		screen_reinit(&sc->wp0->base);
258 		input_free(sc->wp0->ictx);
259 		sc->wp0->ictx = input_init(sc->wp0);
260 		new_wp = sc->wp0;
261 		new_wp->flags &= ~(PANE_STATUSREADY|PANE_STATUSDRAWN);
262 	} else if (sc->lc == NULL) {
263 		new_wp = window_add_pane(w, NULL, hlimit, sc->flags);
264 		layout_init(w, new_wp);
265 	} else {
266 		new_wp = window_add_pane(w, sc->wp0, hlimit, sc->flags);
267 		layout_assign_pane(sc->lc, new_wp);
268 	}
269 
270 	/*
271 	 * Now we have a pane with nothing running in it ready for the new process.
272 	 * Work out the command and arguments and store the working directory.
273 	 */
274 	if (sc->argc == 0 && (~sc->flags & SPAWN_RESPAWN)) {
275 		cmd = options_get_string(s->options, "default-command");
276 		if (cmd != NULL && *cmd != '\0') {
277 			argc = 1;
278 			argv = (char **)&cmd;
279 		} else {
280 			argc = 0;
281 			argv = NULL;
282 		}
283 	} else {
284 		argc = sc->argc;
285 		argv = sc->argv;
286 	}
287 	if (cwd != NULL) {
288 		free(new_wp->cwd);
289 		new_wp->cwd = cwd;
290 	}
291 
292 	/*
293 	 * Replace the stored arguments if there are new ones. If not, the
294 	 * existing ones will be used (they will only exist for respawn).
295 	 */
296 	if (argc > 0) {
297 		cmd_free_argv(new_wp->argc, new_wp->argv);
298 		new_wp->argc = argc;
299 		new_wp->argv = cmd_copy_argv(argc, argv);
300 	}
301 
302 	/* Create an environment for this pane. */
303 	child = environ_for_session(s, 0);
304 	if (sc->environ != NULL)
305 		environ_copy(sc->environ, child);
306 	environ_set(child, "TMUX_PANE", "%%%u", new_wp->id);
307 
308 	/*
309 	 * Then the PATH environment variable. The session one is replaced from
310 	 * the client if there is one because otherwise running "tmux new
311 	 * myprogram" wouldn't work if myprogram isn't in the session's path.
312 	 */
313 	if (c != NULL && c->session == NULL) { /* only unattached clients */
314 		ee = environ_find(c->environ, "PATH");
315 		if (ee != NULL)
316 			environ_set(child, "PATH", "%s", ee->value);
317 	}
318 	if (environ_find(child, "PATH") == NULL)
319 		environ_set(child, "%s", _PATH_DEFPATH);
320 
321 	/* Then the shell. If respawning, use the old one. */
322 	if (~sc->flags & SPAWN_RESPAWN) {
323 		tmp = options_get_string(s->options, "default-shell");
324 		if (!checkshell(tmp))
325 			tmp = _PATH_BSHELL;
326 		free(new_wp->shell);
327 		new_wp->shell = xstrdup(tmp);
328 	}
329 	environ_set(child, "SHELL", "%s", new_wp->shell);
330 
331 	/* Log the arguments we are going to use. */
332 	log_debug("%s: shell=%s", __func__, new_wp->shell);
333 	if (new_wp->argc != 0) {
334 		cp = cmd_stringify_argv(new_wp->argc, new_wp->argv);
335 		log_debug("%s: cmd=%s", __func__, cp);
336 		free(cp);
337 	}
338 	if (cwd != NULL)
339 		log_debug("%s: cwd=%s", __func__, cwd);
340 	cmd_log_argv(new_wp->argc, new_wp->argv, "%s", __func__);
341 	environ_log(child, "%s: environment ", __func__);
342 
343 	/* Initialize the window size. */
344 	memset(&ws, 0, sizeof ws);
345 	ws.ws_col = screen_size_x(&new_wp->base);
346 	ws.ws_row = screen_size_y(&new_wp->base);
347 	ws.ws_xpixel = w->xpixel * ws.ws_col;
348 	ws.ws_ypixel = w->ypixel * ws.ws_row;
349 
350 	/* Block signals until fork has completed. */
351 	sigfillset(&set);
352 	sigprocmask(SIG_BLOCK, &set, &oldset);
353 
354 	/* If the command is empty, don't fork a child process. */
355 	if (sc->flags & SPAWN_EMPTY) {
356 		new_wp->flags |= PANE_EMPTY;
357 		new_wp->base.mode &= ~MODE_CURSOR;
358 		new_wp->base.mode |= MODE_CRLF;
359 		goto complete;
360 	}
361 
362 	/* Fork the new process. */
363 	new_wp->pid = fdforkpty(ptm_fd, &new_wp->fd, new_wp->tty, NULL, &ws);
364 	if (new_wp->pid == -1) {
365 		xasprintf(cause, "fork failed: %s", strerror(errno));
366 		new_wp->fd = -1;
367 		if (~sc->flags & SPAWN_RESPAWN) {
368 			layout_close_pane(new_wp);
369 			window_remove_pane(w, new_wp);
370 		}
371 		sigprocmask(SIG_SETMASK, &oldset, NULL);
372 		return (NULL);
373 	}
374 
375 	/* In the parent process, everything is done now. */
376 	if (new_wp->pid != 0)
377 		goto complete;
378 
379 	/*
380 	 * Child process. Change to the working directory or home if that
381 	 * fails.
382 	 */
383 	if (chdir(new_wp->cwd) != 0) {
384 		if ((tmp = find_home()) == NULL || chdir(tmp) != 0)
385 			chdir("/");
386 	}
387 
388 	/*
389 	 * Update terminal escape characters from the session if available and
390 	 * force VERASE to tmux's backspace.
391 	 */
392 	if (tcgetattr(STDIN_FILENO, &now) != 0)
393 		_exit(1);
394 	if (s->tio != NULL)
395 		memcpy(now.c_cc, s->tio->c_cc, sizeof now.c_cc);
396 	key = options_get_number(global_options, "backspace");
397 	if (key >= 0x7f)
398 		now.c_cc[VERASE] = '\177';
399 	else
400 		now.c_cc[VERASE] = key;
401 	if (tcsetattr(STDIN_FILENO, TCSANOW, &now) != 0)
402 		_exit(1);
403 
404 	/* Clean up file descriptors and signals and update the environment. */
405 	closefrom(STDERR_FILENO + 1);
406 	proc_clear_signals(server_proc, 1);
407 	sigprocmask(SIG_SETMASK, &oldset, NULL);
408 	log_close();
409 	environ_push(child);
410 
411 	/*
412 	 * If given multiple arguments, use execvp(). Copy the arguments to
413 	 * ensure they end in a NULL.
414 	 */
415 	if (new_wp->argc != 0 && new_wp->argc != 1) {
416 		argvp = cmd_copy_argv(new_wp->argc, new_wp->argv);
417 		execvp(argvp[0], argvp);
418 		_exit(1);
419 	}
420 
421 	/*
422 	 * If one argument, pass it to $SHELL -c. Otherwise create a login
423 	 * shell.
424 	 */
425 	cp = strrchr(new_wp->shell, '/');
426 	if (new_wp->argc == 1) {
427 		tmp = new_wp->argv[0];
428 		if (cp != NULL && cp[1] != '\0')
429 			xasprintf(&argv0, "%s", cp + 1);
430 		else
431 			xasprintf(&argv0, "%s", new_wp->shell);
432 		execl(new_wp->shell, argv0, "-c", tmp, (char *)NULL);
433 		_exit(1);
434 	}
435 	if (cp != NULL && cp[1] != '\0')
436 		xasprintf(&argv0, "-%s", cp + 1);
437 	else
438 		xasprintf(&argv0, "-%s", new_wp->shell);
439 	execl(new_wp->shell, argv0, (char *)NULL);
440 	_exit(1);
441 
442 complete:
443 	new_wp->pipe_off = 0;
444 	new_wp->flags &= ~PANE_EXITED;
445 
446 	sigprocmask(SIG_SETMASK, &oldset, NULL);
447 	window_pane_set_event(new_wp);
448 
449 	if (sc->flags & SPAWN_RESPAWN)
450 		return (new_wp);
451 	if ((~sc->flags & SPAWN_DETACHED) || w->active == NULL) {
452 		if (sc->flags & SPAWN_NONOTIFY)
453 			window_set_active_pane(w, new_wp, 0);
454 		else
455 			window_set_active_pane(w, new_wp, 1);
456 	}
457 	if (~sc->flags & SPAWN_NONOTIFY)
458 		notify_window("window-layout-changed", w);
459 	return (new_wp);
460 }
461