log_printf instead of printf
[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 #include "cpu.h"
42 #endif
43
44 #include "psensor_json.h"
45 #include "plib/url.h"
46 #include "plib/plib_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>\
55 </p></body>"))
56
57 static struct option long_options[] = {
58         {"version", no_argument, 0, 'v'},
59         {"help", no_argument, 0, 'h'},
60         {"port", required_argument, 0, 'p'},
61         {"wdir", required_argument, 0, 'w'},
62         {"debug", no_argument, 0, 'd'},
63         {0, 0, 0, 0}
64 };
65
66 static struct server_data server_data;
67
68 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
69
70 static int debug;
71
72 static int server_stop_requested;
73
74 void print_version()
75 {
76         printf("psensor-server %s\n", VERSION);
77         printf(_("Copyright (C) %s jeanfi@gmail.com\n\
78 License GPLv2: GNU GPL version 2 or later \
79 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n\
80 This is free software: you are free to change and redistribute it.\n\
81 There is NO WARRANTY, to the extent permitted by law.\n"),
82                "2010-2011");
83 }
84
85 void print_help()
86 {
87         printf(_("Usage: %s [OPTION]...\n"), program_name);
88
89         puts(_("psensor-server is an HTTP server "
90                "for monitoring hardware sensors remotely."));
91
92         puts("");
93         puts("Options:");
94         puts(_("\
95   -h, --help          display this help and exit\n\
96   -v, --version       display version information and exit"));
97
98         puts("");
99
100         puts(_("\
101   -d,--debug     run in debug mode\n\
102   -p,--port=PORT webserver port\n\
103   -w,--wdir=DIR  directory containing webserver pages"));
104
105         puts("");
106
107         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
108         puts("");
109         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
110 }
111
112 /*
113   Returns the file path corresponding to a given URL
114 */
115 char *get_path(const char *url, const char *www_dir)
116 {
117         const char *p;
118         char *res;
119
120         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
121                 p = "/index.html";
122         else
123                 p = url;
124
125         res = malloc(strlen(www_dir)+strlen(p)+1);
126
127         strcpy(res, www_dir);
128         strcat(res, p);
129
130         return res;
131 }
132
133 #if MHD_VERSION >= 0x00090200
134 static int
135 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
136 #else
137 static int
138 file_reader(void *cls, uint64_t pos, char *buf, int max)
139 #endif
140 {
141         FILE *file = cls;
142
143         fseek(file, pos, SEEK_SET);
144         return fread(buf, 1, max, file);
145 }
146
147 struct MHD_Response *
148 create_response_api(const char *nurl,
149                     const char *method,
150                     unsigned int *rp_code)
151 {
152         struct MHD_Response *resp;
153         struct psensor *s;
154         char *page = NULL;
155
156         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
157
158                 page = sensors_to_json_string(server_data.sensors);
159
160 #ifdef HAVE_GTOP
161         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
162
163                 page = sysinfo_to_json_string(&server_data.psysinfo);
164         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
165                 page = sensor_to_json_string(server_data.cpu_usage);
166 #endif
167         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
168                             strlen(URL_BASE_API_1_0_SENSORS))
169                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
170
171                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
172
173                 s = psensor_list_get_by_id(server_data.sensors, sid);
174
175                 if (s)
176                         page = sensor_to_json_string(s);
177
178         } else if (debug && !strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
179
180                 server_stop_requested = 1;
181                 page = strdup(_("<html><body><p>"
182                                 "Server stop requested</p></body></html>"));
183         }
184
185         if (page) {
186                 *rp_code = MHD_HTTP_OK;
187
188                 resp = MHD_create_response_from_data(strlen(page), page,
189                                                      MHD_YES, MHD_NO);
190
191                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
192                                         "application/json");
193
194                 return resp;
195         }
196
197         return NULL;
198 }
199
200 struct MHD_Response *
201 create_response_file(const char *nurl,
202                      const char *method,
203                      unsigned int *rp_code,
204                      const char *fpath)
205 {
206         if (is_file(fpath)) {
207                 FILE *file = fopen(fpath, "rb");
208
209                 if (file) {
210                         struct stat buf;
211
212                         stat(fpath, &buf);
213                         *rp_code = MHD_HTTP_OK;
214
215                         if (!buf.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                                 (buf.st_size,
223                                  32 * 1024,
224                                  &file_reader,
225                                  file,
226                                  (MHD_ContentReaderFreeCallback)&fclose);
227
228                 }
229         }
230
231         return NULL;
232 }
233
234 struct MHD_Response *
235 create_response(const char *nurl, const char *method, unsigned int *rp_code)
236 {
237         struct MHD_Response *resp = NULL;
238
239         if (!strncmp(nurl, URL_BASE_API_1_0, strlen(URL_BASE_API_1_0))) {
240                 resp = create_response_api(nurl, method, rp_code);
241         } else {
242                 char *fpath = get_path(nurl, server_data.www_dir);
243
244                 resp = create_response_file(nurl, method, rp_code, fpath);
245
246                 free(fpath);
247         }
248
249         if (resp) {
250                 return resp;
251         } else {
252                 char *page = strdup(PAGE_NOT_FOUND);
253                 *rp_code = MHD_HTTP_NOT_FOUND;
254
255                 return MHD_create_response_from_data
256                         (strlen(page), page, MHD_YES, MHD_NO);
257         }
258 }
259
260 static int
261 cbk_http_request(void *cls,
262                  struct MHD_Connection *connection,
263                  const char *url,
264                  const char *method,
265                  const char *version,
266                  const char *upload_data,
267                  size_t *upload_data_size, void **ptr)
268 {
269         static int dummy;
270         struct MHD_Response *response;
271         int ret;
272         char *nurl;
273         unsigned int resp_code;
274
275         if (strcmp(method, "GET"))
276                 return MHD_NO;
277
278         if (&dummy != *ptr) {
279                 /* The first time only the headers are valid, do not
280                    respond in the first round... */
281                 *ptr = &dummy;
282                 return MHD_YES;
283         }
284
285         if (*upload_data_size)
286                 return MHD_NO;
287
288         *ptr = NULL;            /* clear context pointer */
289
290         if (debug)
291                 printf(_("HTTP Request: %s\n"), url);
292
293         nurl = url_normalize(url);
294
295         pthread_mutex_lock(&mutex);
296         response = create_response(nurl, method, &resp_code);
297         pthread_mutex_unlock(&mutex);
298
299         ret = MHD_queue_response(connection, resp_code, response);
300         MHD_destroy_response(response);
301
302         free(nurl);
303
304         return ret;
305 }
306
307 int main(int argc, char *argv[])
308 {
309         struct MHD_Daemon *d;
310         int port = DEFAULT_PORT;
311         int optc;
312         int cmdok = 1;
313
314         program_name = argv[0];
315
316         setlocale(LC_ALL, "");
317
318 #if ENABLE_NLS
319         bindtextdomain(PACKAGE, LOCALEDIR);
320         textdomain(PACKAGE);
321 #endif
322
323         server_data.www_dir = DEFAULT_WWW_DIR;
324         server_data.psysinfo.interfaces = NULL;
325
326         while ((optc = getopt_long(argc, argv,
327                                    "vhp:w:d", long_options, NULL)) != -1) {
328                 switch (optc) {
329                 case 'w':
330                         if (optarg)
331                                 server_data.www_dir = strdup(optarg);
332                         break;
333                 case 'p':
334                         if (optarg)
335                                 port = atoi(optarg);
336                         break;
337                 case 'h':
338                         print_help();
339                         exit(EXIT_SUCCESS);
340                 case 'v':
341                         print_version();
342                         exit(EXIT_SUCCESS);
343                 case 'd':
344                         debug = 1;
345                         break;
346                 default:
347                         cmdok = 0;
348                         break;
349                 }
350         }
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 }