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)
18 if(mi.uordblks > mem) {
21 for(w = web_clients; w ; w = w->next) clients++;
23 info("Allocated memory increased from %d to %d (increased by %d bytes). There are %d web clients connected.", mem, mi.uordblks, mi.uordblks - mem, clients);
30 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
31 int fd = accept(sock, addr, addrlen);
34 if (fd < 0) return fd;
36 if (flags & SOCK_NONBLOCK) {
37 newflags |= O_NONBLOCK;
38 flags &= ~SOCK_NONBLOCK;
42 if (flags & SOCK_CLOEXEC) {
43 newflags |= O_CLOEXEC;
44 flags &= ~SOCK_CLOEXEC;
53 if (fcntl(fd, F_SETFL, newflags) < 0) {
54 int saved_errno = errno;
64 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
68 debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
70 sock = socket(AF_INET, SOCK_STREAM, 0);
72 error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
76 /* avoid "address already in use" */
77 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
78 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
80 struct sockaddr_in name;
81 memset(&name, 0, sizeof(struct sockaddr_in));
82 name.sin_family = AF_INET;
83 name.sin_port = htons (port);
85 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
87 error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
92 if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
94 error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
98 if(listen(sock, listen_backlog) < 0) {
100 fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
104 debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
108 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
113 debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
115 sock = socket(AF_INET6, SOCK_STREAM, 0);
117 error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
121 /* avoid "address already in use" */
122 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
123 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
126 if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
127 error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
129 struct sockaddr_in6 name;
130 memset(&name, 0, sizeof(struct sockaddr_in6));
131 name.sin6_family = AF_INET6;
132 name.sin6_port = htons ((uint16_t) port);
134 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
136 error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
141 name.sin6_scope_id = 0;
143 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
145 error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
149 if (listen(sock, listen_backlog) < 0) {
151 error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
155 debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
159 static inline int add_listen_socket(int fd, const char *ip, int port) {
160 if(listen_fds_count >= MAX_LISTEN_FDS) {
161 error("Too many listening sockets. Failed to add listening socket at ip '%s' port %d", ip, port);
166 listen_fds[listen_fds_count] = fd;
168 char buffer[100 + 1];
169 snprintfz(buffer, 100, "[%s]:%d", ip, port);
170 listen_fds_names[listen_fds_count] = strdupz(buffer);
176 int is_listen_socket(int fd) {
178 for(i = 0; i < listen_fds_count ;i++)
179 if(listen_fds[i] == fd) return 1;
184 static inline void close_listen_sockets(void) {
186 for(i = 0; i < listen_fds_count ;i++) {
187 close(listen_fds[i]);
190 freez(listen_fds_names[i]);
191 listen_fds_names[i] = NULL;
194 listen_fds_count = 0;
197 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
199 struct addrinfo hints;
200 struct addrinfo *result = NULL, *rp = NULL;
202 char buffer[strlen(definition) + 1];
203 strcpy(buffer, definition);
205 char buffer2[10 + 1];
206 snprintfz(buffer2, 10, "%d", default_port);
208 char *ip = buffer, *port = buffer2;
213 while(*e && *e != ']') e++;
220 while(*e && *e != ':') e++;
228 if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
233 memset(&hints, 0, sizeof(struct addrinfo));
234 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
235 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
236 hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
237 hints.ai_protocol = 0; /* Any protocol */
238 hints.ai_canonname = NULL;
239 hints.ai_addr = NULL;
240 hints.ai_next = NULL;
242 int r = getaddrinfo(ip, port, &hints, &result);
244 error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
248 for (rp = result; rp != NULL; rp = rp->ai_next) {
251 char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
252 int rport = default_port;
254 switch (rp->ai_addr->sa_family) {
256 struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
257 inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
258 rport = ntohs(sin->sin_port);
259 fd = create_listen_socket4(rip, rport, listen_backlog);
264 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
265 inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
266 rport = ntohs(sin6->sin6_port);
267 fd = create_listen_socket6(rip, rport, listen_backlog);
273 error("Cannot bind to ip '%s', port %d", rip, default_port);
275 add_listen_socket(fd, rip, rport);
280 freeaddrinfo(result);
285 int create_listen_sockets(void) {
286 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
288 if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
289 config_rename("global", "bind socket to IP", "bind to");
291 if(config_exists("global", "port") && !config_exists("global", "default port"))
292 config_rename("global", "port", "default port");
294 listen_port = (int) config_get_number("global", "default port", LISTEN_PORT);
295 if(listen_port < 1 || listen_port > 65535) {
296 error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
297 listen_port = (int) config_set_number("global", "default port", LISTEN_PORT);
299 debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
301 char *s = config_get("global", "bind to", "*");
305 // skip separators, moving both s(tart) and e(nd)
306 while(isspace(*e) || *e == ',') s = ++e;
308 // move e(nd) to the first separator
309 while(*e && !isspace(*e) && *e != ',') e++;
311 // is there anything?
312 if(!*s || s == e) break;
315 strncpyz(buf, s, e - s);
316 bind_to_one(buf, listen_port, listen_backlog);
321 if(!listen_fds_count)
322 fatal("Cannot listen on any socket. Exiting...");
324 return (int)listen_fds_count;
327 // --------------------------------------------------------------------------------------
328 // the main socket listener
330 static inline void cleanup_web_clients(void) {
331 struct web_client *w;
333 for (w = web_clients; w;) {
335 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
336 // pthread_cancel(w->thread);
337 // pthread_join(w->thread, NULL);
338 w = web_client_free(w);
339 #ifdef NETDATA_INTERNAL_CHECKS
347 // 1. it accepts new incoming requests on our port
348 // 2. creates a new web_client for each connection received
349 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
350 // 4. cleans up old web_clients that their pthreads have been exited
352 #define CLEANUP_EVERY_EVENTS 100
354 void *socket_listen_main_multi_threaded(void *ptr) {
357 web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
358 info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
360 struct web_client *w;
361 int retval, counter = 0;
363 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
364 error("Cannot set pthread cancel type to DEFERRED.");
366 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
367 error("Cannot set pthread cancel state to ENABLE.");
369 if(!listen_fds_count)
370 fatal("LISTENER: No sockets to listen to.");
372 struct pollfd *fds = callocz(sizeof(struct pollfd), listen_fds_count);
375 for(i = 0; i < listen_fds_count ;i++) {
376 fds[i].fd = listen_fds[i];
377 fds[i].events = POLLIN;
380 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
383 int timeout = 10 * 1000;
386 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
387 retval = poll(fds, listen_fds_count, timeout);
389 if(unlikely(retval == -1)) {
390 error("LISTENER: poll() failed.");
393 else if(unlikely(!retval)) {
394 debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
396 cleanup_web_clients();
400 for(i = 0 ; i < listen_fds_count ; i++) {
401 short int revents = fds[i].revents;
403 // check for new incoming connections
404 if(revents & POLLIN || revents & POLLPRI) {
407 w = web_client_create(fds[i].fd);
409 // no need for error log - web_client_create already logged the error
413 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
414 error("%llu: failed to create new thread for web client.", w->id);
417 else if(pthread_detach(w->thread) != 0) {
418 error("%llu: Cannot request detach of newly created web client thread.", w->id);
424 // cleanup unused clients
426 if(counter >= CLEANUP_EVERY_EVENTS) {
428 cleanup_web_clients();
432 debug(D_WEB_CLIENT, "LISTENER: exit!");
433 close_listen_sockets();
438 struct web_client *single_threaded_clients[FD_SETSIZE];
440 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
441 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
444 if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
445 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
449 FD_SET(w->ifd, efds);
450 if(unlikely(*max < w->ifd)) *max = w->ifd;
452 if(unlikely(w->ifd != w->ofd)) {
453 if(*max < w->ofd) *max = w->ofd;
454 FD_SET(w->ofd, efds);
457 if(w->wait_receive) FD_SET(w->ifd, ifds);
458 if(w->wait_send) FD_SET(w->ofd, ofds);
460 single_threaded_clients[w->ifd] = w;
461 single_threaded_clients[w->ofd] = w;
466 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
467 FD_CLR(w->ifd, efds);
468 if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
470 if(w->wait_receive) FD_CLR(w->ifd, ifds);
471 if(w->wait_send) FD_CLR(w->ofd, ofds);
473 single_threaded_clients[w->ifd] = NULL;
474 single_threaded_clients[w->ofd] = NULL;
476 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
482 void *socket_listen_main_single_threaded(void *ptr) {
485 web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
487 info("Single-threaded WEB SERVER thread created with task id %d", gettid());
489 struct web_client *w;
492 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
493 error("Cannot set pthread cancel type to DEFERRED.");
495 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
496 error("Cannot set pthread cancel state to ENABLE.");
498 if(!listen_fds_count)
499 fatal("LISTENER: no listen sockets available.");
502 for(i = 0; i < FD_SETSIZE ; i++)
503 single_threaded_clients[i] = NULL;
505 fd_set ifds, ofds, efds, rifds, rofds, refds;
511 for(i = 0; i < listen_fds_count ; i++) {
512 if (listen_fds[i] < 0 || listen_fds[i] >= FD_SETSIZE)
513 fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fds[i]);
515 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
517 FD_SET(listen_fds[i], &ifds);
518 FD_SET(listen_fds[i], &efds);
519 if(fdmax < listen_fds[i])
520 fdmax = listen_fds[i];
524 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
526 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
530 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
532 if(unlikely(retval == -1)) {
533 error("LISTENER: select() failed.");
536 else if(likely(retval)) {
537 debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
539 for(i = 0; i < listen_fds_count ; i++) {
540 if (FD_ISSET(listen_fds[i], &rifds)) {
541 debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
542 w = web_client_create(listen_fds[i]);
543 if (single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
549 for(i = 0 ; i <= (size_t)fdmax ; i++) {
550 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
553 w = single_threaded_clients[i];
557 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
562 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
567 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
568 if (unlikely(web_client_receive(w) < 0)) {
573 if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
574 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
575 web_client_process(w);
579 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
580 if (unlikely(web_client_send(w) < 0)) {
581 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
587 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
593 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
594 #ifdef NETDATA_INTERNAL_CHECKS
600 debug(D_WEB_CLIENT, "LISTENER: exit!");
601 close_listen_sockets();