style
[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 int main(int argc, char *argv[])
310 {
311         struct MHD_Daemon *d;
312         int port, opti, optc, cmdok;
313         char *log_file, *slog_file;
314
315         program_name = argv[0];
316
317         setlocale(LC_ALL, "");
318
319 #if ENABLE_NLS
320         bindtextdomain(PACKAGE, LOCALEDIR);
321         textdomain(PACKAGE);
322 #endif
323
324         server_data.www_dir = NULL;
325         server_data.psysinfo.interfaces = NULL;
326         log_file = NULL;
327         slog_file = NULL;
328         port = DEFAULT_PORT;
329         cmdok = 1;
330
331         while ((optc = getopt_long(argc,
332                                    argv,
333                                    "vhp:w:d:l:",
334                                    long_options,
335                                    &opti)) != -1) {
336                 switch (optc) {
337                 case 'w':
338                         if (optarg)
339                                 server_data.www_dir = strdup(optarg);
340                         break;
341                 case 'p':
342                         if (optarg)
343                                 port = atoi(optarg);
344                         break;
345                 case 'h':
346                         print_help();
347                         exit(EXIT_SUCCESS);
348                 case 'v':
349                         print_version();
350                         exit(EXIT_SUCCESS);
351                 case 'd':
352                         log_level = atoi(optarg);
353                         log_info(_("Enables debug mode: %d"), log_level);
354                         break;
355                 case 'l':
356                         if (optarg)
357                                 log_file = strdup(optarg);
358                         break;
359                 case 0:
360                         if (!strcmp(long_options[opti].name, "sensor-log-file"))
361                                 slog_file = strdup(optarg);
362                         break;
363                 default:
364                         cmdok = 0;
365                         break;
366                 }
367         }
368
369         if (!cmdok || optind != argc) {
370                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
371                         program_name);
372                 exit(EXIT_FAILURE);
373         }
374
375         if (!server_data.www_dir)
376                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
377
378         if (!log_file)
379                 log_file = strdup(DEFAULT_LOG_FILE);
380
381         log_open(log_file);
382
383         psensor_init();
384
385         server_data.sensors = get_all_sensors(0, 600);
386
387 #ifdef HAVE_GTOP
388         server_data.cpu_usage = create_cpu_usage_sensor(600);
389 #endif
390
391         if (!*server_data.sensors)
392                 log_err(_("No sensors detected."));
393
394         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
395                              port,
396                              NULL, NULL, &cbk_http_request, server_data.sensors,
397                              MHD_OPTION_END);
398         if (!d) {
399                 log_err(_("Failed to create Web server."));
400                 exit(EXIT_FAILURE);
401         }
402
403         log_info(_("Web server started on port: %d"), port);
404         log_info(_("WWW directory: %s"), server_data.www_dir);
405         log_info(_("URL: http://localhost:%d"), port);
406
407         if (slog_file)
408                 slog_init(slog_file, server_data.sensors);
409
410         while (!server_stop_requested) {
411                 pthread_mutex_lock(&mutex);
412
413 #ifdef HAVE_GTOP
414                 sysinfo_update(&server_data.psysinfo);
415                 cpu_usage_sensor_update(server_data.cpu_usage);
416 #endif
417                 psensor_list_update_measures(server_data.sensors);
418
419                 psensor_log_measures(server_data.sensors);
420
421                 slog_write_sensors(server_data.sensors);
422
423                 pthread_mutex_unlock(&mutex);
424                 sleep(5);
425         }
426
427         slog_close();
428
429         MHD_stop_daemon(d);
430
431         /* sanity cleanup for valgrind */
432         psensor_list_free(server_data.sensors);
433 #ifdef HAVE_GTOP
434         psensor_free(server_data.cpu_usage);
435 #endif
436         free(server_data.www_dir);
437         sensors_cleanup();
438
439 #ifdef HAVE_GTOP
440         sysinfo_cleanup();
441         cpu_cleanup();
442 #endif
443
444         if (log_file != DEFAULT_LOG_FILE)
445                 free(log_file);
446
447         return EXIT_SUCCESS;
448 }