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