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