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