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