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