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