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