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