Refactor of file main.c
[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
29 #include <systemd/sd-event.h>
30
31 #include "afb-config.h"
32 #include "afb-hswitch.h"
33 #include "afb-apis.h"
34 #include "afb-api-so.h"
35 #include "afb-api-dbus.h"
36 #include "afb-api-ws.h"
37 #include "afb-hsrv.h"
38 #include "afb-context.h"
39 #include "afb-hreq.h"
40 #include "afb-sig-handler.h"
41 #include "afb-thread.h"
42 #include "afb-session.h"
43 #include "verbose.h"
44 #include "afb-common.h"
45 #include "afb-hook.h"
46
47 #include <afb/afb-binding.h>
48
49 /*----------------------------------------------------------
50  |   helpers for handling list of arguments
51  +--------------------------------------------------------- */
52
53 /*
54  * Calls the callback 'run' for each value of the 'list'
55  * until the callback returns 0 or the end of the list is reached.
56  * Returns either NULL if the end of the list is reached or a pointer
57  * to the item whose value made 'run' return 0.
58  * 'closure' is used for passing user data.
59  */
60 static struct afb_config_list *run_for_list(struct afb_config_list *list,
61                                             int (*run) (void *closure, char *value),
62                                             void *closure)
63 {
64         while (list && run(closure, list->value))
65                 list = list->next;
66         return list;
67 }
68
69 static int run_start(void *closure, char *value)
70 {
71         int (*starter) (const char *value) = closure;
72         return starter(value) >= 0;
73 }
74
75 static void start_list(struct afb_config_list *list,
76                        int (*starter) (const char *value), const char *message)
77 {
78         list = run_for_list(list, run_start, starter);
79         if (list) {
80                 ERROR("can't start %s %s", message, list->value);
81                 exit(1);
82         }
83 }
84
85 /*----------------------------------------------------------
86  | closeSession
87  |   try to close everything before leaving
88  +--------------------------------------------------------- */
89 static void closeSession(int status, void *data)
90 {
91         /* struct afb_config *config = data; */
92 }
93
94 /*----------------------------------------------------------
95  | daemonize
96  |   set the process in background
97  +--------------------------------------------------------- */
98 static void daemonize(struct afb_config *config)
99 {
100         int consoleFD;
101         int pid;
102
103         // open /dev/console to redirect output messAFBes
104         consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
105         if (consoleFD < 0) {
106                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
107                 exit(1);
108         }
109         // fork process when running background mode
110         pid = fork();
111
112         // if fail nothing much to do
113         if (pid == -1) {
114                 ERROR("AFB-daemon Failed to fork son process");
115                 exit(1);
116         }
117         // if in father process, just leave
118         if (pid != 0)
119                 _exit(0);
120
121         // son process get all data in standalone mode
122         NOTICE("background mode [pid:%d console:%s]", getpid(),
123                config->console);
124
125         // redirect default I/O on console
126         close(2);
127         dup(consoleFD);         // redirect stderr
128         close(1);
129         dup(consoleFD);         // redirect stdout
130         close(0);               // no need for stdin
131         close(consoleFD);
132
133 #if 0
134         setsid();               // allow father process to fully exit
135         sleep(2);               // allow main to leave and release port
136 #endif
137 }
138
139 /*---------------------------------------------------------
140  | http server
141  |   Handles the HTTP server
142  +--------------------------------------------------------- */
143 static int init_alias(void *closure, char *spec)
144 {
145         struct afb_hsrv *hsrv = closure;
146         char *path = strchr(spec, ':');
147
148         if (path == NULL) {
149                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
150                 return 1;
151         }
152         *path++ = 0;
153         INFO("Alias for url=%s to path=%s", spec, path);
154         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
155                                   0, 0);
156 }
157
158 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config *config)
159 {
160         if (!afb_hsrv_add_handler
161             (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
162                 return 0;
163
164         if (!afb_hsrv_add_handler
165             (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
166                 return 0;
167
168         if (run_for_list(config->aliases, init_alias, hsrv))
169                 return 0;
170
171         if (config->roothttp != NULL) {
172                 if (!afb_hsrv_add_alias
173                     (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
174                      -10, 1))
175                         return 0;
176         }
177
178         if (!afb_hsrv_add_handler
179             (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
180              -20))
181                 return 0;
182
183         return 1;
184 }
185
186 static struct afb_hsrv *start_http_server(struct afb_config *config)
187 {
188         int rc;
189         struct afb_hsrv *hsrv;
190
191         if (afb_hreq_init_download_path("/tmp")) {      /* TODO: sessiondir? */
192                 ERROR("unable to set the tmp directory");
193                 return NULL;
194         }
195
196         hsrv = afb_hsrv_create();
197         if (hsrv == NULL) {
198                 ERROR("memory allocation failure");
199                 return NULL;
200         }
201
202         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
203             || !init_http_server(hsrv, config)) {
204                 ERROR("initialisation of httpd failed");
205                 afb_hsrv_put(hsrv);
206                 return NULL;
207         }
208
209         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort,
210                config->rootdir);
211         NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
212
213         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
214         if (!rc) {
215                 ERROR("starting of httpd failed");
216                 afb_hsrv_put(hsrv);
217                 return NULL;
218         }
219
220         return hsrv;
221 }
222
223 /*---------------------------------------------------------
224  | main
225  |   Parse option and launch action
226  +--------------------------------------------------------- */
227
228 int main(int argc, char *argv[])
229 {
230         struct afb_hsrv *hsrv;
231         struct afb_config *config;
232         struct sd_event *eventloop;
233
234         LOGAUTH("afb-daemon");
235
236         // ------------- Build session handler & init config -------
237         config = afb_config_parse_arguments(argc, argv);
238         on_exit(closeSession, config);
239
240         // ------------------ sanity check ----------------------------------------
241         if (config->httpdPort <= 0) {
242                 ERROR("no port is defined");
243                 exit(1);
244         }
245
246         afb_session_init(config->nbSessionMax, config->cntxTimeout,
247                          config->token, afb_apis_count());
248
249         afb_api_so_set_timeout(config->apiTimeout);
250         if (config->ldpaths) {
251                 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
252                         ERROR("initialisation of bindings within %s failed",
253                               config->ldpaths);
254                         exit(1);
255                 }
256         }
257
258         start_list(config->dbus_clients, afb_api_dbus_add_client,
259                    "the afb-dbus client");
260         start_list(config->ws_clients, afb_api_ws_add_client,
261                    "the afb-websocket client");
262         start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
263         start_list(config->dbus_servers, afb_api_dbus_add_server,
264                    "the afb-dbus service");
265         start_list(config->ws_servers, afb_api_ws_add_server,
266                    "the afb-websocket service");
267
268         if (!afb_hreq_init_cookie
269             (config->httpdPort, config->rootapi, config->cntxTimeout)) {
270                 ERROR("initialisation of cookies failed");
271                 exit(1);
272         }
273
274         if (afb_sig_handler_init() < 0) {
275                 ERROR("failed to initialise signal handlers");
276                 return 1;
277         }
278         // if directory does not exist createit
279         mkdir(config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
280         if (afb_common_rootdir_set(config->rootdir) < 0) {
281                 ERROR("failed to set common root directory");
282                 return 1;
283         }
284
285         if (afb_thread_init(3, 1, 20) < 0) {
286                 ERROR("failed to initialise threading");
287                 return 1;
288         }
289         // let's run this program with a low priority
290         nice(20);
291
292         // ------------------ Finaly Process Commands -----------------------------
293         // let's not take the risk to run as ROOT
294         //if (getuid() == 0)  goto errorNoRoot;
295
296         DEBUG("Init config done");
297
298         // --------- run -----------
299         if (config->background) {
300                 // --------- in background mode -----------
301                 INFO("entering background mode");
302                 daemonize(config);
303         } else {
304                 // ---- in foreground mode --------------------
305                 INFO("entering foreground mode");
306         }
307
308         /* ignore any SIGPIPE */
309         signal(SIGPIPE, SIG_IGN);
310
311         /* install trace of requests */
312         if (config->tracereq)
313                 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
314
315         /* start the HTTP server */
316         hsrv = start_http_server(config);
317         if (hsrv == NULL)
318                 exit(1);
319
320         /* start the services */
321         if (afb_apis_start_all_services(1) < 0)
322                 exit(1);
323
324         if (config->readyfd != 0) {
325                 static const char readystr[] = "READY=1";
326                 write(config->readyfd, readystr, sizeof(readystr) - 1);
327                 close(config->readyfd);
328         }
329         // infinite loop
330         eventloop = afb_common_get_event_loop();
331         for (;;)
332                 sd_event_run(eventloop, 30000000);
333
334         WARNING("hoops returned from infinite loop [report bug]");
335
336         return 0;
337 }