removed lua support, monitoring page is now using jquery and json http requests
[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 modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU 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 #endif
42
43 #include "psensor_json.h"
44 #include "plib/url.h"
45 #include "plib/plib_io.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>\
54 </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(_("\
94   -h, --help          display this help and exit\n\
95   -v, --version       display version information and exit"));
96
97         puts("");
98
99         puts(_("\
100   -d,--debug     run in debug mode\n\
101   -p,--port=PORT webserver port\n\
102   -w,--wdir=DIR  directory containing webserver pages"));
103
104         puts("");
105
106         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
107         puts("");
108         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
109 }
110
111 /*
112   Returns the file path corresponding to a given URL
113 */
114 char *get_path(const char *url, const char *www_dir)
115 {
116         const char *p;
117         char *res;
118
119         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
120                 p = "/index.html";
121         else
122                 p = url;
123
124         res = malloc(strlen(www_dir)+strlen(p)+1);
125
126         strcpy(res, www_dir);
127         strcat(res, p);
128
129         return res;
130 }
131
132 static int
133 file_reader(void *cls, uint64_t pos, char *buf, int max)
134 {
135         FILE *file = cls;
136
137         fseek(file, pos, SEEK_SET);
138         return fread(buf, 1, max, file);
139 }
140
141 struct MHD_Response *
142 create_response_api(const char *nurl,
143                     const char *method,
144                     unsigned int *rp_code)
145 {
146         struct MHD_Response *resp;
147         struct psensor *s;
148         char *page = NULL;
149
150         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
151
152                 page = sensors_to_json_string(server_data.sensors);
153
154 #ifdef HAVE_GTOP
155         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
156
157                 page = sysinfo_to_json_string(&server_data.psysinfo);
158 #endif
159         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
160                             strlen(URL_BASE_API_1_0_SENSORS))
161                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
162
163                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
164
165                 s = psensor_list_get_by_id(server_data.sensors, sid);
166
167                 if (s)
168                         page = sensor_to_json_string(s);
169
170         } else if (debug && !strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
171
172                 server_stop_requested = 1;
173                 page = strdup(_("<html><body><p>"
174                                 "Server stop requested</p></body></html>"));
175         }
176
177         if (page) {
178                 *rp_code = MHD_HTTP_OK;
179
180                 resp = MHD_create_response_from_data(strlen(page), page,
181                                                      MHD_YES, MHD_NO);
182
183                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
184                                         "application/json");
185
186                 return resp;
187         }
188
189         return NULL;
190 }
191
192 struct MHD_Response *
193 create_response_file(const char *nurl,
194                      const char *method,
195                      unsigned int *rp_code,
196                      const char *fpath)
197 {
198         if (is_file(fpath)) {
199                 FILE *file = fopen(fpath, "rb");
200
201                 if (file) {
202                         struct stat buf;
203
204                         stat(fpath, &buf);
205                         *rp_code = MHD_HTTP_OK;
206
207                         if (!buf.st_size) {
208                                 fclose(file);
209                                 return MHD_create_response_from_data
210                                         (0, NULL, MHD_NO, MHD_NO);
211                         }
212
213                         return MHD_create_response_from_callback
214                                 (buf.st_size,
215                                  32 * 1024,
216                                  &file_reader,
217                                  file,
218                                  (MHD_ContentReaderFreeCallback)&fclose);
219
220                 }
221         }
222
223         return NULL;
224 }
225
226 struct MHD_Response *
227 create_response(const char *nurl, const char *method, unsigned int *rp_code)
228 {
229         struct MHD_Response *resp = NULL;
230
231         if (!strncmp(nurl, URL_BASE_API_1_0, strlen(URL_BASE_API_1_0))) {
232                 resp = create_response_api(nurl, method, rp_code);
233         } else {
234                 char *fpath = get_path(nurl, server_data.www_dir);
235
236                 resp = create_response_file(nurl, method, rp_code, fpath);
237
238                 free(fpath);
239         }
240
241         if (resp) {
242                 return resp;
243         } else {
244                 char *page = strdup(PAGE_NOT_FOUND);
245                 *rp_code = MHD_HTTP_NOT_FOUND;
246
247                 return MHD_create_response_from_data
248                         (strlen(page), page, MHD_YES, MHD_NO);
249         }
250 }
251
252 static int
253 cbk_http_request(void *cls,
254                  struct MHD_Connection *connection,
255                  const char *url,
256                  const char *method,
257                  const char *version,
258                  const char *upload_data,
259                  size_t *upload_data_size, void **ptr)
260 {
261         static int dummy;
262         struct MHD_Response *response;
263         int ret;
264         char *nurl;
265         unsigned int resp_code;
266         char *page = NULL;
267
268         if (strcmp(method, "GET"))
269                 return MHD_NO;
270
271         if (&dummy != *ptr) {
272                 /* The first time only the headers are valid, do not
273                    respond in the first round... */
274                 *ptr = &dummy;
275                 return MHD_YES;
276         }
277
278         if (*upload_data_size)
279                 return MHD_NO;
280
281         *ptr = NULL;            /* clear context pointer */
282
283         if (debug)
284                 printf(_("HTTP Request: %s\n"), url);
285
286         nurl = url_normalize(url);
287
288         pthread_mutex_lock(&mutex);
289         response = create_response(nurl, method, &resp_code);
290         pthread_mutex_unlock(&mutex);
291
292         ret = MHD_queue_response(connection, resp_code, response);
293         MHD_destroy_response(response);
294
295         free(nurl);
296
297         return ret;
298 }
299
300 int main(int argc, char *argv[])
301 {
302         struct MHD_Daemon *d;
303         int port = DEFAULT_PORT;
304         int optc;
305         int cmdok = 1;
306
307         program_name = argv[0];
308
309         setlocale(LC_ALL, "");
310
311 #if ENABLE_NLS
312         bindtextdomain(PACKAGE, LOCALEDIR);
313         textdomain(PACKAGE);
314 #endif
315
316         server_data.www_dir = DEFAULT_WWW_DIR;
317         server_data.psysinfo.interfaces = NULL;
318
319         while ((optc = getopt_long(argc, argv,
320                                    "vhp:w:d", long_options, NULL)) != -1) {
321                 switch (optc) {
322                 case 'w':
323                         if (optarg)
324                                 server_data.www_dir = strdup(optarg);
325                         break;
326                 case 'p':
327                         if (optarg)
328                                 port = atoi(optarg);
329                         break;
330                 case 'h':
331                         print_help();
332                         exit(EXIT_SUCCESS);
333                 case 'v':
334                         print_version();
335                         exit(EXIT_SUCCESS);
336                 case 'd':
337                         debug = 1;
338                         break;
339                 default:
340                         cmdok = 0;
341                         break;
342                 }
343         }
344
345         if (!cmdok || optind != argc) {
346                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
347                         program_name);
348                 exit(EXIT_FAILURE);
349         }
350
351         if (!lmsensor_init()) {
352                 fprintf(stderr, _("ERROR: failed to init lm-sensors\n"));
353                 exit(EXIT_FAILURE);
354         }
355
356         server_data.sensors = get_all_sensors(1);
357
358         if (!*server_data.sensors)
359                 fprintf(stderr, _("ERROR: no sensors detected\n"));
360
361         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
362                              port,
363                              NULL, NULL, &cbk_http_request, server_data.sensors,
364                              MHD_OPTION_END);
365         if (!d) {
366                 fprintf(stderr, _("ERROR: Fail to create web server\n"));
367                 exit(EXIT_FAILURE);
368         }
369
370         printf(_("Web server started on port: %d\n"), port);
371         printf(_("WWW directory: %s\n"), server_data.www_dir);
372         printf(_("URL: http://localhost:%d\n"), port);
373
374         while (!server_stop_requested) {
375                 pthread_mutex_lock(&mutex);
376
377 #ifdef HAVE_GTOP
378                 sysinfo_update(&server_data.psysinfo);
379 #endif
380                 psensor_list_update_measures(server_data.sensors);
381
382                 pthread_mutex_unlock(&mutex);
383                 sleep(5);
384         }
385
386         MHD_stop_daemon(d);
387
388         /* sanity cleanup for valgrind */
389         psensor_list_free(server_data.sensors);
390         free(server_data.www_dir);
391         sensors_cleanup();
392
393 #ifdef HAVE_GTOP
394         sysinfo_cleanup();
395 #endif
396
397         return EXIT_SUCCESS;
398 }