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