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