Quit when requested from the menu
[ladish.git] / daemon / loader.c
blob0eecb70d9ad4adbecb5432831f756fce338d97ea
1 /* -*- Mode: C ; c-basic-offset: 2 -*- */
2 /*
3 * LADI Session Handler (ladish)
5 * Copyright (C) 2008, 2009 Nedko Arnaudov <nedko@arnaudov.name>
6 * Copyright (C) 2008 Juuso Alasuutari <juuso.alasuutari@gmail.com>
7 * Copyright (C) 2002 Robert Ham <rah@bash.sh>
9 **************************************************************************
10 * This file contains code that starts programs
11 **************************************************************************
13 * LADI Session Handler is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * LADI Session Handler is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with LADI Session Handler. If not, see <http://www.gnu.org/licenses/>
25 * or write to the Free Software Foundation, Inc.,
26 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
29 #include "common.h"
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <pty.h> /* forkpty() */
34 #include <sys/wait.h>
36 #include "loader.h"
38 #define XTERM_COMMAND_EXTENSION "&& sh || sh"
40 #define CLIENT_OUTPUT_BUFFER_SIZE 2048
42 struct loader_child
44 struct list_head siblings;
46 char * project_name;
47 char * argv0;
49 bool dead;
50 pid_t pid;
52 bool terminal;
54 int stdout;
55 char stdout_buffer[CLIENT_OUTPUT_BUFFER_SIZE];
56 char stdout_last_line[CLIENT_OUTPUT_BUFFER_SIZE];
57 unsigned int stdout_last_line_repeat_count;
58 char * stdout_buffer_ptr;
60 int stderr;
61 char stderr_buffer[CLIENT_OUTPUT_BUFFER_SIZE];
62 char stderr_last_line[CLIENT_OUTPUT_BUFFER_SIZE];
63 unsigned int stderr_last_line_repeat_count;
64 char * stderr_buffer_ptr;
67 static void (* g_on_child_exit)(pid_t pid);
68 static struct list_head g_childs_list;
70 static struct loader_child *
71 loader_child_find_and_mark_dead(pid_t pid)
73 struct list_head *node_ptr;
74 struct loader_child *child_ptr;
76 list_for_each (node_ptr, &g_childs_list)
78 child_ptr = list_entry(node_ptr, struct loader_child, siblings);
79 if (child_ptr->pid == pid)
81 child_ptr->dead = true;
82 return child_ptr;
86 return NULL;
89 static
90 void
91 loader_check_line_repeat_end(
92 char * project,
93 char * argv0,
94 bool error,
95 unsigned int last_line_repeat_count)
97 if (last_line_repeat_count >= 2)
99 if (error)
101 lash_error_plain("%s:%s: stderr line repeated %u times", project, argv0, last_line_repeat_count);
103 else
105 lash_info("%s:%s: stdout line repeated %u times", project, argv0, last_line_repeat_count);
110 static void
111 loader_childs_bury(void)
113 struct list_head *node_ptr;
114 struct list_head *next_ptr;
115 struct loader_child *child_ptr;
117 list_for_each_safe (node_ptr, next_ptr, &g_childs_list)
119 child_ptr = list_entry(node_ptr, struct loader_child, siblings);
120 if (child_ptr->dead)
122 loader_check_line_repeat_end(
123 child_ptr->project_name,
124 child_ptr->argv0,
125 false,
126 child_ptr->stdout_last_line_repeat_count);
128 loader_check_line_repeat_end(
129 child_ptr->project_name,
130 child_ptr->argv0,
131 true,
132 child_ptr->stderr_last_line_repeat_count);
134 lash_debug("Bury child '%s' with PID %llu", child_ptr->argv0, (unsigned long long)child_ptr->pid);
136 list_del(&child_ptr->siblings);
138 free(&child_ptr->project_name);
139 free(&child_ptr->argv0);
141 if (!child_ptr->terminal)
143 close(child_ptr->stdout);
144 close(child_ptr->stderr);
147 g_on_child_exit(child_ptr->pid);
148 free(child_ptr);
153 static void loader_sigchld_handler(int signum)
155 int status;
156 pid_t pid;
157 struct loader_child *child_ptr;
159 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
161 child_ptr = loader_child_find_and_mark_dead(pid);
163 if (!child_ptr)
165 lash_error("LASH loader detected termination of unknown child process with PID %llu", (unsigned long long)pid);
167 else
169 lash_info("LASH loader detected termination of child process '%s' with PID %llu", child_ptr->argv0, (unsigned long long)pid);
172 if (WIFEXITED(status))
174 lash_info("Child exited, status=%d", WEXITSTATUS(status));
176 else if (WIFSIGNALED(status))
178 lash_info("Child was killed by signal %d", WTERMSIG(status));
180 else if (WIFSTOPPED(status))
182 lash_info("Child was stopped by signal %d", WSTOPSIG(status));
187 void loader_init(void (* on_child_exit)(pid_t pid))
189 signal(SIGCHLD, loader_sigchld_handler);
190 INIT_LIST_HEAD(&g_childs_list);
193 void loader_uninit(void)
195 loader_childs_bury();
198 static void loader_exec_program_in_xterm(const char * const * argv)
200 char * dst_ptr;
201 const char * const * src_ptr_ptr;
202 size_t len;
204 lash_debug("Executing program '%s' with PID %llu in terminal", argv[0], (unsigned long long)getpid());
206 /* Calculate the command string length */
207 len = strlen(XTERM_COMMAND_EXTENSION) + 1;
208 for (src_ptr_ptr = argv; *src_ptr_ptr != NULL; src_ptr_ptr++)
210 len += strlen(*src_ptr_ptr) + 3; /* three additional chars per argument: two double quotes and a space */
213 char buf[len]; /* dynamically allocate in stack */
215 /* Create the command string */
216 src_ptr_ptr = argv;
217 dst_ptr = buf;
218 while (*src_ptr_ptr != NULL)
220 len = strlen(*src_ptr_ptr);
221 dst_ptr[0] = '"';
222 memcpy(dst_ptr + 1, src_ptr_ptr, len);
223 dst_ptr[1 + len] = '"';
224 dst_ptr[1 + len + 1] = ' ';
225 dst_ptr += len + 3;
226 src_ptr_ptr++;
229 strcat(dst_ptr, XTERM_COMMAND_EXTENSION);
231 /* Execute the command */
232 execlp("xterm", "xterm", "-e", "/bin/sh", "-c", buf, NULL);
234 lash_error("Failed to execute command '%s' in terminal: %s", buf, strerror(errno));
236 exit(1);
239 static void loader_exec_program(const char * const * argv, const char * working_dir, bool run_in_terminal)
241 /* for non terminal processes we use forkpty() that calls login_tty() that calls setsid() */
242 /* we can successful call setsid() only once */
243 if (run_in_terminal)
245 /* no longer anything to do with lashd */
246 if (setsid() == -1)
248 lash_error("Could not create new process group: %s", strerror(errno));
252 /* change the working dir */
253 if (chdir(working_dir) == -1)
255 lash_error("Could not change directory to working dir '%s' for program '%s': %s", working_dir, argv[0], strerror(errno));
258 #ifdef LASH_DEBUG
259 char *ptr;
260 const char * const * aptr;
261 size_t len = 0;
263 for (aptr = argv; *aptr; ++aptr)
265 len += strlen(*aptr) + 1;
268 char buf[len];
269 ptr = (char *) buf;
271 for (aptr = argv; *aptr; ++aptr)
273 strcpy(ptr, *aptr);
274 ptr += strlen(*aptr);
275 *ptr = ' ';
276 ++ptr;
278 *ptr = '\0';
280 lash_debug("Running command: %s", buf);
281 #endif
283 lash_info("Executing program '%s' with PID %llu", argv[0], (unsigned long long)getpid());
285 if (run_in_terminal)
287 loader_exec_program_in_xterm(argv);
289 else
291 /* Execute it */
292 execvp(argv[0], (char **)argv);
294 lash_error("Executing program '%s' failed: %s", argv[0], strerror(errno));
297 exit(1);
300 static
301 void
302 loader_read_child_output(
303 char * project,
304 char * argv0,
305 int fd,
306 bool error,
307 char * buffer_ptr,
308 char ** buffer_ptr_ptr,
309 char * last_line,
310 unsigned int * last_line_repeat_count)
312 ssize_t ret;
313 char *char_ptr;
314 char *eol_ptr;
315 size_t left;
316 size_t max_read;
320 max_read = CLIENT_OUTPUT_BUFFER_SIZE - 1 - (*buffer_ptr_ptr - buffer_ptr);
321 ret = read(fd, *buffer_ptr_ptr, max_read);
322 if (ret > 0)
324 (*buffer_ptr_ptr)[ret] = 0;
325 char_ptr = buffer_ptr;
327 while ((eol_ptr = strchr(char_ptr, '\n')) != NULL)
329 *eol_ptr = 0;
331 if (*last_line_repeat_count > 0 && strcmp(last_line, char_ptr) == 0)
333 if (*last_line_repeat_count == 1)
335 if (error)
337 lash_error_plain("%s:%s: last stderr line repeating..", project, argv0);
339 else
341 lash_info("%s:%s: last stdout line repeating...", project, argv0);
345 (*last_line_repeat_count)++;
347 else
349 loader_check_line_repeat_end(project, argv0, error, *last_line_repeat_count);
351 strcpy(last_line, char_ptr);
352 *last_line_repeat_count = 1;
354 if (error)
356 lash_error_plain("%s:%s: %s", project, argv0, char_ptr);
358 else
360 lash_info("%s:%s: %s", project, argv0, char_ptr);
364 char_ptr = eol_ptr + 1;
367 left = ret - (char_ptr - *buffer_ptr_ptr);
368 if (left != 0)
370 /* last line does not end with newline */
372 if (left == CLIENT_OUTPUT_BUFFER_SIZE - 1)
374 /* line is too long to fit in buffer */
375 /* print it like it is, rest (or more) of it will be logged on next interation */
377 if (error)
379 lash_error_plain("%s:%s: %s " ANSI_RESET ANSI_COLOR_RED "(truncated) " ANSI_RESET, project, argv0, char_ptr);
381 else
383 lash_info("%s:%s: %s " ANSI_RESET ANSI_COLOR_RED "(truncated) " ANSI_RESET, project, argv0, char_ptr);
386 left = 0;
388 else
390 memmove(buffer_ptr, char_ptr, left);
394 *buffer_ptr_ptr = buffer_ptr + left;
397 while (ret == max_read); /* if we have read everything as much as we can, then maybe there is more to read */
400 static void
401 loader_read_childs_output(void)
403 struct list_head * node_ptr;
404 struct loader_child * child_ptr;
406 list_for_each (node_ptr, &g_childs_list)
408 child_ptr = list_entry(node_ptr, struct loader_child, siblings);
410 if (!child_ptr->dead && !child_ptr->terminal)
412 loader_read_child_output(
413 child_ptr->project_name,
414 child_ptr->argv0,
415 child_ptr->stdout,
416 false,
417 child_ptr->stdout_buffer,
418 &child_ptr->stdout_buffer_ptr,
419 child_ptr->stdout_last_line,
420 &child_ptr->stdout_last_line_repeat_count);
422 loader_read_child_output(
423 child_ptr->project_name,
424 child_ptr->argv0,
425 child_ptr->stderr,
426 true,
427 child_ptr->stderr_buffer,
428 &child_ptr->stderr_buffer_ptr,
429 child_ptr->stderr_last_line,
430 &child_ptr->stderr_last_line_repeat_count);
435 void
436 loader_run(void)
438 loader_read_childs_output();
439 loader_childs_bury();
442 bool
443 loader_execute(
444 const char * const * argv,
445 const char * working_dir,
446 const char * project_name,
447 bool run_in_terminal,
448 pid_t * pid_ptr)
450 pid_t pid;
451 struct loader_child * child_ptr;
452 int stderr_pipe[2];
454 child_ptr = malloc(sizeof(struct loader_child));
455 if (child_ptr == NULL)
457 lash_error("malloc() failed to allocate struct loader_child");
458 goto fail;
461 child_ptr->project_name = strdup(project_name);
462 if (child_ptr->project_name == NULL)
464 lash_error("strdup() failed to duplicate project name '%s'", project_name);
465 goto free_struct;
468 child_ptr->argv0 = strdup(argv[0]);
469 if (child_ptr->project_name == NULL)
471 lash_error("strdup() failed to duplicate argv[0] '%s'", argv[0]);
472 goto free_project_name;
475 child_ptr->terminal = run_in_terminal;
476 child_ptr->stdout_buffer_ptr = child_ptr->stdout_buffer;
477 child_ptr->stderr_buffer_ptr = child_ptr->stderr_buffer;
478 child_ptr->stdout_last_line_repeat_count = 0;
479 child_ptr->stderr_last_line_repeat_count = 0;
481 if (!run_in_terminal)
483 if (pipe(stderr_pipe) == -1)
485 lash_error("Failed to create stderr pipe");
487 else
489 child_ptr->stderr = stderr_pipe[0];
491 if (fcntl(child_ptr->stderr, F_SETFL, O_NONBLOCK) == -1)
493 lash_error("Failed to set nonblocking mode on "
494 "stderr reading end: %s",
495 strerror(errno));
496 close(stderr_pipe[0]);
497 close(stderr_pipe[1]);
502 list_add_tail(&child_ptr->siblings, &g_childs_list);
504 if (!run_in_terminal)
506 /* We need pty to disable libc buffering of stdout */
507 pid = forkpty(&child_ptr->stdout, NULL, NULL, NULL);
509 else
511 pid = fork();
514 if (pid == -1)
516 lash_error("Could not fork to exec program '%s': %s", argv[0], strerror(errno));
517 list_del(&child_ptr->siblings); /* fork failed so it is not really a child process to watch for. */
518 return false;
521 if (pid == 0)
523 /* Need to close all open file descriptors except the std ones */
524 struct rlimit max_fds;
525 rlim_t fd;
527 getrlimit(RLIMIT_NOFILE, &max_fds);
529 for (fd = 3; fd < max_fds.rlim_cur; ++fd)
531 close(fd);
534 if (!run_in_terminal)
536 /* In child, close unused reading end of pipe */
537 close(stderr_pipe[0]);
539 dup2(stderr_pipe[1], fileno(stderr));
542 loader_exec_program(argv, working_dir, run_in_terminal);
544 return false; /* We should never get here */
547 if (!run_in_terminal)
549 /* In parent, close unused writing ends of pipe */
550 close(stderr_pipe[1]);
552 if (fcntl(child_ptr->stdout, F_SETFL, O_NONBLOCK) == -1)
554 lash_error("Could not set noblocking mode on stdout "
555 "- pty: %s", strerror(errno));
556 close(stderr_pipe[0]);
557 close(child_ptr->stdout);
561 lash_info("Forked to run program '%s' pid = %llu", argv[0], (unsigned long long)pid);
563 *pid_ptr = child_ptr->pid = pid;
565 return true;
567 free_project_name:
568 free(child_ptr->project_name);
570 free_struct:
571 free(child_ptr);
573 fail:
574 return false;