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