Debian Codegraph @

detachtty.c

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * detachtty - run long-lived processes non interactively in the background,
3 * and reattach them to a terminal at later time
4 *
5 * Copyright (C) 2016-2017 Massimiliano Ghilardi
6 * Copyright (C) 2001-2005 Daniel Barlow
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <sys/stat.h>
27 #include <pty.h>
28 #include <fcntl.h>
29
30 #ifndef UNIX_PATH_MAX
31 # define UNIX_PATH_MAX 108
32 #endif
33
34 static char * const MY_NAME = "detachtty";
35
36 /*
37 Create child process and establish the slave pseudo terminal as the
38 child's controlling terminal.
39 extern int forkpty __P ((int *__amaster, char *__name,
40 struct termios *__termp, struct winsize *__winp));
41 __amaster=fd of master pty
42 __name = name of master pty, must be long enough. how do we know?
43
44 In the child, also dups the slave device to fds 0,1,2 and calls setsid()
45 (which causes the right process group stuff to happen too)
46 */
47
48 static int parse_args(int argc, char *argv[], int * next_arg_ptr);
49 static void set_noecho(int fd);
50 static int bind_socket_or_bail(char * socket_path);
51 static void usage(char *name,char *offending_option);
52 static void version(void);
53 static void init_signal_handlers(void);
54 static void process_accumulated_signals(void);
55 static void tidy_up_nicely(int signal);
56
57 /*
58 1) fork and open pty pairs. start child process on the slave end
59 2) open network socket, listen to it - backlog 0
60 (should be unix-domain socket)
61 3) accept a single connection
62 */
63
64 static char *socket_path=NULL;
65 static char *dribble_path=NULL;
66 static char *log_file_path=NULL;
67 static char *pid_file_path=NULL;
68 static int dribble_fd=-1;
69 static volatile int was_signaled = 0, was_sighupped = 0;
70
71 static void reopen_files(int signal) {
72 if (log_file_path) {
73 if (log_fp)
74 fclose(log_fp);
75 log_fp = fopen(log_file_path,"a");
76 if (log_fp==NULL)
77 perror("fopen log file");
78 setvbuf(log_fp, NULL, _IONBF, 0); /* don't buffer */
79 if (signal > 0)
80 logprintf(MY_NAME, "Got signal %d, reopened log file \"%s\"",
81 signal, log_file_path);
82 } else {
83 log_fp = stderr;
84 }
85 if (dribble_path) {
86 if (dribble_fd >= 0)
87 close(dribble_fd);
88 dribble_fd = open(dribble_path, O_WRONLY|O_CREAT|O_APPEND,0600);
89 if (dribble_fd < 0)
90 logprintf(MY_NAME,"Cannot open dribble file %s", dribble_path);
91 }
92 }
93
94
95 static void usage(char *name,char *offending_option) {
96 if(offending_option)
97 fprintf(stderr, "%s: unrecognized option `%s'\n",
98 name,offending_option);
99 else
100 fprintf(stderr, "%s: unrecognized arguments\n",
101 name);
102 fprintf(stderr,"usage:\n"
103 " %s [--version] [--no-detach] [--dribble-file name] [--log-file name] \\\n"
104 " [--pid-file name] socket-path /path/to/command [arg] [arg] [arg] ...\n",
105 name);
106 }
107
108 static void version(void) {
109 fprintf(stdout,"detachtty version %s\n%s", DETACHTTY_VERSION_STR,
110 "Copyright (C) 2016-2017 Massimiliano Ghilardi\n"
111 "Copyright (C) 2001-2005 Daniel Barlow\n"
112 "License GPLv2+: GNU GPL version 2 or later <http://www.gnu.org/licenses/>.\n"
113 "\n"
114 "This is free software: you are free to change and redistribute it.\n"
115 "There is NO WARRANTY, to the extent permitted by law.\n");
116 }
117
118
119 #define CLIENT_CONNECTED (sock>=0)
120
121 int main(int argc,char *argv[], char *envp[]) {
122 struct pollfd ufds[3];
123 struct termios my_termios;
124 struct winsize my_winsize;
125 int pty_master = -1, master_socket = -1, sock = -1, send_fd = -1;
126 int next_arg = 0, pid = -1, detach_p = 1;
127 mode_t old_umask;
128
129 log_fp = stderr; /* may be changed by parse_args */
130
131 detach_p = parse_args(argc, argv, &next_arg);
132
133 /* this assumes we're started from a shell. would be smart to
134 default 80x24 or something if we can't do this */
135 tcgetattr(0, &my_termios);
136 ioctl(0, TIOCGWINSZ, &my_winsize);
137
138 old_umask = umask(077);
139 master_socket = bind_socket_or_bail(socket_path);
140 umask(old_umask);
141
142 if (listen(master_socket, 1) != 0)
143 bail(MY_NAME,"listen");
144
145 if (detach_p) {
146 int dev_null;
147 if (daemon(1, 1))
148 bail(MY_NAME, "daemon");
149 /* we leave stderr open - if the user really wanted his tty back,
150 he'd have specified --log-file */
151 close(0);
152 close(1);
153 dev_null = open("/dev/null",O_RDWR);
154 dup2(dev_null, 0);
155 dup2(dev_null, 1);
156 }
157
158 if (pid_file_path) {
159 FILE *fp = fopen(pid_file_path, "w");
160 if (fp != NULL) {
161 fprintf(fp, "%d\n", (int)getpid());
162 fclose(fp);
163 }
164 }
165 reopen_files(0);
166
167 setlinebuf(stdout);
168 setlinebuf(stderr);
169
170 pid = forkpty(&pty_master,NULL,&my_termios,&my_winsize);
171 if (pid < 0) {
172 /* error */
173 perror("detach: Can't fork");
174 exit(1);
175 } else if (pid==0) {
176 /* child */
177 set_noecho(0);
178 execve(argv[next_arg],&argv[next_arg],envp);
179 bail(MY_NAME,"detach: exec failed");
180 } else {
181 /* parent */
182
183 init_signal_handlers();
184
185 logprintf(MY_NAME, "Successfully started");
186 for (;;) {
187 ufds[0].fd=pty_master; ufds[0].events=POLLIN|POLLHUP;
188 ufds[1].fd=master_socket; ufds[1].events=POLLIN;
189 ufds[2].fd=sock; ufds[2].events=POLLIN|POLLHUP;
190
191 process_accumulated_signals();
192
193 if (poll(ufds, CLIENT_CONNECTED ? 3 : 2, -1) == -1) {
194 int err = errno;
195 if (err != EINTR && err != EAGAIN)
196 logprintf(MY_NAME, "poll failed: %s", strerror(errno));
197 continue;
198 }
199 process_accumulated_signals();
200
201 if (ufds[0].revents & POLLIN) {
202 if (copy_a_bit_sendfd(pty_master,sock,dribble_fd,send_fd,"copying from child") > 0)
203 send_fd = -1;
204 }
205 if (ufds[0].revents & POLLHUP) {
206 logprintf(MY_NAME, "child terminated, exiting");
207 if (sock>=0) { close(sock); sock=-1; }
208 tidy_up_nicely(0);
209 }
210
211 if (ufds[1].revents & POLLIN) {
212 struct sockaddr_un their_addr;
213 #ifdef __linux__
214 socklen_t spare_integer = sizeof(their_addr);
215 #else
216 int spare_integer = sizeof(their_addr);
217 #endif
218 int new_sock = accept(master_socket, (struct sockaddr *) &their_addr,
219 &spare_integer);
220 if (new_sock >= 0)
221 {
222 logprintf(MY_NAME,"accepted connection%s",
223 (CLIENT_CONNECTED ? " (and closing previous one)" : ""));
224 if (CLIENT_CONNECTED)
225 close(sock);
226 sock = new_sock;
227 send_fd = pty_master;
228 /* give them a copy of anything we read recently */
229 if (output_buffer_sendfd(sock, send_fd) > 0)
230 send_fd = -1;
231 continue;
232 }
233 }
234 if (CLIENT_CONNECTED && (ufds[2].revents & POLLIN)) {
235 if (copy_a_bit_with_log(sock, pty_master, dribble_fd,
236 MY_NAME, "copying from socket, closing connection") == 0) {
237 /* end-of-file on socket */
238 if (sock >= 0) { close(sock); sock=-1; }
239 }
240 }
241 if (CLIENT_CONNECTED && (ufds[2].revents & POLLHUP)) {
242 logprintf(MY_NAME, "closed connection due to hangup");
243 close(sock); sock=-1;
244 }
245 }
246 }
247 return 0;
248 }
249
250 static int parse_args(int argc, char *argv[], int * next_arg_ptr) {
251 int next_arg, detach_p = 1;
252 for (next_arg = 1; next_arg < argc; next_arg++) {
253 if (!strcmp("--no-detach", argv[next_arg])) {
254 detach_p = 0;
255 }
256 else if (!strcmp("--dribble-file", argv[next_arg])) {
257 dribble_path = argv[++next_arg];
258 }
259 else if (!strcmp("--log-file", argv[next_arg])) {
260 log_file_path = argv[++next_arg];
261 }
262 else if (!strcmp("--pid-file", argv[next_arg])) {
263 pid_file_path = argv[++next_arg];
264 }
265 else if (!strcmp("--version", argv[next_arg])) {
266 version();
267 exit(0);
268 }
269 else if (!strncmp("--", argv[next_arg], 2)) {
270 usage(argv[0], argv[next_arg]);
271 exit(1);
272 }
273 else {
274 break;
275 }
276 }
277 if (next_arg >= argc - 1) {
278 usage(argv[0], NULL);
279 exit(1);
280 }
281 socket_path=argv[next_arg++];
282
283 if (argv[next_arg][0] != '/') {
284 logprintf(MY_NAME,"\"%s\" is not an absolute path", argv[next_arg]);
285 bail(MY_NAME, "argument parsing");
286 }
287 *next_arg_ptr = next_arg;
288 return detach_p;
289 }
290
291 static int bind_socket_or_bail(char * socket_path) {
292 char pidbuf[80];
293 struct sockaddr_un addr;
294 FILE * fp = NULL;
295 int master_socket, oldpid = -1;
296
297 master_socket = socket(PF_UNIX, SOCK_STREAM, 0);
298 if (master_socket < 0) {
299 bail(MY_NAME, "socket");
300 }
301 addr.sun_family=AF_UNIX;
302 strncpy(addr.sun_path, socket_path, UNIX_PATH_MAX);
303 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
304
305 if (bind(master_socket, (const struct sockaddr *) &addr, sizeof(addr)) == 0) {
306 return master_socket;
307 }
308 if (!pid_file_path) {
309 goto no_pid;
310 }
311 fp = fopen(pid_file_path,"r");
312 if (fp) {
313 if (fgets(pidbuf, sizeof(pidbuf), fp)) {
314 oldpid = atoi(pidbuf);
315 }
316 fclose(fp);
317 }
318 if (oldpid <= 0) {
319 goto no_pid;
320 }
321 if (kill(oldpid,0) == 0 || errno != ESRCH) {
322 logprintf(MY_NAME, "process %d for pid file \"%s\" is still running",
323 oldpid, pid_file_path);
324 goto bind_failed;
325 }
326 /* remove socket_path and try again */
327 if (unlink(pid_file_path) != 0) {
328 goto bind_failed;
329 }
330 logprintf(MY_NAME, "found and removed stale socket \"%s\" from a previous run",
331 socket_path);
332
333 if (bind(master_socket, (const struct sockaddr *) &addr, sizeof(addr)) == 0) {
334 return master_socket;
335 } else {
336 goto bind_failed;
337 }
338
339 no_pid:
340 logprintf(MY_NAME, "Cannot create \"%s\": does it already exist from a previous run?",
341 socket_path);
342 bind_failed:
343 if (master_socket >= 0)
344 close(master_socket);
345
346 bail(MY_NAME, "bind");
347 return -1;
348 }
349
350
351 /* borrowed from APUE example code found at
352 http://www.yendor.com/programming/unix/apue/pty/main.c
353 */
354
355 /* turn off echo (for slave pty) */
356 static void set_noecho(int fd) {
357 #ifdef NEED_SET_NOECHO
358 struct termios stermios;
359
360 if (tcgetattr(fd, &stermios) < 0)
361 bail("detach child","tcgetattr error");
362
363 stermios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
364 stermios.c_lflag|=ICANON;
365 /* stermios.c_oflag &= ~(ONLCR); */
366 /* would also turn off NL to CR/NL mapping on output */
367 stermios.c_cc[VERASE]=0177;
368 #ifdef VERASE2
369 stermios.c_cc[VERASE2]=0177;
370 #endif
371 if (tcsetattr(fd, TCSANOW, &stermios) < 0)
372 bail("detach child","tcsetattr error");
373 #endif /* NEED_SET_NOECHO */
374 }
375
376 static void cleanup_signal_handler(int sig) {
377 struct sigaction act;
378 act.sa_handler = SIG_DFL;
379 sigemptyset(&(act.sa_mask));
380 act.sa_flags = 0;
381 sigaction(sig, &act, 0);
382 }
383
384 static void fatal_signal_handler(int sig) {
385 was_signaled = sig;
386 cleanup_signal_handler(sig);
387 }
388
389 static void sighup_signal_handler(int sig) {
390 was_sighupped = sig;
391 }
392
393 static void init_signal_handlers(void) {
394 struct sigaction act;
395 int i, fatal_sig[] = { SIGHUP, SIGQUIT, SIGILL, SIGABRT, SIGBUS, SIGFPE,
396 SIGSEGV, /*SIGPIPE,*/ SIGTERM, SIGSTKFLT, SIGCHLD,
397 SIGXCPU, SIGXFSZ, };
398
399 /* catch SIGCHLD, SIGQUIT, SIGTERM, SIGILL, SIGFPE... and exit */
400 act.sa_handler = fatal_signal_handler;
401 sigemptyset(&(act.sa_mask));
402 act.sa_flags = SA_RESETHAND;
403 for (i = 0; i < sizeof(fatal_sig)/sizeof(fatal_sig[0]); i++) {
404 sigaction(fatal_sig[i],&act,0);
405 }
406
407 /* we can be HUPped */
408 act.sa_handler = sighup_signal_handler;
409 sigemptyset(&(act.sa_mask));
410 act.sa_flags = 0;
411 sigaction(SIGHUP, &act,0);
412
413 /* ignore SIGPIPE */
414 act.sa_handler = SIG_IGN;
415 sigemptyset(&(act.sa_mask));
416 act.sa_flags = 0;
417 sigaction(SIGPIPE, &act,0);
418 }
419
420 static void process_accumulated_signals(void) {
421 if (was_signaled) {
422 tidy_up_nicely(was_signaled);
423 was_signaled = 0;
424 }
425 if (was_sighupped) {
426 reopen_files(was_sighupped);
427 was_sighupped = 0;
428 }
429 }
430
431 static void tidy_up_nicely(int signal) {
432 if (signal)
433 logprintf(MY_NAME, "got unexpected signal %d, exiting", signal);
434 else
435 logprintf(MY_NAME, "exiting", signal);
436 if (unlink(socket_path))
437 logprintf(MY_NAME, "error unlinking \"%s\": %s", socket_path, strerror(errno));
438 if (pid_file_path && unlink(pid_file_path) != 0)
439 logprintf(MY_NAME, "error unlinking \"%s\": %s", pid_file_path, strerror(errno));
440 exit(signal);
441 }
442
443
444 /*
445 * Local Variables:
446 * c-basic-offset: 4
447 * End:
448 */