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