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;
10 #ifdef NETDATA_INTERNAL_CHECKS
11 static void log_allocations(void)
13 #ifdef HAVE_C_MALLINFO
14 static int heap = 0, used = 0, mmap = 0;
19 if(mi.uordblks > used) {
22 for(w = web_clients; w ; w = w->next) clients++;
24 info("Allocated memory: used %d KB (+%d B), mmap %d KB (+%d B), heap %d KB (+%d B). %d web clients connected.",
37 #else /* ! HAVE_C_MALLINFO */
39 #endif /* ! HAVE_C_MALLINFO */
42 malloc_stats_print(NULL, NULL, NULL);
45 #endif /* NETDATA_INTERNAL_CHECKS */
48 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
49 int fd = accept(sock, addr, addrlen);
52 if (fd < 0) return fd;
54 if (flags & SOCK_NONBLOCK) {
55 newflags |= O_NONBLOCK;
56 flags &= ~SOCK_NONBLOCK;
61 if (flags & SOCK_CLOEXEC) {
62 newflags |= O_CLOEXEC;
63 flags &= ~SOCK_CLOEXEC;
73 if (fcntl(fd, F_SETFL, newflags) < 0) {
74 int saved_errno = errno;
84 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
88 debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
90 sock = socket(AF_INET, SOCK_STREAM, 0);
92 error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
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);
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);
105 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
107 error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
112 if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
114 error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
118 if(listen(sock, listen_backlog) < 0) {
120 fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
124 debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
128 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
133 debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
135 sock = socket(AF_INET6, SOCK_STREAM, 0);
137 error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
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);
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);
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);
154 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
156 error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
161 name.sin6_scope_id = 0;
163 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
165 error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
169 if (listen(sock, listen_backlog) < 0) {
171 error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
175 debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
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);
186 listen_fds[listen_fds_count] = fd;
188 char buffer[100 + 1];
189 snprintfz(buffer, 100, "[%s]:%d", ip, port);
190 listen_fds_names[listen_fds_count] = strdupz(buffer);
196 int is_listen_socket(int fd) {
198 for(i = 0; i < listen_fds_count ;i++)
199 if(listen_fds[i] == fd) return 1;
204 static inline void close_listen_sockets(void) {
206 for(i = 0; i < listen_fds_count ;i++) {
207 close(listen_fds[i]);
210 freez(listen_fds_names[i]);
211 listen_fds_names[i] = NULL;
214 listen_fds_count = 0;
217 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
219 struct addrinfo hints;
220 struct addrinfo *result = NULL, *rp = NULL;
222 char buffer[strlen(definition) + 1];
223 strcpy(buffer, definition);
225 char buffer2[10 + 1];
226 snprintfz(buffer2, 10, "%d", default_port);
228 char *ip = buffer, *port = buffer2;
233 while(*e && *e != ']') e++;
240 while(*e && *e != ':') e++;
248 if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
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;
262 int r = getaddrinfo(ip, port, &hints, &result);
264 error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
268 for (rp = result; rp != NULL; rp = rp->ai_next) {
271 char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
272 int rport = default_port;
274 switch (rp->ai_addr->sa_family) {
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);
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);
293 error("Cannot bind to ip '%s', port %d", rip, default_port);
295 add_listen_socket(fd, rip, rport);
300 freeaddrinfo(result);
305 int create_listen_sockets(void) {
306 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
308 if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
309 config_rename("global", "bind socket to IP", "bind to");
311 if(config_exists("global", "port") && !config_exists("global", "default port"))
312 config_rename("global", "port", "default port");
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);
319 debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
321 char *s = config_get("global", "bind to", "*");
325 // skip separators, moving both s(tart) and e(nd)
326 while(isspace(*e) || *e == ',') s = ++e;
328 // move e(nd) to the first separator
329 while(*e && !isspace(*e) && *e != ',') e++;
331 // is there anything?
332 if(!*s || s == e) break;
335 strncpyz(buf, s, e - s);
336 bind_to_one(buf, listen_port, listen_backlog);
341 if(!listen_fds_count)
342 fatal("Cannot listen on any socket. Exiting...");
344 return (int)listen_fds_count;
347 // --------------------------------------------------------------------------------------
348 // the main socket listener
350 static inline void cleanup_web_clients(void) {
351 struct web_client *w;
353 for (w = web_clients; w;) {
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
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
372 #define CLEANUP_EVERY_EVENTS 100
374 void *socket_listen_main_multi_threaded(void *ptr) {
377 web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
378 info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
380 struct web_client *w;
381 int retval, counter = 0;
383 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
384 error("Cannot set pthread cancel type to DEFERRED.");
386 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
387 error("Cannot set pthread cancel state to ENABLE.");
389 if(!listen_fds_count)
390 fatal("LISTENER: No sockets to listen to.");
392 struct pollfd *fds = callocz(sizeof(struct pollfd), listen_fds_count);
395 for(i = 0; i < listen_fds_count ;i++) {
396 fds[i].fd = listen_fds[i];
397 fds[i].events = POLLIN;
400 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
403 int timeout = 10 * 1000;
406 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
407 retval = poll(fds, listen_fds_count, timeout);
409 if(unlikely(retval == -1)) {
410 error("LISTENER: poll() failed.");
413 else if(unlikely(!retval)) {
414 debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
416 cleanup_web_clients();
420 for(i = 0 ; i < listen_fds_count ; i++) {
421 short int revents = fds[i].revents;
423 // check for new incoming connections
424 if(revents & POLLIN || revents & POLLPRI) {
427 w = web_client_create(fds[i].fd);
429 // no need for error log - web_client_create already logged the error
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);
437 else if(pthread_detach(w->thread) != 0) {
438 error("%llu: Cannot request detach of newly created web client thread.", w->id);
444 // cleanup unused clients
446 if(counter >= CLEANUP_EVERY_EVENTS) {
448 cleanup_web_clients();
452 debug(D_WEB_CLIENT, "LISTENER: exit!");
453 close_listen_sockets();
458 struct web_client *single_threaded_clients[FD_SETSIZE];
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)))
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);
469 FD_SET(w->ifd, efds);
470 if(unlikely(*max < w->ifd)) *max = w->ifd;
472 if(unlikely(w->ifd != w->ofd)) {
473 if(*max < w->ofd) *max = w->ofd;
474 FD_SET(w->ofd, efds);
477 if(w->wait_receive) FD_SET(w->ifd, ifds);
478 if(w->wait_send) FD_SET(w->ofd, ofds);
480 single_threaded_clients[w->ifd] = w;
481 single_threaded_clients[w->ofd] = w;
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);
490 if(w->wait_receive) FD_CLR(w->ifd, ifds);
491 if(w->wait_send) FD_CLR(w->ofd, ofds);
493 single_threaded_clients[w->ifd] = NULL;
494 single_threaded_clients[w->ofd] = NULL;
496 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
502 void *socket_listen_main_single_threaded(void *ptr) {
505 web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
507 info("Single-threaded WEB SERVER thread created with task id %d", gettid());
509 struct web_client *w;
512 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
513 error("Cannot set pthread cancel type to DEFERRED.");
515 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
516 error("Cannot set pthread cancel state to ENABLE.");
518 if(!listen_fds_count)
519 fatal("LISTENER: no listen sockets available.");
522 for(i = 0; i < FD_SETSIZE ; i++)
523 single_threaded_clients[i] = NULL;
525 fd_set ifds, ofds, efds, rifds, rofds, refds;
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]);
535 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
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];
544 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
546 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
550 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
552 if(unlikely(retval == -1)) {
553 error("LISTENER: select() failed.");
556 else if(likely(retval)) {
557 debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
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) {
569 for(i = 0 ; i <= (size_t)fdmax ; i++) {
570 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
573 w = single_threaded_clients[i];
577 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
582 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
587 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
588 if (unlikely(web_client_receive(w) < 0)) {
593 if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
594 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
595 web_client_process(w);
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);
607 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
613 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
614 #ifdef NETDATA_INTERNAL_CHECKS
620 debug(D_WEB_CLIENT, "LISTENER: exit!");
621 close_listen_sockets();