fixed --wdir option.
[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
49 static const char *DEFAULT_LOG_FILE = "/var/log/psensor-server.log";
50
51 static const char *program_name;
52
53 #define DEFAULT_PORT 3131
54
55 #define PAGE_NOT_FOUND (_("<html><body><p>"\
56 "Page not found - Go to <a href='/'>Main page</a></p></body>"))
57
58 static struct option long_options[] = {
59         {"version", no_argument, 0, 'v'},
60         {"help", no_argument, 0, 'h'},
61         {"port", required_argument, 0, 'p'},
62         {"wdir", required_argument, 0, 'w'},
63         {"debug", required_argument, 0, 'd'},
64         {"log-file", required_argument, 0, 'l'},
65         {0, 0, 0, 0}
66 };
67
68 static struct server_data server_data;
69
70 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
71
72 static int server_stop_requested;
73
74 void print_version()
75 {
76         printf("psensor-server %s\n", VERSION);
77         printf(_("Copyright (C) %s jeanfi@gmail.com\n"
78                  "License GPLv2: GNU GPL version 2 or later "
79                  "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
80                  "This is free software: you are free to change and redistribute it.\n"
81                  "There is NO WARRANTY, to the extent permitted by law.\n"),
82                "2010-2012");
83 }
84
85 void print_help()
86 {
87         printf(_("Usage: %s [OPTION]...\n"), program_name);
88
89         puts(_("psensor-server is an HTTP server "
90                "for monitoring hardware sensors remotely."));
91
92         puts("");
93         puts("Options:");
94         puts(_("  -h, --help            display this help and exit\n"
95                "  -v, --version         display version information and exit"));
96
97         puts("");
98         puts(_("  -p,--port=PORT        webserver port\n"
99                "  -w,--wdir=DIR         directory containing webserver pages"));
100
101         puts("");
102         puts(_("  -d, --debug=LEVEL   "
103                "set the debug level, integer between 0 and 3"));
104         puts(_("  -l, --log-file=PATH "
105                "set the log file to PATH"));
106
107         puts("");
108         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
109         puts("");
110         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
111 }
112
113 /*
114   Returns the file path corresponding to a given URL
115 */
116 char *get_path(const char *url, const char *www_dir)
117 {
118         const char *p;
119         char *res;
120
121         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
122                 p = "/index.html";
123         else
124                 p = url;
125
126         res = malloc(strlen(www_dir)+strlen(p)+1);
127
128         strcpy(res, www_dir);
129         strcat(res, p);
130
131         return res;
132 }
133
134 #if MHD_VERSION >= 0x00090200
135 static ssize_t
136 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
137 #else
138 static int
139 file_reader(void *cls, uint64_t pos, char *buf, int max)
140 #endif
141 {
142         FILE *file = cls;
143
144         fseek(file, pos, SEEK_SET);
145         return fread(buf, 1, max, file);
146 }
147
148 struct MHD_Response *
149 create_response_api(const char *nurl,
150                     const char *method,
151                     unsigned int *rp_code)
152 {
153         struct MHD_Response *resp;
154         struct psensor *s;
155         char *page = NULL;
156
157         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
158                 page = sensors_to_json_string(server_data.sensors);
159 #ifdef HAVE_GTOP
160         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
161                 page = sysinfo_to_json_string(&server_data.psysinfo);
162         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
163                 page = sensor_to_json_string(server_data.cpu_usage);
164 #endif
165         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
166                             strlen(URL_BASE_API_1_0_SENSORS))
167                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
168
169                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
170
171                 s = psensor_list_get_by_id(server_data.sensors, sid);
172
173                 if (s)
174                         page = sensor_to_json_string(s);
175
176         } else if (!strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
177
178                 server_stop_requested = 1;
179                 page = strdup(_("<html><body><p>"
180                                 "Server stop requested</p></body></html>"));
181         }
182
183         if (page) {
184                 *rp_code = MHD_HTTP_OK;
185
186                 resp = MHD_create_response_from_data(strlen(page), page,
187                                                      MHD_YES, MHD_NO);
188
189                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
190                                         "application/json");
191
192                 return resp;
193         }
194
195         return NULL;
196 }
197
198 struct MHD_Response *
199 create_response_file(const char *nurl,
200                      const char *method,
201                      unsigned int *rp_code,
202                      const char *fpath)
203 {
204         struct stat st;
205         int ret;
206         FILE *file;
207
208         ret = stat(fpath, &st);
209
210         if (!ret && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
211                 file = fopen(fpath, "rb");
212
213                 if (file) {
214                         *rp_code = MHD_HTTP_OK;
215
216                         if (!st.st_size) {
217                                 fclose(file);
218                                 return MHD_create_response_from_data
219                                         (0, NULL, MHD_NO, MHD_NO);
220                         }
221
222                         return MHD_create_response_from_callback
223                                 (st.st_size,
224                                  32 * 1024,
225                                  &file_reader,
226                                  file,
227                                  (MHD_ContentReaderFreeCallback)&fclose);
228
229                 } else {
230                         log_printf(LOG_ERR, "Failed to open: %s\n", fpath);
231                 }
232         }
233
234         return NULL;
235 }
236
237 struct MHD_Response *
238 create_response(const char *nurl, const char *method, unsigned int *rp_code)
239 {
240         struct MHD_Response *resp = NULL;
241
242         if (!strncmp(nurl, URL_BASE_API_1_0, strlen(URL_BASE_API_1_0))) {
243                 resp = create_response_api(nurl, method, rp_code);
244         } else {
245                 char *fpath = get_path(nurl, server_data.www_dir);
246
247                 resp = create_response_file(nurl, method, rp_code, fpath);
248
249                 free(fpath);
250         }
251
252         if (resp) {
253                 return resp;
254         } else {
255                 char *page = strdup(PAGE_NOT_FOUND);
256                 *rp_code = MHD_HTTP_NOT_FOUND;
257
258                 return MHD_create_response_from_data
259                         (strlen(page), page, MHD_YES, MHD_NO);
260         }
261 }
262
263 static int
264 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 = DEFAULT_PORT;
313         int optc;
314         int cmdok = 1;
315         char *log_file;
316
317         program_name = argv[0];
318
319         setlocale(LC_ALL, "");
320
321 #if ENABLE_NLS
322         bindtextdomain(PACKAGE, LOCALEDIR);
323         textdomain(PACKAGE);
324 #endif
325
326         server_data.www_dir = NULL;
327         server_data.psysinfo.interfaces = NULL;
328         log_file = NULL;
329
330         while ((optc = getopt_long(argc, argv,
331                                    "vhp:w:d:", long_options, NULL)) != -1) {
332                 switch (optc) {
333                 case 'w':
334                         if (optarg)
335                                 server_data.www_dir = strdup(optarg);
336                         break;
337                 case 'p':
338                         if (optarg)
339                                 port = atoi(optarg);
340                         break;
341                 case 'h':
342                         print_help();
343                         exit(EXIT_SUCCESS);
344                 case 'v':
345                         print_version();
346                         exit(EXIT_SUCCESS);
347                 case 'd':
348                         log_level = atoi(optarg);
349                         log_printf(LOG_INFO,
350                                    _("Enables debug mode: %d"),
351                                    log_level);
352                         break;
353                 case 'l':
354                         if (optarg)
355                                 log_file = strdup(optarg);
356                         break;
357                 default:
358                         cmdok = 0;
359                         break;
360                 }
361         }
362
363         if (!server_data.www_dir)
364                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
365
366         if (!log_file)
367                 log_file = strdup(DEFAULT_LOG_FILE);
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         log_open(log_file);
376
377         psensor_init();
378
379         server_data.sensors = get_all_sensors(0, 600);
380
381 #ifdef HAVE_GTOP
382         server_data.cpu_usage = create_cpu_usage_sensor(600);
383 #endif
384
385         if (!*server_data.sensors)
386                 fprintf(stderr, _("ERROR: no sensors detected\n"));
387
388         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
389                              port,
390                              NULL, NULL, &cbk_http_request, server_data.sensors,
391                              MHD_OPTION_END);
392         if (!d) {
393                 fprintf(stderr, _("ERROR: Fail to create web server\n"));
394                 exit(EXIT_FAILURE);
395         }
396
397         log_printf(LOG_INFO, _("Web server started on port: %d"), port);
398         log_printf(LOG_INFO, _("WWW directory: %s"), server_data.www_dir);
399         log_printf(LOG_INFO, _("URL: http://localhost:%d"), port);
400
401         while (!server_stop_requested) {
402                 pthread_mutex_lock(&mutex);
403
404 #ifdef HAVE_GTOP
405                 sysinfo_update(&server_data.psysinfo);
406                 cpu_usage_sensor_update(server_data.cpu_usage);
407 #endif
408                 psensor_list_update_measures(server_data.sensors);
409
410                 psensor_log_measures(server_data.sensors);
411
412                 pthread_mutex_unlock(&mutex);
413                 sleep(5);
414         }
415
416         MHD_stop_daemon(d);
417
418         /* sanity cleanup for valgrind */
419         psensor_list_free(server_data.sensors);
420 #ifdef HAVE_GTOP
421         psensor_free(server_data.cpu_usage);
422 #endif
423         free(server_data.www_dir);
424         sensors_cleanup();
425
426 #ifdef HAVE_GTOP
427         sysinfo_cleanup();
428         cpu_cleanup();
429 #endif
430
431         if (log_file != DEFAULT_LOG_FILE)
432                 free(log_file);
433
434         return EXIT_SUCCESS;
435 }