1 /* $OpenBSD: client.c,v 1.78 2014/01/09 21:20:45 nicm Exp $ */ 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 setproctitle("client (%s)", socket_path); 247 logfile("client"); 248 249 /* Create imsg. */ 250 imsg_init(&client_ibuf, fd); 251 event_set(&client_event, fd, EV_READ, client_callback, shell_cmd); 252 253 /* Create stdin handler. */ 254 setblocking(STDIN_FILENO, 0); 255 event_set(&client_stdin, STDIN_FILENO, EV_READ|EV_PERSIST, 256 client_stdin_callback, NULL); 257 if (flags & CLIENT_CONTROLCONTROL) { 258 if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) { 259 fprintf(stderr, "tcgetattr failed: %s\n", 260 strerror(errno)); 261 return (1); 262 } 263 cfmakeraw(&tio); 264 tio.c_iflag = ICRNL|IXANY; 265 tio.c_oflag = OPOST|ONLCR; 266 tio.c_lflag = NOKERNINFO; 267 tio.c_cflag = CREAD|CS8|HUPCL; 268 tio.c_cc[VMIN] = 1; 269 tio.c_cc[VTIME] = 0; 270 cfsetispeed(&tio, cfgetispeed(&saved_tio)); 271 cfsetospeed(&tio, cfgetospeed(&saved_tio)); 272 tcsetattr(STDIN_FILENO, TCSANOW, &tio); 273 } 274 275 /* Establish signal handlers. */ 276 set_signals(client_signal); 277 278 /* Send identify messages. */ 279 client_send_identify(flags); 280 281 /* Send first command. */ 282 if (msg == MSG_COMMAND) { 283 /* How big is the command? */ 284 size = 0; 285 for (i = 0; i < argc; i++) 286 size += strlen(argv[i]) + 1; 287 data = xmalloc((sizeof *data) + size); 288 289 /* Prepare command for server. */ 290 data->argc = argc; 291 if (cmd_pack_argv(argc, argv, (char*)(data + 1), size) != 0) { 292 fprintf(stderr, "command too long\n"); 293 free(data); 294 return (1); 295 } 296 size += sizeof *data; 297 298 /* Send the command. */ 299 if (client_write_server(msg, data, size) != 0) { 300 fprintf(stderr, "failed to send command\n"); 301 free(data); 302 return (1); 303 } 304 free(data); 305 } else if (msg == MSG_SHELL) 306 client_write_server(msg, NULL, 0); 307 308 /* Set the event and dispatch. */ 309 client_update_event(); 310 event_dispatch(); 311 312 /* Print the exit message, if any, and exit. */ 313 if (client_attached) { 314 if (client_exitreason != CLIENT_EXIT_NONE && !login_shell) 315 printf("[%s]\n", client_exit_message()); 316 317 ppid = getppid(); 318 if (client_exittype == MSG_DETACHKILL && ppid > 1) 319 kill(ppid, SIGHUP); 320 } else if (flags & CLIENT_CONTROLCONTROL) { 321 if (client_exitreason != CLIENT_EXIT_NONE) 322 printf("%%exit %s\n", client_exit_message()); 323 else 324 printf("%%exit\n"); 325 printf("\033\\"); 326 tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio); 327 } 328 setblocking(STDIN_FILENO, 1); 329 return (client_exitval); 330 } 331 332 /* Send identify messages to server. */ 333 void 334 client_send_identify(int flags) 335 { 336 const char *s; 337 char **ss; 338 int fd; 339 340 client_write_one(MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags); 341 342 if ((s = getenv("TERM")) == NULL) 343 s = ""; 344 client_write_one(MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1); 345 346 if ((s = ttyname(STDIN_FILENO)) == NULL) 347 s = ""; 348 client_write_one(MSG_IDENTIFY_TTYNAME, -1, s, strlen(s) + 1); 349 350 if ((fd = open(".", O_RDONLY)) == -1) 351 fd = open("/", O_RDONLY); 352 client_write_one(MSG_IDENTIFY_CWD, fd, NULL, 0); 353 354 if ((fd = dup(STDIN_FILENO)) == -1) 355 fatal("dup failed"); 356 client_write_one(MSG_IDENTIFY_STDIN, fd, NULL, 0); 357 358 for (ss = environ; *ss != NULL; ss++) 359 client_write_one(MSG_IDENTIFY_ENVIRON, -1, *ss, strlen(*ss) + 1); 360 361 client_write_one(MSG_IDENTIFY_DONE, -1, NULL, 0); 362 363 client_update_event(); 364 } 365 366 /* Helper to send one message. */ 367 int 368 client_write_one(enum msgtype type, int fd, const void *buf, size_t len) 369 { 370 int retval; 371 372 retval = imsg_compose(&client_ibuf, type, PROTOCOL_VERSION, -1, fd, 373 (void*)buf, len); 374 if (retval != 1) 375 return (-1); 376 return (0); 377 } 378 379 /* Write a message to the server without a file descriptor. */ 380 int 381 client_write_server(enum msgtype type, const void *buf, size_t len) 382 { 383 int retval; 384 385 retval = client_write_one(type, -1, buf, len); 386 if (retval == 0) 387 client_update_event(); 388 return (retval); 389 } 390 391 /* Update client event based on whether it needs to read or read and write. */ 392 void 393 client_update_event(void) 394 { 395 short events; 396 397 event_del(&client_event); 398 events = EV_READ; 399 if (client_ibuf.w.queued > 0) 400 events |= EV_WRITE; 401 event_set( 402 &client_event, client_ibuf.fd, events, client_callback, shell_cmd); 403 event_add(&client_event, NULL); 404 } 405 406 /* Callback to handle signals in the client. */ 407 void 408 client_signal(int sig, unused short events, unused void *data) 409 { 410 struct sigaction sigact; 411 int status; 412 413 if (!client_attached) { 414 switch (sig) { 415 case SIGCHLD: 416 waitpid(WAIT_ANY, &status, WNOHANG); 417 break; 418 case SIGTERM: 419 event_loopexit(NULL); 420 break; 421 } 422 } else { 423 switch (sig) { 424 case SIGHUP: 425 client_exitreason = CLIENT_EXIT_LOST_TTY; 426 client_exitval = 1; 427 client_write_server(MSG_EXITING, NULL, 0); 428 break; 429 case SIGTERM: 430 client_exitreason = CLIENT_EXIT_TERMINATED; 431 client_exitval = 1; 432 client_write_server(MSG_EXITING, NULL, 0); 433 break; 434 case SIGWINCH: 435 client_write_server(MSG_RESIZE, NULL, 0); 436 break; 437 case SIGCONT: 438 memset(&sigact, 0, sizeof sigact); 439 sigemptyset(&sigact.sa_mask); 440 sigact.sa_flags = SA_RESTART; 441 sigact.sa_handler = SIG_IGN; 442 if (sigaction(SIGTSTP, &sigact, NULL) != 0) 443 fatal("sigaction failed"); 444 client_write_server(MSG_WAKEUP, NULL, 0); 445 break; 446 } 447 } 448 449 client_update_event(); 450 } 451 452 /* Callback for client imsg read events. */ 453 void 454 client_callback(unused int fd, short events, void *data) 455 { 456 ssize_t n; 457 int retval; 458 459 if (events & EV_READ) { 460 if ((n = imsg_read(&client_ibuf)) == -1 || n == 0) 461 goto lost_server; 462 if (client_attached) 463 retval = client_dispatch_attached(); 464 else 465 retval = client_dispatch_wait(data); 466 if (retval != 0) { 467 event_loopexit(NULL); 468 return; 469 } 470 } 471 472 if (events & EV_WRITE) { 473 if (msgbuf_write(&client_ibuf.w) < 0 && errno != EAGAIN) 474 goto lost_server; 475 } 476 477 client_update_event(); 478 return; 479 480 lost_server: 481 client_exitreason = CLIENT_EXIT_LOST_SERVER; 482 client_exitval = 1; 483 event_loopexit(NULL); 484 } 485 486 /* Callback for client stdin read events. */ 487 void 488 client_stdin_callback(unused int fd, unused short events, unused void *data1) 489 { 490 struct msg_stdin_data data; 491 492 data.size = read(STDIN_FILENO, data.data, sizeof data.data); 493 if (data.size < 0 && (errno == EINTR || errno == EAGAIN)) 494 return; 495 496 client_write_server(MSG_STDIN, &data, sizeof data); 497 if (data.size <= 0) 498 event_del(&client_stdin); 499 client_update_event(); 500 } 501 502 /* Force write to file descriptor. */ 503 void 504 client_write(int fd, const char *data, size_t size) 505 { 506 ssize_t used; 507 508 while (size != 0) { 509 used = write(fd, data, size); 510 if (used == -1) { 511 if (errno == EINTR || errno == EAGAIN) 512 continue; 513 break; 514 } 515 data += used; 516 size -= used; 517 } 518 } 519 520 /* Dispatch imsgs when in wait state (before MSG_READY). */ 521 int 522 client_dispatch_wait(void *data0) 523 { 524 struct imsg imsg; 525 char *data; 526 ssize_t n, datalen; 527 struct msg_stdout_data stdoutdata; 528 struct msg_stderr_data stderrdata; 529 int retval; 530 531 for (;;) { 532 if ((n = imsg_get(&client_ibuf, &imsg)) == -1) 533 fatalx("imsg_get failed"); 534 if (n == 0) 535 return (0); 536 537 data = imsg.data; 538 datalen = imsg.hdr.len - IMSG_HEADER_SIZE; 539 540 log_debug("got %d from server", imsg.hdr.type); 541 switch (imsg.hdr.type) { 542 case MSG_EXIT: 543 case MSG_SHUTDOWN: 544 if (datalen != sizeof retval && datalen != 0) 545 fatalx("bad MSG_EXIT size"); 546 if (datalen == sizeof retval) { 547 memcpy(&retval, data, sizeof retval); 548 client_exitval = retval; 549 } 550 imsg_free(&imsg); 551 return (-1); 552 case MSG_READY: 553 if (datalen != 0) 554 fatalx("bad MSG_READY size"); 555 556 event_del(&client_stdin); 557 client_attached = 1; 558 client_write_server(MSG_RESIZE, NULL, 0); 559 break; 560 case MSG_STDIN: 561 if (datalen != 0) 562 fatalx("bad MSG_STDIN size"); 563 564 event_add(&client_stdin, NULL); 565 break; 566 case MSG_STDOUT: 567 if (datalen != sizeof stdoutdata) 568 fatalx("bad MSG_STDOUT size"); 569 memcpy(&stdoutdata, data, sizeof stdoutdata); 570 571 client_write(STDOUT_FILENO, stdoutdata.data, 572 stdoutdata.size); 573 break; 574 case MSG_STDERR: 575 if (datalen != sizeof stderrdata) 576 fatalx("bad MSG_STDERR size"); 577 memcpy(&stderrdata, data, sizeof stderrdata); 578 579 client_write(STDERR_FILENO, stderrdata.data, 580 stderrdata.size); 581 break; 582 case MSG_VERSION: 583 if (datalen != 0) 584 fatalx("bad MSG_VERSION size"); 585 586 fprintf(stderr, "protocol version mismatch " 587 "(client %u, server %u)\n", PROTOCOL_VERSION, 588 imsg.hdr.peerid); 589 client_exitval = 1; 590 591 imsg_free(&imsg); 592 return (-1); 593 case MSG_SHELL: 594 if (datalen == 0 || data[datalen - 1] != '\0') 595 fatalx("bad MSG_SHELL string"); 596 597 clear_signals(0); 598 shell_exec(data, data0); 599 /* NOTREACHED */ 600 case MSG_DETACH: 601 case MSG_DETACHKILL: 602 client_write_server(MSG_EXITING, NULL, 0); 603 break; 604 case MSG_EXITED: 605 imsg_free(&imsg); 606 return (-1); 607 } 608 609 imsg_free(&imsg); 610 } 611 } 612 613 /* Dispatch imsgs in attached state (after MSG_READY). */ 614 int 615 client_dispatch_attached(void) 616 { 617 struct imsg imsg; 618 struct sigaction sigact; 619 char *data; 620 ssize_t n, datalen; 621 622 for (;;) { 623 if ((n = imsg_get(&client_ibuf, &imsg)) == -1) 624 fatalx("imsg_get failed"); 625 if (n == 0) 626 return (0); 627 628 data = imsg.data; 629 datalen = imsg.hdr.len - IMSG_HEADER_SIZE; 630 631 log_debug("got %d from server", imsg.hdr.type); 632 switch (imsg.hdr.type) { 633 case MSG_DETACH: 634 case MSG_DETACHKILL: 635 if (datalen == 0 || data[datalen - 1] != '\0') 636 fatalx("bad MSG_DETACH string"); 637 638 client_exitsession = xstrdup(data); 639 client_exittype = imsg.hdr.type; 640 if (imsg.hdr.type == MSG_DETACHKILL) 641 client_exitreason = CLIENT_EXIT_DETACHED_HUP; 642 else 643 client_exitreason = CLIENT_EXIT_DETACHED; 644 client_write_server(MSG_EXITING, NULL, 0); 645 break; 646 case MSG_EXIT: 647 if (datalen != 0 && datalen != sizeof (int)) 648 fatalx("bad MSG_EXIT size"); 649 650 client_write_server(MSG_EXITING, NULL, 0); 651 client_exitreason = CLIENT_EXIT_EXITED; 652 break; 653 case MSG_EXITED: 654 if (datalen != 0) 655 fatalx("bad MSG_EXITED size"); 656 657 imsg_free(&imsg); 658 return (-1); 659 case MSG_SHUTDOWN: 660 if (datalen != 0) 661 fatalx("bad MSG_SHUTDOWN size"); 662 663 client_write_server(MSG_EXITING, NULL, 0); 664 client_exitreason = CLIENT_EXIT_SERVER_EXITED; 665 client_exitval = 1; 666 break; 667 case MSG_SUSPEND: 668 if (datalen != 0) 669 fatalx("bad MSG_SUSPEND size"); 670 671 memset(&sigact, 0, sizeof sigact); 672 sigemptyset(&sigact.sa_mask); 673 sigact.sa_flags = SA_RESTART; 674 sigact.sa_handler = SIG_DFL; 675 if (sigaction(SIGTSTP, &sigact, NULL) != 0) 676 fatal("sigaction failed"); 677 kill(getpid(), SIGTSTP); 678 break; 679 case MSG_LOCK: 680 if (datalen == 0 || data[datalen - 1] != '\0') 681 fatalx("bad MSG_LOCK string"); 682 683 system(data); 684 client_write_server(MSG_UNLOCK, NULL, 0); 685 break; 686 } 687 688 imsg_free(&imsg); 689 } 690 } 691