(no commit message)
[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/types.h>
30 #include <sys/select.h>
31 #include <sys/socket.h>
32 #include <getopt.h>
33 #include <stdint.h>
34 #include <pthread.h>
35 #include <unistd.h>
36 #include <microhttpd.h>
37
38 #ifdef HAVE_GTOP
39 #include "sysinfo.h"
40 #endif
41
42 #ifdef HAVE_LUA
43 #include "server_lua.h"
44 #endif
45
46 #include "psensor_json.h"
47 #include "plib/url.h"
48 #include "plib/plib_io.h"
49 #include "server.h"
50
51 static const char *program_name;
52
53 #define DEFAULT_PORT 3131
54
55 #define PAGE_NOT_FOUND \
56 "<html><body><p>Page not found - Go to <a href='/index.lua'>Main page</a>\
57 </p></body>"
58
59 static struct option long_options[] = {
60         {"version", no_argument, 0, 'v'},
61         {"help", no_argument, 0, 'h'},
62         {"port", required_argument, 0, 'p'},
63         {"wdir", required_argument, 0, 'w'},
64         {0, 0, 0, 0}
65 };
66
67 static struct server_data server_data;
68
69 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
70
71 void print_version()
72 {
73         printf("psensor-server %s\n", VERSION);
74         printf(_("Copyright (C) %s wpitchoune@gmail.com\n\
75 License GPLv2: GNU GPL version 2 or later \
76 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n\
77 This is free software: you are free to change and redistribute it.\n\
78 There is NO WARRANTY, to the extent permitted by law.\n"),
79                "2010-2011");
80 }
81
82 void print_help()
83 {
84         printf(_("Usage: %s [OPTION]...\n"), program_name);
85
86         puts(_("psensor-server is an HTTP server "
87                "for monitoring hardware sensors remotely."));
88
89         puts("");
90         puts("Options:");
91         puts(_("\
92   -h, --help          display this help and exit\n\
93   -v, --version       display version information and exit"));
94
95         puts("");
96
97         puts(_("\
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 '1' if the path denotates a Lua file, otherwise returns 0.
110  */
111 int is_path_lua(const char *path)
112 {
113         char *dot = rindex(path, '.');
114
115         if (dot && !strcasecmp(dot, ".lua"))
116                 return 1;
117
118         return 0;
119 }
120
121 /*
122   Returns the file path corresponding to a given URL
123 */
124 char *get_path(const char *url, const char *www_dir)
125 {
126         const char *p;
127         char *res;
128
129         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
130                 p = "/index.lua";
131         else
132                 p = url;
133
134         res = malloc(strlen(www_dir)+strlen(p)+1);
135
136         strcpy(res, www_dir);
137         strcat(res, p);
138
139         return res;
140 }
141
142 static int cbk_http_request(void *cls,
143                             struct MHD_Connection *connection,
144                             const char *url,
145                             const char *method,
146                             const char *version,
147                             const char *upload_data,
148                             size_t *upload_data_size, void **ptr)
149 {
150         static int dummy;
151         struct MHD_Response *response;
152         int ret;
153         char *nurl;
154         unsigned int resp_code;
155         char *page = NULL;
156
157         if (strcmp(method, "GET"))
158                 return MHD_NO;  /* unexpected method */
159
160         if (&dummy != *ptr) {
161                 /* The first time only the headers are valid, do not
162                    respond in the first round... */
163                 *ptr = &dummy;
164                 return MHD_YES;
165         }
166
167         if (*upload_data_size)
168                 return MHD_NO;  /* upload data in a GET!? */
169
170         *ptr = NULL;            /* clear context pointer */
171
172         nurl = url_normalize(url);
173
174         pthread_mutex_lock(&mutex);
175
176         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS)) {
177                 page = sensors_to_json_string(server_data.sensors);
178
179         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
180                             strlen(URL_BASE_API_1_0_SENSORS))
181                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
182
183                 char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
184                 struct psensor *s
185                         = psensor_list_get_by_id(server_data.sensors, sid);
186
187                 if (s)
188                         page = sensor_to_json_string(s);
189
190         } else {
191                 char *fpath = get_path(nurl, server_data.www_dir);
192                 int n = strlen(nurl);
193
194                 if (is_path_lua(fpath)) {
195 #if HAVE_LUA
196                         page = lua_to_html_page(&server_data, fpath);
197 #else
198                         page = strdup(_("ERROR: Lua support not enabled\n"));
199 #endif
200                 } else {
201                         page = file_get_content(fpath);
202                 }
203
204                 free(fpath);
205         }
206
207         if (page) {
208                 resp_code = MHD_HTTP_OK;
209         } else {
210                 page = strdup(PAGE_NOT_FOUND);
211                 resp_code = MHD_HTTP_NOT_FOUND;
212         }
213
214         pthread_mutex_unlock(&mutex);
215
216         response = MHD_create_response_from_data(strlen(page),
217                                                  (void *)page, MHD_YES, MHD_NO);
218
219         ret = MHD_queue_response(connection, resp_code, response);
220         MHD_destroy_response(response);
221
222         free(nurl);
223
224         return ret;
225 }
226
227 int main(int argc, char *argv[])
228 {
229         struct MHD_Daemon *d;
230         int port = DEFAULT_PORT;
231         int optc;
232         int cmdok = 1;
233
234         program_name = argv[0];
235
236         setlocale(LC_ALL, "");
237
238 #if ENABLE_NLS
239         bindtextdomain(PACKAGE, LOCALEDIR);
240         textdomain(PACKAGE);
241 #endif
242
243         server_data.www_dir = DEFAULT_WWW_DIR;
244
245         while ((optc = getopt_long(argc, argv,
246                                    "vhp:w:", long_options, NULL)) != -1) {
247                 switch (optc) {
248                 case 'w':
249                         if (optarg)
250                                 server_data.www_dir = strdup(optarg);
251                         break;
252                 case 'p':
253                         if (optarg)
254                                 port = atoi(optarg);
255                         break;
256                 case 'h':
257                         print_help();
258                         exit(EXIT_SUCCESS);
259                 case 'v':
260                         print_version();
261                         exit(EXIT_SUCCESS);
262                 default:
263                         cmdok = 0;
264                         break;
265                 }
266         }
267
268         if (!cmdok || optind != argc) {
269                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
270                         program_name);
271                 exit(EXIT_FAILURE);
272         }
273
274         if (!lmsensor_init()) {
275                 fprintf(stderr, _("ERROR: failed to init lm-sensors\n"));
276                 exit(EXIT_FAILURE);
277         }
278
279         server_data.sensors = get_all_sensors(1);
280
281         if (!*server_data.sensors)
282                 fprintf(stderr, _("ERROR: no sensors detected\n"));
283
284         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
285                              port,
286                              NULL, NULL, &cbk_http_request, server_data.sensors,
287                              MHD_OPTION_END);
288         if (!d) {
289                 fprintf(stderr, _("ERROR: Fail to create web server\n"));
290                 exit(EXIT_FAILURE);
291         }
292
293         printf(_("Web server started on port: %d\n"), port);
294         printf(_("WWW directory: %s\n"), server_data.www_dir);
295         printf(_("URL: http://localhost:%d\n"), port);
296
297         while (1) {
298                 pthread_mutex_lock(&mutex);
299
300 #ifdef HAVE_GTOP
301                 sysinfo_update(&server_data.cpu_rate);
302 #endif
303                 psensor_list_update_measures(server_data.sensors);
304
305                 pthread_mutex_unlock(&mutex);
306                 sleep(5);
307         }
308
309         MHD_stop_daemon(d);
310
311         return 0;
312 }