150b78102b9bd1a57d34a9197f613219c7b7bd35
[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 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
289 {
290         if (info->si_pid == childpid) {
291                 switch (info->si_code) {
292                 case CLD_EXITED:
293                 case CLD_KILLED:
294                 case CLD_DUMPED:
295                         childpid = 0;
296                         if (!SELF_PGROUP)
297                                 killpg(info->si_pid, SIGKILL);
298                         waitpid(info->si_pid, NULL, 0);
299                         exit(0);
300                 }
301         }
302 }
303
304 /*
305 # @@ @
306 # @p port
307 # @t token
308 */
309
310 #define SUBST_CHAR  '@'
311 #define SUBST_STR   "@"
312
313 static char *instanciate_string(char *arg, const char *port, const char *token)
314 {
315         char *resu, *it, *wr;
316         int chg, dif;
317
318         /* get the changes */
319         chg = 0;
320         dif = 0;
321         it = strchrnul(arg, SUBST_CHAR);
322         while (*it) {
323                 switch(*++it) {
324                 case 'p': chg++; dif += (int)strlen(port) - 2; break;
325                 case 't': chg++; dif += (int)strlen(token) - 2; break;
326                 case SUBST_CHAR: it++; chg++; dif--; break;
327                 default: break;
328                 }
329                 it = strchrnul(it, SUBST_CHAR);
330         }
331
332         /* return arg when no change */
333         if (!chg)
334                 return arg;
335
336         /* allocates the result */
337         resu = malloc((it - arg) + dif + 1);
338         if (!resu) {
339                 ERROR("out of memory");
340                 return NULL;
341         }
342
343         /* instanciate the arguments */
344         wr = resu;
345         for (;;) {
346                 it = strchrnul(arg, SUBST_CHAR);
347                 wr = mempcpy(wr, arg, it - arg);
348                 if (!*it)
349                         break;
350                 switch(*++it) {
351                 case 'p': wr = stpcpy(wr, port); break;
352                 case 't': wr = stpcpy(wr, token); break;
353                 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
354                 case SUBST_CHAR: *wr++ = *it;
355                 }
356                 arg = ++it;
357         }
358
359         *wr = 0;
360         return resu;
361 }
362
363 static int instanciate_environ(const char *port, const char *token)
364 {
365         extern char **environ;
366         char *repl;
367         int i;
368
369         /* instanciate the environment */
370         for (i = 0 ; environ[i] ; i++) {
371                 repl = instanciate_string(environ[i], port, token);
372                 if (!repl)
373                         return -1;
374                 environ[i] = repl;
375         }
376         return 0;
377 }
378
379 static int instanciate_command_args(const char *port, const char *token)
380 {
381         char *repl;
382         int i;
383
384         /* instanciate the arguments */
385         for (i = 0 ; config->exec[i] ; i++) {
386                 repl = instanciate_string(config->exec[i], port, token);
387                 if (!repl)
388                         return -1;
389                 config->exec[i] = repl;
390         }
391         return 0;
392 }
393
394 static int execute_command()
395 {
396         struct sigaction siga;
397         char port[20];
398         const char *token;
399         int rc;
400
401         /* check whether a command is to execute or not */
402         if (!config->exec || !config->exec[0])
403                 return 0;
404
405         if (SELF_PGROUP)
406                 setpgid(0, 0);
407
408         /* install signal handler */
409         memset(&siga, 0, sizeof siga);
410         siga.sa_sigaction = on_sigchld;
411         siga.sa_flags = SA_SIGINFO;
412         sigaction(SIGCHLD, &siga, NULL);
413
414         /* fork now */
415         childpid = fork();
416         if (childpid)
417                 return 0;
418
419         /* compute the string for port */
420         if (config->httpdPort)
421                 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
422         else
423                 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
424         if (rc < 0 || rc >= (int)(sizeof port)) {
425                 ERROR("port->txt failed");
426         }
427         else {
428                 /* instanciate arguments and environment */
429                 token = afb_session_initial_token();
430                 if (instanciate_command_args(port, token) >= 0
431                  && instanciate_environ(port, token) >= 0) {
432                         /* run */
433                         if (!SELF_PGROUP)
434                                 setpgid(0, 0);
435                         execv(config->exec[0], config->exec);
436                         ERROR("can't launch %s: %m", config->exec[0]);
437                 }
438         }
439         exit(1);
440         return -1;
441 }
442
443 /*---------------------------------------------------------
444  | startup calls
445  +--------------------------------------------------------- */
446
447 struct startup_req
448 {
449         struct afb_xreq xreq;
450         char *api;
451         char *verb;
452         struct afb_config_list *current;
453         struct afb_session *session;
454 };
455
456 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
457 {
458         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
459
460         if (status >= 0)
461                 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
462         else {
463                 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
464                 exit(1);
465         }
466 }
467
468 static void startup_call_current(struct startup_req *sreq);
469
470 static void startup_call_unref(struct afb_xreq *xreq)
471 {
472         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
473
474         free(sreq->api);
475         free(sreq->verb);
476         json_object_put(sreq->xreq.json);
477         sreq->current = sreq->current->next;
478         if (sreq->current)
479                 startup_call_current(sreq);
480         else {
481                 afb_session_close(sreq->session);
482                 afb_session_unref(sreq->session);
483                 free(sreq);
484         }
485 }
486
487 static struct afb_xreq_query_itf startup_xreq_itf =
488 {
489         .reply = startup_call_reply,
490         .unref = startup_call_unref
491 };
492
493 static void startup_call_current(struct startup_req *sreq)
494 {
495         char *api, *verb, *json;
496
497         api = sreq->current->value;
498         verb = strchr(api, '/');
499         if (verb) {
500                 json = strchr(verb, ':');
501                 if (json) {
502                         afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
503                         afb_context_init(&sreq->xreq.context, sreq->session, NULL);
504                         sreq->xreq.context.validated = 1;
505                         sreq->api = strndup(api, verb - api);
506                         sreq->verb = strndup(verb + 1, json - verb - 1);
507                         sreq->xreq.request.api = sreq->api;
508                         sreq->xreq.request.verb = sreq->verb;
509                         sreq->xreq.json = json_tokener_parse(json + 1);
510                         if (sreq->api && sreq->verb && sreq->xreq.json) {
511                                 afb_xreq_process(&sreq->xreq, main_apiset);
512                                 return;
513                         }
514                 }
515         }
516         ERROR("Bad call specification %s", sreq->current->value);
517         exit(1);
518 }
519
520 static void run_startup_calls()
521 {
522         struct afb_config_list *list;
523         struct startup_req *sreq;
524
525         list = config->calls;
526         if (list) {
527                 sreq = calloc(1, sizeof *sreq);
528                 sreq->session = afb_session_create(3600);
529                 sreq->current = list;
530                 startup_call_current(sreq);
531         }
532 }
533
534 /*---------------------------------------------------------
535  | job for starting the daemon
536  +--------------------------------------------------------- */
537
538 static void start(int signum)
539 {
540         struct afb_hsrv *hsrv;
541
542         afb_debug("start-entry");
543
544         if (signum) {
545                 ERROR("start aborted: received signal %s", strsignal(signum));
546                 exit(1);
547         }
548
549         // ------------------ sanity check ----------------------------------------
550         if (config->httpdPort <= 0) {
551                 ERROR("no port is defined");
552                 goto error;
553         }
554
555         /* set the directories */
556         mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
557         if (chdir(config->workdir) < 0) {
558                 ERROR("Can't enter working dir %s", config->workdir);
559                 goto error;
560         }
561         if (afb_common_rootdir_set(config->rootdir) < 0) {
562                 ERROR("failed to set common root directory");
563                 goto error;
564         }
565
566         /* configure the daemon */
567         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
568         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
569                 ERROR("initialisation of cookies failed");
570                 goto error;
571         }
572         main_apiset = afb_apiset_create("main", config->apiTimeout);
573         if (!main_apiset) {
574                 ERROR("can't create main api set");
575                 goto error;
576         }
577         if (afb_monitor_init() < 0) {
578                 ERROR("failed to setup monitor");
579                 goto error;
580         }
581
582         /* install hooks */
583         if (config->tracereq)
584                 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
585         if (config->traceditf)
586                 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
587         if (config->tracesvc)
588                 afb_hook_create_svc(NULL, config->tracesvc, NULL, NULL);
589         if (config->traceevt)
590                 afb_hook_create_evt(NULL, config->traceevt, NULL, NULL);
591
592         /* load bindings */
593         afb_debug("start-load");
594         apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
595         apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
596         apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
597         apiset_start_list(config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
598         apiset_start_list(config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
599
600         apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
601         apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
602
603         DEBUG("Init config done");
604
605         /* start the services */
606         afb_debug("start-start");
607 #if !defined(NO_CALL_PERSONALITY)
608         personality((unsigned long)-1L);
609 #endif
610         if (afb_apiset_start_all_services(main_apiset, 1) < 0)
611                 goto error;
612
613         /* start the HTTP server */
614         afb_debug("start-http");
615         if (!config->noHttpd) {
616                 hsrv = start_http_server();
617                 if (hsrv == NULL)
618                         goto error;
619         }
620
621         /* run the startup calls */
622         afb_debug("start-call");
623         run_startup_calls();
624
625         /* run the command */
626         afb_debug("start-exec");
627         if (execute_command() < 0)
628                 goto error;
629
630         /* ready */
631         sd_notify(1, "READY=1");
632         return;
633 error:
634         exit(1);
635 }
636
637 /*---------------------------------------------------------
638  | main
639  |   Parse option and launch action
640  +--------------------------------------------------------- */
641
642 int main(int argc, char *argv[])
643 {
644         afb_debug("main-entry");
645
646         // let's run this program with a low priority
647         nice(20);
648
649         sd_fds_init();
650
651         // ------------- Build session handler & init config -------
652         config = afb_config_parse_arguments(argc, argv);
653         if (config->name) {
654                 verbose_set_name(config->name, 0);
655                 process_name_set_name(config->name);
656                 process_name_replace_cmdline(argv, config->name);
657         }
658         afb_debug("main-args");
659
660         // --------- run -----------
661         if (config->background) {
662                 // --------- in background mode -----------
663                 INFO("entering background mode");
664                 daemonize();
665         } else {
666                 // ---- in foreground mode --------------------
667                 INFO("entering foreground mode");
668         }
669         INFO("running with pid %d", getpid());
670
671         /* set the daemon environment */
672         setup_daemon();
673
674         afb_debug("main-start");
675
676         /* enter job processing */
677         jobs_start(3, 0, 50, start);
678         WARNING("hoops returned from jobs_enter! [report bug]");
679         return 1;
680 }
681