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