updated checkpatch.pl
[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
155                 page = sensors_to_json_string(server_data.sensors);
156
157 #ifdef HAVE_GTOP
158         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
159
160                 page = sysinfo_to_json_string(&server_data.psysinfo);
161         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
162                 page = sensor_to_json_string(server_data.cpu_usage);
163 #endif
164         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
165                             strlen(URL_BASE_API_1_0_SENSORS))
166                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
167
168                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
169
170                 s = psensor_list_get_by_id(server_data.sensors, sid);
171
172                 if (s)
173                         page = sensor_to_json_string(s);
174
175         } else if (debug && !strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
176
177                 server_stop_requested = 1;
178                 page = strdup(_("<html><body><p>"
179                                 "Server stop requested</p></body></html>"));
180         }
181
182         if (page) {
183                 *rp_code = MHD_HTTP_OK;
184
185                 resp = MHD_create_response_from_data(strlen(page), page,
186                                                      MHD_YES, MHD_NO);
187
188                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
189                                         "application/json");
190
191                 return resp;
192         }
193
194         return NULL;
195 }
196
197 struct MHD_Response *
198 create_response_file(const char *nurl,
199                      const char *method,
200                      unsigned int *rp_code,
201                      const char *fpath)
202 {
203         struct stat st;
204         int ret;
205         FILE *file;
206
207         ret = stat(fpath, &st);
208
209         if (!ret && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
210                 file = fopen(fpath, "rb");
211
212                 if (file) {
213                         *rp_code = MHD_HTTP_OK;
214
215                         if (!st.st_size) {
216                                 fclose(file);
217                                 return MHD_create_response_from_data
218                                         (0, NULL, MHD_NO, MHD_NO);
219                         }
220
221                         return MHD_create_response_from_callback
222                                 (st.st_size,
223                                  32 * 1024,
224                                  &file_reader,
225                                  file,
226                                  (MHD_ContentReaderFreeCallback)&fclose);
227
228                 } else {
229                         log_printf(LOG_ERR, "Failed to open: %s\n", fpath);
230                 }
231         }
232
233         return NULL;
234 }
235
236 struct MHD_Response *
237 create_response(const char *nurl, const char *method, unsigned int *rp_code)
238 {
239         struct MHD_Response *resp = NULL;
240
241         if (!strncmp(nurl, URL_BASE_API_1_0, strlen(URL_BASE_API_1_0))) {
242                 resp = create_response_api(nurl, method, rp_code);
243         } else {
244                 char *fpath = get_path(nurl, server_data.www_dir);
245
246                 resp = create_response_file(nurl, method, rp_code, fpath);
247
248                 free(fpath);
249         }
250
251         if (resp) {
252                 return resp;
253         } else {
254                 char *page = strdup(PAGE_NOT_FOUND);
255                 *rp_code = MHD_HTTP_NOT_FOUND;
256
257                 return MHD_create_response_from_data
258                         (strlen(page), page, MHD_YES, MHD_NO);
259         }
260 }
261
262 static int
263 cbk_http_request(void *cls,
264                  struct MHD_Connection *connection,
265                  const char *url,
266                  const char *method,
267                  const char *version,
268                  const char *upload_data,
269                  size_t *upload_data_size, void **ptr)
270 {
271         static int dummy;
272         struct MHD_Response *response;
273         int ret;
274         char *nurl;
275         unsigned int resp_code;
276
277         if (strcmp(method, "GET"))
278                 return MHD_NO;
279
280         if (&dummy != *ptr) {
281                 /* The first time only the headers are valid, do not
282                    respond in the first round... */
283                 *ptr = &dummy;
284                 return MHD_YES;
285         }
286
287         if (*upload_data_size)
288                 return MHD_NO;
289
290         *ptr = NULL;            /* clear context pointer */
291
292         if (debug)
293                 printf(_("HTTP Request: %s\n"), 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
316         program_name = argv[0];
317
318         setlocale(LC_ALL, "");
319
320 #if ENABLE_NLS
321         bindtextdomain(PACKAGE, LOCALEDIR);
322         textdomain(PACKAGE);
323 #endif
324
325         server_data.www_dir = DEFAULT_WWW_DIR;
326         server_data.psysinfo.interfaces = NULL;
327
328         while ((optc = getopt_long(argc, argv,
329                                    "vhp:w:d", long_options, NULL)) != -1) {
330                 switch (optc) {
331                 case 'w':
332                         if (optarg)
333                                 server_data.www_dir = strdup(optarg);
334                         break;
335                 case 'p':
336                         if (optarg)
337                                 port = atoi(optarg);
338                         break;
339                 case 'h':
340                         print_help();
341                         exit(EXIT_SUCCESS);
342                 case 'v':
343                         print_version();
344                         exit(EXIT_SUCCESS);
345                 case 'd':
346                         debug = 1;
347                         break;
348                 default:
349                         cmdok = 0;
350                         break;
351                 }
352         }
353
354         if (!cmdok || optind != argc) {
355                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
356                         program_name);
357                 exit(EXIT_FAILURE);
358         }
359
360         psensor_init();
361
362         server_data.sensors = get_all_sensors(600);
363
364 #ifdef HAVE_GTOP
365         server_data.cpu_usage = create_cpu_usage_sensor(600);
366 #endif
367
368         if (!*server_data.sensors)
369                 fprintf(stderr, _("ERROR: no sensors detected\n"));
370
371         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
372                              port,
373                              NULL, NULL, &cbk_http_request, server_data.sensors,
374                              MHD_OPTION_END);
375         if (!d) {
376                 fprintf(stderr, _("ERROR: Fail to create web server\n"));
377                 exit(EXIT_FAILURE);
378         }
379
380         log_printf(LOG_INFO, _("Web server started on port: %d"), port);
381         log_printf(LOG_INFO, _("WWW directory: %s"), server_data.www_dir);
382         log_printf(LOG_INFO, _("URL: http://localhost:%d"), port);
383
384         while (!server_stop_requested) {
385                 pthread_mutex_lock(&mutex);
386
387 #ifdef HAVE_GTOP
388                 sysinfo_update(&server_data.psysinfo);
389                 cpu_usage_sensor_update(server_data.cpu_usage);
390 #endif
391                 psensor_list_update_measures(server_data.sensors);
392
393                 pthread_mutex_unlock(&mutex);
394                 sleep(5);
395         }
396
397         MHD_stop_daemon(d);
398
399         /* sanity cleanup for valgrind */
400         psensor_list_free(server_data.sensors);
401 #ifdef HAVE_GTOP
402         psensor_free(server_data.cpu_usage);
403 #endif
404         free(server_data.www_dir);
405         sensors_cleanup();
406
407 #ifdef HAVE_GTOP
408         sysinfo_cleanup();
409         cpu_cleanup();
410 #endif
411
412         return EXIT_SUCCESS;
413 }