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