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 char *listen_fds_names[MAX_LISTEN_FDS] = { [0 ... 99] = NULL };
35 int listen_port = LISTEN_PORT;
36 int web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
38 #ifdef NETDATA_INTERNAL_CHECKS
39 static void log_allocations(void)
46 if(mi.uordblks > mem) {
49 for(w = web_clients; w ; w = w->next) clients++;
51 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);
58 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
59 int fd = accept(sock, addr, addrlen);
62 if (fd < 0) return fd;
64 if (flags & SOCK_NONBLOCK) {
65 newflags |= O_NONBLOCK;
66 flags &= ~SOCK_NONBLOCK;
69 if (flags & SOCK_CLOEXEC) {
70 newflags |= O_CLOEXEC;
71 flags &= ~SOCK_CLOEXEC;
79 if (fcntl(fd, F_SETFL, newflags) < 0) {
80 int saved_errno = errno;
90 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
94 debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
96 sock = socket(AF_INET, SOCK_STREAM, 0);
98 error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
102 /* avoid "address already in use" */
103 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
104 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
106 struct sockaddr_in name;
107 memset(&name, 0, sizeof(struct sockaddr_in));
108 name.sin_family = AF_INET;
109 name.sin_port = htons (port);
111 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
113 error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
118 if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
120 error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
124 if(listen(sock, listen_backlog) < 0) {
126 fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
130 debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
134 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
139 debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
141 sock = socket(AF_INET6, SOCK_STREAM, 0);
143 error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
147 /* avoid "address already in use" */
148 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
149 error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
152 if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
153 error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
155 struct sockaddr_in6 name;
156 memset(&name, 0, sizeof(struct sockaddr_in6));
157 name.sin6_family = AF_INET6;
158 name.sin6_port = htons ((uint16_t) port);
160 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
162 error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
167 name.sin6_scope_id = 0;
169 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
171 error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
175 if (listen(sock, listen_backlog) < 0) {
177 error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
181 debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
185 static inline int add_listen_socket(int fd, const char *ip, int port) {
186 if(listen_fds_count >= MAX_LISTEN_FDS) {
187 error("Too many listening sockets. Failed to add listening socket at ip '%s' port %d", ip, port);
192 listen_fds[listen_fds_count] = fd;
194 char buffer[100 + 1];
195 snprintfz(buffer, 100, "[%s]:%d", ip, port);
196 listen_fds_names[listen_fds_count] = strdup(buffer);
202 int is_listen_socket(int fd) {
204 for(i = 0; i < listen_fds_count ;i++)
205 if(listen_fds[i] == fd) return 1;
210 static inline void close_listen_sockets(void) {
212 for(i = 0; i < listen_fds_count ;i++) {
213 close(listen_fds[i]);
216 if(listen_fds_names[i]) free(listen_fds_names[i]);
217 listen_fds_names[i] = NULL;
220 listen_fds_count = 0;
223 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
225 struct addrinfo hints;
226 struct addrinfo *result, *rp;
228 char buffer[strlen(definition) + 1];
229 strcpy(buffer, definition);
231 char buffer2[10 + 1];
232 snprintfz(buffer2, 10, "%d", default_port);
234 char *ip = buffer, *port = buffer2;
239 while(*e && *e != ']') e++;
246 while(*e && *e != ':') e++;
254 if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
259 memset(&hints, 0, sizeof(struct addrinfo));
260 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
261 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
262 hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
263 hints.ai_protocol = 0; /* Any protocol */
264 hints.ai_canonname = NULL;
265 hints.ai_addr = NULL;
266 hints.ai_next = NULL;
268 int r = getaddrinfo(ip, port, &hints, &result);
270 error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
274 for (rp = result; rp != NULL; rp = rp->ai_next) {
277 char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
278 int rport = default_port;
280 switch (rp->ai_addr->sa_family) {
282 struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
283 inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
284 rport = ntohs(sin->sin_port);
285 fd = create_listen_socket4(rip, rport, listen_backlog);
290 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
291 inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
292 rport = ntohs(sin6->sin6_port);
293 fd = create_listen_socket6(rip, rport, listen_backlog);
299 error("Cannot bind to ip '%s', port %d", rip, default_port);
301 add_listen_socket(fd, rip, rport);
309 int create_listen_sockets(void) {
310 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
312 if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
313 config_rename("global", "bind socket to IP", "bind to");
315 if(config_exists("global", "port") && !config_exists("global", "default port"))
316 config_rename("global", "port", "default port");
318 listen_port = (int) config_get_number("global", "default port", LISTEN_PORT);
319 if(listen_port < 1 || listen_port > 65535) {
320 error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
321 listen_port = (int) config_set_number("global", "default port", LISTEN_PORT);
323 debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
325 char *s = config_get("global", "bind to", "*");
329 // skip separators, moving both s(tart) and e(nd)
330 while(isspace(*e) || *e == ',') s = ++e;
332 // move e(nd) to the first separator
333 while(*e && !isspace(*e) && *e != ',') e++;
335 // is there anything?
336 if(!*s || s == e) break;
339 strncpyz(buf, s, e - s);
340 bind_to_one(buf, listen_port, listen_backlog);
345 if(!listen_fds_count)
346 fatal("Cannot listen on any socket. Exiting...");
348 return listen_fds_count;
351 // --------------------------------------------------------------------------------------
352 // the main socket listener
354 static inline void cleanup_web_clients(void) {
355 struct web_client *w;
357 for (w = web_clients; w;) {
359 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
360 // pthread_cancel(w->thread);
361 // pthread_join(w->thread, NULL);
362 w = web_client_free(w);
363 #ifdef NETDATA_INTERNAL_CHECKS
371 // 1. it accepts new incoming requests on our port
372 // 2. creates a new web_client for each connection received
373 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
374 // 4. cleans up old web_clients that their pthreads have been exited
376 #define CLEANUP_EVERY_EVENTS 100
378 void *socket_listen_main_multi_threaded(void *ptr) {
381 web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
382 info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
384 struct web_client *w;
385 int retval, counter = 0;
387 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
388 error("Cannot set pthread cancel type to DEFERRED.");
390 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
391 error("Cannot set pthread cancel state to ENABLE.");
393 if(!listen_fds_count)
394 fatal("LISTENER: No sockets to listen to.");
396 struct pollfd *fds = calloc(sizeof(struct pollfd), listen_fds_count);
398 fatal("LISTENER: Cannot allocate memory for poll fds.");
401 for(i = 0; i < listen_fds_count ;i++) {
402 fds[i].fd = listen_fds[i];
403 fds[i].events = POLLIN;
406 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
409 int timeout = 10 * 1000;
412 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
413 retval = poll(fds, listen_fds_count, timeout);
415 if(unlikely(retval == -1)) {
416 error("LISTENER: poll() failed.");
419 else if(unlikely(!retval)) {
420 debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
422 cleanup_web_clients();
426 for(i = 0 ; i < listen_fds_count ; i++) {
427 short int revents = fds[i].revents;
429 // check for new incoming connections
430 if(revents & POLLIN || revents & POLLPRI) {
433 w = web_client_create(fds[i].fd);
435 // no need for error log - web_client_create already logged the error
439 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
440 error("%llu: failed to create new thread for web client.", w->id);
443 else if(pthread_detach(w->thread) != 0) {
444 error("%llu: Cannot request detach of newly created web client thread.", w->id);
450 // cleanup unused clients
452 if(counter >= CLEANUP_EVERY_EVENTS) {
454 cleanup_web_clients();
458 debug(D_WEB_CLIENT, "LISTENER: exit!");
459 close_listen_sockets();
464 struct web_client *single_threaded_clients[FD_SETSIZE];
466 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
467 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
470 if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
471 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
475 FD_SET(w->ifd, efds);
476 if(unlikely(*max < w->ifd)) *max = w->ifd;
478 if(unlikely(w->ifd != w->ofd)) {
479 if(*max < w->ofd) *max = w->ofd;
480 FD_SET(w->ofd, efds);
483 if(w->wait_receive) FD_SET(w->ifd, ifds);
484 if(w->wait_send) FD_SET(w->ofd, ofds);
486 single_threaded_clients[w->ifd] = w;
487 single_threaded_clients[w->ofd] = w;
492 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
493 FD_CLR(w->ifd, efds);
494 if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
496 if(w->wait_receive) FD_CLR(w->ifd, ifds);
497 if(w->wait_send) FD_CLR(w->ofd, ofds);
499 single_threaded_clients[w->ifd] = NULL;
500 single_threaded_clients[w->ofd] = NULL;
502 if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
508 void *socket_listen_main_single_threaded(void *ptr) {
511 web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
513 info("Single-threaded WEB SERVER thread created with task id %d", gettid());
515 struct web_client *w;
520 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
521 error("Cannot set pthread cancel type to DEFERRED.");
523 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
524 error("Cannot set pthread cancel state to ENABLE.");
528 if(!listen_fds_count)
529 fatal("LISTENER: no listen sockets available.");
531 for(i = 0; i < FD_SETSIZE ; i++)
532 single_threaded_clients[i] = NULL;
534 fd_set ifds, ofds, efds, rifds, rofds, refds;
540 for(i = 0; i < listen_fds_count ; i++) {
541 if (listen_fds[i] < 0 || listen_fds[i] >= FD_SETSIZE)
542 fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fds[i]);
544 info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
546 FD_SET(listen_fds[i], &ifds);
547 FD_SET(listen_fds[i], &efds);
548 if(fdmax < listen_fds[i])
549 fdmax = listen_fds[i];
553 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
555 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
559 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
561 if(unlikely(retval == -1)) {
562 error("LISTENER: select() failed.");
565 else if(likely(retval)) {
566 debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
568 for(i = 0; i < listen_fds_count ; i++) {
569 if (FD_ISSET(listen_fds[i], &rifds)) {
570 debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
571 w = web_client_create(listen_fds[i]);
572 if (single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
578 for(i = 0 ; i <= fdmax ; i++) {
579 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
582 w = single_threaded_clients[i];
586 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
591 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
596 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
597 if (unlikely(web_client_receive(w) < 0)) {
602 if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
603 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
604 web_client_process(w);
608 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
609 if (unlikely(web_client_send(w) < 0)) {
610 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
616 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
622 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
623 #ifdef NETDATA_INTERNAL_CHECKS
629 debug(D_WEB_CLIENT, "LISTENER: exit!");
630 close_listen_sockets();