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