added log_info fct
[psensor.git] / src / server / server.c
1 /*
2  * Copyright (C) 2010-2012 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  */
19 #include <locale.h>
20 #include <libintl.h>
21 #define _(str) gettext(str)
22
23 #include "config.h"
24
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/select.h>
32 #include <sys/socket.h>
33 #include <getopt.h>
34 #include <stdint.h>
35 #include <pthread.h>
36 #include <unistd.h>
37 #include <microhttpd.h>
38
39 #ifdef HAVE_GTOP
40 #include "sysinfo.h"
41 #include "cpu.h"
42 #endif
43
44 #include "log.h"
45 #include "psensor_json.h"
46 #include "url.h"
47 #include "server.h"
48
49 static const char *DEFAULT_LOG_FILE = "/var/log/psensor-server.log";
50
51 #define HTML_STOP_REQUESTED \
52 (_("<html><body><p>Server stop requested</p></body></html>"))
53
54 static const char *program_name;
55
56 #define DEFAULT_PORT 3131
57
58 #define PAGE_NOT_FOUND (_("<html><body><p>"\
59 "Page not found - Go to <a href='/'>Main page</a></p></body>"))
60
61 static struct option long_options[] = {
62         {"version", no_argument, 0, 'v'},
63         {"help", no_argument, 0, 'h'},
64         {"port", required_argument, 0, 'p'},
65         {"wdir", required_argument, 0, 'w'},
66         {"debug", required_argument, 0, 'd'},
67         {"log-file", required_argument, 0, 'l'},
68         {0, 0, 0, 0}
69 };
70
71 static struct server_data server_data;
72
73 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
74
75 static int server_stop_requested;
76
77 void print_version()
78 {
79         printf("psensor-server %s\n", VERSION);
80         printf(_("Copyright (C) %s jeanfi@gmail.com\n"
81                  "License GPLv2: GNU GPL version 2 or later "
82                  "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
83                  "This is free software: you are free to change and redistribute it.\n"
84                  "There is NO WARRANTY, to the extent permitted by law.\n"),
85                "2010-2012");
86 }
87
88 void print_help()
89 {
90         printf(_("Usage: %s [OPTION]...\n"), program_name);
91
92         puts(_("psensor-server is an HTTP server for monitoring hardware "
93                "sensors remotely."));
94
95         puts("");
96         puts("Options:");
97         puts(_("  -h, --help            display this help and exit\n"
98                "  -v, --version         display version information and exit"));
99
100         puts("");
101         puts(_("  -p,--port=PORT        webserver port\n"
102                "  -w,--wdir=DIR         directory containing webserver pages"));
103
104         puts("");
105         puts(_("  -d, --debug=LEVEL     "
106                "set the debug level, integer between 0 and 3"));
107         puts(_("  -l, --log-file=PATH   set the log file to PATH"));
108
109         puts("");
110         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
111         puts("");
112         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
113 }
114
115 /*
116   Returns the file path corresponding to a given URL
117 */
118 char *get_path(const char *url, const char *www_dir)
119 {
120         const char *p;
121         char *res;
122
123         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
124                 p = "/index.html";
125         else
126                 p = url;
127
128         res = malloc(strlen(www_dir)+strlen(p)+1);
129
130         strcpy(res, www_dir);
131         strcat(res, p);
132
133         return res;
134 }
135
136 #if MHD_VERSION >= 0x00090200
137 static ssize_t
138 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
139 #else
140 static int
141 file_reader(void *cls, uint64_t pos, char *buf, int max)
142 #endif
143 {
144         FILE *file = cls;
145
146         fseek(file, pos, SEEK_SET);
147         return fread(buf, 1, max, file);
148 }
149
150 struct MHD_Response *
151 create_response_api(const char *nurl,
152                     const char *method,
153                     unsigned int *rp_code)
154 {
155         struct MHD_Response *resp;
156         struct psensor *s;
157         char *page = NULL;
158
159         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
160                 page = sensors_to_json_string(server_data.sensors);
161 #ifdef HAVE_GTOP
162         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
163                 page = sysinfo_to_json_string(&server_data.psysinfo);
164         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
165                 page = sensor_to_json_string(server_data.cpu_usage);
166 #endif
167         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
168                             strlen(URL_BASE_API_1_0_SENSORS))
169                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
170
171                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
172
173                 s = psensor_list_get_by_id(server_data.sensors, sid);
174
175                 if (s)
176                         page = sensor_to_json_string(s);
177
178         } else if (!strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
179
180                 server_stop_requested = 1;
181                 page = strdup(HTML_STOP_REQUESTED);
182         }
183
184         if (page) {
185                 *rp_code = MHD_HTTP_OK;
186
187                 resp = MHD_create_response_from_data(strlen(page), page,
188                                                      MHD_YES, MHD_NO);
189
190                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
191                                         "application/json");
192
193                 return resp;
194         }
195
196         return NULL;
197 }
198
199 struct MHD_Response *
200 create_response_file(const char *nurl,
201                      const char *method,
202                      unsigned int *rp_code,
203                      const char *fpath)
204 {
205         struct stat st;
206         int ret;
207         FILE *file;
208
209         ret = stat(fpath, &st);
210
211         if (!ret && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
212                 file = fopen(fpath, "rb");
213
214                 if (file) {
215                         *rp_code = MHD_HTTP_OK;
216
217                         if (!st.st_size) {
218                                 fclose(file);
219                                 return MHD_create_response_from_data
220                                         (0, NULL, MHD_NO, MHD_NO);
221                         }
222
223                         return MHD_create_response_from_callback
224                                 (st.st_size,
225                                  32 * 1024,
226                                  &file_reader,
227                                  file,
228                                  (MHD_ContentReaderFreeCallback)&fclose);
229
230                 } else {
231                         log_err("Failed to open: %s.", fpath);
232                 }
233         }
234
235         return NULL;
236 }
237
238 struct MHD_Response *
239 create_response(const char *nurl, const char *method, unsigned int *rp_code)
240 {
241         struct MHD_Response *resp = NULL;
242
243         if (!strncmp(nurl, URL_BASE_API_1_0, strlen(URL_BASE_API_1_0))) {
244                 resp = create_response_api(nurl, method, rp_code);
245         } else {
246                 char *fpath = get_path(nurl, server_data.www_dir);
247
248                 resp = create_response_file(nurl, method, rp_code, fpath);
249
250                 free(fpath);
251         }
252
253         if (resp) {
254                 return resp;
255         } else {
256                 char *page = strdup(PAGE_NOT_FOUND);
257                 *rp_code = MHD_HTTP_NOT_FOUND;
258
259                 return MHD_create_response_from_data
260                         (strlen(page), page, MHD_YES, MHD_NO);
261         }
262 }
263
264 static int
265 cbk_http_request(void *cls,
266                  struct MHD_Connection *connection,
267                  const char *url,
268                  const char *method,
269                  const char *version,
270                  const char *upload_data,
271                  size_t *upload_data_size, void **ptr)
272 {
273         static int dummy;
274         struct MHD_Response *response;
275         int ret;
276         char *nurl;
277         unsigned int resp_code;
278
279         if (strcmp(method, "GET"))
280                 return MHD_NO;
281
282         if (&dummy != *ptr) {
283                 /* The first time only the headers are valid, do not
284                    respond in the first round... */
285                 *ptr = &dummy;
286                 return MHD_YES;
287         }
288
289         if (*upload_data_size)
290                 return MHD_NO;
291
292         *ptr = NULL;            /* clear context pointer */
293
294         log_debug(_("HTTP Request: %s"), url);
295
296         nurl = url_normalize(url);
297
298         pthread_mutex_lock(&mutex);
299         response = create_response(nurl, method, &resp_code);
300         pthread_mutex_unlock(&mutex);
301
302         ret = MHD_queue_response(connection, resp_code, response);
303         MHD_destroy_response(response);
304
305         free(nurl);
306
307         return ret;
308 }
309
310 int main(int argc, char *argv[])
311 {
312         struct MHD_Daemon *d;
313         int port = DEFAULT_PORT;
314         int optc;
315         int cmdok = 1;
316         char *log_file;
317
318         program_name = argv[0];
319
320         setlocale(LC_ALL, "");
321
322 #if ENABLE_NLS
323         bindtextdomain(PACKAGE, LOCALEDIR);
324         textdomain(PACKAGE);
325 #endif
326
327         server_data.www_dir = NULL;
328         server_data.psysinfo.interfaces = NULL;
329         log_file = NULL;
330
331         while ((optc = getopt_long(argc, argv,
332                                    "vhp:w:d:l:", long_options, NULL)) != -1) {
333                 switch (optc) {
334                 case 'w':
335                         if (optarg)
336                                 server_data.www_dir = strdup(optarg);
337                         break;
338                 case 'p':
339                         if (optarg)
340                                 port = atoi(optarg);
341                         break;
342                 case 'h':
343                         print_help();
344                         exit(EXIT_SUCCESS);
345                 case 'v':
346                         print_version();
347                         exit(EXIT_SUCCESS);
348                 case 'd':
349                         log_level = atoi(optarg);
350                         log_info(_("Enables debug mode: %d"), log_level);
351                         break;
352                 case 'l':
353                         if (optarg)
354                                 log_file = strdup(optarg);
355                         break;
356                 default:
357                         cmdok = 0;
358                         break;
359                 }
360         }
361
362         if (!server_data.www_dir)
363                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
364
365         if (!log_file)
366                 log_file = strdup(DEFAULT_LOG_FILE);
367
368         if (!cmdok || optind != argc) {
369                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
370                         program_name);
371                 exit(EXIT_FAILURE);
372         }
373
374         log_open(log_file);
375
376         psensor_init();
377
378         server_data.sensors = get_all_sensors(0, 600);
379
380 #ifdef HAVE_GTOP
381         server_data.cpu_usage = create_cpu_usage_sensor(600);
382 #endif
383
384         if (!*server_data.sensors)
385                 log_err(_("No sensors detected."));
386
387         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
388                              port,
389                              NULL, NULL, &cbk_http_request, server_data.sensors,
390                              MHD_OPTION_END);
391         if (!d) {
392                 log_err(_("Failed to create Web server."));
393                 exit(EXIT_FAILURE);
394         }
395
396         log_info(_("Web server started on port: %d"), port);
397         log_info(_("WWW directory: %s"), server_data.www_dir);
398         log_info(_("URL: http://localhost:%d"), port);
399
400         while (!server_stop_requested) {
401                 pthread_mutex_lock(&mutex);
402
403 #ifdef HAVE_GTOP
404                 sysinfo_update(&server_data.psysinfo);
405                 cpu_usage_sensor_update(server_data.cpu_usage);
406 #endif
407                 psensor_list_update_measures(server_data.sensors);
408
409                 psensor_log_measures(server_data.sensors);
410
411                 pthread_mutex_unlock(&mutex);
412                 sleep(5);
413         }
414
415         MHD_stop_daemon(d);
416
417         /* sanity cleanup for valgrind */
418         psensor_list_free(server_data.sensors);
419 #ifdef HAVE_GTOP
420         psensor_free(server_data.cpu_usage);
421 #endif
422         free(server_data.www_dir);
423         sensors_cleanup();
424
425 #ifdef HAVE_GTOP
426         sysinfo_cleanup();
427         cpu_cleanup();
428 #endif
429
430         if (log_file != DEFAULT_LOG_FILE)
431                 free(log_file);
432
433         return EXIT_SUCCESS;
434 }