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