]> arthur.barton.de Git - netdata.git/blob - src/web_server.c
fix for compiling in RHEL 5.x; fixes #911
[netdata.git] / src / web_server.c
1 #include "common.h"
2
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;
9
10 #ifdef NETDATA_INTERNAL_CHECKS
11 static void log_allocations(void)
12 {
13     static int mem = 0;
14
15     struct mallinfo mi;
16
17     mi = mallinfo();
18     if(mi.uordblks > mem) {
19         int clients = 0;
20         struct web_client *w;
21         for(w = web_clients; w ; w = w->next) clients++;
22
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);
24         mem = mi.uordblks;
25     }
26 }
27 #endif
28
29 #ifndef HAVE_ACCEPT4
30 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
31     int fd = accept(sock, addr, addrlen);
32     int newflags = 0;
33
34     if (fd < 0) return fd;
35
36     if (flags & SOCK_NONBLOCK) {
37         newflags |= O_NONBLOCK;
38         flags &= ~SOCK_NONBLOCK;
39     }
40
41 #ifdef SOCK_CLOEXEC
42 #ifdef O_CLOEXEC
43     if (flags & SOCK_CLOEXEC) {
44         newflags |= O_CLOEXEC;
45         flags &= ~SOCK_CLOEXEC;
46     }
47 #endif
48 #endif
49
50     if (flags) {
51         errno = -EINVAL;
52         return -1;
53     }
54
55     if (fcntl(fd, F_SETFL, newflags) < 0) {
56         int saved_errno = errno;
57         close(fd);
58         errno = saved_errno;
59         return -1;
60     }
61
62     return fd;
63 }
64 #endif
65
66 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
67     int sock;
68     int sockopt = 1;
69
70     debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
71
72     sock = socket(AF_INET, SOCK_STREAM, 0);
73     if(sock < 0) {
74         error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
75         return -1;
76     }
77
78     /* avoid "address already in use" */
79     if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
80         error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
81
82     struct sockaddr_in name;
83     memset(&name, 0, sizeof(struct sockaddr_in));
84     name.sin_family = AF_INET;
85     name.sin_port = htons (port);
86
87     int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
88     if(ret != 1) {
89         error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
90         close(sock);
91         return -1;
92     }
93
94     if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
95         close(sock);
96         error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
97         return -1;
98     }
99
100     if(listen(sock, listen_backlog) < 0) {
101         close(sock);
102         fatal("IPv4 listen() on ip '%s' port %d failed.", ip, port);
103         return -1;
104     }
105
106     debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
107     return sock;
108 }
109
110 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
111     int sock = -1;
112     int sockopt = 1;
113     int ipv6only = 1;
114
115     debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
116
117     sock = socket(AF_INET6, SOCK_STREAM, 0);
118     if (sock < 0) {
119         error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
120         return -1;
121     }
122
123     /* avoid "address already in use" */
124     if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
125         error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
126
127     /* IPv6 only */
128     if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
129         error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
130
131     struct sockaddr_in6 name;
132     memset(&name, 0, sizeof(struct sockaddr_in6));
133     name.sin6_family = AF_INET6;
134     name.sin6_port = htons ((uint16_t) port);
135
136     int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
137     if(ret != 1) {
138         error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
139         close(sock);
140         return -1;
141     }
142
143     name.sin6_scope_id = 0;
144
145     if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
146         close(sock);
147         error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
148         return -1;
149     }
150
151     if (listen(sock, listen_backlog) < 0) {
152         close(sock);
153         error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
154         return -1;
155     }
156
157     debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
158     return sock;
159 }
160
161 static inline int add_listen_socket(int fd, const char *ip, int port) {
162     if(listen_fds_count >= MAX_LISTEN_FDS) {
163         error("Too many listening sockets. Failed to add listening socket at ip '%s' port %d", ip, port);
164         close(fd);
165         return -1;
166     }
167
168     listen_fds[listen_fds_count] = fd;
169
170     char buffer[100 + 1];
171     snprintfz(buffer, 100, "[%s]:%d", ip, port);
172     listen_fds_names[listen_fds_count] = strdupz(buffer);
173
174     listen_fds_count++;
175     return 0;
176 }
177
178 int is_listen_socket(int fd) {
179     size_t i;
180     for(i = 0; i < listen_fds_count ;i++)
181         if(listen_fds[i] == fd) return 1;
182
183     return 0;
184 }
185
186 static inline void close_listen_sockets(void) {
187     size_t i;
188     for(i = 0; i < listen_fds_count ;i++) {
189         close(listen_fds[i]);
190         listen_fds[i] = -1;
191
192         freez(listen_fds_names[i]);
193         listen_fds_names[i] = NULL;
194     }
195
196     listen_fds_count = 0;
197 }
198
199 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
200     int added = 0;
201     struct addrinfo hints;
202     struct addrinfo *result = NULL, *rp = NULL;
203
204     char buffer[strlen(definition) + 1];
205     strcpy(buffer, definition);
206
207     char buffer2[10 + 1];
208     snprintfz(buffer2, 10, "%d", default_port);
209
210     char *ip = buffer, *port = buffer2;
211
212     char *e = ip;
213     if(*e == '[') {
214         e = ++ip;
215         while(*e && *e != ']') e++;
216         if(*e == ']') {
217             *e = '\0';
218             e++;
219         }
220     }
221     else {
222         while(*e && *e != ':') e++;
223     }
224
225     if(*e == ':') {
226         port = e + 1;
227         *e = '\0';
228     }
229
230     if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
231         ip = NULL;
232     if(!*port)
233         port = buffer2;
234
235     memset(&hints, 0, sizeof(struct addrinfo));
236     hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
237     hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
238     hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
239     hints.ai_protocol = 0;          /* Any protocol */
240     hints.ai_canonname = NULL;
241     hints.ai_addr = NULL;
242     hints.ai_next = NULL;
243
244     int r = getaddrinfo(ip, port, &hints, &result);
245     if (r != 0) {
246         error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
247         return -1;
248     }
249
250     for (rp = result; rp != NULL; rp = rp->ai_next) {
251         int fd = -1;
252
253         char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
254         int rport = default_port;
255
256         switch (rp->ai_addr->sa_family) {
257             case AF_INET: {
258                 struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
259                 inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
260                 rport = ntohs(sin->sin_port);
261                 fd = create_listen_socket4(rip, rport, listen_backlog);
262                 break;
263             }
264
265             case AF_INET6: {
266                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
267                 inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
268                 rport = ntohs(sin6->sin6_port);
269                 fd = create_listen_socket6(rip, rport, listen_backlog);
270                 break;
271             }
272         }
273
274         if (fd == -1)
275             error("Cannot bind to ip '%s', port %d", rip, default_port);
276         else {
277             add_listen_socket(fd, rip, rport);
278             added++;
279         }
280     }
281
282     freeaddrinfo(result);
283
284     return added;
285 }
286
287 int create_listen_sockets(void) {
288     listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
289
290     if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
291         config_rename("global", "bind socket to IP", "bind to");
292
293     if(config_exists("global", "port") && !config_exists("global", "default port"))
294         config_rename("global", "port", "default port");
295
296     listen_port = (int) config_get_number("global", "default port", LISTEN_PORT);
297     if(listen_port < 1 || listen_port > 65535) {
298         error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
299         listen_port = (int) config_set_number("global", "default port", LISTEN_PORT);
300     }
301     debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
302
303     char *s = config_get("global", "bind to", "*");
304     while(*s) {
305         char *e = s;
306
307         // skip separators, moving both s(tart) and e(nd)
308         while(isspace(*e) || *e == ',') s = ++e;
309
310         // move e(nd) to the first separator
311         while(*e && !isspace(*e) && *e != ',') e++;
312
313         // is there anything?
314         if(!*s || s == e) break;
315
316         char buf[e - s + 1];
317         strncpyz(buf, s, e - s);
318         bind_to_one(buf, listen_port, listen_backlog);
319
320         s = e;
321     }
322
323     if(!listen_fds_count)
324         fatal("Cannot listen on any socket. Exiting...");
325
326     return (int)listen_fds_count;
327 }
328
329 // --------------------------------------------------------------------------------------
330 // the main socket listener
331
332 static inline void cleanup_web_clients(void) {
333     struct web_client *w;
334
335     for (w = web_clients; w;) {
336         if (w->obsolete) {
337             debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
338             // pthread_cancel(w->thread);
339             // pthread_join(w->thread, NULL);
340             w = web_client_free(w);
341 #ifdef NETDATA_INTERNAL_CHECKS
342             log_allocations();
343 #endif
344         }
345         else w = w->next;
346     }
347 }
348
349 // 1. it accepts new incoming requests on our port
350 // 2. creates a new web_client for each connection received
351 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
352 // 4. cleans up old web_clients that their pthreads have been exited
353
354 #define CLEANUP_EVERY_EVENTS 100
355
356 void *socket_listen_main_multi_threaded(void *ptr) {
357     (void)ptr;
358
359     web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
360     info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
361
362     struct web_client *w;
363     int retval, counter = 0;
364
365     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
366         error("Cannot set pthread cancel type to DEFERRED.");
367
368     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
369         error("Cannot set pthread cancel state to ENABLE.");
370
371     if(!listen_fds_count)
372         fatal("LISTENER: No sockets to listen to.");
373
374     struct pollfd *fds = callocz(sizeof(struct pollfd), listen_fds_count);
375
376     size_t i;
377     for(i = 0; i < listen_fds_count ;i++) {
378         fds[i].fd = listen_fds[i];
379         fds[i].events = POLLIN;
380         fds[i].revents = 0;
381
382         info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
383     }
384
385     int timeout = 10 * 1000;
386
387     for(;;) {
388         // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
389         retval = poll(fds, listen_fds_count, timeout);
390
391         if(unlikely(retval == -1)) {
392             error("LISTENER: poll() failed.");
393             continue;
394         }
395         else if(unlikely(!retval)) {
396             debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
397             counter = 0;
398             cleanup_web_clients();
399             continue;
400         }
401
402         for(i = 0 ; i < listen_fds_count ; i++) {
403             short int revents = fds[i].revents;
404
405             // check for new incoming connections
406             if(revents & POLLIN || revents & POLLPRI) {
407                 fds[i].revents = 0;
408
409                 w = web_client_create(fds[i].fd);
410                 if(unlikely(!w)) {
411                     // no need for error log - web_client_create already logged the error
412                     continue;
413                 }
414
415                 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
416                     error("%llu: failed to create new thread for web client.", w->id);
417                     w->obsolete = 1;
418                 }
419                 else if(pthread_detach(w->thread) != 0) {
420                     error("%llu: Cannot request detach of newly created web client thread.", w->id);
421                     w->obsolete = 1;
422                 }
423             }
424         }
425
426         // cleanup unused clients
427         counter++;
428         if(counter >= CLEANUP_EVERY_EVENTS) {
429             counter = 0;
430             cleanup_web_clients();
431         }
432     }
433
434     debug(D_WEB_CLIENT, "LISTENER: exit!");
435     close_listen_sockets();
436
437     return NULL;
438 }
439
440 struct web_client *single_threaded_clients[FD_SETSIZE];
441
442 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
443     if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
444         return 1;
445
446     if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
447         error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
448         return 1;
449     }
450
451     FD_SET(w->ifd, efds);
452     if(unlikely(*max < w->ifd)) *max = w->ifd;
453
454     if(unlikely(w->ifd != w->ofd)) {
455         if(*max < w->ofd) *max = w->ofd;
456         FD_SET(w->ofd, efds);
457     }
458
459     if(w->wait_receive) FD_SET(w->ifd, ifds);
460     if(w->wait_send)    FD_SET(w->ofd, ofds);
461
462     single_threaded_clients[w->ifd] = w;
463     single_threaded_clients[w->ofd] = w;
464
465     return 0;
466 }
467
468 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
469     FD_CLR(w->ifd, efds);
470     if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
471
472     if(w->wait_receive) FD_CLR(w->ifd, ifds);
473     if(w->wait_send)    FD_CLR(w->ofd, ofds);
474
475     single_threaded_clients[w->ifd] = NULL;
476     single_threaded_clients[w->ofd] = NULL;
477
478     if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
479         return 1;
480
481     return 0;
482 }
483
484 void *socket_listen_main_single_threaded(void *ptr) {
485     (void)ptr;
486
487     web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
488
489     info("Single-threaded WEB SERVER thread created with task id %d", gettid());
490
491     struct web_client *w;
492     int retval;
493
494     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
495         error("Cannot set pthread cancel type to DEFERRED.");
496
497     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
498         error("Cannot set pthread cancel state to ENABLE.");
499
500     if(!listen_fds_count)
501         fatal("LISTENER: no listen sockets available.");
502
503     size_t i;
504     for(i = 0; i < FD_SETSIZE ; i++)
505         single_threaded_clients[i] = NULL;
506
507     fd_set ifds, ofds, efds, rifds, rofds, refds;
508     FD_ZERO (&ifds);
509     FD_ZERO (&ofds);
510     FD_ZERO (&efds);
511     int fdmax = 0;
512
513     for(i = 0; i < listen_fds_count ; i++) {
514         if (listen_fds[i] < 0 || listen_fds[i] >= FD_SETSIZE)
515             fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fds[i]);
516
517         info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
518
519         FD_SET(listen_fds[i], &ifds);
520         FD_SET(listen_fds[i], &efds);
521         if(fdmax < listen_fds[i])
522             fdmax = listen_fds[i];
523     }
524
525     for(;;) {
526         debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
527
528         struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
529         rifds = ifds;
530         rofds = ofds;
531         refds = efds;
532         retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
533
534         if(unlikely(retval == -1)) {
535             error("LISTENER: select() failed.");
536             continue;
537         }
538         else if(likely(retval)) {
539             debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
540
541             for(i = 0; i < listen_fds_count ; i++) {
542                 if (FD_ISSET(listen_fds[i], &rifds)) {
543                     debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
544                     w = web_client_create(listen_fds[i]);
545                     if (single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
546                         web_client_free(w);
547                     }
548                 }
549             }
550
551             for(i = 0 ; i <= (size_t)fdmax ; i++) {
552                 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
553                     continue;
554
555                 w = single_threaded_clients[i];
556                 if(unlikely(!w))
557                     continue;
558
559                 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
560                     web_client_free(w);
561                     continue;
562                 }
563
564                 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
565                     web_client_free(w);
566                     continue;
567                 }
568
569                 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
570                     if (unlikely(web_client_receive(w) < 0)) {
571                         web_client_free(w);
572                         continue;
573                     }
574
575                     if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
576                         debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
577                         web_client_process(w);
578                     }
579                 }
580
581                 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
582                     if (unlikely(web_client_send(w) < 0)) {
583                         debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
584                         web_client_free(w);
585                         continue;
586                     }
587                 }
588
589                 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
590                     web_client_free(w);
591                 }
592             }
593         }
594         else {
595             debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
596 #ifdef NETDATA_INTERNAL_CHECKS
597             log_allocations();
598 #endif
599         }
600     }
601
602     debug(D_WEB_CLIENT, "LISTENER: exit!");
603     close_listen_sockets();
604     return NULL;
605 }