added comment
[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 #include "slog.h"
49
50 static const char *DEFAULT_LOG_FILE = "/var/log/psensor-server.log";
51
52 #define HTML_STOP_REQUESTED \
53 (_("<html><body><p>Server stop requested</p></body></html>"))
54
55 static const char *program_name;
56
57 static const int DEFAULT_PORT = 3131;
58
59 #define PAGE_NOT_FOUND (_("<html><body><p>"\
60 "Page not found - Go to <a href='/'>Main page</a></p></body>"))
61
62 static struct option long_options[] = {
63         {"version", no_argument, 0, 'v'},
64         {"help", no_argument, 0, 'h'},
65         {"port", required_argument, 0, 'p'},
66         {"wdir", required_argument, 0, 'w'},
67         {"debug", required_argument, 0, 'd'},
68         {"log-file", required_argument, 0, 'l'},
69         {"sensor-log-file", required_argument, 0, 0},
70         {0, 0, 0, 0}
71 };
72
73 static struct server_data server_data;
74
75 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
76
77 static int server_stop_requested;
78
79 static void print_version()
80 {
81         printf("psensor-server %s\n", VERSION);
82         printf(_("Copyright (C) %s jeanfi@gmail.com\n"
83                  "License GPLv2: GNU GPL version 2 or later "
84                  "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
85                  "This is free software: you are free to change and redistribute it.\n"
86                  "There is NO WARRANTY, to the extent permitted by law.\n"),
87                "2010-2012");
88 }
89
90 static void print_help()
91 {
92         printf(_("Usage: %s [OPTION]...\n"), program_name);
93
94         puts(_("psensor-server is an HTTP server for monitoring hardware "
95                "sensors remotely."));
96
97         puts("");
98         puts("Options:");
99         puts(_("  -h, --help            display this help and exit\n"
100                "  -v, --version         display version information and exit"));
101
102         puts("");
103         puts(_("  -p,--port=PORT        webserver port\n"
104                "  -w,--wdir=DIR         directory containing webserver pages"));
105
106         puts("");
107         puts(_("  -d, --debug=LEVEL     "
108                "set the debug level, integer between 0 and 3"));
109         puts(_("  -l, --log-file=PATH   set the log file to PATH"));
110         puts(_("  --sensor-log-file=PATH set the sensor log file to PATH"));
111
112         puts("");
113         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
114         puts("");
115         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
116 }
117
118 /*
119  * Returns the file path corresponding to a given URL
120  */
121 static char *get_path(const char *url, const char *www_dir)
122 {
123         const char *p;
124         char *res;
125
126         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
127                 p = "/index.html";
128         else
129                 p = url;
130
131         res = malloc(strlen(www_dir)+strlen(p)+1);
132
133         strcpy(res, www_dir);
134         strcat(res, p);
135
136         return res;
137 }
138
139 #if MHD_VERSION >= 0x00090200
140 static ssize_t
141 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
142 #else
143 static int
144 file_reader(void *cls, uint64_t pos, char *buf, int max)
145 #endif
146 {
147         FILE *file = cls;
148
149         fseek(file, pos, SEEK_SET);
150         return fread(buf, 1, max, file);
151 }
152
153 static struct MHD_Response *
154 create_response_api(const char *nurl, const char *method, unsigned int *rp_code)
155 {
156         struct MHD_Response *resp;
157         struct psensor *s;
158         char *page = NULL;
159
160         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
161                 page = sensors_to_json_string(server_data.sensors);
162 #ifdef HAVE_GTOP
163         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
164                 page = sysinfo_to_json_string(&server_data.psysinfo);
165         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
166                 page = sensor_to_json_string(server_data.cpu_usage);
167 #endif
168         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
169                             strlen(URL_BASE_API_1_0_SENSORS))
170                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
171
172                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
173
174                 s = psensor_list_get_by_id(server_data.sensors, sid);
175
176                 if (s)
177                         page = sensor_to_json_string(s);
178
179         } else if (!strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
180
181                 server_stop_requested = 1;
182                 page = strdup(HTML_STOP_REQUESTED);
183         }
184
185         if (page) {
186                 *rp_code = MHD_HTTP_OK;
187
188                 resp = MHD_create_response_from_data(strlen(page), page,
189                                                      MHD_YES, MHD_NO);
190
191                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
192                                         "application/json");
193
194                 return resp;
195         }
196
197         return NULL;
198 }
199
200 static struct MHD_Response *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 static 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 cbk_http_request(void *cls,
265                             struct MHD_Connection *connection,
266                             const char *url,
267                             const char *method,
268                             const char *version,
269                             const char *upload_data,
270                             size_t *upload_data_size, void **ptr)
271 {
272         static int dummy;
273         struct MHD_Response *response;
274         int ret;
275         char *nurl;
276         unsigned int resp_code;
277
278         if (strcmp(method, "GET"))
279                 return MHD_NO;
280
281         if (&dummy != *ptr) {
282                 /* The first time only the headers are valid, do not
283                    respond in the first round... */
284                 *ptr = &dummy;
285                 return MHD_YES;
286         }
287
288         if (*upload_data_size)
289                 return MHD_NO;
290
291         *ptr = NULL;            /* clear context pointer */
292
293         log_debug(_("HTTP Request: %s"), url);
294
295         nurl = url_normalize(url);
296
297         pthread_mutex_lock(&mutex);
298         response = create_response(nurl, method, &resp_code);
299         pthread_mutex_unlock(&mutex);
300
301         ret = MHD_queue_response(connection, resp_code, response);
302         MHD_destroy_response(response);
303
304         free(nurl);
305
306         return ret;
307 }
308
309 static void *slog_routine(void *data)
310 {
311         char *path;
312
313         path = (char *)data;
314
315         log_debug("slog_routine");
316
317         slog_init(path, server_data.sensors);
318
319         while (1) {
320                 pthread_mutex_lock(&mutex);
321                 slog_write_sensors(server_data.sensors);
322                 pthread_mutex_unlock(&mutex);
323
324                 sleep(5);
325         }
326
327         /* not reachable but avoid compilation error. */
328         pthread_exit(0);
329 }
330
331 int main(int argc, char *argv[])
332 {
333         struct MHD_Daemon *d;
334         int port, opti, optc, cmdok, ret;
335         char *log_file, *slog_file;
336         pthread_t slog_thread;
337
338         program_name = argv[0];
339
340         setlocale(LC_ALL, "");
341
342 #if ENABLE_NLS
343         bindtextdomain(PACKAGE, LOCALEDIR);
344         textdomain(PACKAGE);
345 #endif
346
347         server_data.www_dir = NULL;
348         server_data.psysinfo.interfaces = NULL;
349         log_file = NULL;
350         slog_file = NULL;
351         port = DEFAULT_PORT;
352         cmdok = 1;
353
354         while ((optc = getopt_long(argc,
355                                    argv,
356                                    "vhp:w:d:l:",
357                                    long_options,
358                                    &opti)) != -1) {
359                 switch (optc) {
360                 case 'w':
361                         if (optarg)
362                                 server_data.www_dir = strdup(optarg);
363                         break;
364                 case 'p':
365                         if (optarg)
366                                 port = atoi(optarg);
367                         break;
368                 case 'h':
369                         print_help();
370                         exit(EXIT_SUCCESS);
371                 case 'v':
372                         print_version();
373                         exit(EXIT_SUCCESS);
374                 case 'd':
375                         log_level = atoi(optarg);
376                         log_info(_("Enables debug mode: %d"), log_level);
377                         break;
378                 case 'l':
379                         if (optarg)
380                                 log_file = strdup(optarg);
381                         break;
382                 case 0:
383                         if (!strcmp(long_options[opti].name, "sensor-log-file"))
384                                 slog_file = strdup(optarg);
385                         break;
386                 default:
387                         cmdok = 0;
388                         break;
389                 }
390         }
391
392         if (!cmdok || optind != argc) {
393                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
394                         program_name);
395                 exit(EXIT_FAILURE);
396         }
397
398         if (!server_data.www_dir)
399                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
400
401         if (!log_file)
402                 log_file = strdup(DEFAULT_LOG_FILE);
403
404         log_open(log_file);
405
406         psensor_init();
407
408         server_data.sensors = get_all_sensors(0, 600);
409
410 #ifdef HAVE_GTOP
411         server_data.cpu_usage = create_cpu_usage_sensor(600);
412 #endif
413
414         if (!*server_data.sensors)
415                 log_err(_("No sensors detected."));
416
417         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
418                              port,
419                              NULL, NULL, &cbk_http_request, server_data.sensors,
420                              MHD_OPTION_END);
421         if (!d) {
422                 log_err(_("Failed to create Web server."));
423                 exit(EXIT_FAILURE);
424         }
425
426         log_info(_("Web server started on port: %d"), port);
427         log_info(_("WWW directory: %s"), server_data.www_dir);
428         log_info(_("URL: http://localhost:%d"), port);
429
430         if (slog_file) {
431                 ret = pthread_create(&slog_thread,
432                                      NULL,
433                                      slog_routine,
434                                      slog_file);
435                 if (ret)
436                         log_err(_("Failed to create sensor log thread."));
437         }
438
439         while (!server_stop_requested) {
440                 pthread_mutex_lock(&mutex);
441
442 #ifdef HAVE_GTOP
443                 sysinfo_update(&server_data.psysinfo);
444                 cpu_usage_sensor_update(server_data.cpu_usage);
445 #endif
446                 psensor_list_update_measures(server_data.sensors);
447
448                 psensor_log_measures(server_data.sensors);
449
450                 pthread_mutex_unlock(&mutex);
451                 sleep(5);
452         }
453
454         slog_close();
455
456         MHD_stop_daemon(d);
457
458         /* sanity cleanup for valgrind */
459         psensor_list_free(server_data.sensors);
460 #ifdef HAVE_GTOP
461         psensor_free(server_data.cpu_usage);
462 #endif
463         free(server_data.www_dir);
464         sensors_cleanup();
465
466 #ifdef HAVE_GTOP
467         sysinfo_cleanup();
468         cpu_cleanup();
469 #endif
470
471         if (log_file != DEFAULT_LOG_FILE)
472                 free(log_file);
473
474         return EXIT_SUCCESS;
475 }