Alter how tmux handles the working directory to internally use file
[tmux-openbsd.git] / client.c
blob82e439929f87d4eb37914c69b17c155efe8682ec
1 /* $OpenBSD$ */
3 /*
4 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
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.
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.
19 #include <sys/types.h>
20 #include <sys/file.h>
21 #include <sys/socket.h>
22 #include <sys/stat.h>
23 #include <sys/un.h>
24 #include <sys/wait.h>
26 #include <errno.h>
27 #include <event.h>
28 #include <fcntl.h>
29 #include <pwd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
34 #include "tmux.h"
36 struct imsgbuf client_ibuf;
37 struct event client_event;
38 struct event client_stdin;
39 enum {
40 CLIENT_EXIT_NONE,
41 CLIENT_EXIT_DETACHED,
42 CLIENT_EXIT_DETACHED_HUP,
43 CLIENT_EXIT_LOST_TTY,
44 CLIENT_EXIT_TERMINATED,
45 CLIENT_EXIT_LOST_SERVER,
46 CLIENT_EXIT_EXITED,
47 CLIENT_EXIT_SERVER_EXITED,
48 } client_exitreason = CLIENT_EXIT_NONE;
49 int client_exitval;
50 enum msgtype client_exittype;
51 int client_attached;
53 int client_get_lock(char *);
54 int client_connect(char *, int);
55 void client_send_identify(int);
56 int client_write_one(enum msgtype, int, const void *, size_t);
57 int client_write_server(enum msgtype, const void *, size_t);
58 void client_update_event(void);
59 void client_signal(int, short, void *);
60 void client_stdin_callback(int, short, void *);
61 void client_write(int, const char *, size_t);
62 void client_callback(int, short, void *);
63 int client_dispatch_attached(void);
64 int client_dispatch_wait(void *);
65 const char *client_exit_message(void);
68 * Get server create lock. If already held then server start is happening in
69 * another client, so block until the lock is released and return -1 to
70 * retry. Ignore other errors - just continue and start the server without the
71 * lock.
73 int
74 client_get_lock(char *lockfile)
76 int lockfd;
78 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1)
79 fatal("open failed");
81 if (lockf(lockfd, F_TLOCK, 0) == -1 && errno == EAGAIN) {
82 while (lockf(lockfd, F_LOCK, 0) == -1 && errno == EINTR)
83 /* nothing */;
84 close(lockfd);
85 return (-1);
88 return (lockfd);
91 /* Connect client to server. */
92 int
93 client_connect(char *path, int start_server)
95 struct sockaddr_un sa;
96 size_t size;
97 int fd, lockfd;
98 char *lockfile;
100 memset(&sa, 0, sizeof sa);
101 sa.sun_family = AF_UNIX;
102 size = strlcpy(sa.sun_path, path, sizeof sa.sun_path);
103 if (size >= sizeof sa.sun_path) {
104 errno = ENAMETOOLONG;
105 return (-1);
108 retry:
109 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
110 fatal("socket failed");
112 if (connect(fd, (struct sockaddr *) &sa, SUN_LEN(&sa)) == -1) {
113 if (errno != ECONNREFUSED && errno != ENOENT)
114 goto failed;
115 if (!start_server)
116 goto failed;
117 close(fd);
119 xasprintf(&lockfile, "%s.lock", path);
120 if ((lockfd = client_get_lock(lockfile)) == -1)
121 goto retry;
122 if (unlink(path) != 0 && errno != ENOENT)
123 return (-1);
124 fd = server_start(lockfd, lockfile);
125 free(lockfile);
126 close(lockfd);
129 setblocking(fd, 0);
130 return (fd);
132 failed:
133 close(fd);
134 return (-1);
137 /* Get exit string from reason number. */
138 const char *
139 client_exit_message(void)
141 switch (client_exitreason) {
142 case CLIENT_EXIT_NONE:
143 break;
144 case CLIENT_EXIT_DETACHED:
145 return ("detached");
146 case CLIENT_EXIT_DETACHED_HUP:
147 return ("detached and SIGHUP");
148 case CLIENT_EXIT_LOST_TTY:
149 return ("lost tty");
150 case CLIENT_EXIT_TERMINATED:
151 return ("terminated");
152 case CLIENT_EXIT_LOST_SERVER:
153 return ("lost server");
154 case CLIENT_EXIT_EXITED:
155 return ("exited");
156 case CLIENT_EXIT_SERVER_EXITED:
157 return ("server exited");
159 return ("unknown reason");
162 /* Client main loop. */
164 client_main(int argc, char **argv, int flags)
166 struct cmd *cmd;
167 struct cmd_list *cmdlist;
168 struct msg_command_data *data;
169 int cmdflags, fd, i;
170 pid_t ppid;
171 enum msgtype msg;
172 char *cause;
173 struct termios tio, saved_tio;
174 size_t size;
176 /* Set up the initial command. */
177 cmdflags = 0;
178 if (shell_cmd != NULL) {
179 msg = MSG_SHELL;
180 cmdflags = CMD_STARTSERVER;
181 } else if (argc == 0) {
182 msg = MSG_COMMAND;
183 cmdflags = CMD_STARTSERVER|CMD_CANTNEST;
184 } else {
185 msg = MSG_COMMAND;
188 * It sucks parsing the command string twice (in client and
189 * later in server) but it is necessary to get the start server
190 * flag.
192 cmdlist = cmd_list_parse(argc, argv, NULL, 0, &cause);
193 if (cmdlist == NULL) {
194 fprintf(stderr, "%s\n", cause);
195 return (1);
197 cmdflags &= ~CMD_STARTSERVER;
198 TAILQ_FOREACH(cmd, &cmdlist->list, qentry) {
199 if (cmd->entry->flags & CMD_STARTSERVER)
200 cmdflags |= CMD_STARTSERVER;
201 if (cmd->entry->flags & CMD_CANTNEST)
202 cmdflags |= CMD_CANTNEST;
204 cmd_list_free(cmdlist);
208 * Check if this could be a nested session, if the command can't nest:
209 * if the socket path matches $TMUX, this is probably the same server.
211 if (shell_cmd == NULL && environ_path != NULL &&
212 (cmdflags & CMD_CANTNEST) &&
213 strcmp(socket_path, environ_path) == 0) {
214 fprintf(stderr, "sessions should be nested with care, "
215 "unset $TMUX to force\n");
216 return (1);
219 /* Initialise the client socket and start the server. */
220 fd = client_connect(socket_path, cmdflags & CMD_STARTSERVER);
221 if (fd == -1) {
222 fprintf(stderr, "failed to connect to server\n");
223 return (1);
226 /* Set process title, log and signals now this is the client. */
227 setproctitle("client (%s)", socket_path);
228 logfile("client");
230 /* Create imsg. */
231 imsg_init(&client_ibuf, fd);
232 event_set(&client_event, fd, EV_READ, client_callback, shell_cmd);
234 /* Create stdin handler. */
235 setblocking(STDIN_FILENO, 0);
236 event_set(&client_stdin, STDIN_FILENO, EV_READ|EV_PERSIST,
237 client_stdin_callback, NULL);
238 if (flags & CLIENT_CONTROLCONTROL) {
239 if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
240 fprintf(stderr, "tcgetattr failed: %s\n",
241 strerror(errno));
242 return (1);
244 cfmakeraw(&tio);
245 tio.c_iflag = ICRNL|IXANY;
246 tio.c_oflag = OPOST|ONLCR;
247 tio.c_lflag = NOKERNINFO;
248 tio.c_cflag = CREAD|CS8|HUPCL;
249 tio.c_cc[VMIN] = 1;
250 tio.c_cc[VTIME] = 0;
251 cfsetispeed(&tio, cfgetispeed(&saved_tio));
252 cfsetospeed(&tio, cfgetospeed(&saved_tio));
253 tcsetattr(STDIN_FILENO, TCSANOW, &tio);
256 /* Establish signal handlers. */
257 set_signals(client_signal);
259 /* Send identify messages. */
260 client_send_identify(flags);
262 /* Send first command. */
263 if (msg == MSG_COMMAND) {
264 /* How big is the command? */
265 size = 0;
266 for (i = 0; i < argc; i++)
267 size += strlen(argv[i]) + 1;
268 data = xmalloc((sizeof *data) + size);
270 /* Fill in command line arguments. */
271 data->pid = environ_pid;
272 data->session_id = environ_session_id;
274 /* Prepare command for server. */
275 data->argc = argc;
276 if (cmd_pack_argv(argc, argv, (char*)(data + 1), size) != 0) {
277 fprintf(stderr, "command too long\n");
278 free(data);
279 return (1);
281 size += sizeof *data;
283 /* Send the command. */
284 if (client_write_server(msg, data, size) != 0) {
285 fprintf(stderr, "failed to send command\n");
286 free(data);
287 return (1);
289 free(data);
290 } else if (msg == MSG_SHELL)
291 client_write_server(msg, NULL, 0);
293 /* Set the event and dispatch. */
294 client_update_event();
295 event_dispatch();
297 /* Print the exit message, if any, and exit. */
298 if (client_attached) {
299 if (client_exitreason != CLIENT_EXIT_NONE && !login_shell)
300 printf("[%s]\n", client_exit_message());
302 ppid = getppid();
303 if (client_exittype == MSG_DETACHKILL && ppid > 1)
304 kill(ppid, SIGHUP);
305 } else if (flags & CLIENT_CONTROLCONTROL) {
306 if (client_exitreason != CLIENT_EXIT_NONE)
307 printf("%%exit %s\n", client_exit_message());
308 else
309 printf("%%exit\n");
310 printf("\033\\");
311 tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
313 setblocking(STDIN_FILENO, 1);
314 return (client_exitval);
317 /* Send identify messages to server. */
318 void
319 client_send_identify(int flags)
321 const char *s;
322 char **ss;
323 int fd;
325 client_write_one(MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
327 if ((s = getenv("TERM")) == NULL)
328 s = "";
329 client_write_one(MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1);
331 if ((s = ttyname(STDIN_FILENO)) == NULL)
332 s = "";
333 client_write_one(MSG_IDENTIFY_TTYNAME, -1, s, strlen(s) + 1);
335 if ((fd = open(".", O_RDONLY)) == -1)
336 fd = open("/", O_RDONLY);
337 client_write_one(MSG_IDENTIFY_CWD, fd, NULL, 0);
339 if ((fd = dup(STDIN_FILENO)) == -1)
340 fatal("dup failed");
341 client_write_one(MSG_IDENTIFY_STDIN, fd, NULL, 0);
343 for (ss = environ; *ss != NULL; ss++)
344 client_write_one(MSG_IDENTIFY_ENVIRON, -1, *ss, strlen(*ss) + 1);
345 client_write_one(MSG_IDENTIFY_DONE, -1, NULL, 0);
347 client_update_event();
350 /* Helper to send one message. */
352 client_write_one(enum msgtype type, int fd, const void *buf, size_t len)
354 int retval;
356 retval = imsg_compose(&client_ibuf, type, PROTOCOL_VERSION, -1, fd,
357 (void*)buf, len);
358 if (retval != 1)
359 return (-1);
360 return (0);
363 /* Write a message to the server without a file descriptor. */
365 client_write_server(enum msgtype type, const void *buf, size_t len)
367 int retval;
369 retval = client_write_one(type, -1, buf, len);
370 if (retval == 0)
371 client_update_event();
372 return (retval);
375 /* Update client event based on whether it needs to read or read and write. */
376 void
377 client_update_event(void)
379 short events;
381 event_del(&client_event);
382 events = EV_READ;
383 if (client_ibuf.w.queued > 0)
384 events |= EV_WRITE;
385 event_set(
386 &client_event, client_ibuf.fd, events, client_callback, shell_cmd);
387 event_add(&client_event, NULL);
390 /* Callback to handle signals in the client. */
391 void
392 client_signal(int sig, unused short events, unused void *data)
394 struct sigaction sigact;
395 int status;
397 if (!client_attached) {
398 switch (sig) {
399 case SIGCHLD:
400 waitpid(WAIT_ANY, &status, WNOHANG);
401 break;
402 case SIGTERM:
403 event_loopexit(NULL);
404 break;
406 } else {
407 switch (sig) {
408 case SIGHUP:
409 client_exitreason = CLIENT_EXIT_LOST_TTY;
410 client_exitval = 1;
411 client_write_server(MSG_EXITING, NULL, 0);
412 break;
413 case SIGTERM:
414 client_exitreason = CLIENT_EXIT_TERMINATED;
415 client_exitval = 1;
416 client_write_server(MSG_EXITING, NULL, 0);
417 break;
418 case SIGWINCH:
419 client_write_server(MSG_RESIZE, NULL, 0);
420 break;
421 case SIGCONT:
422 memset(&sigact, 0, sizeof sigact);
423 sigemptyset(&sigact.sa_mask);
424 sigact.sa_flags = SA_RESTART;
425 sigact.sa_handler = SIG_IGN;
426 if (sigaction(SIGTSTP, &sigact, NULL) != 0)
427 fatal("sigaction failed");
428 client_write_server(MSG_WAKEUP, NULL, 0);
429 break;
433 client_update_event();
436 /* Callback for client imsg read events. */
437 void
438 client_callback(unused int fd, short events, void *data)
440 ssize_t n;
441 int retval;
443 if (events & EV_READ) {
444 if ((n = imsg_read(&client_ibuf)) == -1 || n == 0)
445 goto lost_server;
446 if (client_attached)
447 retval = client_dispatch_attached();
448 else
449 retval = client_dispatch_wait(data);
450 if (retval != 0) {
451 event_loopexit(NULL);
452 return;
456 if (events & EV_WRITE) {
457 if (msgbuf_write(&client_ibuf.w) < 0)
458 goto lost_server;
461 client_update_event();
462 return;
464 lost_server:
465 client_exitreason = CLIENT_EXIT_LOST_SERVER;
466 client_exitval = 1;
467 event_loopexit(NULL);
470 /* Callback for client stdin read events. */
471 void
472 client_stdin_callback(unused int fd, unused short events, unused void *data1)
474 struct msg_stdin_data data;
476 data.size = read(STDIN_FILENO, data.data, sizeof data.data);
477 if (data.size < 0 && (errno == EINTR || errno == EAGAIN))
478 return;
480 client_write_server(MSG_STDIN, &data, sizeof data);
481 if (data.size <= 0)
482 event_del(&client_stdin);
483 client_update_event();
486 /* Force write to file descriptor. */
487 void
488 client_write(int fd, const char *data, size_t size)
490 ssize_t used;
492 while (size != 0) {
493 used = write(fd, data, size);
494 if (used == -1) {
495 if (errno == EINTR || errno == EAGAIN)
496 continue;
497 break;
499 data += used;
500 size -= used;
504 /* Dispatch imsgs when in wait state (before MSG_READY). */
506 client_dispatch_wait(void *data0)
508 struct imsg imsg;
509 char *data;
510 ssize_t n, datalen;
511 struct msg_stdout_data stdoutdata;
512 struct msg_stderr_data stderrdata;
513 int retval;
515 for (;;) {
516 if ((n = imsg_get(&client_ibuf, &imsg)) == -1)
517 fatalx("imsg_get failed");
518 if (n == 0)
519 return (0);
521 data = imsg.data;
522 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
524 log_debug("got %d from server", imsg.hdr.type);
525 switch (imsg.hdr.type) {
526 case MSG_EXIT:
527 case MSG_SHUTDOWN:
528 if (datalen != sizeof retval && datalen != 0)
529 fatalx("bad MSG_EXIT size");
530 if (datalen == sizeof retval) {
531 memcpy(&retval, data, sizeof retval);
532 client_exitval = retval;
534 imsg_free(&imsg);
535 return (-1);
536 case MSG_READY:
537 if (datalen != 0)
538 fatalx("bad MSG_READY size");
540 event_del(&client_stdin);
541 client_attached = 1;
542 client_write_server(MSG_RESIZE, NULL, 0);
543 break;
544 case MSG_STDIN:
545 if (datalen != 0)
546 fatalx("bad MSG_STDIN size");
548 event_add(&client_stdin, NULL);
549 break;
550 case MSG_STDOUT:
551 if (datalen != sizeof stdoutdata)
552 fatalx("bad MSG_STDOUT size");
553 memcpy(&stdoutdata, data, sizeof stdoutdata);
555 client_write(STDOUT_FILENO, stdoutdata.data,
556 stdoutdata.size);
557 break;
558 case MSG_STDERR:
559 if (datalen != sizeof stderrdata)
560 fatalx("bad MSG_STDERR size");
561 memcpy(&stderrdata, data, sizeof stderrdata);
563 client_write(STDERR_FILENO, stderrdata.data,
564 stderrdata.size);
565 break;
566 case MSG_VERSION:
567 if (datalen != 0)
568 fatalx("bad MSG_VERSION size");
570 fprintf(stderr, "protocol version mismatch "
571 "(client %u, server %u)\n", PROTOCOL_VERSION,
572 imsg.hdr.peerid);
573 client_exitval = 1;
575 imsg_free(&imsg);
576 return (-1);
577 case MSG_SHELL:
578 if (data[datalen - 1] != '\0')
579 fatalx("bad MSG_SHELL string");
581 clear_signals(0);
582 shell_exec(data, data0);
583 /* NOTREACHED */
584 case MSG_DETACH:
585 client_write_server(MSG_EXITING, NULL, 0);
586 break;
587 case MSG_EXITED:
588 imsg_free(&imsg);
589 return (-1);
592 imsg_free(&imsg);
596 /* Dispatch imsgs in attached state (after MSG_READY). */
598 client_dispatch_attached(void)
600 struct imsg imsg;
601 struct sigaction sigact;
602 char *data;
603 ssize_t n, datalen;
605 for (;;) {
606 if ((n = imsg_get(&client_ibuf, &imsg)) == -1)
607 fatalx("imsg_get failed");
608 if (n == 0)
609 return (0);
611 data = imsg.data;
612 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
614 log_debug("got %d from server", imsg.hdr.type);
615 switch (imsg.hdr.type) {
616 case MSG_DETACHKILL:
617 case MSG_DETACH:
618 if (datalen != 0)
619 fatalx("bad MSG_DETACH size");
621 client_exittype = imsg.hdr.type;
622 if (imsg.hdr.type == MSG_DETACHKILL)
623 client_exitreason = CLIENT_EXIT_DETACHED_HUP;
624 else
625 client_exitreason = CLIENT_EXIT_DETACHED;
626 client_write_server(MSG_EXITING, NULL, 0);
627 break;
628 case MSG_EXIT:
629 if (datalen != 0 && datalen != sizeof (int))
630 fatalx("bad MSG_EXIT size");
632 client_write_server(MSG_EXITING, NULL, 0);
633 client_exitreason = CLIENT_EXIT_EXITED;
634 break;
635 case MSG_EXITED:
636 if (datalen != 0)
637 fatalx("bad MSG_EXITED size");
639 imsg_free(&imsg);
640 return (-1);
641 case MSG_SHUTDOWN:
642 if (datalen != 0)
643 fatalx("bad MSG_SHUTDOWN size");
645 client_write_server(MSG_EXITING, NULL, 0);
646 client_exitreason = CLIENT_EXIT_SERVER_EXITED;
647 client_exitval = 1;
648 break;
649 case MSG_SUSPEND:
650 if (datalen != 0)
651 fatalx("bad MSG_SUSPEND size");
653 memset(&sigact, 0, sizeof sigact);
654 sigemptyset(&sigact.sa_mask);
655 sigact.sa_flags = SA_RESTART;
656 sigact.sa_handler = SIG_DFL;
657 if (sigaction(SIGTSTP, &sigact, NULL) != 0)
658 fatal("sigaction failed");
659 kill(getpid(), SIGTSTP);
660 break;
661 case MSG_LOCK:
662 if (data[datalen - 1] != '\0')
663 fatalx("bad MSG_LOCK string");
665 system(data);
666 client_write_server(MSG_UNLOCK, NULL, 0);
667 break;
670 imsg_free(&imsg);