Print MSG_EXIT packet exit code in debug output
[abduco.git] / abduco.c
bloba2884906d2414384b34360e146410e9dd7a59dee
1 /*
2 * Copyright (c) 2013-2018 Marc André Tanner <mat at brain-dump.org>
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <inttypes.h>
19 #include <stdio.h>
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #include <stdbool.h>
23 #include <stddef.h>
24 #include <signal.h>
25 #include <libgen.h>
26 #include <string.h>
27 #include <limits.h>
28 #include <dirent.h>
29 #include <termios.h>
30 #include <time.h>
31 #include <unistd.h>
32 #include <pwd.h>
33 #include <sys/select.h>
34 #include <sys/stat.h>
35 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #if defined(__linux__) || defined(__CYGWIN__)
41 # include <pty.h>
42 #elif defined(__FreeBSD__) || defined(__DragonFly__)
43 # include <libutil.h>
44 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
45 # include <util.h>
46 #endif
48 #if defined CTRL && defined _AIX
49 #undef CTRL
50 #endif
51 #ifndef CTRL
52 #define CTRL(k) ((k) & 0x1F)
53 #endif
55 #include "config.h"
57 #if defined(_AIX)
58 # include "forkpty-aix.c"
59 #elif defined(__sun)
60 # include "forkpty-sunos.c"
61 #endif
63 #define countof(arr) (sizeof(arr) / sizeof((arr)[0]))
65 enum PacketType {
66 MSG_CONTENT = 0,
67 MSG_ATTACH = 1,
68 MSG_DETACH = 2,
69 MSG_RESIZE = 3,
70 MSG_REDRAW = 4,
71 MSG_EXIT = 5,
74 typedef struct {
75 uint32_t type;
76 uint32_t len;
77 union {
78 char msg[4096 - 2*sizeof(uint32_t)];
79 struct {
80 uint16_t rows;
81 uint16_t cols;
82 } ws;
83 uint32_t i;
84 } u;
85 } Packet;
87 typedef struct Client Client;
88 struct Client {
89 int socket;
90 enum {
91 STATE_CONNECTED,
92 STATE_ATTACHED,
93 STATE_DETACHED,
94 STATE_DISCONNECTED,
95 } state;
96 bool need_resize;
97 enum {
98 CLIENT_READONLY = 1 << 0,
99 CLIENT_LOWPRIORITY = 1 << 1,
100 } flags;
101 Client *next;
104 typedef struct {
105 Client *clients;
106 int socket;
107 Packet pty_output;
108 int pty;
109 int exit_status;
110 struct termios term;
111 struct winsize winsize;
112 pid_t pid;
113 volatile sig_atomic_t running;
114 const char *name;
115 const char *session_name;
116 char host[255];
117 bool read_pty;
118 } Server;
120 static Server server = { .running = true, .exit_status = -1, .host = "@localhost" };
121 static Client client;
122 static struct termios orig_term, cur_term;
123 static bool has_term, alternate_buffer, quiet, passthrough;
125 static struct sockaddr_un sockaddr = {
126 .sun_family = AF_UNIX,
129 static bool set_socket_name(struct sockaddr_un *sockaddr, const char *name);
130 static void die(const char *s);
131 static void info(const char *str, ...);
133 #include "debug.c"
135 static inline size_t packet_header_size() {
136 return offsetof(Packet, u);
139 static size_t packet_size(Packet *pkt) {
140 return packet_header_size() + pkt->len;
143 static ssize_t write_all(int fd, const char *buf, size_t len) {
144 debug("write_all(%d)\n", len);
145 ssize_t ret = len;
146 while (len > 0) {
147 ssize_t res = write(fd, buf, len);
148 if (res < 0) {
149 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
150 continue;
151 return -1;
153 if (res == 0)
154 return ret - len;
155 buf += res;
156 len -= res;
158 return ret;
161 static ssize_t read_all(int fd, char *buf, size_t len) {
162 debug("read_all(%d)\n", len);
163 ssize_t ret = len;
164 while (len > 0) {
165 ssize_t res = read(fd, buf, len);
166 if (res < 0) {
167 if (errno == EWOULDBLOCK)
168 return ret - len;
169 if (errno == EAGAIN || errno == EINTR)
170 continue;
171 return -1;
173 if (res == 0)
174 return ret - len;
175 buf += res;
176 len -= res;
178 return ret;
181 static bool send_packet(int socket, Packet *pkt) {
182 size_t size = packet_size(pkt);
183 if (size > sizeof(*pkt))
184 return false;
185 return write_all(socket, (char *)pkt, size) == size;
188 static bool recv_packet(int socket, Packet *pkt) {
189 ssize_t len = read_all(socket, (char*)pkt, packet_header_size());
190 if (len <= 0 || len != packet_header_size())
191 return false;
192 if (pkt->len > sizeof(pkt->u.msg)) {
193 pkt->len = 0;
194 return false;
196 if (pkt->len > 0) {
197 len = read_all(socket, pkt->u.msg, pkt->len);
198 if (len <= 0 || len != pkt->len)
199 return false;
201 return true;
204 #include "client.c"
205 #include "server.c"
207 static void info(const char *str, ...) {
208 va_list ap;
209 va_start(ap, str);
210 if (str && !quiet) {
211 fprintf(stderr, "%s: %s: ", server.name, server.session_name);
212 vfprintf(stderr, str, ap);
213 fprintf(stderr, "\r\n");
214 fflush(stderr);
216 va_end(ap);
219 static void die(const char *s) {
220 perror(s);
221 exit(EXIT_FAILURE);
224 static void usage(void) {
225 fprintf(stderr, "usage: abduco [-a|-A|-c|-n] [-p] [-r] [-q] [-l] [-f] [-e detachkey] name command\n");
226 exit(EXIT_FAILURE);
229 static bool xsnprintf(char *buf, size_t size, const char *fmt, ...) {
230 va_list ap;
231 if (size > INT_MAX)
232 return false;
233 va_start(ap, fmt);
234 int n = vsnprintf(buf, size, fmt, ap);
235 va_end(ap);
236 if (n == -1)
237 return false;
238 if (n >= size) {
239 errno = ENAMETOOLONG;
240 return false;
242 return true;
245 static int session_connect(const char *name) {
246 int fd;
247 struct stat sb;
248 if (!set_socket_name(&sockaddr, name) || (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
249 return -1;
250 socklen_t socklen = offsetof(struct sockaddr_un, sun_path) + strlen(sockaddr.sun_path) + 1;
251 if (connect(fd, (struct sockaddr*)&sockaddr, socklen) == -1) {
252 if (errno == ECONNREFUSED && stat(sockaddr.sun_path, &sb) == 0 && S_ISSOCK(sb.st_mode))
253 unlink(sockaddr.sun_path);
254 close(fd);
255 return -1;
257 return fd;
260 static bool session_exists(const char *name) {
261 int fd = session_connect(name);
262 if (fd != -1)
263 close(fd);
264 return fd != -1;
267 static bool session_alive(const char *name) {
268 struct stat sb;
269 return session_exists(name) &&
270 stat(sockaddr.sun_path, &sb) == 0 &&
271 S_ISSOCK(sb.st_mode) && (sb.st_mode & S_IXGRP) == 0;
274 static bool create_socket_dir(struct sockaddr_un *sockaddr) {
275 sockaddr->sun_path[0] = '\0';
276 int socketfd = socket(AF_UNIX, SOCK_STREAM, 0);
277 if (socketfd == -1)
278 return false;
280 size_t maxlen = sizeof(sockaddr->sun_path);
281 uid_t uid = getuid();
282 struct passwd *pw = getpwuid(uid);
284 for (unsigned int i = 0; i < countof(socket_dirs); i++) {
285 struct stat sb;
286 struct Dir *dir = &socket_dirs[i];
287 bool ishome = false;
288 if (dir->env) {
289 dir->path = getenv(dir->env);
290 ishome = !strcmp(dir->env, "HOME");
291 if (ishome && (!dir->path || !dir->path[0]) && pw)
292 dir->path = pw->pw_dir;
294 if (!dir->path || !dir->path[0])
295 continue;
296 if (!xsnprintf(sockaddr->sun_path, maxlen, "%s/%s%s/", dir->path, ishome ? "." : "", server.name))
297 continue;
298 mode_t mask = umask(0);
299 int r = mkdir(sockaddr->sun_path, dir->personal ? S_IRWXU : S_IRWXU|S_IRWXG|S_IRWXO|S_ISVTX);
300 umask(mask);
301 if (r != 0 && errno != EEXIST)
302 continue;
303 if (lstat(sockaddr->sun_path, &sb) != 0)
304 continue;
305 if (!S_ISDIR(sb.st_mode)) {
306 errno = ENOTDIR;
307 continue;
310 size_t dirlen = strlen(sockaddr->sun_path);
311 if (!dir->personal) {
312 /* create subdirectory only accessible to user */
313 if (pw && !xsnprintf(sockaddr->sun_path+dirlen, maxlen-dirlen, "%s/", pw->pw_name))
314 continue;
315 if (!pw && !xsnprintf(sockaddr->sun_path+dirlen, maxlen-dirlen, "%d/", uid))
316 continue;
317 if (mkdir(sockaddr->sun_path, S_IRWXU) != 0 && errno != EEXIST)
318 continue;
319 if (lstat(sockaddr->sun_path, &sb) != 0)
320 continue;
321 if (!S_ISDIR(sb.st_mode)) {
322 errno = ENOTDIR;
323 continue;
325 dirlen = strlen(sockaddr->sun_path);
328 if (sb.st_uid != uid || sb.st_mode & (S_IRWXG|S_IRWXO)) {
329 errno = EACCES;
330 continue;
333 if (!xsnprintf(sockaddr->sun_path+dirlen, maxlen-dirlen, ".abduco-%d", getpid()))
334 continue;
336 socklen_t socklen = offsetof(struct sockaddr_un, sun_path) + strlen(sockaddr->sun_path) + 1;
337 if (bind(socketfd, (struct sockaddr*)sockaddr, socklen) == -1)
338 continue;
339 unlink(sockaddr->sun_path);
340 close(socketfd);
341 sockaddr->sun_path[dirlen] = '\0';
342 return true;
345 close(socketfd);
346 return false;
349 static bool set_socket_name(struct sockaddr_un *sockaddr, const char *name) {
350 size_t maxlen = sizeof(sockaddr->sun_path);
351 if (name[0] == '/') {
352 if (strlen(name) >= maxlen) {
353 errno = ENAMETOOLONG;
354 return false;
356 strncpy(sockaddr->sun_path, name, maxlen);
357 } else if (name[0] == '.' && (name[1] == '.' || name[1] == '/')) {
358 char buf[maxlen], *cwd = getcwd(buf, sizeof buf);
359 if (!cwd)
360 return false;
361 if (!xsnprintf(sockaddr->sun_path, maxlen, "%s/%s", cwd, name))
362 return false;
363 } else {
364 if (!create_socket_dir(sockaddr))
365 return false;
366 if (strlen(sockaddr->sun_path) + strlen(name) + strlen(server.host) >= maxlen) {
367 errno = ENAMETOOLONG;
368 return false;
370 strncat(sockaddr->sun_path, name, maxlen - strlen(sockaddr->sun_path) - 1);
371 strncat(sockaddr->sun_path, server.host, maxlen - strlen(sockaddr->sun_path) - 1);
373 return true;
376 static bool create_session(const char *name, char * const argv[]) {
377 /* this uses the well known double fork strategy as described in section 1.7 of
379 * http://www.faqs.org/faqs/unix-faq/programmer/faq/
381 * pipes are used for synchronization and error reporting i.e. the child sets
382 * the close on exec flag before calling execvp(3) the parent blocks on a read(2)
383 * in case of failure the error message is written to the pipe, success is
384 * indicated by EOF on the pipe.
386 int client_pipe[2], server_pipe[2];
387 pid_t pid;
388 char errormsg[255];
389 struct sigaction sa;
391 if (session_exists(name)) {
392 errno = EADDRINUSE;
393 return false;
396 if (pipe(client_pipe) == -1)
397 return false;
398 if ((server.socket = server_create_socket(name)) == -1)
399 return false;
401 switch ((pid = fork())) {
402 case 0: /* child process */
403 setsid();
404 close(client_pipe[0]);
405 switch ((pid = fork())) {
406 case 0: /* child process */
407 if (pipe(server_pipe) == -1) {
408 snprintf(errormsg, sizeof(errormsg), "server-pipe: %s\n", strerror(errno));
409 write_all(client_pipe[1], errormsg, strlen(errormsg));
410 close(client_pipe[1]);
411 _exit(EXIT_FAILURE);
413 sa.sa_flags = 0;
414 sigemptyset(&sa.sa_mask);
415 sa.sa_handler = server_pty_died_handler;
416 sigaction(SIGCHLD, &sa, NULL);
417 switch (server.pid = forkpty(&server.pty, NULL, has_term ? &server.term : NULL, &server.winsize)) {
418 case 0: /* child = user application process */
419 close(server.socket);
420 close(server_pipe[0]);
421 if (fcntl(client_pipe[1], F_SETFD, FD_CLOEXEC) == 0 &&
422 fcntl(server_pipe[1], F_SETFD, FD_CLOEXEC) == 0)
423 execvp(argv[0], argv);
424 snprintf(errormsg, sizeof(errormsg), "server-execvp: %s: %s\n",
425 argv[0], strerror(errno));
426 write_all(client_pipe[1], errormsg, strlen(errormsg));
427 write_all(server_pipe[1], errormsg, strlen(errormsg));
428 close(client_pipe[1]);
429 close(server_pipe[1]);
430 _exit(EXIT_FAILURE);
431 break;
432 case -1: /* forkpty failed */
433 snprintf(errormsg, sizeof(errormsg), "server-forkpty: %s\n", strerror(errno));
434 write_all(client_pipe[1], errormsg, strlen(errormsg));
435 close(client_pipe[1]);
436 close(server_pipe[0]);
437 close(server_pipe[1]);
438 _exit(EXIT_FAILURE);
439 break;
440 default: /* parent = server process */
441 sa.sa_handler = server_sigterm_handler;
442 sigaction(SIGTERM, &sa, NULL);
443 sigaction(SIGINT, &sa, NULL);
444 sa.sa_handler = server_sigusr1_handler;
445 sigaction(SIGUSR1, &sa, NULL);
446 sa.sa_handler = SIG_IGN;
447 sigaction(SIGPIPE, &sa, NULL);
448 sigaction(SIGHUP, &sa, NULL);
449 chdir("/");
450 #ifdef NDEBUG
451 int fd = open("/dev/null", O_RDWR);
452 if (fd != -1) {
453 dup2(fd, STDIN_FILENO);
454 dup2(fd, STDOUT_FILENO);
455 dup2(fd, STDERR_FILENO);
456 close(fd);
458 #endif /* NDEBUG */
459 close(client_pipe[1]);
460 close(server_pipe[1]);
461 if (read_all(server_pipe[0], errormsg, sizeof(errormsg)) > 0)
462 _exit(EXIT_FAILURE);
463 close(server_pipe[0]);
464 server_mainloop();
465 break;
467 break;
468 case -1: /* fork failed */
469 snprintf(errormsg, sizeof(errormsg), "server-fork: %s\n", strerror(errno));
470 write_all(client_pipe[1], errormsg, strlen(errormsg));
471 close(client_pipe[1]);
472 _exit(EXIT_FAILURE);
473 break;
474 default: /* parent = intermediate process */
475 close(client_pipe[1]);
476 _exit(EXIT_SUCCESS);
477 break;
479 break;
480 case -1: /* fork failed */
481 close(client_pipe[0]);
482 close(client_pipe[1]);
483 return false;
484 default: /* parent = client process */
485 close(client_pipe[1]);
486 int status;
487 wait(&status); /* wait for first fork */
488 ssize_t len = read_all(client_pipe[0], errormsg, sizeof(errormsg));
489 if (len > 0) {
490 write_all(STDERR_FILENO, errormsg, len);
491 unlink(sockaddr.sun_path);
492 exit(EXIT_FAILURE);
494 close(client_pipe[0]);
496 return true;
499 static bool attach_session(const char *name, const bool terminate) {
500 if (server.socket > 0)
501 close(server.socket);
502 if ((server.socket = session_connect(name)) == -1)
503 return false;
504 if (server_set_socket_non_blocking(server.socket) == -1)
505 return false;
507 struct sigaction sa;
508 sa.sa_flags = 0;
509 sigemptyset(&sa.sa_mask);
510 sa.sa_handler = client_sigwinch_handler;
511 sigaction(SIGWINCH, &sa, NULL);
512 sa.sa_handler = SIG_IGN;
513 sigaction(SIGPIPE, &sa, NULL);
515 client_setup_terminal();
516 int status = client_mainloop();
517 client_restore_terminal();
518 if (status == -1) {
519 info("detached");
520 } else if (status == -EIO) {
521 info("exited due to I/O errors");
522 } else {
523 info("session terminated with exit status %d", status);
524 if (terminate)
525 exit(status);
528 return terminate;
531 static int session_filter(const struct dirent *d) {
532 return strstr(d->d_name, server.host) != NULL;
535 static int session_comparator(const struct dirent **a, const struct dirent **b) {
536 struct stat sa, sb;
537 if (stat((*a)->d_name, &sa) != 0)
538 return -1;
539 if (stat((*b)->d_name, &sb) != 0)
540 return 1;
541 return sa.st_atime < sb.st_atime ? -1 : 1;
544 static int list_session(void) {
545 if (!create_socket_dir(&sockaddr))
546 return 1;
547 if (chdir(sockaddr.sun_path) == -1)
548 die("list-session");
549 struct dirent **namelist;
550 int n = scandir(sockaddr.sun_path, &namelist, session_filter, session_comparator);
551 if (n < 0)
552 return 1;
553 printf("Active sessions (on host %s)\n", server.host+1);
554 while (n--) {
555 struct stat sb; char buf[255];
556 if (stat(namelist[n]->d_name, &sb) == 0 && S_ISSOCK(sb.st_mode)) {
557 strftime(buf, sizeof(buf), "%a%t %F %T", localtime(&sb.st_mtime));
558 char status = ' ';
559 char *local = strstr(namelist[n]->d_name, server.host);
560 if (local) {
561 *local = '\0'; /* truncate hostname if we are local */
562 if (!session_exists(namelist[n]->d_name))
563 continue;
565 if (sb.st_mode & S_IXUSR)
566 status = '*';
567 else if (sb.st_mode & S_IXGRP)
568 status = '+';
569 printf("%c %s\t%s\n", status, buf, namelist[n]->d_name);
571 free(namelist[n]);
573 free(namelist);
574 return 0;
577 int main(int argc, char *argv[]) {
578 int opt;
579 bool force = false;
580 char **cmd = NULL, action = '\0';
582 char *default_cmd[4] = { "/bin/sh", "-c", getenv("ABDUCO_CMD"), NULL };
583 if (!default_cmd[2]) {
584 default_cmd[0] = ABDUCO_CMD;
585 default_cmd[1] = NULL;
588 server.name = basename(argv[0]);
589 gethostname(server.host+1, sizeof(server.host) - 1);
591 passthrough = !isatty(STDIN_FILENO);
593 while ((opt = getopt(argc, argv, "aAclne:fpqrv")) != -1) {
594 switch (opt) {
595 case 'a':
596 case 'A':
597 case 'c':
598 case 'n':
599 action = opt;
600 break;
601 case 'e':
602 if (!optarg)
603 usage();
604 if (optarg[0] == '^' && optarg[1])
605 optarg[0] = CTRL(optarg[1]);
606 KEY_DETACH = optarg[0];
607 break;
608 case 'f':
609 force = true;
610 break;
611 case 'p':
612 passthrough = true;
613 break;
614 case 'q':
615 quiet = true;
616 break;
617 case 'r':
618 client.flags |= CLIENT_READONLY;
619 break;
620 case 'l':
621 client.flags |= CLIENT_LOWPRIORITY;
622 break;
623 case 'v':
624 puts("abduco-"VERSION" © 2013-2018 Marc André Tanner");
625 exit(EXIT_SUCCESS);
626 default:
627 usage();
631 if (passthrough) {
632 if (!action)
633 action = 'a';
634 quiet = true;
635 client.flags |= CLIENT_LOWPRIORITY;
638 /* collect the session name if trailing args */
639 if (optind < argc)
640 server.session_name = argv[optind];
642 /* if yet more trailing arguments, they must be the command */
643 if (optind + 1 < argc)
644 cmd = &argv[optind + 1];
645 else
646 cmd = default_cmd;
648 if (!action && !server.session_name)
649 exit(list_session());
650 if (!action || !server.session_name)
651 usage();
653 if (!passthrough && tcgetattr(STDIN_FILENO, &orig_term) != -1) {
654 server.term = orig_term;
655 has_term = true;
658 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &server.winsize) == -1) {
659 server.winsize.ws_col = 80;
660 server.winsize.ws_row = 25;
663 server.read_pty = (action == 'n');
665 redo:
666 switch (action) {
667 case 'n':
668 case 'c':
669 if (force) {
670 if (session_alive(server.session_name)) {
671 info("session exists and has not yet terminated");
672 return 1;
674 if (session_exists(server.session_name))
675 attach_session(server.session_name, false);
677 if (!create_session(server.session_name, cmd))
678 die("create-session");
679 if (action == 'n')
680 break;
681 case 'a':
682 if (!attach_session(server.session_name, true))
683 die("attach-session");
684 break;
685 case 'A':
686 if (session_alive(server.session_name)) {
687 if (!attach_session(server.session_name, true))
688 die("attach-session");
689 } else if (!attach_session(server.session_name, !force)) {
690 force = false;
691 action = 'c';
692 goto redo;
694 break;
697 return 0;