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 */
41 #endif /* NETDATA_INTERNAL_CHECKS */
44 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
45 int fd = accept(sock, addr, addrlen);
48 if (fd < 0) return fd;
50 if (flags & SOCK_NONBLOCK) {
51 newflags |= O_NONBLOCK;
52 flags &= ~SOCK_NONBLOCK;
57 if (flags & SOCK_CLOEXEC) {
58 newflags |= O_CLOEXEC;
59 flags &= ~SOCK_CLOEXEC;
69 if (fcntl(fd, F_SETFL, newflags) < 0) {
70 int saved_errno = errno;
80 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
84 debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
86 sock = socket(AF_INET, SOCK_STREAM, 0);
88 error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
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);
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);
101 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
103 error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
108 if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
110 error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
114 if(listen(sock, listen_backlog) < 0) {
116 fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
120 debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
124 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
129 debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
131 sock = socket(AF_INET6, SOCK_STREAM, 0);
133 error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
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);
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);
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);
150 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
152 error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
157 name.sin6_scope_id = 0;
159 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
161 error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
165 if (listen(sock, listen_backlog) < 0) {
167 error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
171 debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
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);
182 listen_fds[listen_fds_count] = fd;
184 char buffer[100 + 1];
185 snprintfz(buffer, 100, "[%s]:%d", ip, port);
186 listen_fds_names[listen_fds_count] = strdupz(buffer);
192 int is_listen_socket(int fd) {
194 for(i = 0; i < listen_fds_count ;i++)
195 if(listen_fds[i] == fd) return 1;
200 static inline void close_listen_sockets(void) {
202 for(i = 0; i < listen_fds_count ;i++) {
203 close(listen_fds[i]);
206 freez(listen_fds_names[i]);
207 listen_fds_names[i] = NULL;
210 listen_fds_count = 0;
213 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
215 struct addrinfo hints;
216 struct addrinfo *result = NULL, *rp = NULL;
218 char buffer[strlen(definition) + 1];
219 strcpy(buffer, definition);
221 char buffer2[10 + 1];
222 snprintfz(buffer2, 10, "%d", default_port);
224 char *ip = buffer, *port = buffer2;
229 while(*e && *e != ']') e++;
236 while(*e && *e != ':') e++;
244 if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
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;
258 int r = getaddrinfo(ip, port, &hints, &result);
260 error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
264 for (rp = result; rp != NULL; rp = rp->ai_next) {
267 char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
268 int rport = default_port;
270 switch (rp->ai_addr->sa_family) {
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);
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);
289 error("Cannot bind to ip '%s', port %d", rip, default_port);
291 add_listen_socket(fd, rip, rport);
296 freeaddrinfo(result);
301 int create_listen_sockets(void) {
302 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
304 if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
305 config_rename("global", "bind socket to IP", "bind to");
307 if(config_exists("global", "port") && !config_exists("global", "default port"))
308 config_rename("global", "port", "default port");
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);
315 debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
317 char *s = config_get("global", "bind to", "*");
321 // skip separators, moving both s(tart) and e(nd)
322 while(isspace(*e) || *e == ',') s = ++e;
324 // move e(nd) to the first separator
325 while(*e && !isspace(*e) && *e != ',') e++;
327 // is there anything?
328 if(!*s || s == e) break;
331 strncpyz(buf, s, e - s);
332 bind_to_one(buf, listen_port, listen_backlog);
337 if(!listen_fds_count)
338 fatal("Cannot listen on any socket. Exiting...");
340 return (int)listen_fds_count;
343 // --------------------------------------------------------------------------------------
344 // the main socket listener
346 static inline void cleanup_web_clients(void) {
347 struct web_client *w;
349 for (w = web_clients; w;) {
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
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
368 #define CLEANUP_EVERY_EVENTS 100
370 void *socket_listen_main_multi_threaded(void *ptr) {
373 web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
374 info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
376 struct web_client *w;
377 int retval, counter = 0;
379 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
380 error("Cannot set pthread cancel type to DEFERRED.");
382 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
383 error("Cannot set pthread cancel state to ENABLE.");
385 if(!listen_fds_count)
386 fatal("LISTENER: No sockets to listen to.");
388 struct pollfd *fds = callocz(sizeof(struct pollfd), listen_fds_count);
391 for(i = 0; i < listen_fds_count ;i++) {
392 fds[i].fd = listen_fds[i];
393 fds[i].events = POLLIN;
396 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
399 int timeout = 10 * 1000;
402 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
403 retval = poll(fds, listen_fds_count, timeout);
405 if(unlikely(retval == -1)) {
406 error("LISTENER: poll() failed.");
409 else if(unlikely(!retval)) {
410 debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
412 cleanup_web_clients();
416 for(i = 0 ; i < listen_fds_count ; i++) {
417 short int revents = fds[i].revents;
419 // check for new incoming connections
420 if(revents & POLLIN || revents & POLLPRI) {
423 w = web_client_create(fds[i].fd);
425 // no need for error log - web_client_create already logged the error
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);
433 else if(pthread_detach(w->thread) != 0) {
434 error("%llu: Cannot request detach of newly created web client thread.", w->id);
440 // cleanup unused clients
442 if(counter >= CLEANUP_EVERY_EVENTS) {
444 cleanup_web_clients();
448 debug(D_WEB_CLIENT, "LISTENER: exit!");
449 close_listen_sockets();
454 struct web_client *single_threaded_clients[FD_SETSIZE];
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)))
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);
465 FD_SET(w->ifd, efds);
466 if(unlikely(*max < w->ifd)) *max = w->ifd;
468 if(unlikely(w->ifd != w->ofd)) {
469 if(*max < w->ofd) *max = w->ofd;
470 FD_SET(w->ofd, efds);
473 if(w->wait_receive) FD_SET(w->ifd, ifds);
474 if(w->wait_send) FD_SET(w->ofd, ofds);
476 single_threaded_clients[w->ifd] = w;
477 single_threaded_clients[w->ofd] = w;
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);
486 if(w->wait_receive) FD_CLR(w->ifd, ifds);
487 if(w->wait_send) FD_CLR(w->ofd, ofds);
489 single_threaded_clients[w->ifd] = NULL;
490 single_threaded_clients[w->ofd] = NULL;
492 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
498 void *socket_listen_main_single_threaded(void *ptr) {
501 web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
503 info("Single-threaded WEB SERVER thread created with task id %d", gettid());
505 struct web_client *w;
508 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
509 error("Cannot set pthread cancel type to DEFERRED.");
511 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
512 error("Cannot set pthread cancel state to ENABLE.");
514 if(!listen_fds_count)
515 fatal("LISTENER: no listen sockets available.");
518 for(i = 0; i < FD_SETSIZE ; i++)
519 single_threaded_clients[i] = NULL;
521 fd_set ifds, ofds, efds, rifds, rofds, refds;
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]);
531 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
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];
540 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
542 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
546 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
548 if(unlikely(retval == -1)) {
549 error("LISTENER: select() failed.");
552 else if(likely(retval)) {
553 debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
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) {
565 for(i = 0 ; i <= (size_t)fdmax ; i++) {
566 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
569 w = single_threaded_clients[i];
573 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
578 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
583 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
584 if (unlikely(web_client_receive(w) < 0)) {
589 if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
590 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
591 web_client_process(w);
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);
603 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
609 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
610 #ifdef NETDATA_INTERNAL_CHECKS
616 debug(D_WEB_CLIENT, "LISTENER: exit!");
617 close_listen_sockets();