Improve handling of verbosity in bindings
[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
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdint.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30
31 #if !defined(NO_CALL_PERSONALITY)
32 #include <sys/personality.h>
33 #endif
34
35 #include <json-c/json.h>
36
37 #include <systemd/sd-daemon.h>
38
39 #include "afb-config.h"
40 #include "afb-hswitch.h"
41 #include "afb-apiset.h"
42 #include "afb-api-so.h"
43 #include "afb-api-dbus.h"
44 #include "afb-api-ws.h"
45 #include "afb-hsrv.h"
46 #include "afb-hreq.h"
47 #include "afb-xreq.h"
48 #include "jobs.h"
49 #include "afb-session.h"
50 #include "verbose.h"
51 #include "afb-common.h"
52 #include "afb-monitor.h"
53 #include "afb-hook.h"
54 #include "sd-fds.h"
55 #include "afb-debug.h"
56 #include "process-name.h"
57
58 /*
59    if SELF_PGROUP == 0 the launched command is the group leader
60    if SELF_PGROUP != 0 afb-daemon is the group leader
61 */
62 #define SELF_PGROUP 1
63
64 struct afb_apiset *main_apiset;
65
66 static struct afb_config *config;
67 static pid_t childpid;
68
69 /*----------------------------------------------------------
70  |   helpers for handling list of arguments
71  +--------------------------------------------------------- */
72
73 /*
74  * Calls the callback 'run' for each value of the 'list'
75  * until the callback returns 0 or the end of the list is reached.
76  * Returns either NULL if the end of the list is reached or a pointer
77  * to the item whose value made 'run' return 0.
78  * 'closure' is used for passing user data.
79  */
80 static struct afb_config_list *run_for_list(struct afb_config_list *list,
81                                             int (*run) (void *closure, char *value),
82                                             void *closure)
83 {
84         while (list && run(closure, list->value))
85                 list = list->next;
86         return list;
87 }
88
89 static int run_start(void *closure, char *value)
90 {
91         int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
92         return starter(value, main_apiset) >= 0;
93 }
94
95 static void apiset_start_list(struct afb_config_list *list,
96                        int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
97 {
98         list = run_for_list(list, run_start, starter);
99         if (list) {
100                 ERROR("can't start %s %s", message, list->value);
101                 exit(1);
102         }
103 }
104
105 /*----------------------------------------------------------
106  | exit_handler
107  |   Handles on exit specific actions
108  +--------------------------------------------------------- */
109 static void exit_handler()
110 {
111         struct sigaction siga;
112
113         memset(&siga, 0, sizeof siga);
114         siga.sa_handler = SIG_IGN;
115         sigaction(SIGTERM, &siga, NULL);
116
117         if (SELF_PGROUP)
118                 killpg(0, SIGTERM);
119         else if (childpid > 0)
120                 killpg(childpid, SIGTERM);
121 }
122
123 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
124 {
125         NOTICE("Received SIGTERM");
126         exit(0);
127 }
128
129 static void on_sighup(int signum, siginfo_t *info, void *uctx)
130 {
131         NOTICE("Received SIGHUP");
132         /* TODO */
133 }
134
135 static void setup_daemon()
136 {
137         struct sigaction siga;
138
139         /* install signal handlers */
140         memset(&siga, 0, sizeof siga);
141         siga.sa_flags = SA_SIGINFO;
142
143         siga.sa_sigaction = on_sigterm;
144         sigaction(SIGTERM, &siga, NULL);
145
146         siga.sa_sigaction = on_sighup;
147         sigaction(SIGHUP, &siga, NULL);
148
149         /* handle groups */
150         atexit(exit_handler);
151
152         /* ignore any SIGPIPE */
153         signal(SIGPIPE, SIG_IGN);
154 }
155
156 /*----------------------------------------------------------
157  | daemonize
158  |   set the process in background
159  +--------------------------------------------------------- */
160 static void daemonize()
161 {
162         int consoleFD;
163         int pid;
164
165         // open /dev/console to redirect output messAFBes
166         consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
167         if (consoleFD < 0) {
168                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
169                 exit(1);
170         }
171         // fork process when running background mode
172         pid = fork();
173
174         // if fail nothing much to do
175         if (pid == -1) {
176                 ERROR("AFB-daemon Failed to fork son process");
177                 exit(1);
178         }
179         // if in father process, just leave
180         if (pid != 0)
181                 _exit(0);
182
183         // son process get all data in standalone mode
184         NOTICE("background mode [pid:%d console:%s]", getpid(),
185                config->console);
186
187         // redirect default I/O on console
188         close(2);
189         dup(consoleFD);         // redirect stderr
190         close(1);
191         dup(consoleFD);         // redirect stdout
192         close(0);               // no need for stdin
193         close(consoleFD);
194
195 #if 0
196         setsid();               // allow father process to fully exit
197         sleep(2);               // allow main to leave and release port
198 #endif
199 }
200
201 /*---------------------------------------------------------
202  | http server
203  |   Handles the HTTP server
204  +--------------------------------------------------------- */
205 static int init_alias(void *closure, char *spec)
206 {
207         struct afb_hsrv *hsrv = closure;
208         char *path = strchr(spec, ':');
209
210         if (path == NULL) {
211                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
212                 return 1;
213         }
214         *path++ = 0;
215         INFO("Alias for url=%s to path=%s", spec, path);
216         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
217                                   0, 0);
218 }
219
220 static int init_http_server(struct afb_hsrv *hsrv)
221 {
222         if (!afb_hsrv_add_handler
223             (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
224                 return 0;
225
226         if (!afb_hsrv_add_handler
227             (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
228                 return 0;
229
230         if (run_for_list(config->aliases, init_alias, hsrv))
231                 return 0;
232
233         if (config->roothttp != NULL) {
234                 if (!afb_hsrv_add_alias
235                     (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
236                      -10, 1))
237                         return 0;
238         }
239
240         if (!afb_hsrv_add_handler
241             (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
242              -20))
243                 return 0;
244
245         return 1;
246 }
247
248 static struct afb_hsrv *start_http_server()
249 {
250         int rc;
251         struct afb_hsrv *hsrv;
252
253         if (afb_hreq_init_download_path(config->uploaddir)) {
254                 ERROR("unable to set the upload directory %s", config->uploaddir);
255                 return NULL;
256         }
257
258         hsrv = afb_hsrv_create();
259         if (hsrv == NULL) {
260                 ERROR("memory allocation failure");
261                 return NULL;
262         }
263
264         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
265             || !init_http_server(hsrv)) {
266                 ERROR("initialisation of httpd failed");
267                 afb_hsrv_put(hsrv);
268                 return NULL;
269         }
270
271         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
272         NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
273
274         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
275         if (!rc) {
276                 ERROR("starting of httpd failed");
277                 afb_hsrv_put(hsrv);
278                 return NULL;
279         }
280
281         return hsrv;
282 }
283
284 /*---------------------------------------------------------
285  | execute_command
286  |   
287  +--------------------------------------------------------- */
288
289 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
290 {
291         if (info->si_pid == childpid) {
292                 switch (info->si_code) {
293                 case CLD_EXITED:
294                 case CLD_KILLED:
295                 case CLD_DUMPED:
296                         childpid = 0;
297                         if (!SELF_PGROUP)
298                                 killpg(info->si_pid, SIGKILL);
299                         waitpid(info->si_pid, NULL, 0);
300                         exit(0);
301                 }
302         }
303 }
304
305 /*
306 # @@ @
307 # @p port
308 # @t token
309 */
310
311 #define SUBST_CHAR  '@'
312 #define SUBST_STR   "@"
313
314 static char *instanciate_string(char *arg, const char *port, const char *token)
315 {
316         char *resu, *it, *wr;
317         int chg, dif;
318
319         /* get the changes */
320         chg = 0;
321         dif = 0;
322         it = strchrnul(arg, SUBST_CHAR);
323         while (*it) {
324                 switch(*++it) {
325                 case 'p': chg++; dif += (int)strlen(port) - 2; break;
326                 case 't': chg++; dif += (int)strlen(token) - 2; break;
327                 case SUBST_CHAR: it++; chg++; dif--; break;
328                 default: break;
329                 }
330                 it = strchrnul(it, SUBST_CHAR);
331         }
332
333         /* return arg when no change */
334         if (!chg)
335                 return arg;
336
337         /* allocates the result */
338         resu = malloc((it - arg) + dif + 1);
339         if (!resu) {
340                 ERROR("out of memory");
341                 return NULL;
342         }
343
344         /* instanciate the arguments */
345         wr = resu;
346         for (;;) {
347                 it = strchrnul(arg, SUBST_CHAR);
348                 wr = mempcpy(wr, arg, it - arg);
349                 if (!*it)
350                         break;
351                 switch(*++it) {
352                 case 'p': wr = stpcpy(wr, port); break;
353                 case 't': wr = stpcpy(wr, token); break;
354                 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
355                 case SUBST_CHAR: *wr++ = *it;
356                 }
357                 arg = ++it;
358         }
359
360         *wr = 0;
361         return resu;
362 }
363
364 static int instanciate_environ(const char *port, const char *token)
365 {
366         extern char **environ;
367         char *repl;
368         int i;
369
370         /* instanciate the environment */
371         for (i = 0 ; environ[i] ; i++) {
372                 repl = instanciate_string(environ[i], port, token);
373                 if (!repl)
374                         return -1;
375                 environ[i] = repl;
376         }
377         return 0;
378 }
379
380 static int instanciate_command_args(const char *port, const char *token)
381 {
382         char *repl;
383         int i;
384
385         /* instanciate the arguments */
386         for (i = 0 ; config->exec[i] ; i++) {
387                 repl = instanciate_string(config->exec[i], port, token);
388                 if (!repl)
389                         return -1;
390                 config->exec[i] = repl;
391         }
392         return 0;
393 }
394
395 static int execute_command()
396 {
397         struct sigaction siga;
398         char port[20];
399         const char *token;
400         int rc;
401
402         /* check whether a command is to execute or not */
403         if (!config->exec || !config->exec[0])
404                 return 0;
405
406         if (SELF_PGROUP)
407                 setpgid(0, 0);
408
409         /* install signal handler */
410         memset(&siga, 0, sizeof siga);
411         siga.sa_sigaction = on_sigchld;
412         siga.sa_flags = SA_SIGINFO;
413         sigaction(SIGCHLD, &siga, NULL);
414
415         /* fork now */
416         childpid = fork();
417         if (childpid)
418                 return 0;
419
420         /* compute the string for port */
421         if (config->httpdPort)
422                 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
423         else
424                 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
425         if (rc < 0 || rc >= (int)(sizeof port)) {
426                 ERROR("port->txt failed");
427         }
428         else {
429                 /* instanciate arguments and environment */
430                 token = afb_session_initial_token();
431                 if (instanciate_command_args(port, token) >= 0
432                  && instanciate_environ(port, token) >= 0) {
433                         /* run */
434                         if (!SELF_PGROUP)
435                                 setpgid(0, 0);
436                         execv(config->exec[0], config->exec);
437                         ERROR("can't launch %s: %m", config->exec[0]);
438                 }
439         }
440         exit(1);
441         return -1;
442 }
443
444 /*---------------------------------------------------------
445  | startup calls
446  +--------------------------------------------------------- */
447
448 struct startup_req
449 {
450         struct afb_xreq xreq;
451         char *api;
452         char *verb;
453         struct afb_config_list *current;
454         struct afb_session *session;
455 };
456
457 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
458 {
459         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
460
461         if (status >= 0)
462                 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
463         else {
464                 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
465                 exit(1);
466         }
467 }
468
469 static void startup_call_current(struct startup_req *sreq);
470
471 static void startup_call_unref(struct afb_xreq *xreq)
472 {
473         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
474
475         free(sreq->api);
476         free(sreq->verb);
477         json_object_put(sreq->xreq.json);
478         sreq->current = sreq->current->next;
479         if (sreq->current)
480                 startup_call_current(sreq);
481         else {
482                 afb_session_close(sreq->session);
483                 afb_session_unref(sreq->session);
484                 free(sreq);
485         }
486 }
487
488 static struct afb_xreq_query_itf startup_xreq_itf =
489 {
490         .reply = startup_call_reply,
491         .unref = startup_call_unref
492 };
493
494 static void startup_call_current(struct startup_req *sreq)
495 {
496         char *api, *verb, *json;
497
498         api = sreq->current->value;
499         verb = strchr(api, '/');
500         if (verb) {
501                 json = strchr(verb, ':');
502                 if (json) {
503                         afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
504                         afb_context_init(&sreq->xreq.context, sreq->session, NULL);
505                         sreq->xreq.context.validated = 1;
506                         sreq->api = strndup(api, verb - api);
507                         sreq->verb = strndup(verb + 1, json - verb - 1);
508                         sreq->xreq.api = sreq->api;
509                         sreq->xreq.verb = sreq->verb;
510                         sreq->xreq.json = json_tokener_parse(json + 1);
511                         if (sreq->api && sreq->verb && sreq->xreq.json) {
512                                 afb_xreq_process(&sreq->xreq, main_apiset);
513                                 return;
514                         }
515                 }
516         }
517         ERROR("Bad call specification %s", sreq->current->value);
518         exit(1);
519 }
520
521 static void run_startup_calls()
522 {
523         struct afb_config_list *list;
524         struct startup_req *sreq;
525
526         list = config->calls;
527         if (list) {
528                 sreq = calloc(1, sizeof *sreq);
529                 sreq->session = afb_session_create("startup", 3600);
530                 sreq->current = list;
531                 startup_call_current(sreq);
532         }
533 }
534
535 /*---------------------------------------------------------
536  | job for starting the daemon
537  +--------------------------------------------------------- */
538
539 static void start(int signum)
540 {
541         struct afb_hsrv *hsrv;
542
543         afb_debug("start-entry");
544
545         if (signum) {
546                 ERROR("start aborted: received signal %s", strsignal(signum));
547                 exit(1);
548         }
549
550         // ------------------ sanity check ----------------------------------------
551         if (config->httpdPort <= 0) {
552                 ERROR("no port is defined");
553                 goto error;
554         }
555
556         /* set the directories */
557         mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
558         if (chdir(config->workdir) < 0) {
559                 ERROR("Can't enter working dir %s", config->workdir);
560                 goto error;
561         }
562         if (afb_common_rootdir_set(config->rootdir) < 0) {
563                 ERROR("failed to set common root directory");
564                 goto error;
565         }
566
567         /* configure the daemon */
568         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
569         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
570                 ERROR("initialisation of cookies failed");
571                 goto error;
572         }
573         main_apiset = afb_apiset_create("main", config->apiTimeout);
574         if (!main_apiset) {
575                 ERROR("can't create main api set");
576                 goto error;
577         }
578         if (afb_monitor_init() < 0) {
579                 ERROR("failed to setup monitor");
580                 goto error;
581         }
582
583         /* install hooks */
584         if (config->tracereq)
585                 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
586         if (config->traceditf)
587                 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
588         if (config->tracesvc)
589                 afb_hook_create_svc(NULL, config->tracesvc, NULL, NULL);
590         if (config->traceevt)
591                 afb_hook_create_evt(NULL, config->traceevt, NULL, NULL);
592
593         /* load bindings */
594         afb_debug("start-load");
595         apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
596         apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
597         apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
598         apiset_start_list(config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
599         apiset_start_list(config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
600
601         apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
602         apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
603
604         DEBUG("Init config done");
605
606         /* start the services */
607         afb_debug("start-start");
608 #if !defined(NO_CALL_PERSONALITY)
609         personality((unsigned long)-1L);
610 #endif
611         if (afb_apiset_start_all_services(main_apiset, 1) < 0)
612                 goto error;
613
614         /* start the HTTP server */
615         afb_debug("start-http");
616         if (!config->noHttpd) {
617                 hsrv = start_http_server();
618                 if (hsrv == NULL)
619                         goto error;
620         }
621
622         /* run the startup calls */
623         afb_debug("start-call");
624         run_startup_calls();
625
626         /* run the command */
627         afb_debug("start-exec");
628         if (execute_command() < 0)
629                 goto error;
630
631         /* ready */
632         sd_notify(1, "READY=1");
633         return;
634 error:
635         exit(1);
636 }
637
638 /*---------------------------------------------------------
639  | main
640  |   Parse option and launch action
641  +--------------------------------------------------------- */
642
643 int main(int argc, char *argv[])
644 {
645         afb_debug("main-entry");
646
647         // let's run this program with a low priority
648         nice(20);
649
650         sd_fds_init();
651
652         // ------------- Build session handler & init config -------
653         config = afb_config_parse_arguments(argc, argv);
654         if (config->name) {
655                 verbose_set_name(config->name, 0);
656                 process_name_set_name(config->name);
657                 process_name_replace_cmdline(argv, config->name);
658         }
659         afb_debug("main-args");
660
661         // --------- run -----------
662         if (config->background) {
663                 // --------- in background mode -----------
664                 INFO("entering background mode");
665                 daemonize();
666         } else {
667                 // ---- in foreground mode --------------------
668                 INFO("entering foreground mode");
669         }
670         INFO("running with pid %d", getpid());
671
672         /* set the daemon environment */
673         setup_daemon();
674
675         afb_debug("main-start");
676
677         /* enter job processing */
678         jobs_start(3, 0, 50, start);
679         WARNING("hoops returned from jobs_enter! [report bug]");
680         return 1;
681 }
682