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