]> arthur.barton.de Git - netdata.git/blob - src/web_server.c
netdata can now bind to multiple ip:port combinations; hostnames and ips but also...
[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 #include <ctype.h>
18
19 #include "common.h"
20 #include "log.h"
21 #include "appconfig.h"
22 #include "url.h"
23 #include "web_buffer.h"
24 #include "web_client.h"
25 #include "web_server.h"
26 #include "global_statistics.h"
27 #include "rrd.h"
28 #include "rrd2json.h"
29 #include "../config.h"
30
31 int listen_backlog = LISTEN_BACKLOG;
32 int listen_fds_count = 0;
33 int listen_fds[MAX_LISTEN_FDS] = { [0 ... 99] = -1 };
34 int listen_port = LISTEN_PORT;
35 int web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
36
37 #ifdef NETDATA_INTERNAL_CHECKS
38 static void log_allocations(void)
39 {
40         static int mem = 0;
41
42         struct mallinfo mi;
43
44         mi = mallinfo();
45         if(mi.uordblks > mem) {
46                 int clients = 0;
47                 struct web_client *w;
48                 for(w = web_clients; w ; w = w->next) clients++;
49
50                 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);
51                 mem = mi.uordblks;
52         }
53 }
54 #endif
55
56 #ifndef HAVE_ACCEPT4
57 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
58         int fd = accept(sock, addr, addrlen);
59         int newflags = 0;
60
61         if (fd < 0) return fd;
62
63         if (flags & SOCK_NONBLOCK) {
64                 newflags |= O_NONBLOCK;
65                 flags &= ~SOCK_NONBLOCK;
66         }
67
68         if (flags & SOCK_CLOEXEC) {
69                 newflags |= O_CLOEXEC;
70                 flags &= ~SOCK_CLOEXEC;
71         }
72
73         if (flags) {
74                 errno = -EINVAL;
75                 return -1;
76         }
77
78         if (fcntl(fd, F_SETFL, newflags) < 0) {
79                 int saved_errno = errno;
80                 close(fd);
81                 errno = saved_errno;
82                 return -1;
83         }
84
85         return fd;
86 }
87 #endif
88
89 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
90         int sock;
91         int sockopt = 1;
92
93         debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
94
95         sock = socket(AF_INET, SOCK_STREAM, 0);
96         if(sock < 0) {
97                 error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
98                 return -1;
99         }
100
101         /* avoid "address already in use" */
102         if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
103                 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
104
105         struct sockaddr_in name;
106         memset(&name, 0, sizeof(struct sockaddr_in));
107         name.sin_family = AF_INET;
108         name.sin_port = htons (port);
109
110     int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
111     if(ret != 1) {
112         error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
113         close(sock);
114         return -1;
115     }
116
117         if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
118                 close(sock);
119                 error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
120                 return -1;
121         }
122
123         if(listen(sock, listen_backlog) < 0) {
124                 close(sock);
125                 fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
126                 return -1;
127         }
128
129         debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
130         return sock;
131 }
132
133 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
134         int sock = -1;
135         int sockopt = 1;
136     int ipv6only = 1;
137
138         debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
139
140         sock = socket(AF_INET6, SOCK_STREAM, 0);
141         if (sock < 0) {
142                 error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
143                 return -1;
144         }
145
146     /* avoid "address already in use" */
147     if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
148         error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
149
150     /* IPv6 only */
151     if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
152         error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
153
154     struct sockaddr_in6 name;
155         memset(&name, 0, sizeof(struct sockaddr_in6));
156         name.sin6_family = AF_INET6;
157         name.sin6_port = htons ((uint16_t) port);
158
159     int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
160     if(ret != 1) {
161         error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
162         close(sock);
163         return -1;
164     }
165
166         name.sin6_scope_id = 0;
167
168         if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
169                 close(sock);
170                 error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
171                 return -1;
172         }
173
174         if (listen(sock, listen_backlog) < 0) {
175                 close(sock);
176                 error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
177                 return -1;
178         }
179
180         debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
181         return sock;
182 }
183
184 static inline int add_listen_socket(int fd) {
185     if(listen_fds_count >= MAX_LISTEN_FDS)
186         return -1;
187
188     listen_fds[listen_fds_count++] = fd;
189
190     return 0;
191 }
192
193 int is_listen_socket(int fd) {
194     int i;
195     for(i = 0; i < listen_fds_count ;i++)
196         if(listen_fds[i] == fd) return 1;
197
198     return 0;
199 }
200
201 static inline void close_listen_sockets(void) {
202     int i;
203     for(i = 0; i < listen_fds_count ;i++)
204         close(listen_fds[i]);
205     listen_fds_count = 0;
206 }
207
208 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
209     int added = 0;
210     struct addrinfo hints;
211     struct addrinfo *result, *rp;
212
213     char buffer[strlen(definition) + 1];
214     strcpy(buffer, definition);
215
216     char buffer2[10 + 1];
217     snprintfz(buffer2, 10, "%d", default_port);
218
219     char *ip = buffer, *port = buffer2;
220
221     char *e = ip;
222     if(*e == '[') {
223         e = ++ip;
224         while(*e && *e != ']') e++;
225         if(*e == ']') {
226             *e = '\0';
227             e++;
228         }
229     }
230     else {
231         while(*e && *e != ':') e++;
232     }
233
234     if(*e == ':') {
235         port = e + 1;
236         *e = '\0';
237     }
238
239     if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
240         ip = NULL;
241     if(!*port)
242         port = buffer2;
243
244     memset(&hints, 0, sizeof(struct addrinfo));
245     hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
246     hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
247     hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
248     hints.ai_protocol = 0;          /* Any protocol */
249     hints.ai_canonname = NULL;
250     hints.ai_addr = NULL;
251     hints.ai_next = NULL;
252
253     int r = getaddrinfo(ip, port, &hints, &result);
254     if (r != 0) {
255         error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
256         return -1;
257     }
258
259     for (rp = result; rp != NULL; rp = rp->ai_next) {
260         int fd = -1;
261
262         char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
263         switch (rp->ai_addr->sa_family) {
264             case AF_INET: {
265                 struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
266                 inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
267                 fd = create_listen_socket4(rip, ntohs(sin->sin_port), listen_backlog);
268                 break;
269             }
270
271             case AF_INET6: {
272                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
273                 inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
274                 fd = create_listen_socket6(rip, ntohs(sin6->sin6_port), listen_backlog);
275                 break;
276             }
277         }
278
279         if (fd == -1)
280             error("Cannot bind to ip '%s', port %d", rip, default_port);
281         else {
282             add_listen_socket(fd);
283             added++;
284         }
285     }
286
287     return added;
288 }
289
290 int create_listen_sockets(void) {
291         listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
292
293     if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
294         config_rename("global", "bind socket to IP", "bind to");
295
296     if(config_exists("global", "port") && !config_exists("global", "default port"))
297         config_rename("global", "port", "default port");
298
299     listen_port = (int) config_get_number("global", "default port", LISTEN_PORT);
300         if(listen_port < 1 || listen_port > 65535) {
301                 error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
302         listen_port = (int) config_set_number("global", "default port", LISTEN_PORT);
303         }
304         debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
305
306     char *s = config_get("global", "bind to", "*");
307     while(*s) {
308         char *e = s;
309
310         // skip separators, moving both s(tart) and e(nd)
311         while(isspace(*e) || *e == ',') s = ++e;
312
313         // move e(nd) to the first separator
314         while(*e && !isspace(*e) && *e != ',') e++;
315
316         // is there anything?
317         if(!*s || s == e) break;
318
319         char buf[e - s + 1];
320         strncpyz(buf, s, e - s);
321         bind_to_one(buf, listen_port, listen_backlog);
322
323         s = e;
324     }
325
326     if(!listen_fds_count)
327         fatal("Cannot listen on any socket. Exiting...");
328
329         return listen_fds_count;
330 }
331
332 // --------------------------------------------------------------------------------------
333 // the main socket listener
334
335 static inline void cleanup_web_clients(void) {
336         struct web_client *w;
337
338         for (w = web_clients; w;) {
339                 if (w->obsolete) {
340                         debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
341                         // pthread_cancel(w->thread);
342                         // pthread_join(w->thread, NULL);
343                         w = web_client_free(w);
344 #ifdef NETDATA_INTERNAL_CHECKS
345                         log_allocations();
346 #endif
347                 }
348                 else w = w->next;
349         }
350 }
351
352 // 1. it accepts new incoming requests on our port
353 // 2. creates a new web_client for each connection received
354 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
355 // 4. cleans up old web_clients that their pthreads have been exited
356
357 #define CLEANUP_EVERY_EVENTS 100
358
359 void *socket_listen_main_multi_threaded(void *ptr) {
360         (void)ptr;
361
362         web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
363         info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
364
365         struct web_client *w;
366         int retval, counter = 0;
367
368         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
369                 error("Cannot set pthread cancel type to DEFERRED.");
370
371         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
372                 error("Cannot set pthread cancel state to ENABLE.");
373
374         if(!listen_fds_count)
375                 fatal("LISTENER: No sockets to listen to.");
376
377         struct pollfd *fds = calloc(sizeof(struct pollfd), listen_fds_count);
378         if(!fds)
379                 fatal("LISTENER: Cannot allocate memory for poll fds.");
380
381         int i;
382         for(i = 0; i < listen_fds_count ;i++) {
383                 fds[i].fd = listen_fds[i];
384                 fds[i].events = POLLIN;
385                 fds[i].revents = 0;
386         }
387
388         int timeout = 10 * 1000;
389
390         for(;;) {
391                 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
392                 retval = poll(fds, listen_fds_count, timeout);
393
394                 if(unlikely(retval == -1)) {
395                         error("LISTENER: poll() failed.");
396                         continue;
397                 }
398                 else if(unlikely(!retval)) {
399                         debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
400                         counter = 0;
401                         cleanup_web_clients();
402                         continue;
403                 }
404
405                 for(i = 0 ; i < listen_fds_count ; i++) {
406                         short int revents = fds[i].revents;
407
408                         // check for new incoming connections
409                         if(revents & POLLIN || revents & POLLPRI) {
410                                 fds[i].revents = 0;
411
412                                 w = web_client_create(fds[i].fd);
413                                 if(unlikely(!w)) {
414                                         // no need for error log - web_client_create already logged the error
415                                         continue;
416                                 }
417
418                                 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
419                                         error("%llu: failed to create new thread for web client.", w->id);
420                                         w->obsolete = 1;
421                                 }
422                                 else if(pthread_detach(w->thread) != 0) {
423                                         error("%llu: Cannot request detach of newly created web client thread.", w->id);
424                                         w->obsolete = 1;
425                                 }
426                         }
427                 }
428
429                 // cleanup unused clients
430                 counter++;
431                 if(counter >= CLEANUP_EVERY_EVENTS) {
432                         counter = 0;
433                         cleanup_web_clients();
434                 }
435         }
436
437         debug(D_WEB_CLIENT, "LISTENER: exit!");
438     close_listen_sockets();
439
440         return NULL;
441 }
442
443 struct web_client *single_threaded_clients[FD_SETSIZE];
444
445 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
446         if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
447                 return 1;
448
449         if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
450                 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
451                 return 1;
452         }
453
454         FD_SET(w->ifd, efds);
455         if(unlikely(*max < w->ifd)) *max = w->ifd;
456
457         if(unlikely(w->ifd != w->ofd)) {
458                 if(*max < w->ofd) *max = w->ofd;
459                 FD_SET(w->ofd, efds);
460         }
461
462         if(w->wait_receive) FD_SET(w->ifd, ifds);
463         if(w->wait_send)    FD_SET(w->ofd, ofds);
464
465         single_threaded_clients[w->ifd] = w;
466         single_threaded_clients[w->ofd] = w;
467
468         return 0;
469 }
470
471 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
472         FD_CLR(w->ifd, efds);
473         if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
474
475         if(w->wait_receive) FD_CLR(w->ifd, ifds);
476         if(w->wait_send)    FD_CLR(w->ofd, ofds);
477
478         single_threaded_clients[w->ifd] = NULL;
479         single_threaded_clients[w->ofd] = NULL;
480
481         if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
482                 return 1;
483
484         return 0;
485 }
486
487 void *socket_listen_main_single_threaded(void *ptr) {
488         (void)ptr;
489
490         web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
491
492         info("Single threaded WEB SERVER thread created with task id %d", gettid());
493
494         struct web_client *w;
495         int retval;
496
497         if(ptr) { ; }
498
499         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
500                 error("Cannot set pthread cancel type to DEFERRED.");
501
502         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
503                 error("Cannot set pthread cancel state to ENABLE.");
504
505         int i;
506
507         if(!listen_fds_count)
508                 fatal("LISTENER: no listen sockets available.");
509
510         for(i = 0; i < FD_SETSIZE ; i++)
511                 single_threaded_clients[i] = NULL;
512
513         fd_set ifds, ofds, efds, rifds, rofds, refds;
514         FD_ZERO (&ifds);
515         FD_ZERO (&ofds);
516         FD_ZERO (&efds);
517         int fdmax = 0;
518
519         for(i = 0; i < listen_fds_count ; i++) {
520                 if (listen_fds[i] < 0 || listen_fds[i] >= FD_SETSIZE)
521                         fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fds[i]);
522
523                 FD_SET(listen_fds[i], &ifds);
524                 FD_SET(listen_fds[i], &efds);
525                 if(fdmax < listen_fds[i])
526             fdmax = listen_fds[i];
527         }
528
529         for(;;) {
530                 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
531
532                 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
533                 rifds = ifds;
534                 rofds = ofds;
535                 refds = efds;
536                 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
537
538                 if(unlikely(retval == -1)) {
539                         error("LISTENER: select() failed.");
540                         continue;
541                 }
542                 else if(likely(retval)) {
543                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
544
545                         for(i = 0; i < listen_fds_count ; i++) {
546                                 if (FD_ISSET(listen_fds[i], &rifds)) {
547                                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
548                                         w = web_client_create(listen_fds[i]);
549                                         if (single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
550                                                 web_client_free(w);
551                                         }
552                                 }
553                         }
554
555                         for(i = 0 ; i <= fdmax ; i++) {
556                                 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
557                                         continue;
558
559                                 w = single_threaded_clients[i];
560                                 if(unlikely(!w))
561                                         continue;
562
563                                 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
564                                         web_client_free(w);
565                                         continue;
566                                 }
567
568                                 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
569                                         web_client_free(w);
570                                         continue;
571                                 }
572
573                                 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
574                                         if (unlikely(web_client_receive(w) < 0)) {
575                                                 web_client_free(w);
576                                                 continue;
577                                         }
578
579                                         if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
580                                                 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
581                                                 web_client_process(w);
582                                         }
583                                 }
584
585                                 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
586                                         if (unlikely(web_client_send(w) < 0)) {
587                                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
588                                                 web_client_free(w);
589                                                 continue;
590                                         }
591                                 }
592
593                                 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
594                                         web_client_free(w);
595                                 }
596                         }
597                 }
598                 else {
599                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
600 #ifdef NETDATA_INTERNAL_CHECKS
601                         log_allocations();
602 #endif
603                 }
604         }
605
606         debug(D_WEB_CLIENT, "LISTENER: exit!");
607     close_listen_sockets();
608         return NULL;
609 }