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