7 #include <sys/socket.h>
8 #include <netinet/in.h>
14 #include <netinet/tcp.h>
21 #include "appconfig.h"
23 #include "web_buffer.h"
24 #include "web_client.h"
25 #include "web_server.h"
26 #include "global_statistics.h"
29 #include "../config.h"
31 int listen_backlog = LISTEN_BACKLOG;
32 int listen_fds_count = 0;
33 int listen_fds[MAX_LISTEN_FDS] = { [0 ... 99] = -1 };
34 int listen_port = LISTEN_PORT;
35 int web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
37 #ifdef NETDATA_INTERNAL_CHECKS
38 static void log_allocations(void)
45 if(mi.uordblks > mem) {
48 for(w = web_clients; w ; w = w->next) clients++;
50 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);
57 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
58 int fd = accept(sock, addr, addrlen);
61 if (fd < 0) return fd;
63 if (flags & SOCK_NONBLOCK) {
64 newflags |= O_NONBLOCK;
65 flags &= ~SOCK_NONBLOCK;
68 if (flags & SOCK_CLOEXEC) {
69 newflags |= O_CLOEXEC;
70 flags &= ~SOCK_CLOEXEC;
78 if (fcntl(fd, F_SETFL, newflags) < 0) {
79 int saved_errno = errno;
89 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
93 debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
95 sock = socket(AF_INET, SOCK_STREAM, 0);
97 error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
101 /* avoid "address already in use" */
102 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
103 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
105 struct sockaddr_in name;
106 memset(&name, 0, sizeof(struct sockaddr_in));
107 name.sin_family = AF_INET;
108 name.sin_port = htons (port);
110 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
112 error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
117 if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
119 error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
123 if(listen(sock, listen_backlog) < 0) {
125 fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
129 debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
133 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
138 debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
140 sock = socket(AF_INET6, SOCK_STREAM, 0);
142 error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
146 /* avoid "address already in use" */
147 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
148 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
151 if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
152 error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
154 struct sockaddr_in6 name;
155 memset(&name, 0, sizeof(struct sockaddr_in6));
156 name.sin6_family = AF_INET6;
157 name.sin6_port = htons ((uint16_t) port);
159 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
161 error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
166 name.sin6_scope_id = 0;
168 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
170 error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
174 if (listen(sock, listen_backlog) < 0) {
176 error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
180 debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
184 static inline int add_listen_socket(int fd) {
185 if(listen_fds_count >= MAX_LISTEN_FDS)
188 listen_fds[listen_fds_count++] = fd;
193 int is_listen_socket(int fd) {
195 for(i = 0; i < listen_fds_count ;i++)
196 if(listen_fds[i] == fd) return 1;
201 static inline void close_listen_sockets(void) {
203 for(i = 0; i < listen_fds_count ;i++)
204 close(listen_fds[i]);
205 listen_fds_count = 0;
208 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
210 struct addrinfo hints;
211 struct addrinfo *result, *rp;
213 char buffer[strlen(definition) + 1];
214 strcpy(buffer, definition);
216 char buffer2[10 + 1];
217 snprintfz(buffer2, 10, "%d", default_port);
219 char *ip = buffer, *port = buffer2;
224 while(*e && *e != ']') e++;
231 while(*e && *e != ':') e++;
239 if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
244 memset(&hints, 0, sizeof(struct addrinfo));
245 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
246 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
247 hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
248 hints.ai_protocol = 0; /* Any protocol */
249 hints.ai_canonname = NULL;
250 hints.ai_addr = NULL;
251 hints.ai_next = NULL;
253 int r = getaddrinfo(ip, port, &hints, &result);
255 error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
259 for (rp = result; rp != NULL; rp = rp->ai_next) {
262 char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
263 switch (rp->ai_addr->sa_family) {
265 struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
266 inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
267 fd = create_listen_socket4(rip, ntohs(sin->sin_port), listen_backlog);
272 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
273 inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
274 fd = create_listen_socket6(rip, ntohs(sin6->sin6_port), listen_backlog);
280 error("Cannot bind to ip '%s', port %d", rip, default_port);
282 add_listen_socket(fd);
290 int create_listen_sockets(void) {
291 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
293 if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
294 config_rename("global", "bind socket to IP", "bind to");
296 if(config_exists("global", "port") && !config_exists("global", "default port"))
297 config_rename("global", "port", "default port");
299 listen_port = (int) config_get_number("global", "default port", LISTEN_PORT);
300 if(listen_port < 1 || listen_port > 65535) {
301 error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
302 listen_port = (int) config_set_number("global", "default port", LISTEN_PORT);
304 debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
306 char *s = config_get("global", "bind to", "*");
310 // skip separators, moving both s(tart) and e(nd)
311 while(isspace(*e) || *e == ',') s = ++e;
313 // move e(nd) to the first separator
314 while(*e && !isspace(*e) && *e != ',') e++;
316 // is there anything?
317 if(!*s || s == e) break;
320 strncpyz(buf, s, e - s);
321 bind_to_one(buf, listen_port, listen_backlog);
326 if(!listen_fds_count)
327 fatal("Cannot listen on any socket. Exiting...");
329 return listen_fds_count;
332 // --------------------------------------------------------------------------------------
333 // the main socket listener
335 static inline void cleanup_web_clients(void) {
336 struct web_client *w;
338 for (w = web_clients; w;) {
340 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
341 // pthread_cancel(w->thread);
342 // pthread_join(w->thread, NULL);
343 w = web_client_free(w);
344 #ifdef NETDATA_INTERNAL_CHECKS
352 // 1. it accepts new incoming requests on our port
353 // 2. creates a new web_client for each connection received
354 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
355 // 4. cleans up old web_clients that their pthreads have been exited
357 #define CLEANUP_EVERY_EVENTS 100
359 void *socket_listen_main_multi_threaded(void *ptr) {
362 web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
363 info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
365 struct web_client *w;
366 int retval, counter = 0;
368 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
369 error("Cannot set pthread cancel type to DEFERRED.");
371 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
372 error("Cannot set pthread cancel state to ENABLE.");
374 if(!listen_fds_count)
375 fatal("LISTENER: No sockets to listen to.");
377 struct pollfd *fds = calloc(sizeof(struct pollfd), listen_fds_count);
379 fatal("LISTENER: Cannot allocate memory for poll fds.");
382 for(i = 0; i < listen_fds_count ;i++) {
383 fds[i].fd = listen_fds[i];
384 fds[i].events = POLLIN;
388 int timeout = 10 * 1000;
391 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
392 retval = poll(fds, listen_fds_count, timeout);
394 if(unlikely(retval == -1)) {
395 error("LISTENER: poll() failed.");
398 else if(unlikely(!retval)) {
399 debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
401 cleanup_web_clients();
405 for(i = 0 ; i < listen_fds_count ; i++) {
406 short int revents = fds[i].revents;
408 // check for new incoming connections
409 if(revents & POLLIN || revents & POLLPRI) {
412 w = web_client_create(fds[i].fd);
414 // no need for error log - web_client_create already logged the error
418 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
419 error("%llu: failed to create new thread for web client.", w->id);
422 else if(pthread_detach(w->thread) != 0) {
423 error("%llu: Cannot request detach of newly created web client thread.", w->id);
429 // cleanup unused clients
431 if(counter >= CLEANUP_EVERY_EVENTS) {
433 cleanup_web_clients();
437 debug(D_WEB_CLIENT, "LISTENER: exit!");
438 close_listen_sockets();
443 struct web_client *single_threaded_clients[FD_SETSIZE];
445 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
446 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
449 if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
450 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
454 FD_SET(w->ifd, efds);
455 if(unlikely(*max < w->ifd)) *max = w->ifd;
457 if(unlikely(w->ifd != w->ofd)) {
458 if(*max < w->ofd) *max = w->ofd;
459 FD_SET(w->ofd, efds);
462 if(w->wait_receive) FD_SET(w->ifd, ifds);
463 if(w->wait_send) FD_SET(w->ofd, ofds);
465 single_threaded_clients[w->ifd] = w;
466 single_threaded_clients[w->ofd] = w;
471 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
472 FD_CLR(w->ifd, efds);
473 if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
475 if(w->wait_receive) FD_CLR(w->ifd, ifds);
476 if(w->wait_send) FD_CLR(w->ofd, ofds);
478 single_threaded_clients[w->ifd] = NULL;
479 single_threaded_clients[w->ofd] = NULL;
481 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
487 void *socket_listen_main_single_threaded(void *ptr) {
490 web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
492 info("Single threaded WEB SERVER thread created with task id %d", gettid());
494 struct web_client *w;
499 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
500 error("Cannot set pthread cancel type to DEFERRED.");
502 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
503 error("Cannot set pthread cancel state to ENABLE.");
507 if(!listen_fds_count)
508 fatal("LISTENER: no listen sockets available.");
510 for(i = 0; i < FD_SETSIZE ; i++)
511 single_threaded_clients[i] = NULL;
513 fd_set ifds, ofds, efds, rifds, rofds, refds;
519 for(i = 0; i < listen_fds_count ; i++) {
520 if (listen_fds[i] < 0 || listen_fds[i] >= FD_SETSIZE)
521 fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fds[i]);
523 FD_SET(listen_fds[i], &ifds);
524 FD_SET(listen_fds[i], &efds);
525 if(fdmax < listen_fds[i])
526 fdmax = listen_fds[i];
530 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
532 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
536 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
538 if(unlikely(retval == -1)) {
539 error("LISTENER: select() failed.");
542 else if(likely(retval)) {
543 debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
545 for(i = 0; i < listen_fds_count ; i++) {
546 if (FD_ISSET(listen_fds[i], &rifds)) {
547 debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
548 w = web_client_create(listen_fds[i]);
549 if (single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
555 for(i = 0 ; i <= fdmax ; i++) {
556 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
559 w = single_threaded_clients[i];
563 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
568 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
573 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
574 if (unlikely(web_client_receive(w) < 0)) {
579 if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
580 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
581 web_client_process(w);
585 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
586 if (unlikely(web_client_send(w) < 0)) {
587 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
593 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
599 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
600 #ifdef NETDATA_INTERNAL_CHECKS
606 debug(D_WEB_CLIENT, "LISTENER: exit!");
607 close_listen_sockets();