First step for grouping processes
[src/app-framework-binder.git] / src / main.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author José Bollo <jose.bollo@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #define _GNU_SOURCE
20 #define NO_BINDING_VERBOSE_MACRO
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29
30 #include <systemd/sd-event.h>
31
32 #include "afb-config.h"
33 #include "afb-hswitch.h"
34 #include "afb-apis.h"
35 #include "afb-api-so.h"
36 #include "afb-api-dbus.h"
37 #include "afb-api-ws.h"
38 #include "afb-hsrv.h"
39 #include "afb-context.h"
40 #include "afb-hreq.h"
41 #include "afb-sig-handler.h"
42 #include "afb-thread.h"
43 #include "afb-session.h"
44 #include "verbose.h"
45 #include "afb-common.h"
46 #include "afb-hook.h"
47
48 #include <afb/afb-binding.h>
49
50 /*
51    if SELF_PGROUP == 0 the launched command is the group leader
52    if SELF_PGROUP != 0 afb-daemon is the group leader
53 */
54 #define SELF_PGROUP 1
55
56 static struct afb_config *config;
57 static pid_t childpid;
58
59 /*----------------------------------------------------------
60  |   helpers for handling list of arguments
61  +--------------------------------------------------------- */
62
63 /*
64  * Calls the callback 'run' for each value of the 'list'
65  * until the callback returns 0 or the end of the list is reached.
66  * Returns either NULL if the end of the list is reached or a pointer
67  * to the item whose value made 'run' return 0.
68  * 'closure' is used for passing user data.
69  */
70 static struct afb_config_list *run_for_list(struct afb_config_list *list,
71                                             int (*run) (void *closure, char *value),
72                                             void *closure)
73 {
74         while (list && run(closure, list->value))
75                 list = list->next;
76         return list;
77 }
78
79 static int run_start(void *closure, char *value)
80 {
81         int (*starter) (const char *value) = closure;
82         return starter(value) >= 0;
83 }
84
85 static void start_list(struct afb_config_list *list,
86                        int (*starter) (const char *value), const char *message)
87 {
88         list = run_for_list(list, run_start, starter);
89         if (list) {
90                 ERROR("can't start %s %s", message, list->value);
91                 exit(1);
92         }
93 }
94
95 /*----------------------------------------------------------
96  | exit_handler
97  |   Handles on exit specific actions
98  +--------------------------------------------------------- */
99 static void exit_handler()
100 {
101         /* TODO: check whether using SIGHUP isn't better */
102         if (SELF_PGROUP)
103                 killpg(0, SIGKILL);
104         else if (childpid > 0)
105                 killpg(childpid, SIGKILL);
106 }
107
108 /*----------------------------------------------------------
109  | daemonize
110  |   set the process in background
111  +--------------------------------------------------------- */
112 static void daemonize()
113 {
114         int consoleFD;
115         int pid;
116
117         // open /dev/console to redirect output messAFBes
118         consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
119         if (consoleFD < 0) {
120                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
121                 exit(1);
122         }
123         // fork process when running background mode
124         pid = fork();
125
126         // if fail nothing much to do
127         if (pid == -1) {
128                 ERROR("AFB-daemon Failed to fork son process");
129                 exit(1);
130         }
131         // if in father process, just leave
132         if (pid != 0)
133                 _exit(0);
134
135         // son process get all data in standalone mode
136         NOTICE("background mode [pid:%d console:%s]", getpid(),
137                config->console);
138
139         // redirect default I/O on console
140         close(2);
141         dup(consoleFD);         // redirect stderr
142         close(1);
143         dup(consoleFD);         // redirect stdout
144         close(0);               // no need for stdin
145         close(consoleFD);
146
147 #if 0
148         setsid();               // allow father process to fully exit
149         sleep(2);               // allow main to leave and release port
150 #endif
151 }
152
153 /*---------------------------------------------------------
154  | http server
155  |   Handles the HTTP server
156  +--------------------------------------------------------- */
157 static int init_alias(void *closure, char *spec)
158 {
159         struct afb_hsrv *hsrv = closure;
160         char *path = strchr(spec, ':');
161
162         if (path == NULL) {
163                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
164                 return 1;
165         }
166         *path++ = 0;
167         INFO("Alias for url=%s to path=%s", spec, path);
168         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
169                                   0, 0);
170 }
171
172 static int init_http_server(struct afb_hsrv *hsrv)
173 {
174         if (!afb_hsrv_add_handler
175             (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
176                 return 0;
177
178         if (!afb_hsrv_add_handler
179             (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
180                 return 0;
181
182         if (run_for_list(config->aliases, init_alias, hsrv))
183                 return 0;
184
185         if (config->roothttp != NULL) {
186                 if (!afb_hsrv_add_alias
187                     (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
188                      -10, 1))
189                         return 0;
190         }
191
192         if (!afb_hsrv_add_handler
193             (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
194              -20))
195                 return 0;
196
197         return 1;
198 }
199
200 static struct afb_hsrv *start_http_server()
201 {
202         int rc;
203         struct afb_hsrv *hsrv;
204
205         if (afb_hreq_init_download_path("/tmp")) {      /* TODO: sessiondir? */
206                 ERROR("unable to set the tmp directory");
207                 return NULL;
208         }
209
210         hsrv = afb_hsrv_create();
211         if (hsrv == NULL) {
212                 ERROR("memory allocation failure");
213                 return NULL;
214         }
215
216         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
217             || !init_http_server(hsrv)) {
218                 ERROR("initialisation of httpd failed");
219                 afb_hsrv_put(hsrv);
220                 return NULL;
221         }
222
223         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort,
224                config->rootdir);
225         NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
226
227         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
228         if (!rc) {
229                 ERROR("starting of httpd failed");
230                 afb_hsrv_put(hsrv);
231                 return NULL;
232         }
233
234         return hsrv;
235 }
236
237 /*---------------------------------------------------------
238  | execute_command
239  |   
240  +--------------------------------------------------------- */
241
242 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
243 {
244         if (info->si_pid == childpid) {
245                 switch (info->si_code) {
246                 case CLD_EXITED:
247                 case CLD_KILLED:
248                 case CLD_DUMPED:
249                         childpid = 0;
250                         if (!SELF_PGROUP)
251                                 killpg(info->si_pid, SIGKILL);
252                         waitpid(info->si_pid, NULL, 0);
253                         exit(0);
254                 }
255         }
256 }
257
258 /*
259 # @@ @
260 # @p port
261 # @t token
262 */
263
264 #define SUBST_CHAR  '@'
265 #define SUBST_STR   "@"
266
267 static int instanciate_command_args()
268 {
269         char *orig, *repl, *sub, *val, port[20];
270         int i, rc, r;
271         size_t s, l;
272
273         rc = snprintf(port, sizeof port, "%d", config->httpdPort);
274         if (rc < 0 || rc >= (int)(sizeof port))
275                 return -1;
276
277         for (i = 0 ; (orig = config->exec[i]) ; i++) {
278                 repl = 0;
279                 s = 0;
280                 for(;;) {
281                         sub = strchrnul(orig, SUBST_CHAR);
282                         l = sub - orig;
283                         if (repl)
284                                 repl = mempcpy(repl, orig, l);
285                         else
286                                 s += l;
287                         if (!*sub) {
288                                 /* at end */
289                                 if (repl || orig == config->exec[i])
290                                         break;
291                                 repl = malloc(1 + s);
292                                 if (!repl)
293                                         return -1;
294                                 orig = config->exec[i];
295                                 config->exec[i] = repl;
296                                 repl[s] = 0;
297                         } else {
298                                 r = 2;
299                                 switch(sub[1]) {
300                                 case 'p': val = port;  break;
301                                 case 't': val = config->token ? : ""; break;
302                                 default: r = 1;
303                                 case SUBST_CHAR: val = SUBST_STR; break;
304                                 }
305                                 orig = &sub[r];
306                                 l = strlen(val);
307                                 if (repl)
308                                         repl = mempcpy(repl, val, l);
309                                 else
310                                         s += l;
311                         }
312                 }
313         }
314         return 0;
315 }
316
317 static int execute_command()
318 {
319         struct sigaction siga;
320
321         /* check whether a command is to execute or not */
322         if (!config->exec || !config->exec[0])
323                 return 0;
324
325         if (SELF_PGROUP)
326                 setpgid(0, 0);
327
328         /* install signal handler */
329         memset(&siga, 0, sizeof siga);
330         siga.sa_sigaction = on_sigchld;
331         siga.sa_flags = SA_SIGINFO;
332         sigaction(SIGCHLD, &siga, NULL);
333
334         /* fork now */
335         childpid = fork();
336         if (childpid)
337                 return 0;
338
339         /* makes arguments */
340         if (instanciate_command_args() >= 0) {
341                 if (!SELF_PGROUP)
342                         setpgid(0, 0);
343                 execv(config->exec[0], config->exec);
344                 ERROR("can't launch %s: %m", config->exec[0]);
345         }
346         exit(1);
347         return -1;
348 }
349
350 /*---------------------------------------------------------
351  | main
352  |   Parse option and launch action
353  +--------------------------------------------------------- */
354
355 int main(int argc, char *argv[])
356 {
357         struct afb_hsrv *hsrv;
358         struct sd_event *eventloop;
359
360         LOGAUTH("afb-daemon");
361
362         // ------------- Build session handler & init config -------
363         config = afb_config_parse_arguments(argc, argv);
364         atexit(exit_handler);
365
366         // ------------------ sanity check ----------------------------------------
367         if (config->httpdPort <= 0) {
368                 ERROR("no port is defined");
369                 exit(1);
370         }
371
372         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
373
374         afb_api_so_set_timeout(config->apiTimeout);
375         start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
376         start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
377         start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
378         start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
379         start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
380         start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
381
382         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
383                 ERROR("initialisation of cookies failed");
384                 exit(1);
385         }
386
387         if (afb_sig_handler_init() < 0) {
388                 ERROR("failed to initialise signal handlers");
389                 return 1;
390         }
391         // if directory does not exist createit
392         mkdir(config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
393         if (afb_common_rootdir_set(config->rootdir) < 0) {
394                 ERROR("failed to set common root directory");
395                 return 1;
396         }
397
398         if (afb_thread_init(3, 1, 20) < 0) {
399                 ERROR("failed to initialise threading");
400                 return 1;
401         }
402         // let's run this program with a low priority
403         nice(20);
404
405         // ------------------ Finaly Process Commands -----------------------------
406         // let's not take the risk to run as ROOT
407         //if (getuid() == 0)  goto errorNoRoot;
408
409         DEBUG("Init config done");
410
411         // --------- run -----------
412         if (config->background) {
413                 // --------- in background mode -----------
414                 INFO("entering background mode");
415                 daemonize();
416         } else {
417                 // ---- in foreground mode --------------------
418                 INFO("entering foreground mode");
419         }
420
421         /* ignore any SIGPIPE */
422         signal(SIGPIPE, SIG_IGN);
423
424         /* install trace of requests */
425         if (config->tracereq)
426                 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
427
428         /* start the services */
429         if (afb_apis_start_all_services(1) < 0)
430                 exit(1);
431
432         /* start the HTTP server */
433         if (!config->noHttpd) {
434                 hsrv = start_http_server();
435                 if (hsrv == NULL)
436                         exit(1);
437         }
438
439         /* run the command */
440         if (execute_command() < 0)
441                 exit(1);
442
443         /* signal that ready */
444         if (config->readyfd != 0) {
445                 static const char readystr[] = "READY=1";
446                 write(config->readyfd, readystr, sizeof(readystr) - 1);
447                 close(config->readyfd);
448         }
449
450         // infinite loop
451         eventloop = afb_common_get_event_loop();
452         for (;;)
453                 sd_event_run(eventloop, 30000000);
454
455         WARNING("hoops returned from infinite loop [report bug]");
456
457         return 0;
458 }