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