Fixed compilation without gtop2 lib.
[psensor.git] / src / server / server.c
1 /*
2  * Copyright (C) 2010-2013 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         {"sensor-log-interval", required_argument, 0, 0},
71         {0, 0, 0, 0}
72 };
73
74 static struct server_data server_data;
75
76 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
77
78 static int server_stop_requested;
79
80 static void print_version()
81 {
82         printf("psensor-server %s\n", VERSION);
83         printf(_("Copyright (C) %s jeanfi@gmail.com\n"
84                  "License GPLv2: GNU GPL version 2 or later "
85                  "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
86                  "This is free software: you are free to change and redistribute it.\n"
87                  "There is NO WARRANTY, to the extent permitted by law.\n"),
88                "2010-2012");
89 }
90
91 static void print_help()
92 {
93         printf(_("Usage: %s [OPTION]...\n"), program_name);
94
95         puts(_("psensor-server is an HTTP server for monitoring hardware "
96                "sensors remotely."));
97
98         puts("");
99         puts("Options:");
100         puts(_("  -h, --help            display this help and exit\n"
101                "  -v, --version         display version information and exit"));
102
103         puts("");
104         puts(_("  -p,--port=PORT        webserver port\n"
105                "  -w,--wdir=DIR         directory containing webserver pages"));
106
107         puts("");
108         puts(_("  -d, --debug=LEVEL     "
109                "set the debug level, integer between 0 and 3"));
110         puts(_("  -l, --log-file=PATH   set the log file to PATH"));
111         puts(_("  --sensor-log-file=PATH set the sensor log file to PATH"));
112         puts(_("  --sensor-log-interval=S "
113                "set the sensor log interval to S (seconds)"));
114
115         puts("");
116         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
117         puts("");
118         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
119 }
120
121 /*
122  * Returns the file path corresponding to a given URL
123  */
124 static char *get_path(const char *url, const char *www_dir)
125 {
126         const char *p;
127         char *res;
128
129         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
130                 p = "/index.html";
131         else
132                 p = url;
133
134         res = malloc(strlen(www_dir)+strlen(p)+1);
135
136         strcpy(res, www_dir);
137         strcat(res, p);
138
139         return res;
140 }
141
142 #if MHD_VERSION >= 0x00090200
143 static ssize_t
144 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
145 #else
146 static int
147 file_reader(void *cls, uint64_t pos, char *buf, int max)
148 #endif
149 {
150         FILE *file = cls;
151
152         fseek(file, pos, SEEK_SET);
153         return fread(buf, 1, max, file);
154 }
155
156 static struct MHD_Response *
157 create_response_api(const char *nurl, const char *method, unsigned int *rp_code)
158 {
159         struct MHD_Response *resp;
160         struct psensor *s;
161         char *page = NULL;
162
163         if (!strcmp(nurl, URL_BASE_API_1_1_SENSORS))  {
164                 page = sensors_to_json_string(server_data.sensors);
165 #ifdef HAVE_GTOP
166         } else if (!strcmp(nurl, URL_API_1_1_SYSINFO)) {
167                 page = sysinfo_to_json_string(&server_data.psysinfo);
168         } else if (!strcmp(nurl, URL_API_1_1_CPU_USAGE)) {
169                 page = sensor_to_json_string(server_data.cpu_usage);
170 #endif
171         } else if (!strncmp(nurl, URL_BASE_API_1_1_SENSORS,
172                             strlen(URL_BASE_API_1_1_SENSORS))
173                    && nurl[strlen(URL_BASE_API_1_1_SENSORS)] == '/') {
174
175                 const char *sid = nurl + strlen(URL_BASE_API_1_1_SENSORS) + 1;
176
177                 s = psensor_list_get_by_id(server_data.sensors, sid);
178
179                 if (s)
180                         page = sensor_to_json_string(s);
181
182         } else if (!strcmp(nurl, URL_API_1_1_SERVER_STOP)) {
183
184                 server_stop_requested = 1;
185                 page = strdup(HTML_STOP_REQUESTED);
186         }
187
188         if (page) {
189                 *rp_code = MHD_HTTP_OK;
190
191                 resp = MHD_create_response_from_data(strlen(page), page,
192                                                      MHD_YES, MHD_NO);
193
194                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
195                                         "application/json");
196
197                 return resp;
198         }
199
200         return NULL;
201 }
202
203 static struct MHD_Response *create_response_file(const char *nurl,
204                                                  const char *method,
205                                                  unsigned int *rp_code,
206                                                  const char *fpath)
207 {
208         struct stat st;
209         int ret;
210         FILE *file;
211
212         ret = stat(fpath, &st);
213
214         if (!ret && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
215                 file = fopen(fpath, "rb");
216
217                 if (file) {
218                         *rp_code = MHD_HTTP_OK;
219
220                         if (!st.st_size) {
221                                 fclose(file);
222                                 return MHD_create_response_from_data
223                                         (0, NULL, MHD_NO, MHD_NO);
224                         }
225
226                         return MHD_create_response_from_callback
227                                 (st.st_size,
228                                  32 * 1024,
229                                  &file_reader,
230                                  file,
231                                  (MHD_ContentReaderFreeCallback)&fclose);
232
233                 } else {
234                         log_err("Failed to open: %s.", fpath);
235                 }
236         }
237
238         return NULL;
239 }
240
241 static struct MHD_Response *
242 create_response(const char *nurl, const char *method, unsigned int *rp_code)
243 {
244         struct MHD_Response *resp = NULL;
245
246         if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) {
247                 resp = create_response_api(nurl, method, rp_code);
248         } else {
249                 char *fpath = get_path(nurl, server_data.www_dir);
250
251                 resp = create_response_file(nurl, method, rp_code, fpath);
252
253                 free(fpath);
254         }
255
256         if (resp) {
257                 return resp;
258         } else {
259                 char *page = strdup(PAGE_NOT_FOUND);
260                 *rp_code = MHD_HTTP_NOT_FOUND;
261
262                 return MHD_create_response_from_data
263                         (strlen(page), page, MHD_YES, MHD_NO);
264         }
265 }
266
267 static int cbk_http_request(void *cls,
268                             struct MHD_Connection *connection,
269                             const char *url,
270                             const char *method,
271                             const char *version,
272                             const char *upload_data,
273                             size_t *upload_data_size, void **ptr)
274 {
275         static int dummy;
276         struct MHD_Response *response;
277         int ret;
278         char *nurl;
279         unsigned int resp_code;
280
281         if (strcmp(method, "GET"))
282                 return MHD_NO;
283
284         if (&dummy != *ptr) {
285                 /* The first time only the headers are valid, do not
286                    respond in the first round... */
287                 *ptr = &dummy;
288                 return MHD_YES;
289         }
290
291         if (*upload_data_size)
292                 return MHD_NO;
293
294         *ptr = NULL;            /* clear context pointer */
295
296         log_debug(_("HTTP Request: %s"), url);
297
298         nurl = url_normalize(url);
299
300         pthread_mutex_lock(&mutex);
301         response = create_response(nurl, method, &resp_code);
302         pthread_mutex_unlock(&mutex);
303
304         ret = MHD_queue_response(connection, resp_code, response);
305         MHD_destroy_response(response);
306
307         free(nurl);
308
309         return ret;
310 }
311
312 int main(int argc, char *argv[])
313 {
314         struct MHD_Daemon *d;
315         int port, opti, optc, cmdok, ret, slog_interval;
316         char *log_file, *slog_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 #ifdef HAVE_GTOP
329         server_data.psysinfo.interfaces = NULL;
330 #endif
331         log_file = NULL;
332         slog_file = NULL;
333         slog_interval = 300;
334         port = DEFAULT_PORT;
335         cmdok = 1;
336
337         while ((optc = getopt_long(argc,
338                                    argv,
339                                    "vhp:w:d:l:",
340                                    long_options,
341                                    &opti)) != -1) {
342                 switch (optc) {
343                 case 'w':
344                         if (optarg)
345                                 server_data.www_dir = strdup(optarg);
346                         break;
347                 case 'p':
348                         if (optarg)
349                                 port = atoi(optarg);
350                         break;
351                 case 'h':
352                         print_help();
353                         exit(EXIT_SUCCESS);
354                 case 'v':
355                         print_version();
356                         exit(EXIT_SUCCESS);
357                 case 'd':
358                         log_level = atoi(optarg);
359                         log_info(_("Enables debug mode: %d"), log_level);
360                         break;
361                 case 'l':
362                         if (optarg)
363                                 log_file = strdup(optarg);
364                         break;
365                 case 0:
366                         if (!strcmp(long_options[opti].name, "sensor-log-file"))
367                                 slog_file = strdup(optarg);
368                         else if (!strcmp(long_options[opti].name,
369                                          "sensor-log-interval"))
370                                 slog_interval = atoi(optarg);
371                         break;
372                 default:
373                         cmdok = 0;
374                         break;
375                 }
376         }
377
378         if (!cmdok || optind != argc) {
379                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
380                         program_name);
381                 exit(EXIT_FAILURE);
382         }
383
384         if (!server_data.www_dir)
385                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
386
387         if (!log_file)
388                 log_file = strdup(DEFAULT_LOG_FILE);
389
390         log_open(log_file);
391
392         psensor_init();
393
394         server_data.sensors = get_all_sensors(0, 600);
395
396 #ifdef HAVE_GTOP
397         server_data.cpu_usage = create_cpu_usage_sensor(600);
398 #endif
399
400         if (!*server_data.sensors)
401                 log_err(_("No sensors detected."));
402
403         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
404                              port,
405                              NULL, NULL, &cbk_http_request, server_data.sensors,
406                              MHD_OPTION_END);
407         if (!d) {
408                 log_err(_("Failed to create Web server."));
409                 exit(EXIT_FAILURE);
410         }
411
412         log_info(_("Web server started on port: %d"), port);
413         log_info(_("WWW directory: %s"), server_data.www_dir);
414         log_info(_("URL: http://localhost:%d"), port);
415
416         if (slog_file) {
417                 if (slog_interval <= 0)
418                         slog_interval = 300;
419                 ret = slog_activate(slog_file,
420                                     server_data.sensors,
421                                     &mutex,
422                                     slog_interval);
423                 if (!ret)
424                         log_err(_("Failed to activate logging of sensors."));
425         }
426
427         while (!server_stop_requested) {
428                 pthread_mutex_lock(&mutex);
429
430 #ifdef HAVE_GTOP
431                 sysinfo_update(&server_data.psysinfo);
432                 cpu_usage_sensor_update(server_data.cpu_usage);
433 #endif
434                 psensor_list_update_measures(server_data.sensors);
435
436                 psensor_log_measures(server_data.sensors);
437
438                 pthread_mutex_unlock(&mutex);
439                 sleep(5);
440         }
441
442         slog_close();
443
444         MHD_stop_daemon(d);
445
446         /* sanity cleanup for valgrind */
447         psensor_list_free(server_data.sensors);
448 #ifdef HAVE_GTOP
449         psensor_free(server_data.cpu_usage);
450 #endif
451         free(server_data.www_dir);
452         sensors_cleanup();
453
454 #ifdef HAVE_GTOP
455         sysinfo_cleanup();
456         cpu_cleanup();
457 #endif
458
459         if (log_file != DEFAULT_LOG_FILE)
460                 free(log_file);
461
462         return EXIT_SUCCESS;
463 }