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