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