Expand build matrix on Travis CI
[abduco.git] / abduco.c
blob1e6f01f1e413271fdbc051d098aad2195ccdfec9
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_EXIT = 4,
71 MSG_PID = 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 uint64_t l;
85 } u;
86 } Packet;
88 typedef struct Client Client;
89 struct Client {
90 int socket;
91 enum {
92 STATE_CONNECTED,
93 STATE_ATTACHED,
94 STATE_DETACHED,
95 STATE_DISCONNECTED,
96 } state;
97 bool need_resize;
98 enum {
99 CLIENT_READONLY = 1 << 0,
100 CLIENT_LOWPRIORITY = 1 << 1,
101 } flags;
102 Client *next;
105 typedef struct {
106 Client *clients;
107 int socket;
108 Packet pty_output;
109 int pty;
110 int exit_status;
111 struct termios term;
112 struct winsize winsize;
113 pid_t pid;
114 volatile sig_atomic_t running;
115 const char *name;
116 const char *session_name;
117 char host[255];
118 bool read_pty;
119 } Server;
121 static Server server = { .running = true, .exit_status = -1, .host = "@localhost" };
122 static Client client;
123 static struct termios orig_term, cur_term;
124 static bool has_term, alternate_buffer, quiet, passthrough;
126 static struct sockaddr_un sockaddr = {
127 .sun_family = AF_UNIX,
130 static bool set_socket_name(struct sockaddr_un *sockaddr, const char *name);
131 static void die(const char *s);
132 static void info(const char *str, ...);
134 #include "debug.c"
136 static inline size_t packet_header_size() {
137 return offsetof(Packet, u);
140 static size_t packet_size(Packet *pkt) {
141 return packet_header_size() + pkt->len;
144 static ssize_t write_all(int fd, const char *buf, size_t len) {
145 debug("write_all(%d)\n", len);
146 ssize_t ret = len;
147 while (len > 0) {
148 ssize_t res = write(fd, buf, len);
149 if (res < 0) {
150 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
151 continue;
152 return -1;
154 if (res == 0)
155 return ret - len;
156 buf += res;
157 len -= res;
159 return ret;
162 static ssize_t read_all(int fd, char *buf, size_t len) {
163 debug("read_all(%d)\n", len);
164 ssize_t ret = len;
165 while (len > 0) {
166 ssize_t res = read(fd, buf, len);
167 if (res < 0) {
168 if (errno == EWOULDBLOCK)
169 return ret - len;
170 if (errno == EAGAIN || errno == EINTR)
171 continue;
172 return -1;
174 if (res == 0)
175 return ret - len;
176 buf += res;
177 len -= res;
179 return ret;
182 static bool send_packet(int socket, Packet *pkt) {
183 size_t size = packet_size(pkt);
184 if (size > sizeof(*pkt))
185 return false;
186 return write_all(socket, (char *)pkt, size) == size;
189 static bool recv_packet(int socket, Packet *pkt) {
190 ssize_t len = read_all(socket, (char*)pkt, packet_header_size());
191 if (len <= 0 || len != packet_header_size())
192 return false;
193 if (pkt->len > sizeof(pkt->u.msg)) {
194 pkt->len = 0;
195 return false;
197 if (pkt->len > 0) {
198 len = read_all(socket, pkt->u.msg, pkt->len);
199 if (len <= 0 || len != pkt->len)
200 return false;
202 return true;
205 #include "client.c"
206 #include "server.c"
208 static void info(const char *str, ...) {
209 va_list ap;
210 va_start(ap, str);
211 if (str && !quiet) {
212 fprintf(stderr, "%s: %s: ", server.name, server.session_name);
213 vfprintf(stderr, str, ap);
214 fprintf(stderr, "\r\n");
215 fflush(stderr);
217 va_end(ap);
220 static void die(const char *s) {
221 perror(s);
222 exit(EXIT_FAILURE);
225 static void usage(void) {
226 fprintf(stderr, "usage: abduco [-a|-A|-c|-n] [-p] [-r] [-q] [-l] [-f] [-e detachkey] name command\n");
227 exit(EXIT_FAILURE);
230 static bool xsnprintf(char *buf, size_t size, const char *fmt, ...) {
231 va_list ap;
232 if (size > INT_MAX)
233 return false;
234 va_start(ap, fmt);
235 int n = vsnprintf(buf, size, fmt, ap);
236 va_end(ap);
237 if (n == -1)
238 return false;
239 if (n >= size) {
240 errno = ENAMETOOLONG;
241 return false;
243 return true;
246 static int session_connect(const char *name) {
247 int fd;
248 struct stat sb;
249 if (!set_socket_name(&sockaddr, name) || (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
250 return -1;
251 socklen_t socklen = offsetof(struct sockaddr_un, sun_path) + strlen(sockaddr.sun_path) + 1;
252 if (connect(fd, (struct sockaddr*)&sockaddr, socklen) == -1) {
253 if (errno == ECONNREFUSED && stat(sockaddr.sun_path, &sb) == 0 && S_ISSOCK(sb.st_mode))
254 unlink(sockaddr.sun_path);
255 close(fd);
256 return -1;
258 return fd;
261 static pid_t session_exists(const char *name) {
262 Packet pkt;
263 pid_t pid = 0;
264 if ((server.socket = session_connect(name)) == -1)
265 return pid;
266 if (client_recv_packet(&pkt) && pkt.type == MSG_PID)
267 pid = pkt.u.l;
268 close(server.socket);
269 return pid;
272 static bool session_alive(const char *name) {
273 struct stat sb;
274 return session_exists(name) &&
275 stat(sockaddr.sun_path, &sb) == 0 &&
276 S_ISSOCK(sb.st_mode) && (sb.st_mode & S_IXGRP) == 0;
279 static bool create_socket_dir(struct sockaddr_un *sockaddr) {
280 sockaddr->sun_path[0] = '\0';
281 int socketfd = socket(AF_UNIX, SOCK_STREAM, 0);
282 if (socketfd == -1)
283 return false;
285 size_t maxlen = sizeof(sockaddr->sun_path);
286 uid_t uid = getuid();
287 struct passwd *pw = getpwuid(uid);
289 for (unsigned int i = 0; i < countof(socket_dirs); i++) {
290 struct stat sb;
291 struct Dir *dir = &socket_dirs[i];
292 bool ishome = false;
293 if (dir->env) {
294 dir->path = getenv(dir->env);
295 ishome = !strcmp(dir->env, "HOME");
296 if (ishome && (!dir->path || !dir->path[0]) && pw)
297 dir->path = pw->pw_dir;
299 if (!dir->path || !dir->path[0])
300 continue;
301 if (!xsnprintf(sockaddr->sun_path, maxlen, "%s/%s%s/", dir->path, ishome ? "." : "", server.name))
302 continue;
303 mode_t mask = umask(0);
304 int r = mkdir(sockaddr->sun_path, dir->personal ? S_IRWXU : S_IRWXU|S_IRWXG|S_IRWXO|S_ISVTX);
305 umask(mask);
306 if (r != 0 && errno != EEXIST)
307 continue;
308 if (lstat(sockaddr->sun_path, &sb) != 0)
309 continue;
310 if (!S_ISDIR(sb.st_mode)) {
311 errno = ENOTDIR;
312 continue;
315 size_t dirlen = strlen(sockaddr->sun_path);
316 if (!dir->personal) {
317 /* create subdirectory only accessible to user */
318 if (pw && !xsnprintf(sockaddr->sun_path+dirlen, maxlen-dirlen, "%s/", pw->pw_name))
319 continue;
320 if (!pw && !xsnprintf(sockaddr->sun_path+dirlen, maxlen-dirlen, "%d/", uid))
321 continue;
322 if (mkdir(sockaddr->sun_path, S_IRWXU) != 0 && errno != EEXIST)
323 continue;
324 if (lstat(sockaddr->sun_path, &sb) != 0)
325 continue;
326 if (!S_ISDIR(sb.st_mode)) {
327 errno = ENOTDIR;
328 continue;
330 dirlen = strlen(sockaddr->sun_path);
333 if (sb.st_uid != uid || sb.st_mode & (S_IRWXG|S_IRWXO)) {
334 errno = EACCES;
335 continue;
338 if (!xsnprintf(sockaddr->sun_path+dirlen, maxlen-dirlen, ".abduco-%d", getpid()))
339 continue;
341 socklen_t socklen = offsetof(struct sockaddr_un, sun_path) + strlen(sockaddr->sun_path) + 1;
342 if (bind(socketfd, (struct sockaddr*)sockaddr, socklen) == -1)
343 continue;
344 unlink(sockaddr->sun_path);
345 close(socketfd);
346 sockaddr->sun_path[dirlen] = '\0';
347 return true;
350 close(socketfd);
351 return false;
354 static bool set_socket_name(struct sockaddr_un *sockaddr, const char *name) {
355 size_t maxlen = sizeof(sockaddr->sun_path);
356 if (name[0] == '/') {
357 if (strlen(name) >= maxlen) {
358 errno = ENAMETOOLONG;
359 return false;
361 strncpy(sockaddr->sun_path, name, maxlen);
362 } else if (name[0] == '.' && (name[1] == '.' || name[1] == '/')) {
363 char buf[maxlen], *cwd = getcwd(buf, sizeof buf);
364 if (!cwd)
365 return false;
366 if (!xsnprintf(sockaddr->sun_path, maxlen, "%s/%s", cwd, name))
367 return false;
368 } else {
369 if (!create_socket_dir(sockaddr))
370 return false;
371 if (strlen(sockaddr->sun_path) + strlen(name) + strlen(server.host) >= maxlen) {
372 errno = ENAMETOOLONG;
373 return false;
375 strncat(sockaddr->sun_path, name, maxlen - strlen(sockaddr->sun_path) - 1);
376 strncat(sockaddr->sun_path, server.host, maxlen - strlen(sockaddr->sun_path) - 1);
378 return true;
381 static bool create_session(const char *name, char * const argv[]) {
382 /* this uses the well known double fork strategy as described in section 1.7 of
384 * http://www.faqs.org/faqs/unix-faq/programmer/faq/
386 * pipes are used for synchronization and error reporting i.e. the child sets
387 * the close on exec flag before calling execvp(3) the parent blocks on a read(2)
388 * in case of failure the error message is written to the pipe, success is
389 * indicated by EOF on the pipe.
391 int client_pipe[2], server_pipe[2];
392 pid_t pid;
393 char errormsg[255];
394 struct sigaction sa;
396 if (session_exists(name)) {
397 errno = EADDRINUSE;
398 return false;
401 if (pipe(client_pipe) == -1)
402 return false;
403 if ((server.socket = server_create_socket(name)) == -1)
404 return false;
406 switch ((pid = fork())) {
407 case 0: /* child process */
408 setsid();
409 close(client_pipe[0]);
410 switch ((pid = fork())) {
411 case 0: /* child process */
412 if (pipe(server_pipe) == -1) {
413 snprintf(errormsg, sizeof(errormsg), "server-pipe: %s\n", strerror(errno));
414 write_all(client_pipe[1], errormsg, strlen(errormsg));
415 close(client_pipe[1]);
416 _exit(EXIT_FAILURE);
418 sa.sa_flags = 0;
419 sigemptyset(&sa.sa_mask);
420 sa.sa_handler = server_pty_died_handler;
421 sigaction(SIGCHLD, &sa, NULL);
422 switch (server.pid = forkpty(&server.pty, NULL, has_term ? &server.term : NULL, &server.winsize)) {
423 case 0: /* child = user application process */
424 close(server.socket);
425 close(server_pipe[0]);
426 if (fcntl(client_pipe[1], F_SETFD, FD_CLOEXEC) == 0 &&
427 fcntl(server_pipe[1], F_SETFD, FD_CLOEXEC) == 0)
428 execvp(argv[0], argv);
429 snprintf(errormsg, sizeof(errormsg), "server-execvp: %s: %s\n",
430 argv[0], strerror(errno));
431 write_all(client_pipe[1], errormsg, strlen(errormsg));
432 write_all(server_pipe[1], errormsg, strlen(errormsg));
433 close(client_pipe[1]);
434 close(server_pipe[1]);
435 _exit(EXIT_FAILURE);
436 break;
437 case -1: /* forkpty failed */
438 snprintf(errormsg, sizeof(errormsg), "server-forkpty: %s\n", strerror(errno));
439 write_all(client_pipe[1], errormsg, strlen(errormsg));
440 close(client_pipe[1]);
441 close(server_pipe[0]);
442 close(server_pipe[1]);
443 _exit(EXIT_FAILURE);
444 break;
445 default: /* parent = server process */
446 sa.sa_handler = server_sigterm_handler;
447 sigaction(SIGTERM, &sa, NULL);
448 sigaction(SIGINT, &sa, NULL);
449 sa.sa_handler = server_sigusr1_handler;
450 sigaction(SIGUSR1, &sa, NULL);
451 sa.sa_handler = SIG_IGN;
452 sigaction(SIGPIPE, &sa, NULL);
453 sigaction(SIGHUP, &sa, NULL);
454 chdir("/");
455 #ifdef NDEBUG
456 int fd = open("/dev/null", O_RDWR);
457 if (fd != -1) {
458 dup2(fd, STDIN_FILENO);
459 dup2(fd, STDOUT_FILENO);
460 dup2(fd, STDERR_FILENO);
461 close(fd);
463 #endif /* NDEBUG */
464 close(client_pipe[1]);
465 close(server_pipe[1]);
466 if (read_all(server_pipe[0], errormsg, sizeof(errormsg)) > 0)
467 _exit(EXIT_FAILURE);
468 close(server_pipe[0]);
469 server_mainloop();
470 break;
472 break;
473 case -1: /* fork failed */
474 snprintf(errormsg, sizeof(errormsg), "server-fork: %s\n", strerror(errno));
475 write_all(client_pipe[1], errormsg, strlen(errormsg));
476 close(client_pipe[1]);
477 _exit(EXIT_FAILURE);
478 break;
479 default: /* parent = intermediate process */
480 close(client_pipe[1]);
481 _exit(EXIT_SUCCESS);
482 break;
484 break;
485 case -1: /* fork failed */
486 close(client_pipe[0]);
487 close(client_pipe[1]);
488 return false;
489 default: /* parent = client process */
490 close(client_pipe[1]);
491 int status;
492 wait(&status); /* wait for first fork */
493 ssize_t len = read_all(client_pipe[0], errormsg, sizeof(errormsg));
494 if (len > 0) {
495 write_all(STDERR_FILENO, errormsg, len);
496 unlink(sockaddr.sun_path);
497 exit(EXIT_FAILURE);
499 close(client_pipe[0]);
501 return true;
504 static bool attach_session(const char *name, const bool terminate) {
505 if (server.socket > 0)
506 close(server.socket);
507 if ((server.socket = session_connect(name)) == -1)
508 return false;
509 if (server_set_socket_non_blocking(server.socket) == -1)
510 return false;
512 struct sigaction sa;
513 sa.sa_flags = 0;
514 sigemptyset(&sa.sa_mask);
515 sa.sa_handler = client_sigwinch_handler;
516 sigaction(SIGWINCH, &sa, NULL);
517 sa.sa_handler = SIG_IGN;
518 sigaction(SIGPIPE, &sa, NULL);
520 client_setup_terminal();
521 int status = client_mainloop();
522 client_restore_terminal();
523 if (status == -1) {
524 info("detached");
525 } else if (status == -EIO) {
526 info("exited due to I/O errors");
527 } else {
528 info("session terminated with exit status %d", status);
529 if (terminate)
530 exit(status);
533 return terminate;
536 static int session_filter(const struct dirent *d) {
537 return strstr(d->d_name, server.host) != NULL;
540 static int session_comparator(const struct dirent **a, const struct dirent **b) {
541 struct stat sa, sb;
542 if (stat((*a)->d_name, &sa) != 0)
543 return -1;
544 if (stat((*b)->d_name, &sb) != 0)
545 return 1;
546 return sa.st_atime < sb.st_atime ? -1 : 1;
549 static int list_session(void) {
550 if (!create_socket_dir(&sockaddr))
551 return 1;
552 if (chdir(sockaddr.sun_path) == -1)
553 die("list-session");
554 struct dirent **namelist;
555 int n = scandir(sockaddr.sun_path, &namelist, session_filter, session_comparator);
556 if (n < 0)
557 return 1;
558 printf("Active sessions (on host %s)\n", server.host+1);
559 while (n--) {
560 struct stat sb; char buf[255];
561 if (stat(namelist[n]->d_name, &sb) == 0 && S_ISSOCK(sb.st_mode)) {
562 pid_t pid = 0;
563 strftime(buf, sizeof(buf), "%a%t %F %T", localtime(&sb.st_mtime));
564 char status = ' ';
565 char *local = strstr(namelist[n]->d_name, server.host);
566 if (local) {
567 *local = '\0'; /* truncate hostname if we are local */
568 if (!(pid = session_exists(namelist[n]->d_name)))
569 continue;
571 if (sb.st_mode & S_IXUSR)
572 status = '*';
573 else if (sb.st_mode & S_IXGRP)
574 status = '+';
575 printf("%c %s\t%jd\t%s\n", status, buf, (intmax_t)pid, namelist[n]->d_name);
577 free(namelist[n]);
579 free(namelist);
580 return 0;
583 int main(int argc, char *argv[]) {
584 int opt;
585 bool force = false;
586 char **cmd = NULL, action = '\0';
588 char *default_cmd[4] = { "/bin/sh", "-c", getenv("ABDUCO_CMD"), NULL };
589 if (!default_cmd[2]) {
590 default_cmd[0] = ABDUCO_CMD;
591 default_cmd[1] = NULL;
594 server.name = basename(argv[0]);
595 gethostname(server.host+1, sizeof(server.host) - 1);
597 passthrough = !isatty(STDIN_FILENO);
599 while ((opt = getopt(argc, argv, "aAclne:fpqrv")) != -1) {
600 switch (opt) {
601 case 'a':
602 case 'A':
603 case 'c':
604 case 'n':
605 action = opt;
606 break;
607 case 'e':
608 if (!optarg)
609 usage();
610 if (optarg[0] == '^' && optarg[1])
611 optarg[0] = CTRL(optarg[1]);
612 KEY_DETACH = optarg[0];
613 break;
614 case 'f':
615 force = true;
616 break;
617 case 'p':
618 passthrough = true;
619 break;
620 case 'q':
621 quiet = true;
622 break;
623 case 'r':
624 client.flags |= CLIENT_READONLY;
625 break;
626 case 'l':
627 client.flags |= CLIENT_LOWPRIORITY;
628 break;
629 case 'v':
630 puts("abduco-"VERSION" © 2013-2018 Marc André Tanner");
631 exit(EXIT_SUCCESS);
632 default:
633 usage();
637 if (passthrough) {
638 if (!action)
639 action = 'a';
640 quiet = true;
641 client.flags |= CLIENT_LOWPRIORITY;
644 /* collect the session name if trailing args */
645 if (optind < argc)
646 server.session_name = argv[optind];
648 /* if yet more trailing arguments, they must be the command */
649 if (optind + 1 < argc)
650 cmd = &argv[optind + 1];
651 else
652 cmd = default_cmd;
654 if (!action && !server.session_name)
655 exit(list_session());
656 if (!action || !server.session_name)
657 usage();
659 if (!passthrough && tcgetattr(STDIN_FILENO, &orig_term) != -1) {
660 server.term = orig_term;
661 has_term = true;
664 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &server.winsize) == -1) {
665 server.winsize.ws_col = 80;
666 server.winsize.ws_row = 25;
669 server.read_pty = (action == 'n');
671 redo:
672 switch (action) {
673 case 'n':
674 case 'c':
675 if (force) {
676 if (session_alive(server.session_name)) {
677 info("session exists and has not yet terminated");
678 return 1;
680 if (session_exists(server.session_name))
681 attach_session(server.session_name, false);
683 if (!create_session(server.session_name, cmd))
684 die("create-session");
685 if (action == 'n')
686 break;
687 case 'a':
688 if (!attach_session(server.session_name, true))
689 die("attach-session");
690 break;
691 case 'A':
692 if (session_alive(server.session_name)) {
693 if (!attach_session(server.session_name, true))
694 die("attach-session");
695 } else if (!attach_session(server.session_name, !force)) {
696 force = false;
697 action = 'c';
698 goto redo;
700 break;
703 return 0;