]> arthur.barton.de Git - netdata.git/blob - src/web_server.c
Merge pull request #539 from ktsaou/master
[netdata.git] / src / web_server.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <arpa/inet.h>
10 #include <errno.h>
11 #include <pthread.h>
12 #include <sys/stat.h>
13 #include <fcntl.h>
14 #include <netinet/tcp.h>
15 #include <malloc.h>
16 #include <poll.h>
17
18 #include "common.h"
19 #include "log.h"
20 #include "appconfig.h"
21 #include "url.h"
22 #include "web_buffer.h"
23 #include "web_client.h"
24 #include "web_server.h"
25 #include "global_statistics.h"
26 #include "rrd.h"
27 #include "rrd2json.h"
28 #include "../config.h"
29
30 int listen_backlog = LISTEN_BACKLOG;
31 int listen_fd = -1;
32 int listen_port = LISTEN_PORT;
33 int web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
34
35 #ifdef NETDATA_INTERNAL_CHECKS
36 static void log_allocations(void)
37 {
38         static int mem = 0;
39
40         struct mallinfo mi;
41
42         mi = mallinfo();
43         if(mi.uordblks > mem) {
44                 int clients = 0;
45                 struct web_client *w;
46                 for(w = web_clients; w ; w = w->next) clients++;
47
48                 info("Allocated memory increased from %d to %d (increased by %d bytes). There are %d web clients connected.", mem, mi.uordblks, mi.uordblks - mem, clients);
49                 mem = mi.uordblks;
50         }
51 }
52 #endif
53
54 #ifndef HAVE_ACCEPT4
55 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
56         int fd = accept(sock, addr, addrlen);
57         int newflags = 0;
58
59         if (fd < 0) return fd;
60
61         if (flags & SOCK_NONBLOCK) {
62                 newflags |= O_NONBLOCK;
63                 flags &= ~SOCK_NONBLOCK;
64         }
65
66         if (flags & SOCK_CLOEXEC) {
67                 newflags |= O_CLOEXEC;
68                 flags &= ~SOCK_CLOEXEC;
69         }
70
71         if (flags) {
72                 errno = -EINVAL;
73                 return -1;
74         }
75
76         if (fcntl(fd, F_SETFL, newflags) < 0) {
77                 int saved_errno = errno;
78                 close(fd);
79                 errno = saved_errno;
80                 return -1;
81         }
82
83         return fd;
84 }
85 #endif
86
87 static int is_ip_anything(const char *ip)
88 {
89         if(!ip || !*ip
90                         || !strcmp(ip, "any")
91                         || !strcmp(ip, "all")
92                         || !strcmp(ip, "*")
93                         || !strcmp(ip, "::")
94                         || !strcmp(ip, "0.0.0.0")
95                         ) return 1;
96
97         return 0;
98 }
99
100 int create_listen_socket4(const char *ip, int port, int listen_backlog)
101 {
102         int sock;
103         int sockopt = 1;
104
105         debug(D_LISTENER, "IPv4 creating new listening socket on port %d", port);
106
107         sock = socket(AF_INET, SOCK_STREAM, 0);
108         if(sock < 0) {
109                 error("IPv4 socket() failed.");
110                 return -1;
111         }
112
113         /* avoid "address already in use" */
114         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
115
116         struct sockaddr_in name;
117         memset(&name, 0, sizeof(struct sockaddr_in));
118         name.sin_family = AF_INET;
119         name.sin_port = htons (port);
120
121         if(is_ip_anything(ip)) {
122                 name.sin_addr.s_addr = htonl(INADDR_ANY);
123                 // info("Listening on any IPs (IPv4).");
124         }
125         else {
126                 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
127                 if(ret != 1) {
128                         error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
129                         close(sock);
130                         return -1;
131                 }
132                 // info("Listening on IP '%s' (IPv4).", ip);
133         }
134
135         if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
136                 close(sock);
137                 error("IPv4 bind() failed.");
138                 return -1;
139         }
140
141         if(listen(sock, listen_backlog) < 0) {
142                 close(sock);
143                 fatal("IPv4 listen() failed.");
144                 return -1;
145         }
146
147         debug(D_LISTENER, "IPv4 listening port %d created", port);
148         return sock;
149 }
150
151 int create_listen_socket6(const char *ip, int port, int listen_backlog)
152 {
153         int sock = -1;
154         int sockopt = 1;
155
156         debug(D_LISTENER, "IPv6 creating new listening socket on port %d", port);
157
158         sock = socket(AF_INET6, SOCK_STREAM, 0);
159         if (sock < 0) {
160                 error("IPv6 socket() failed. Disabling IPv6.");
161                 return -1;
162         }
163
164         /* avoid "address already in use" */
165         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
166
167         struct sockaddr_in6 name;
168         memset(&name, 0, sizeof(struct sockaddr_in6));
169         name.sin6_family = AF_INET6;
170         name.sin6_port = htons ((uint16_t) port);
171
172         if(is_ip_anything(ip)) {
173                 name.sin6_addr = in6addr_any;
174                 // info("Listening on all IPs (IPv6 and IPv4)");
175         }
176         else {
177                 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
178                 if(ret != 1) {
179                         error("Failed to convert IP '%s' to a valid IPv6 address. Disabling IPv6.", ip);
180                         close(sock);
181                         return -1;
182                 }
183                 // info("Listening on IP '%s' (IPv6)", ip);
184         }
185
186         name.sin6_scope_id = 0;
187
188         if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
189                 close(sock);
190                 error("IPv6 bind() failed. Disabling IPv6.");
191                 return -1;
192         }
193
194         if (listen(sock, listen_backlog) < 0) {
195                 close(sock);
196                 error("IPv6 listen() failed. Disabling IPv6.");
197                 return -1;
198         }
199
200         debug(D_LISTENER, "IPv6 listening port %d created", port);
201         return sock;
202 }
203
204
205 int create_listen_socket(void) {
206         listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
207
208         listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
209         if(listen_port < 1 || listen_port > 65535) {
210                 error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
211                 listen_port = LISTEN_PORT;
212         }
213         else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
214
215         int ip = 0;
216         char *ipv = config_get("global", "ip version", "any");
217         if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
218         else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
219         else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
220         else error("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
221
222         if(ip == 0 || ip == 6)
223                 listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
224
225         if(listen_fd == -1) {
226                 listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
227                 //if(listen_fd != -1 && ip != 4)
228                 //      info("Managed to open an IPv4 socket on port %d.", listen_port);
229         }
230
231         return listen_fd;
232 }
233
234 // --------------------------------------------------------------------------------------
235 // the main socket listener
236
237 // 1. it accepts new incoming requests on our port
238 // 2. creates a new web_client for each connection received
239 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
240 // 4. cleans up old web_clients that their pthreads have been exited
241
242 #define CLEANUP_EVERY_EVENTS 100
243
244 void *socket_listen_main_multi_threaded(void *ptr) {
245         (void)ptr;
246
247         web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
248         info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
249
250         struct web_client *w;
251         int retval, failures = 0, counter = 0;
252
253         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
254                 error("Cannot set pthread cancel type to DEFERRED.");
255
256         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
257                 error("Cannot set pthread cancel state to ENABLE.");
258
259         if(listen_fd < 0)
260                 fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fd);
261
262         for(;;) {
263                 struct pollfd fd = { .fd = listen_fd, .events = POLLIN, .revents = 0 };
264                 int timeout = 10 * 1000;
265
266                 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
267                 retval = poll(&fd, 1, timeout);
268
269                 if(unlikely(retval == -1)) {
270                         debug(D_WEB_CLIENT, "LISTENER: poll() failed.");
271                         failures++;
272
273                         if(failures > 10) {
274                                 error("LISTENER: our listen port %d seems dead. Re-opening it.", listen_fd);
275                                 close(listen_fd);
276                                 listen_fd = -1;
277                                 sleep(5);
278                                 create_listen_socket();
279                                 if(listen_fd < 0)
280                                         fatal("Cannot listen for web clients (connected clients %lu).", global_statistics.connected_clients);
281
282                                 failures = 0;
283                         }
284
285                         continue;
286                 }
287                 else if(likely(retval)) {
288                         // check for new incoming connections
289                         if(fd.revents & POLLIN || fd.revents & POLLPRI) {
290                                 w = web_client_create(listen_fd);
291                                 if(unlikely(!w)) {
292                                         // no need for error log - web_client_create already logged the error
293                                         continue;
294                                 }
295
296                                 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
297                                         error("%llu: failed to create new thread for web client.", w->id);
298                                         w->obsolete = 1;
299                                 }
300                                 else if(pthread_detach(w->thread) != 0) {
301                                         error("%llu: Cannot request detach of newly created web client thread.", w->id);
302                                         w->obsolete = 1;
303                                 }
304                         }
305                         else {
306                                 failures++;
307                                 debug(D_WEB_CLIENT, "LISTENER: select() didn't do anything.");
308                                 continue;
309                         }
310                 }
311                 else {
312                         debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
313                         counter = CLEANUP_EVERY_EVENTS;
314                 }
315
316                 // cleanup unused clients
317                 counter++;
318                 if(counter > CLEANUP_EVERY_EVENTS) {
319                         counter = 0;
320                         for (w = web_clients; w;) {
321                                 if (w->obsolete) {
322                                         debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
323                                         // pthread_cancel(w->thread);
324                                         // pthread_join(w->thread, NULL);
325                                         w = web_client_free(w);
326 #ifdef NETDATA_INTERNAL_CHECKS
327                                         log_allocations();
328 #endif
329                                 }
330                                 else w = w->next;
331                         }
332                 }
333
334                 failures = 0;
335         }
336
337         debug(D_WEB_CLIENT, "LISTENER: exit!");
338         close(listen_fd);
339         listen_fd = -1;
340         return NULL;
341 }
342
343 struct web_client *single_threaded_clients[FD_SETSIZE];
344
345 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
346         if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
347                 return 1;
348
349         if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
350                 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
351                 return 1;
352         }
353
354         FD_SET(w->ifd, efds);
355         if(unlikely(*max < w->ifd)) *max = w->ifd;
356
357         if(unlikely(w->ifd != w->ofd)) {
358                 if(*max < w->ofd) *max = w->ofd;
359                 FD_SET(w->ofd, efds);
360         }
361
362         if(w->wait_receive) FD_SET(w->ifd, ifds);
363         if(w->wait_send)    FD_SET(w->ofd, ofds);
364
365         single_threaded_clients[w->ifd] = w;
366         single_threaded_clients[w->ofd] = w;
367
368         return 0;
369 }
370
371 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
372         FD_CLR(w->ifd, efds);
373         if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
374
375         if(w->wait_receive) FD_CLR(w->ifd, ifds);
376         if(w->wait_send)    FD_CLR(w->ofd, ofds);
377
378         single_threaded_clients[w->ifd] = NULL;
379         single_threaded_clients[w->ofd] = NULL;
380
381         if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
382                 return 1;
383
384         return 0;
385 }
386
387 void *socket_listen_main_single_threaded(void *ptr) {
388         (void)ptr;
389
390         web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
391
392         info("Single threaded WEB SERVER thread created with task id %d", gettid());
393
394         struct web_client *w;
395         int retval, failures = 0;
396
397         if(ptr) { ; }
398
399         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
400                 error("Cannot set pthread cancel type to DEFERRED.");
401
402         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
403                 error("Cannot set pthread cancel state to ENABLE.");
404
405         if(listen_fd < 0 || listen_fd >= FD_SETSIZE)
406                 fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fd);
407
408         int i;
409         for(i = 0; i < FD_SETSIZE ; i++)
410                 single_threaded_clients[i] = NULL;
411
412         fd_set ifds, ofds, efds, rifds, rofds, refds;
413         FD_ZERO (&ifds);
414         FD_ZERO (&ofds);
415         FD_ZERO (&efds);
416         FD_SET(listen_fd, &ifds);
417         FD_SET(listen_fd, &efds);
418         int fdmax = listen_fd;
419
420         for(;;) {
421                 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (listen fd = %d, fdmax = %d)...", listen_fd, fdmax);
422
423                 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
424                 rifds = ifds;
425                 rofds = ofds;
426                 refds = efds;
427                 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
428
429                 if(unlikely(retval == -1)) {
430                         debug(D_WEB_CLIENT, "LISTENER: select() failed.");
431                         failures++;
432                         if(failures > 10) {
433                                 if(global_statistics.connected_clients) {
434                                         error("REMOVING ALL %lu WEB CLIENTS !", global_statistics.connected_clients);
435                                         while (web_clients) {
436                                                 single_threaded_unlink_client(web_clients, &ifds, &ofds, &efds);
437                                                 web_client_free(web_clients);
438                                         }
439                                 }
440
441                                 error("LISTENER: our listen port %d seems dead. Re-opening it.", listen_fd);
442
443                                 close(listen_fd);
444                                 listen_fd = -1;
445                                 sleep(5);
446
447                                 create_listen_socket();
448                                 if(listen_fd < 0 || listen_fd >= FD_SETSIZE)
449                                         fatal("Cannot listen for web clients (connected clients %lu).", global_statistics.connected_clients);
450
451                                 FD_ZERO (&ifds);
452                                 FD_ZERO (&ofds);
453                                 FD_ZERO (&efds);
454                                 FD_SET(listen_fd, &ifds);
455                                 FD_SET(listen_fd, &efds);
456                                 failures = 0;
457                         }
458                 }
459                 else if(likely(retval)) {
460                         failures = 0;
461                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
462
463                         if(FD_ISSET(listen_fd, &rifds)) {
464                                 debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
465                                 w = web_client_create(listen_fd);
466                                 if(single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
467                                         web_client_free(w);
468                                 }
469                         }
470
471                         for(i = 0 ; i <= fdmax ; i++) {
472                                 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
473                                         continue;
474
475                                 w = single_threaded_clients[i];
476                                 if(unlikely(!w))
477                                         continue;
478
479                                 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
480                                         web_client_free(w);
481                                         continue;
482                                 }
483
484                                 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
485                                         web_client_free(w);
486                                         continue;
487                                 }
488
489                                 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
490                                         if (unlikely(web_client_receive(w) < 0)) {
491                                                 web_client_free(w);
492                                                 continue;
493                                         }
494
495                                         if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
496                                                 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
497                                                 web_client_process(w);
498                                         }
499                                 }
500
501                                 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
502                                         if (unlikely(web_client_send(w) < 0)) {
503                                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
504                                                 web_client_free(w);
505                                                 continue;
506                                         }
507                                 }
508
509                                 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
510                                         web_client_free(w);
511                                 }
512                         }
513                 }
514                 else {
515                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
516 #ifdef NETDATA_INTERNAL_CHECKS
517                         log_allocations();
518 #endif
519                 }
520         }
521
522         debug(D_WEB_CLIENT, "LISTENER: exit!");
523         close(listen_fd);
524         listen_fd = -1;
525         return NULL;
526 }