summaryrefslogtreecommitdiffstats
path: root/web/server/web_client.c
blob: 8bc72e71f6f2181dbe37426d3cd93ae9edf29076 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
// SPDX-License-Identifier: GPL-3.0-or-later

#include "web_client.h"

// this is an async I/O implementation of the web server request parser
// it is used by all netdata web servers

int respect_web_browser_do_not_track_policy = 0;
char *web_x_frame_options = NULL;

#ifdef NETDATA_WITH_ZLIB
int web_enable_gzip = 1, web_gzip_level = 3, web_gzip_strategy = Z_DEFAULT_STRATEGY;
#endif /* NETDATA_WITH_ZLIB */

inline int web_client_permission_denied(struct web_client *w) {
    w->response.data->content_type = CT_TEXT_PLAIN;
    buffer_flush(w->response.data);
    buffer_strcat(w->response.data, "You are not allowed to access this resource.");
    w->response.code = HTTP_RESP_FORBIDDEN;
    return HTTP_RESP_FORBIDDEN;
}

static inline int web_client_crock_socket(struct web_client *w __maybe_unused) {
#ifdef TCP_CORK
    if(likely(web_client_is_corkable(w) && !w->tcp_cork && w->ofd != -1)) {
        w->tcp_cork = true;
        if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
            error("%llu: failed to enable TCP_CORK on socket.", w->id);

            w->tcp_cork = false;
            return -1;
        }
    }
#endif /* TCP_CORK */

    return 0;
}

static inline void web_client_enable_wait_from_ssl(struct web_client *w, int bytes) {
    int ssl_err = SSL_get_error(w->ssl.conn, bytes);
    if (ssl_err == SSL_ERROR_WANT_READ)
        web_client_enable_ssl_wait_receive(w);
    else if (ssl_err == SSL_ERROR_WANT_WRITE)
        web_client_enable_ssl_wait_send(w);
    else {
        web_client_disable_ssl_wait_receive(w);
        web_client_disable_ssl_wait_send(w);
    }
}

static inline int web_client_uncrock_socket(struct web_client *w __maybe_unused) {
#ifdef TCP_CORK
    if(likely(w->tcp_cork && w->ofd != -1)) {
        if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
            error("%llu: failed to disable TCP_CORK on socket.", w->id);
            w->tcp_cork = true;
            return -1;
        }
    }
#endif /* TCP_CORK */

    w->tcp_cork = false;
    return 0;
}

char *strip_control_characters(char *url) {
    char *s = url;
    if(!s) return "";

    if(iscntrl(*s)) *s = ' ';
    while(*++s) {
        if(iscntrl(*s)) *s = ' ';
    }

    return url;
}

static void web_client_reset_allocations(struct web_client *w, bool free_all) {

    if(free_all) {
        // the web client is to be destroyed

        buffer_free(w->url_as_received);
        w->url_as_received = NULL;

        buffer_free(w->url_path_decoded);
        w->url_path_decoded = NULL;

        buffer_free(w->url_query_string_decoded);
        w->url_query_string_decoded = NULL;

        buffer_free(w->response.header_output);
        w->response.header_output = NULL;

        buffer_free(w->response.header);
        w->response.header = NULL;

        buffer_free(w->response.data);
        w->response.data = NULL;

        freez(w->post_payload);
        w->post_payload = NULL;
        w->post_payload_size = 0;

#ifdef ENABLE_HTTPS
        if ((!web_client_check_unix(w)) && (netdata_ssl_srv_ctx)) {
            if (w->ssl.conn) {
                SSL_free(w->ssl.conn);
                w->ssl.conn = NULL;
            }
        }
#endif
    }
    else {
        // the web client is to be re-used

        buffer_reset(w->url_as_received);
        buffer_reset(w->url_path_decoded);
        buffer_reset(w->url_query_string_decoded);

        buffer_reset(w->response.header_output);
        buffer_reset(w->response.header);
        buffer_reset(w->response.data);

        // leave w->post_payload
        // leave w->ssl
    }

    freez(w->server_host);
    w->server_host = NULL;

    freez(w->forwarded_host);
    w->forwarded_host = NULL;

    freez(w->origin);
    w->origin = NULL;

    freez(w->user_agent);
    w->user_agent = NULL;

    freez(w->auth_bearer_token);
    w->auth_bearer_token = NULL;

    // if we had enabled compression, release it
#ifdef NETDATA_WITH_ZLIB
    if(w->response.zinitialized) {
        deflateEnd(&w->response.zstream);
        w->response.zsent = 0;
        w->response.zhave = 0;
        w->response.zstream.avail_in = 0;
        w->response.zstream.avail_out = 0;
        w->response.zstream.total_in = 0;
        w->response.zstream.total_out = 0;
        w->response.zinitialized = false;
        w->flags &= ~WEB_CLIENT_CHUNKED_TRANSFER;
    }
#endif // NETDATA_WITH_ZLIB
}

void web_client_request_done(struct web_client *w) {
    web_client_uncrock_socket(w);

    debug(D_WEB_CLIENT, "%llu: Resetting client.", w->id);

    if(likely(buffer_strlen(w->url_as_received))) {
        struct timeval tv;
        now_monotonic_high_precision_timeval(&tv);

        size_t size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
        size_t sent = size;
#ifdef NETDATA_WITH_ZLIB
        if(likely(w->response.zoutput)) sent = (size_t)w->response.zstream.total_out;
#endif

        // --------------------------------------------------------------------
        // global statistics

        global_statistics_web_request_completed(dt_usec(&tv, &w->timings.tv_in),
                                                w->statistics.received_bytes,
                                                w->statistics.sent_bytes,
                                                size,
                                                sent);

        w->statistics.received_bytes = 0;
        w->statistics.sent_bytes = 0;


        // --------------------------------------------------------------------

        const char *mode;
        switch(w->mode) {
            case WEB_CLIENT_MODE_FILECOPY:
                mode = "FILECOPY";
                break;

            case WEB_CLIENT_MODE_OPTIONS:
                mode = "OPTIONS";
                break;

            case WEB_CLIENT_MODE_STREAM:
                mode = "STREAM";
                break;

            case WEB_CLIENT_MODE_POST:
            case WEB_CLIENT_MODE_GET:
                mode = "DATA";
                break;

            default:
                mode = "UNKNOWN";
                break;
        }

        // access log
        log_access("%llu: %d '[%s]:%s' '%s' (sent/all = %zu/%zu bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %d '%s'",
                   w->id
                   , gettid()
                   , w->client_ip
                   , w->client_port
                   , mode
                   , sent
                   , size
                   , -((size > 0) ? ((double)(size - sent) / (double) size * 100.0) : 0.0)
                   , (double)dt_usec(&w->timings.tv_ready, &w->timings.tv_in) / 1000.0
                   , (double)dt_usec(&tv, &w->timings.tv_ready) / 1000.0
                   , (double)dt_usec(&tv, &w->timings.tv_in) / 1000.0
                   , w->response.code
                   , strip_control_characters((char *)buffer_tostring(w->url_as_received))
        );
    }

    if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
        if(w->ifd != w->ofd) {
            debug(D_WEB_CLIENT, "%llu: Closing filecopy input file descriptor %d.", w->id, w->ifd);

            if(web_server_mode != WEB_SERVER_MODE_STATIC_THREADED) {
                if (w->ifd != -1){
                    close(w->ifd);
                }
            }

            w->ifd = w->ofd;
        }
    }

    web_client_reset_allocations(w, false);

    w->mode = WEB_CLIENT_MODE_GET;

    web_client_disable_donottrack(w);
    web_client_disable_tracking_required(w);
    web_client_disable_keepalive(w);

    w->header_parse_tries = 0;
    w->header_parse_last_size = 0;

    web_client_enable_wait_receive(w);
    web_client_disable_wait_send(w);

    w->response.has_cookies = false;
    w->response.rlen = 0;
    w->response.sent = 0;
    w->response.code = 0;
    w->response.zoutput = false;
}

static struct {
    const char *extension;
    uint32_t hash;
    uint8_t contenttype;
} mime_types[] = {
        {  "html" , 0    , CT_TEXT_HTML}
        , {"js"   , 0    , CT_APPLICATION_X_JAVASCRIPT}
        , {"css"  , 0    , CT_TEXT_CSS}
        , {"xml"  , 0    , CT_TEXT_XML}
        , {"xsl"  , 0    , CT_TEXT_XSL}
        , {"txt"  , 0    , CT_TEXT_PLAIN}
        , {"svg"  , 0    , CT_IMAGE_SVG_XML}
        , {"ttf"  , 0    , CT_APPLICATION_X_FONT_TRUETYPE}
        , {"otf"  , 0    , CT_APPLICATION_X_FONT_OPENTYPE}
        , {"woff2", 0    , CT_APPLICATION_FONT_WOFF2}
        , {"woff" , 0    , CT_APPLICATION_FONT_WOFF}
        , {"eot"  , 0    , CT_APPLICATION_VND_MS_FONTOBJ}
        , {"png"  , 0    , CT_IMAGE_PNG}
        , {"jpg"  , 0    , CT_IMAGE_JPG}
        , {"jpeg" , 0    , CT_IMAGE_JPG}
        , {"gif"  , 0    , CT_IMAGE_GIF}
        , {"bmp"  , 0    , CT_IMAGE_BMP}
        , {"ico"  , 0    , CT_IMAGE_XICON}
        , {"icns" , 0    , CT_IMAGE_ICNS}
        , {       NULL, 0, 0}
};

static inline uint8_t contenttype_for_filename(const char *filename) {
    // info("checking filename '%s'", filename);

    static int initialized = 0;
    int i;

    if(unlikely(!initialized)) {
        for (i = 0; mime_types[i].extension; i++)
            mime_types[i].hash = simple_hash(mime_types[i].extension);

        initialized = 1;
    }

    const char *s = filename, *last_dot = NULL;

    // find the last dot
    while(*s) {
        if(unlikely(*s == '.')) last_dot = s;
        s++;
    }

    if(unlikely(!last_dot || !*last_dot || !last_dot[1])) {
        // info("no extension for filename '%s'", filename);
        return CT_APPLICATION_OCTET_STREAM;
    }
    last_dot++;

    // info("extension for filename '%s' is '%s'", filename, last_dot);

    uint32_t hash = simple_hash(last_dot);
    for(i = 0; mime_types[i].extension ; i++) {
        if(unlikely(hash == mime_types[i].hash && !strcmp(last_dot, mime_types[i].extension))) {
            // info("matched extension for filename '%s': '%s'", filename, last_dot);
            return mime_types[i].contenttype;
        }
    }

    // info("not matched extension for filename '%s': '%s'", filename, last_dot);
    return CT_APPLICATION_OCTET_STREAM;
}

static inline int access_to_file_is_not_permitted(struct web_client *w, const char *filename) {
    w->response.data->content_type = CT_TEXT_HTML;
    buffer_strcat(w->response.data, "Access to file is not permitted: ");
    buffer_strcat_htmlescape(w->response.data, filename);
    return HTTP_RESP_FORBIDDEN;
}

// Work around a bug in the CMocka library by removing this function during testing.
#ifndef REMOVE_MYSENDFILE
int mysendfile(struct web_client *w, char *filename) {
    debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, netdata_configured_web_dir, filename);

    if(!web_client_can_access_dashboard(w))
        return web_client_permission_denied(w);

    // skip leading slashes
    while (*filename == '/') filename++;

    // if the filename contains "strange" characters, refuse to serve it
    char *s;
    for(s = filename; *s ;s++) {
        if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
            debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
            w->response.data->content_type = CT_TEXT_HTML;
            buffer_sprintf(w->response.data, "Filename contains invalid characters: ");
            buffer_strcat_htmlescape(w->response.data, filename);
            return HTTP_RESP_BAD_REQUEST;
        }
    }

    // if the filename contains a double dot refuse to serve it
    if(strstr(filename, "..") != 0) {
        debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
        w->response.data->content_type = CT_TEXT_HTML;
        buffer_strcat(w->response.data, "Relative filenames are not supported: ");
        buffer_strcat_htmlescape(w->response.data, filename);
        return HTTP_RESP_BAD_REQUEST;
    }

    // find the physical file on disk
    char webfilename[FILENAME_MAX + 1];
    snprintfz(webfilename, FILENAME_MAX, "%s/%s", netdata_configured_web_dir, filename);

    struct stat statbuf;
    int done = 0;
    while(!done) {
        // check if the file exists
        if (lstat(webfilename, &statbuf) != 0) {
            debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
            w->response.data->content_type = CT_TEXT_HTML;
            buffer_strcat(w->response.data, "File does not exist, or is not accessible: ");
            buffer_strcat_htmlescape(w->response.data, webfilename);
            return HTTP_RESP_NOT_FOUND;
        }

        if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
            snprintfz(webfilename, FILENAME_MAX, "%s/%s/index.html", netdata_configured_web_dir, filename);
            continue;
        }

        if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
            error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
            return access_to_file_is_not_permitted(w, webfilename);
        }

        done = 1;
    }

    // open the file
    w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
    if(w->ifd == -1) {
        w->ifd = w->ofd;

        if(errno == EBUSY || errno == EAGAIN) {
            error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
            w->response.data->content_type = CT_TEXT_HTML;
            buffer_sprintf(w->response.header, "Location: /%s\r\n", filename);
            buffer_strcat(w->response.data, "File is currently busy, please try again later: ");
            buffer_strcat_htmlescape(w->response.data, webfilename);
            return HTTP_RESP_REDIR_TEMP;
        }
        else {
            error("%llu: Cannot open file '%s'.", w->id, webfilename);
            w->response.data->content_type = CT_TEXT_HTML;
            buffer_strcat(w->response.data, "Cannot open file: ");
            buffer_strcat_htmlescape(w->response.data, webfilename);
            return HTTP_RESP_NOT_FOUND;
        }
    }

    sock_setnonblock(w->ifd);

    w->response.data->content_type = contenttype_for_filename(webfilename);
    debug(D_WEB_CLIENT_ACCESS, "%llu: Sending file '%s' (%"PRId64" bytes, ifd %d, ofd %d).", w->id, webfilename, (int64_t)statbuf.st_size, w->ifd, w->ofd);

    w->mode = WEB_CLIENT_MODE_FILECOPY;
    web_client_enable_wait_receive(w);
    web_client_disable_wait_send(w);
    buffer_flush(w->response.data);
    buffer_need_bytes(w->response.data, (size_t)statbuf.st_size);
    w->response.rlen = (size_t)statbuf.st_size;
#ifdef __APPLE__
    w->response.data->date = statbuf.st_mtimespec.tv_sec;
#else
    w->response.data->date = statbuf.st_mtim.tv_sec;
#endif 
    buffer_cacheable(w->response.data);

    return HTTP_RESP_OK;
}
#endif



#ifdef NETDATA_WITH_ZLIB
void web_client_enable_deflate(struct web_client *w, int gzip) {
    if(unlikely(w->response.zinitialized)) {
        debug(D_DEFLATE, "%llu: Compression has already be initialized for this client.", w->id);
        return;
    }

    if(unlikely(w->response.sent)) {
        error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
        return;
    }

    w->response.zstream.zalloc = Z_NULL;
    w->response.zstream.zfree = Z_NULL;
    w->response.zstream.opaque = Z_NULL;

    w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
    w->response.zstream.avail_in = 0;
    w->response.zstream.total_in = 0;

    w->response.zstream.next_out = w->response.zbuffer;
    w->response.zstream.avail_out = 0;
    w->response.zstream.total_out = 0;

    w->response.zstream.zalloc = Z_NULL;
    w->response.zstream.zfree = Z_NULL;
    w->response.zstream.opaque = Z_NULL;

//  if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
//      error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
//      return;
//  }

    // Select GZIP compression: windowbits = 15 + 16 = 31
    if(deflateInit2(&w->response.zstream, web_gzip_level, Z_DEFLATED, 15 + ((gzip)?16:0), 8, web_gzip_strategy) != Z_OK) {
        error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
        return;
    }

    w->response.zsent = 0;
    w->response.zoutput = true;
    w->response.zinitialized = true;
    w->flags |= WEB_CLIENT_CHUNKED_TRANSFER;

    debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
}
#endif // NETDATA_WITH_ZLIB

void buffer_data_options2string(BUFFER *wb, uint32_t options) {
    int count = 0;

    if(options & RRDR_OPTION_NONZERO) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "nonzero");
    }

    if(options & RRDR_OPTION_REVERSED) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "flip");
    }

    if(options & RRDR_OPTION_JSON_WRAP) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "jsonwrap");
    }

    if(options & RRDR_OPTION_MIN2MAX) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "min2max");
    }

    if(options & RRDR_OPTION_MILLISECONDS) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "ms");
    }

    if(options & RRDR_OPTION_ABSOLUTE) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "absolute");
    }

    if(options & RRDR_OPTION_SECONDS) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "seconds");
    }

    if(options & RRDR_OPTION_NULL2ZERO) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "null2zero");
    }

    if(options & RRDR_OPTION_OBJECTSROWS) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "objectrows");
    }

    if(options & RRDR_OPTION_GOOGLE_JSON) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "google_json");
    }

    if(options & RRDR_OPTION_PERCENTAGE) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "percentage");
    }

    if(options & RRDR_OPTION_NOT_ALIGNED) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "unaligned");
    }

    if(options & RRDR_OPTION_ANOMALY_BIT) {
        if(count++) buffer_strcat(wb, " ");
        buffer_strcat(wb, "anomaly-bit");
    }
}

static inline int check_host_and_call(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
    //if(unlikely(host->rrd_memory_mode == RRD_MEMORY_MODE_NONE)) {
    //    buffer_flush(w->response.data);
    //    buffer_strcat(w->response.data, "This host does not maintain a database");
    //    return HTTP_RESP_BAD_REQUEST;
    //}

    return func(host, w, url);
}

static inline int UNUSED_FUNCTION(check_host_and_dashboard_acl_and_call)(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
    if(!web_client_can_access_dashboard(w))
        return web_client_permission_denied(w);

    return check_host_and_call(host, w, url, func);
}

static inline int UNUSED_FUNCTION(check_host_and_mgmt_acl_and_call)(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
    if(!web_client_can_access_mgmt(w))
        return web_client_permission_denied(w);

    return check_host_and_call(host, w, url, func);
}

int web_client_api_request(RRDHOST *host, struct web_client *w, char *url_path_fragment)
{
    // get the api version
    char *tok = strsep_skip_consecutive_separators(&url_path_fragment, "/");
    if(tok && *tok) {
        debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
        if(strcmp(tok, "v2") == 0)
            return web_client_api_request_v2(host, w, url_path_fragment);
        else if(strcmp(tok, "v1") == 0)
            return web_client_api_request_v1(host, w, url_path_fragment);
        else {
            buffer_flush(w->response.data);
            w->response.data->content_type = CT_TEXT_HTML;
            buffer_strcat(w->response.data, "Unsupported API version: ");
            buffer_strcat_htmlescape(w->response.data, tok);
            return HTTP_RESP_NOT_FOUND;
        }
    }
    else {
        buffer_flush(w->response.data);
        buffer_sprintf(w->response.data, "Which API version?");
        return HTTP_RESP_BAD_REQUEST;
    }
}

const char *web_content_type_to_string(HTTP_CONTENT_TYPE content_type) {
    switch(content_type) {
        case CT_TEXT_HTML:
            return "text/html; charset=utf-8";

        case CT_APPLICATION_XML:
            return "application/xml; charset=utf-8";

        case CT_APPLICATION_JSON:
            return "application/json; charset=utf-8";

        case CT_APPLICATION_X_JAVASCRIPT:
            return "application/x-javascript; charset=utf-8";

        case CT_TEXT_CSS:
            return "text/css; charset=utf-8";

        case CT_TEXT_XML:
            return "text/xml; charset=utf-8";

        case CT_TEXT_XSL:
            return "text/xsl; charset=utf-8";

        case CT_APPLICATION_OCTET_STREAM:
            return "application/octet-stream";

        case CT_IMAGE_SVG_XML:
            return "image/svg+xml";

        case CT_APPLICATION_X_FONT_TRUETYPE:
            return "application/x-font-truetype";

        case CT_APPLICATION_X_FONT_OPENTYPE:
            return "application/x-font-opentype";

        case CT_APPLICATION_FONT_WOFF:
            return "application/font-woff";

        case CT_APPLICATION_FONT_WOFF2:
            return "application/font-woff2";

        case CT_APPLICATION_VND_MS_FONTOBJ:
            return "application/vnd.ms-fontobject";

        case CT_IMAGE_PNG:
            return "image/png";

        case CT_IMAGE_JPG:
            return "image/jpeg";

        case CT_IMAGE_GIF:
            return "image/gif";

        case CT_IMAGE_XICON:
            return "image/x-icon";

        case CT_IMAGE_BMP:
            return "image/bmp";

        case CT_IMAGE_ICNS:
            return "image/icns";

        case CT_PROMETHEUS:
            return "text/plain; version=0.0.4";

        default:
        case CT_TEXT_PLAIN:
            return "text/plain; charset=utf-8";
    }
}


const char *web_response_code_to_string(int code) {
    switch(code) {
        case HTTP_RESP_OK:
            return "OK";

        case HTTP_RESP_MOVED_PERM:
            return "Moved Permanently";

        case HTTP_RESP_REDIR_TEMP:
            return "Temporary Redirect";

        case HTTP_RESP_BAD_REQUEST:
            return "Bad Request";

        case HTTP_RESP_FORBIDDEN:
            return "Forbidden";

        case HTTP_RESP_NOT_FOUND:
            return "Not Found";

        case HTTP_RESP_PRECOND_FAIL:
            return "Preconditions Failed";

        default:
            if(code >= 100 && code < 200)
                return "Informational";

            if(code >= 200 && code < 300)
                return "Successful";

            if(code >= 300 && code < 400)
                return "Redirection";

            if(code >= 400 && code < 500)
                return "Bad Request";

            if(code >= 500 && code < 600)
                return "Server Error";

            return "Undefined Error";
    }
}

static inline char *http_header_parse(struct web_client *w, char *s, int parse_useragent) {
    static uint32_t hash_origin = 0, hash_connection = 0, hash_donottrack = 0, hash_useragent = 0,
                    hash_authorization = 0, hash_host = 0, hash_forwarded_proto = 0, hash_forwarded_host = 0;
#ifdef NETDATA_WITH_ZLIB
    static uint32_t hash_accept_encoding = 0;
#endif

    if(unlikely(!hash_origin)) {
        hash_origin = simple_uhash("Origin");
        hash_connection = simple_uhash("Connection");
#ifdef NETDATA_WITH_ZLIB
        hash_accept_encoding = simple_uhash("Accept-Encoding");
#endif
        hash_donottrack = simple_uhash("DNT");
        hash_useragent = simple_uhash("User-Agent");
        hash_authorization = simple_uhash("X-Auth-Token");
        hash_host = simple_uhash("Host");
        hash_forwarded_proto = simple_uhash("X-Forwarded-Proto");
        hash_forwarded_host = simple_uhash("X-Forwarded-Host");
    }

    char *e = s;

    // find the :
    while(*e && *e != ':') e++;
    if(!*e) return e;

    // get the name
    *e = '\0';

    // find the value
    char *v = e + 1, *ve;

    // skip leading spaces from value
    while(*v == ' ') v++;
    ve = v;

    // find the \r
    while(*ve && *ve != '\r') ve++;
    if(!*ve || ve[1] != '\n') {
        *e = ':';
        return ve;
    }

    // terminate the value
    *ve = '\0';

    uint32_t hash = simple_uhash(s);

    if(hash == hash_origin && !strcasecmp(s, "Origin"))
        w->origin = strdupz(v);

    else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
        if(strcasestr(v, "keep-alive"))
            web_client_enable_keepalive(w);
    }
    else if(respect_web_browser_do_not_track_policy && hash == hash_donottrack && !strcasecmp(s, "DNT")) {
        if(*v == '0') web_client_disable_donottrack(w);
        else if(*v == '1') web_client_enable_donottrack(w);
    }
    else if(parse_useragent && hash == hash_useragent && !strcasecmp(s, "User-Agent")) {
        w->user_agent = strdupz(v);
    }
    else if(hash == hash_authorization&& !strcasecmp(s, "X-Auth-Token")) {
        w->auth_bearer_token = strdupz(v);
    }
    else if(hash == hash_host && !strcasecmp(s, "Host")) {
        char buffer[NI_MAXHOST];
        strncpyz(buffer, v, ((size_t)(ve - v) < sizeof(buffer) - 1 ? (size_t)(ve - v) : sizeof(buffer) - 1));
        w->server_host = strdupz(buffer);
    }
#ifdef NETDATA_WITH_ZLIB
    else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
        if(web_enable_gzip) {
            if(strcasestr(v, "gzip"))
                web_client_enable_deflate(w, 1);
            //
            // does not seem to work
            // else if(strcasestr(v, "deflate"))
            //  web_client_enable_deflate(w, 0);
        }
    }
#endif /* NETDATA_WITH_ZLIB */
#ifdef ENABLE_HTTPS
    else if(hash == hash_forwarded_proto && !strcasecmp(s, "X-Forwarded-Proto")) {
        if(strcasestr(v, "https"))
            w->ssl.flags |= NETDATA_SSL_PROXY_HTTPS;
    }
#endif
    else if(hash == hash_forwarded_host && !strcasecmp(s, "X-Forwarded-Host")) {
        char buffer[NI_MAXHOST];
        strncpyz(buffer, v, ((size_t)(ve - v) < sizeof(buffer) - 1 ? (size_t)(ve - v) : sizeof(buffer) - 1));
        w->forwarded_host = strdupz(buffer);
    }

    *e = ':';
    *ve = '\r';
    return ve;
}

/**
 * Valid Method
 *
 * Netdata accepts only three methods, including one of these three(STREAM) is an internal method.
 *
 * @param w is the structure with the client request
 * @param s is the start string to parse
 *
 * @return it returns the next address to parse case the method is valid and NULL otherwise.
 */
static inline char *web_client_valid_method(struct web_client *w, char *s) {
    // is is a valid request?
    if(!strncmp(s, "GET ", 4)) {
        s = &s[4];
        w->mode = WEB_CLIENT_MODE_GET;
    }
    else if(!strncmp(s, "OPTIONS ", 8)) {
        s = &s[8];
        w->mode = WEB_CLIENT_MODE_OPTIONS;
    }
    else if(!strncmp(s, "POST ", 5)) {
        s = &s[5];
        w->mode = WEB_CLIENT_MODE_POST;
    }
    else if(!strncmp(s, "STREAM ", 7)) {
        s = &s[7];

#ifdef ENABLE_HTTPS
        if (w->ssl.flags && web_client_is_using_ssl_force(w)){
            w->header_parse_tries = 0;
            w->header_parse_last_size = 0;
            web_client_disable_wait_receive(w);

            char hostname[256];
            char *copyme = strstr(s,"hostname=");
            if ( copyme ){
                copyme += 9;
                char *end = strchr(copyme,'&');
                if(end){
                    size_t length = MIN(255, end - copyme);
                    memcpy(hostname,copyme,length);
                    hostname[length] = 0X00;
                }
                else{
                    memcpy(hostname,"not available",13);
                    hostname[13] = 0x00;
                }
            }
            else{
                memcpy(hostname,"not available",13);
                hostname[13] = 0x00;
            }
            error("The server is configured to always use encrypted connections, please enable the SSL on child with hostname '%s'.",hostname);
            s = NULL;
        }
#endif

        w->mode = WEB_CLIENT_MODE_STREAM;
    }
    else {
        s = NULL;
    }

    return s;
}

/**
 * Request validate
 *
 * @param w is the structure with the client request
 *
 * @return It returns HTTP_VALIDATION_OK on success and another code present
 *          in the enum HTTP_VALIDATION otherwise.
 */
static inline HTTP_VALIDATION http_request_validate(struct web_client *w) {
    char *s = (char *)buffer_tostring(w->response.data), *encoded_url = NULL;

    size_t last_pos = w->header_parse_last_size;

    w->header_parse_tries++;
    w->header_parse_last_size = buffer_strlen(w->response.data);

    int is_it_valid;
    if(w->header_parse_tries > 1) {
        if(last_pos > 4) last_pos -= 4; // allow searching for \r\n\r\n
        else last_pos = 0;

        if(w->header_parse_last_size < last_pos)
            last_pos = 0;

        is_it_valid = url_is_request_complete(s, &s[last_pos], w->header_parse_last_size, &w->post_payload, &w->post_payload_size);
        if(!is_it_valid) {
            if(w->header_parse_tries > HTTP_REQ_MAX_HEADER_FETCH_TRIES) {
                info("Disabling slow client after %zu attempts to read the request (%zu bytes received)", w->header_parse_tries, buffer_strlen(w->response.data));
                w->header_parse_tries = 0;
                w->header_parse_last_size = 0;
                web_client_disable_wait_receive(w);
                return HTTP_VALIDATION_TOO_MANY_READ_RETRIES;
            }

            return HTTP_VALIDATION_INCOMPLETE;
        }

        is_it_valid = 1;
    } else {
        last_pos = w->header_parse_last_size;
        is_it_valid = url_is_request_complete(s, &s[last_pos], w->header_parse_last_size, &w->post_payload, &w->post_payload_size);
    }

    s = web_client_valid_method(w, s);
    if (!s) {
        w->header_parse_tries = 0;
        w->header_parse_last_size = 0;
        web_client_disable_wait_receive(w);

        return HTTP_VALIDATION_NOT_SUPPORTED;
    } else if (!is_it_valid) {
        //Invalid request, we have more data after the end of message
        char *check = strstr((char *)buffer_tostring(w->response.data), "\r\n\r\n");
        if(check) {
            check += 4;
            if (*check) {
                w->header_parse_tries = 0;
                w->header_parse_last_size = 0;
                web_client_disable_wait_receive(w);
                return HTTP_VALIDATION_EXCESS_REQUEST_DATA;
            }
        }
        web_client_enable_wait_receive(w);
        return HTTP_VALIDATION_INCOMPLETE;
    }

    //After the method we have the path and query string together
    encoded_url = s;

    //we search for the position where we have " HTTP/", because it finishes the user request
    s = url_find_protocol(s);

    // incomplete requests
    if(unlikely(!*s)) {
        web_client_enable_wait_receive(w);
        return HTTP_VALIDATION_INCOMPLETE;
    }

    // we have the end of encoded_url - remember it
    char *ue = s;

    // make sure we have complete request
    // complete requests contain: \r\n\r\n
    while(*s) {
        // find a line feed
        while(*s && *s++ != '\r');

        // did we reach the end?
        if(unlikely(!*s)) break;

        // is it \r\n ?
        if(likely(*s++ == '\n')) {

            // is it again \r\n ? (header end)
            if(unlikely(*s == '\r' && s[1] == '\n')) {
                // a valid complete HTTP request found

                char c = *ue;
                *ue = '\0';
                web_client_decode_path_and_query_string(w, encoded_url);
                *ue = c;

#ifdef ENABLE_HTTPS
                if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
                    if ((w->ssl.conn) && ((w->ssl.flags & NETDATA_SSL_NO_HANDSHAKE) && (web_client_is_using_ssl_force(w) || web_client_is_using_ssl_default(w)) && (w->mode != WEB_CLIENT_MODE_STREAM))  ) {
                        w->header_parse_tries = 0;
                        w->header_parse_last_size = 0;
                        web_client_disable_wait_receive(w);
                        return HTTP_VALIDATION_REDIRECT;
                    }
                }
#endif

                w->header_parse_tries = 0;
                w->header_parse_last_size = 0;
                web_client_disable_wait_receive(w);
                return HTTP_VALIDATION_OK;
            }

            // another header line
            s = http_header_parse(w, s, (w->mode == WEB_CLIENT_MODE_STREAM)); // parse user agent
        }
    }

    // incomplete request
    web_client_enable_wait_receive(w);
    return HTTP_VALIDATION_INCOMPLETE;
}

static inline ssize_t web_client_send_data(struct web_client *w,const void *buf,size_t len, int flags)
{
    ssize_t bytes;
#ifdef ENABLE_HTTPS
    if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
        if ( ( w->ssl.conn ) && ( !w->ssl.flags ) ){
            bytes = netdata_ssl_write(w->ssl.conn, buf, len) ;
            web_client_enable_wait_from_ssl(w, bytes);
        } else {
            bytes = send(w->ofd,buf, len , flags);
        }
    } else {
        bytes = send(w->ofd,buf, len , flags);
    }
#else
    bytes = send(w->ofd, buf, len, flags);
#endif

    return bytes;
}

void web_client_build_http_header(struct web_client *w) {
    if(unlikely(w->response.code != HTTP_RESP_OK))
        buffer_no_cacheable(w->response.data);

    // set a proper expiration date, if not already set
    if(unlikely(!w->response.data->expires)) {
        if(w->response.data->options & WB_CONTENT_NO_CACHEABLE)
            w->response.data->expires = w->timings.tv_ready.tv_sec + localhost->rrd_update_every;
        else
            w->response.data->expires = w->timings.tv_ready.tv_sec + 86400;
    }

    // prepare the HTTP response header
    debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, w->response.code);

    const char *content_type_string = web_content_type_to_string(w->response.data->content_type);
    const char *code_msg = web_response_code_to_string(w->response.code);

    // prepare the last modified and expiration dates
    char date[32], edate[32];
    {
        struct tm tmbuf, *tm;

        tm = gmtime_r(&w->response.data->date, &tmbuf);
        strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);

        tm = gmtime_r(&w->response.data->expires, &tmbuf);
        strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", tm);
    }

    if (w->response.code == HTTP_RESP_MOVED_PERM) {
        buffer_sprintf(w->response.header_output,
                       "HTTP/1.1 %d %s\r\n"
                       "Location: https://%s%s\r\n",
                       w->response.code, code_msg,
                       w->server_host ? w->server_host : "",
                       buffer_tostring(w->url_as_received));
    }else {
        buffer_sprintf(w->response.header_output,
                       "HTTP/1.1 %d %s\r\n"
                       "Connection: %s\r\n"
                       "Server: Netdata Embedded HTTP Server %s\r\n"
                       "Access-Control-Allow-Origin: %s\r\n"
                       "Access-Control-Allow-Credentials: true\r\n"
                       "Content-Type: %s\r\n"
                       "Date: %s\r\n",
                       w->response.code,
                       code_msg,
                       web_client_has_keepalive(w)?"keep-alive":"close",
                       VERSION,
                       w->origin ? w->origin : "*",
                       content_type_string,
                       date);
    }

    if(unlikely(web_x_frame_options))
        buffer_sprintf(w->response.header_output, "X-Frame-Options: %s\r\n", web_x_frame_options);

    if(w->response.has_cookies) {
        if(respect_web_browser_do_not_track_policy)
            buffer_sprintf(w->response.header_output,
                           "Tk: T;cookies\r\n");
    }
    else {
        if(respect_web_browser_do_not_track_policy) {
            if(web_client_has_tracking_required(w))
                buffer_sprintf(w->response.header_output,
                               "Tk: T;cookies\r\n");
            else
                buffer_sprintf(w->response.header_output,
                               "Tk: N\r\n");
        }
    }

    if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
        buffer_strcat(w->response.header_output,
                "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
                        "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie, pragma, cache-control, x-auth-token\r\n"
                        "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
        );
    }
    else {
        buffer_sprintf(w->response.header_output,
                "Cache-Control: %s\r\n"
                        "Expires: %s\r\n",
                (w->response.data->options & WB_CONTENT_NO_CACHEABLE)?"no-cache, no-store, must-revalidate\r\nPragma: no-cache":"public",
                edate);
    }

    // copy a possibly available custom header
    if(unlikely(buffer_strlen(w->response.header)))
        buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));

    // headers related to the transfer method
    if(likely(w->response.zoutput))
        buffer_strcat(w->response.header_output, "Content-Encoding: gzip\r\n");

    if(likely(w->flags & WEB_CLIENT_CHUNKED_TRANSFER))
        buffer_strcat(w->response.header_output, "Transfer-Encoding: chunked\r\n");
    else {
        if(likely((w->response.data->len || w->response.rlen))) {
            // we know the content length, put it
            buffer_sprintf(w->response.header_output, "Content-Length: %zu\r\n", w->response.data->len? w->response.data->len: w->response.rlen);
        }
        else {
            // we don't know the content length, disable keep-alive
            web_client_disable_keepalive(w);
        }
    }

    // end of HTTP header
    buffer_strcat(w->response.header_output, "\r\n");
}

static inline void web_client_send_http_header(struct web_client *w) {
    web_client_build_http_header(w);

    // sent the HTTP header
    debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %zu: '%s'"
          , w->id
          , buffer_strlen(w->response.header_output)
          , buffer_tostring(w->response.header_output)
    );

    web_client_crock_socket(w);

    size_t count = 0;
    ssize_t bytes;
#ifdef ENABLE_HTTPS
    if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
        if ( ( w->ssl.conn ) && ( w->ssl.flags == NETDATA_SSL_HANDSHAKE_COMPLETE ) ) {
            bytes = netdata_ssl_write(w->ssl.conn, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output));
            web_client_enable_wait_from_ssl(w, bytes);
        }
        else {
            while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
                count++;

                if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
                    error("Cannot send HTTP headers to web client.");
                    break;
                }
            }
        }
    }
    else {
        while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
            count++;

            if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
                error("Cannot send HTTP headers to web client.");
                break;
            }
        }
    }
#else
    while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
        count++;

        if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
            error("Cannot send HTTP headers to web client.");
            break;
        }
    }
#endif

    if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
        if(bytes > 0)
            w->statistics.sent_bytes += bytes;

        if (bytes < 0) {

            error("HTTP headers failed to be sent (I sent %zu bytes but the system sent %zd bytes). Closing web client."
                  , buffer_strlen(w->response.header_output)
                  , bytes);

            WEB_CLIENT_IS_DEAD(w);
            return;
        }
    }
    else
        w->statistics.sent_bytes += bytes;
}

static inline int web_client_switch_host(RRDHOST *host, struct web_client *w, char *url, bool nodeid, int (*func)(RRDHOST *, struct web_client *, char *)) {
    static uint32_t hash_localhost = 0;

    if(unlikely(!hash_localhost)) {
        hash_localhost = simple_hash("localhost");
    }

    if(host != localhost) {
        buffer_flush(w->response.data);
        buffer_strcat(w->response.data, "Nesting of hosts is not allowed.");
        return HTTP_RESP_BAD_REQUEST;
    }

    char *tok = strsep_skip_consecutive_separators(&url, "/");
    if(tok && *tok) {
        debug(D_WEB_CLIENT, "%llu: Searching for host with name '%s'.", w->id, tok);

        if(nodeid) {
            host = find_host_by_node_id(tok);
            if(!host) {
                host = rrdhost_find_by_hostname(tok);
                if (!host)
                    host = rrdhost_find_by_guid(tok);
            }
        }
        else {
            host = rrdhost_find_by_hostname(tok);
            if(!host) {
                host = rrdhost_find_by_guid(tok);
                if (!host)
                    host = find_host_by_node_id(tok);
            }
        }

        if(!host) {
            // we didn't find it, but it may be a uuid case mismatch for MACHINE_GUID
            // so, recreate the machine guid in lower-case.
            uuid_t uuid;
            char txt[UUID_STR_LEN];
            if (uuid_parse(tok, uuid) == 0) {
                uuid_unparse_lower(uuid, txt);
                host = rrdhost_find_by_guid(txt);
            }
        }

        if (host) {
            if(!url) { //no delim found
                debug(D_WEB_CLIENT, "%llu: URL doesn't end with / generating redirect.", w->id);
                char *protocol, *url_host;
#ifdef ENABLE_HTTPS
                protocol = ((w->ssl.conn && !w->ssl.flags) || w->ssl.flags & NETDATA_SSL_PROXY_HTTPS) ? "https" : "http";
#else
                protocol = "http";
#endif

                url_host = w->forwarded_host;
                if(!url_host) {
                    url_host = w->server_host;
                    if(!url_host) url_host = "";
                }

                buffer_sprintf(w->response.header, "Location: %s://%s/%s/%s/%s",
                               protocol, url_host, nodeid?"node":"host", tok, buffer_tostring(w->url_path_decoded));

                if(buffer_strlen(w->url_query_string_decoded)) {
                    const char *query_string = buffer_tostring(w->url_query_string_decoded);
                    if(*query_string) {
                        if(*query_string != '?')
                            buffer_fast_strcat(w->response.header, "?", 1);
                        buffer_strcat(w->response.header, query_string);
                    }
                }
                buffer_fast_strcat(w->response.header, "\r\n", 2);
                buffer_strcat(w->response.data, "Permanent redirect");
                return HTTP_RESP_REDIR_PERM;
            }

            size_t len = strlen(url) + 2;
            char buf[len];
            buf[0] = '/';
            strcpy(&buf[1], url);
            buf[len - 1] = '\0';

            buffer_flush(w->url_path_decoded);
            buffer_strcat(w->url_path_decoded, buf);
            return func(host, w, buf);
        }
    }

    buffer_flush(w->response.data);
    w->response.data->content_type = CT_TEXT_HTML;
    buffer_strcat(w->response.data, "This netdata does not maintain a database for host: ");
    buffer_strcat_htmlescape(w->response.data, tok?tok:"");
    return HTTP_RESP_NOT_FOUND;
}

int web_client_api_request_with_node_selection(RRDHOST *host, struct web_client *w, char *decoded_url_path) {
    static uint32_t
            hash_api = 0,
            hash_host = 0,
            hash_node = 0;

    if(unlikely(!hash_api)) {
        hash_api = simple_hash("api");
        hash_host = simple_hash("host");
        hash_node = simple_hash("node");
    }

    char *tok = strsep_skip_consecutive_separators(&decoded_url_path, "/?");
    if(likely(tok && *tok)) {
        uint32_t hash = simple_hash(tok);

        if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) {
            // current API
            debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
            return check_host_and_call(host, w, decoded_url_path, web_client_api_request);
        }
        else if(unlikely((hash == hash_host && strcmp(tok, "host") == 0) || (hash == hash_node && strcmp(tok, "node") == 0))) {
            // host switching
            debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
            return web_client_switch_host(host, w, decoded_url_path, hash == hash_node, web_client_api_request_with_node_selection);
        }
    }

    buffer_flush(w->response.data);
    buffer_strcat(w->response.data, "Unknown API endpoint.");
    w->response.data->content_type = CT_TEXT_HTML;
    return HTTP_RESP_NOT_FOUND;
}

static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *decoded_url_path) {
    if(unlikely(!service_running(ABILITY_WEB_REQUESTS)))
        return web_client_permission_denied(w);

    static uint32_t
            hash_api = 0,
            hash_netdata_conf = 0,
            hash_host = 0,
            hash_node = 0;

#ifdef NETDATA_INTERNAL_CHECKS
    static uint32_t hash_exit = 0, hash_debug = 0, hash_mirror = 0;
#endif

    if(unlikely(!hash_api)) {
        hash_api = simple_hash("api");
        hash_netdata_conf = simple_hash("netdata.conf");
        hash_host = simple_hash("host");
        hash_node = simple_hash("node");
#ifdef NETDATA_INTERNAL_CHECKS
        hash_exit = simple_hash("exit");
        hash_debug = simple_hash("debug");
        hash_mirror = simple_hash("mirror");
#endif
    }

    // keep a copy of the decoded path, in case we need to serve it as a filename
    char filename[FILENAME_MAX + 1];
    strncpyz(filename, buffer_tostring(w->url_path_decoded), FILENAME_MAX);

    char *tok = strsep_skip_consecutive_separators(&decoded_url_path, "/?");
    if(likely(tok && *tok)) {
        uint32_t hash = simple_hash(tok);
        debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);

        if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) {                           // current API
            debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
            return check_host_and_call(host, w, decoded_url_path, web_client_api_request);
        }
        else if(unlikely((hash == hash_host && strcmp(tok, "host") == 0) || (hash == hash_node && strcmp(tok, "node") == 0))) { // host switching
            debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
            return web_client_switch_host(host, w, decoded_url_path, hash == hash_node, web_client_process_url);
        }
        else if(unlikely(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0)) {    // netdata.conf
            if(unlikely(!web_client_can_access_netdataconf(w)))
                return web_client_permission_denied(w);

            debug(D_WEB_CLIENT_ACCESS, "%llu: generating netdata.conf ...", w->id);
            w->response.data->content_type = CT_TEXT_PLAIN;
            buffer_flush(w->response.data);
            config_generate(w->response.data, 0);
            return HTTP_RESP_OK;
        }
#ifdef NETDATA_INTERNAL_CHECKS
        else if(unlikely(hash == hash_exit && strcmp(tok, "exit") == 0)) {
            if(unlikely(!web_client_can_access_netdataconf(w)))
                return web_client_permission_denied(w);

            w->response.data->content_type = CT_TEXT_PLAIN;
            buffer_flush(w->response.data);

            if(!netdata_exit)
                buffer_strcat(w->response.data, "ok, will do...");
            else
                buffer_strcat(w->response.data, "I am doing it already");

            error("web request to exit received.");
            netdata_cleanup_and_exit(0);
            return HTTP_RESP_OK;
        }
        else if(unlikely(hash == hash_debug && strcmp(tok, "debug") == 0)) {
            if(unlikely(!web_client_can_access_netdataconf(w)))
                return web_client_permission_denied(w);

            buffer_flush(w->response.data);

            // get the name of the data to show
            tok = strsep_skip_consecutive_separators(&decoded_url_path, "&");
            if(tok && *tok) {
                debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);

                // do we have such a data set?
                RRDSET *st = rrdset_find_byname(host, tok);
                if(!st) st = rrdset_find(host, tok);
                if(!st) {
                    w->response.data->content_type = CT_TEXT_HTML;
                    buffer_strcat(w->response.data, "Chart is not found: ");
                    buffer_strcat_htmlescape(w->response.data, tok);
                    debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
                    return HTTP_RESP_NOT_FOUND;
                }

                debug_flags |= D_RRD_STATS;

                if(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))
                    rrdset_flag_clear(st, RRDSET_FLAG_DEBUG);
                else
                    rrdset_flag_set(st, RRDSET_FLAG_DEBUG);

                w->response.data->content_type = CT_TEXT_HTML;
                buffer_sprintf(w->response.data, "Chart has now debug %s: ", rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
                buffer_strcat_htmlescape(w->response.data, tok);
                debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
                return HTTP_RESP_OK;
            }

            buffer_flush(w->response.data);
            buffer_strcat(w->response.data, "debug which chart?\r\n");
            return HTTP_RESP_BAD_REQUEST;
        }
        else if(unlikely(hash == hash_mirror && strcmp(tok, "mirror") == 0)) {
            if(unlikely(!web_client_can_access_netdataconf(w)))
                return web_client_permission_denied(w);

            debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);

            // replace the zero bytes with spaces
            buffer_char_replace(w->response.data, '\0', ' ');

            // just leave the buffer as-is
            // it will be copied back to the client

            return HTTP_RESP_OK;
        }
#endif  /* NETDATA_INTERNAL_CHECKS */
    }

    buffer_flush(w->response.data);
    return mysendfile(w, filename);
}

void web_client_process_request(struct web_client *w) {

    // start timing us
    web_client_timeout_checkpoint_init(w);

    switch(http_request_validate(w)) {
        case HTTP_VALIDATION_OK:
            switch(w->mode) {
                case WEB_CLIENT_MODE_STREAM:
                    if(unlikely(!web_client_can_access_stream(w))) {
                        web_client_permission_denied(w);
                        return;
                    }

                    w->response.code = rrdpush_receiver_thread_spawn(w, (char *)buffer_tostring(w->url_query_string_decoded));
                    return;

                case WEB_CLIENT_MODE_OPTIONS:
                    if(unlikely(
                            !web_client_can_access_dashboard(w) &&
                            !web_client_can_access_registry(w) &&
                            !web_client_can_access_badges(w) &&
                            !web_client_can_access_mgmt(w) &&
                            !web_client_can_access_netdataconf(w)
                    )) {
                        web_client_permission_denied(w);
                        break;
                    }

                    w->response.data->content_type = CT_TEXT_PLAIN;
                    buffer_flush(w->response.data);
                    buffer_strcat(w->response.data, "OK");
                    w->response.code = HTTP_RESP_OK;
                    break;

                case WEB_CLIENT_MODE_FILECOPY:
                case WEB_CLIENT_MODE_POST:
                case WEB_CLIENT_MODE_GET:
                    if(unlikely(
                            !web_client_can_access_dashboard(w) &&
                            !web_client_can_access_registry(w) &&
                            !web_client_can_access_badges(w) &&
                            !web_client_can_access_mgmt(w) &&
                            !web_client_can_access_netdataconf(w)
                    )) {
                        web_client_permission_denied(w);
                        break;
                    }

                    w->response.code = web_client_process_url(localhost, w, (char *)buffer_tostring(w->url_path_decoded));
                    break;
            }
            break;

        case HTTP_VALIDATION_INCOMPLETE:
            if(w->response.data->len > NETDATA_WEB_REQUEST_MAX_SIZE) {
                buffer_flush(w->url_as_received);
                buffer_strcat(w->url_as_received, "too big request");

                debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zu bytes).", w->id, w->response.data->len);

                size_t len = w->response.data->len;
                buffer_flush(w->response.data);
                buffer_sprintf(w->response.data, "Received request is too big  (received %zu bytes, max is %zu bytes).\r\n", len, (size_t)NETDATA_WEB_REQUEST_MAX_SIZE);
                w->response.code = HTTP_RESP_BAD_REQUEST;
            }
            else {
                // wait for more data
                // set to normal to prevent web_server_rcv_callback
                // from going into stream mode
                if (w->mode == WEB_CLIENT_MODE_STREAM)
                    w->mode = WEB_CLIENT_MODE_GET;
                return;
            }
            break;
#ifdef ENABLE_HTTPS
        case HTTP_VALIDATION_REDIRECT:
        {
            buffer_flush(w->response.data);
            w->response.data->content_type = CT_TEXT_HTML;
            buffer_strcat(w->response.data,
                          "<!DOCTYPE html><!-- SPDX-License-Identifier: GPL-3.0-or-later --><html>"
                          "<body onload=\"window.location.href ='https://'+ window.location.hostname +"
                          " ':' + window.location.port + window.location.pathname + window.location.search\">"
                          "Redirecting to safety connection, case your browser does not support redirection, please"
                          " click <a onclick=\"window.location.href ='https://'+ window.location.hostname + ':' "
                          " + window.location.port + window.location.pathname + window.location.search\">here</a>."
                          "</body></html>");
            w->response.code = HTTP_RESP_MOVED_PERM;
            break;
        }
#endif
        case HTTP_VALIDATION_MALFORMED_URL:
            debug(D_WEB_CLIENT_ACCESS, "%llu: Malformed URL '%s'.", w->id, w->response.data->buffer);

            buffer_flush(w->response.data);
            buffer_strcat(w->response.data, "Malformed URL...\r\n");
            w->response.code = HTTP_RESP_BAD_REQUEST;
            break;
        case HTTP_VALIDATION_EXCESS_REQUEST_DATA:
            debug(D_WEB_CLIENT_ACCESS, "%llu: Excess data in request '%s'.", w->id, w->response.data->buffer);

            buffer_flush(w->response.data);
            buffer_strcat(w->response.data, "Excess data in request.\r\n");
            w->response.code = HTTP_RESP_BAD_REQUEST;
            break;
        case HTTP_VALIDATION_TOO_MANY_READ_RETRIES:
            debug(D_WEB_CLIENT_ACCESS, "%llu: Too many retries to read request '%s'.", w->id, w->response.data->buffer);

            buffer_flush(w->response.data);
            buffer_strcat(w->response.data, "Too many retries to read request.\r\n");
            w->response.code = HTTP_RESP_BAD_REQUEST;
            break;
        case HTTP_VALIDATION_NOT_SUPPORTED:
            debug(D_WEB_CLIENT_ACCESS, "%llu: HTTP method requested is not supported '%s'.", w->id, w->response.data->buffer);

            buffer_flush(w->response.data);
            buffer_strcat(w->response.data, "HTTP method requested is not supported...\r\n");
            w->response.code = HTTP_RESP_BAD_REQUEST;
            break;
    }

    // keep track of the processing time
    web_client_timeout_checkpoint_response_ready(w, NULL);

    w->response.sent = 0;

    // set a proper last modified date
    if(unlikely(!w->response.data->date))
        w->response.data->date = w->timings.tv_ready.tv_sec;

    web_client_send_http_header(w);

    // enable sending immediately if we have data
    if(w->response.data->len) web_client_enable_wait_send(w);
    else web_client_disable_wait_send(w);

    switch(w->mode) {
        case WEB_CLIENT_MODE_STREAM:
            debug(D_WEB_CLIENT, "%llu: STREAM done.", w->id);
            break;

        case WEB_CLIENT_MODE_OPTIONS:
            debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
            break;

        case WEB_CLIENT_MODE_POST:
        case WEB_CLIENT_MODE_GET:
            debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
            break;

        case WEB_CLIENT_MODE_FILECOPY:
            if(w->response.rlen) {
                debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %zu bytes to client.", w->id, w->response.rlen);
                web_client_enable_wait_receive(w);

                /*
                // utilize the kernel sendfile() for copying the file to the socket.
                // this block of code can be commented, without anything missing.
                // when it is commented, the program will copy the data using async I/O.
                {
                    long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
                    if(len != w->response.data->rbytes)
                        error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
                    else
                        web_client_request_done(w);
                }
                */
            }
            else
                debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
            break;

        default:
            fatal("%llu: Unknown client mode %u.", w->id, w->mode);
            break;
    }
}

ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
{
    debug(D_DEFLATE, "%llu: OPEN CHUNK of %zu bytes (hex: %zx).", w->id, len, len);
    char buf[24];
    ssize_t bytes;
    bytes = (ssize_t)sprintf(buf, "%zX\r\n", len);
    buf[bytes] = 0x00;

    bytes = web_client_send_data(w,buf,strlen(buf),0);
    if(bytes > 0) {
        debug(D_DEFLATE, "%llu: Sent chunk header %zd bytes.", w->id, bytes);
        w->statistics.sent_bytes += bytes;
    }

    else if(bytes == 0) {
        debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
    }
    else {
        debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    }

    return bytes;
}

ssize_t web_client_send_chunk_close(struct web_client *w)
{
    //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);

    ssize_t bytes;
    bytes = web_client_send_data(w,"\r\n",2,0);
    if(bytes > 0) {
        debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
        w->statistics.sent_bytes += bytes;
    }

    else if(bytes == 0) {
        debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
    }
    else {
        debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    }

    return bytes;
}

ssize_t web_client_send_chunk_finalize(struct web_client *w)
{
    //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);

    ssize_t bytes;
    bytes = web_client_send_data(w,"\r\n0\r\n\r\n",7,0);
    if(bytes > 0) {
        debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
        w->statistics.sent_bytes += bytes;
    }

    else if(bytes == 0) {
        debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
    }
    else {
        debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    }

    return bytes;
}

#ifdef NETDATA_WITH_ZLIB
ssize_t web_client_send_deflate(struct web_client *w)
{
    ssize_t len = 0, t = 0;

    // when using compression,
    // w->response.sent is the amount of bytes passed through compression

    debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %zu, w->response.sent = %zu, w->response.zhave = %zu, w->response.zsent = %zu, w->response.zstream.avail_in = %u, w->response.zstream.avail_out = %u, w->response.zstream.total_in = %lu, w->response.zstream.total_out = %lu.",
        w->id, w->response.data->len, w->response.sent, w->response.zhave, w->response.zsent, w->response.zstream.avail_in, w->response.zstream.avail_out, w->response.zstream.total_in, w->response.zstream.total_out);

    if(w->response.data->len - w->response.sent == 0 && w->response.zstream.avail_in == 0 && w->response.zhave == w->response.zsent && w->response.zstream.avail_out != 0) {
        // there is nothing to send

        debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);

        // finalize the chunk
        if(w->response.sent != 0) {
            t = web_client_send_chunk_finalize(w);
            if(t < 0) return t;
        }

        if(w->mode == WEB_CLIENT_MODE_FILECOPY && web_client_has_wait_receive(w) && w->response.rlen && w->response.rlen > w->response.data->len) {
            // we have to wait, more data will come
            debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
            web_client_disable_wait_send(w);
            return t;
        }

        if(unlikely(!web_client_has_keepalive(w))) {
            debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
            WEB_CLIENT_IS_DEAD(w);
            return t;
        }

        // reset the client
        web_client_request_done(w);
        debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
        return t;
    }

    if(w->response.zhave == w->response.zsent) {
        // compress more input data

        // close the previous open chunk
        if(w->response.sent != 0) {
            t = web_client_send_chunk_close(w);
            if(t < 0) return t;
        }

        debug(D_DEFLATE, "%llu: Compressing %zu new bytes starting from %zu (and %u left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);

        // give the compressor all the data not passed through the compressor yet
        if(w->response.data->len > w->response.sent) {
            w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
            w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
        }

        // reset the compressor output buffer
        w->response.zstream.next_out = w->response.zbuffer;
        w->response.zstream.avail_out = NETDATA_WEB_RESPONSE_ZLIB_CHUNK_SIZE;

        // ask for FINISH if we have all the input
        int flush = Z_SYNC_FLUSH;
        if((w->mode == WEB_CLIENT_MODE_GET || w->mode == WEB_CLIENT_MODE_POST)
            || (w->mode == WEB_CLIENT_MODE_FILECOPY && !web_client_has_wait_receive(w) && w->response.data->len == w->response.rlen)) {
            flush = Z_FINISH;
            debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
        }
        else {
            debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
        }

        // compress
        if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
            error("%llu: Compression failed. Closing down client.", w->id);
            web_client_request_done(w);
            return(-1);
        }

        w->response.zhave = NETDATA_WEB_RESPONSE_ZLIB_CHUNK_SIZE - w->response.zstream.avail_out;
        w->response.zsent = 0;

        // keep track of the bytes passed through the compressor
        w->response.sent = w->response.data->len;

        debug(D_DEFLATE, "%llu: Compression produced %zu bytes.", w->id, w->response.zhave);

        // open a new chunk
        ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
        if(t2 < 0) return t2;
        t += t2;
    }
    
    debug(D_WEB_CLIENT, "%llu: Sending %zu bytes of data (+%zd of chunk header).", w->id, w->response.zhave - w->response.zsent, t);

    len = web_client_send_data(w,&w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
    if(len > 0) {
        w->statistics.sent_bytes += len;
        w->response.zsent += len;
        len += t;
        debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, len);
    }
    else if(len == 0) {
        debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %zu, zsent = %zu, need to send = %zu).",
            w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);

    }
    else {
        debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    }

    return(len);
}
#endif // NETDATA_WITH_ZLIB

ssize_t web_client_send(struct web_client *w) {
#ifdef NETDATA_WITH_ZLIB
    if(likely(w->response.zoutput)) return web_client_send_deflate(w);
#endif // NETDATA_WITH_ZLIB

    ssize_t bytes;

    if(unlikely(w->response.data->len - w->response.sent == 0)) {
        // there is nothing to send

        debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);

        // there can be two cases for this
        // A. we have done everything
        // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd

        if(w->mode == WEB_CLIENT_MODE_FILECOPY && web_client_has_wait_receive(w) && w->response.rlen && w->response.rlen > w->response.data->len) {
            // we have to wait, more data will come
            debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
            web_client_disable_wait_send(w);
            return 0;
        }

        if(unlikely(!web_client_has_keepalive(w))) {
            debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
            WEB_CLIENT_IS_DEAD(w);
            return 0;
        }

        web_client_request_done(w);
        debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
        return 0;
    }

    bytes = web_client_send_data(w,&w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
    if(likely(bytes > 0)) {
        w->statistics.sent_bytes += bytes;
        w->response.sent += bytes;
        debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, bytes);
    }
    else if(likely(bytes == 0)) {
        debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
    }
    else {
        debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    }

    return(bytes);
}

ssize_t web_client_read_file(struct web_client *w)
{
    if(unlikely(w->response.rlen > w->response.data->size))
        buffer_need_bytes(w->response.data, w->response.rlen - w->response.data->size);

    if(unlikely(w->response.rlen <= w->response.data->len))
        return 0;

    ssize_t left = (ssize_t)(w->response.rlen - w->response.data->len);
    ssize_t bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t)left);
    if(likely(bytes > 0)) {
        size_t old = w->response.data->len;
        (void)old;

        w->response.data->len += bytes;
        w->response.data->buffer[w->response.data->len] = '\0';

        debug(D_WEB_CLIENT, "%llu: Read %zd bytes.", w->id, bytes);
        debug(D_WEB_DATA, "%llu: Read data: '%s'.", w->id, &w->response.data->buffer[old]);

        web_client_enable_wait_send(w);

        if(w->response.rlen && w->response.data->len >= w->response.rlen)
            web_client_disable_wait_receive(w);
    }
    else if(likely(bytes == 0)) {
        debug(D_WEB_CLIENT, "%llu: Out of input file data.", w->id);

        // if we cannot read, it means we have an error on input.
        // if however, we are copying a file from ifd to ofd, we should not return an error.
        // in this case, the error should be generated when the file has been sent to the client.

        // we are copying data from ifd to ofd
        // let it finish copying...
        web_client_disable_wait_receive(w);

        debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);

        if(web_server_mode != WEB_SERVER_MODE_STATIC_THREADED) {
            if (w->ifd != w->ofd) close(w->ifd);
        }

        w->ifd = w->ofd;
    }
    else {
        debug(D_WEB_CLIENT, "%llu: read data failed.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    }

    return(bytes);
}

ssize_t web_client_receive(struct web_client *w)
{
    if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
        return web_client_read_file(w);

    ssize_t bytes;
    ssize_t left = (ssize_t)(w->response.data->size - w->response.data->len);

    // do we have any space for more data?
    buffer_need_bytes(w->response.data, NETDATA_WEB_REQUEST_INITIAL_SIZE);

#ifdef ENABLE_HTTPS
    if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
        if ( ( w->ssl.conn ) && (!w->ssl.flags)) {
            bytes = netdata_ssl_read(w->ssl.conn, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
            web_client_enable_wait_from_ssl(w, bytes);
        }else {
            bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
        }
    }
    else{
        bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
    }
#else
    bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
#endif

    if(likely(bytes > 0)) {
        w->statistics.received_bytes += bytes;

        size_t old = w->response.data->len;
        (void)old;

        w->response.data->len += bytes;
        w->response.data->buffer[w->response.data->len] = '\0';

        debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
        debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
    }
    else if (bytes < 0) {
        debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
        WEB_CLIENT_IS_DEAD(w);
    } else
        debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);

    return(bytes);
}


int web_client_socket_is_now_used_for_streaming(struct web_client *w) {
    // prevent the web_client from closing the streaming socket

    WEB_CLIENT_IS_DEAD(w);

    if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
        web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
    }
    else {
        if(w->ifd == w->ofd)
            w->ifd = w->ofd = -1;
        else
            w->ifd = -1;
    }

    buffer_flush(w->response.data);

    return HTTP_RESP_OK;
}

void web_client_decode_path_and_query_string(struct web_client *w, const char *path_and_query_string) {
    char buffer[NETDATA_WEB_REQUEST_URL_SIZE + 2];
    buffer[0] = '\0';

    buffer_flush(w->url_path_decoded);
    buffer_flush(w->url_query_string_decoded);

    if(buffer_strlen(w->url_as_received) == 0)
        // do not overwrite this if it is already filled
        buffer_strcat(w->url_as_received, path_and_query_string);

    if(w->mode == WEB_CLIENT_MODE_STREAM) {
        // in stream mode, there is no path

        url_decode_r(buffer, path_and_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1);

        buffer[NETDATA_WEB_REQUEST_URL_SIZE + 1] = '\0';
        buffer_strcat(w->url_query_string_decoded, buffer);
    }
    else {
        // in non-stream mode, there is a path

        // FIXME - the way this is implemented, query string params never accept the symbol &, not even encoded as %26
        // To support the symbol & in query string params, we need to turn the url_query_string_decoded into a
        // dictionary and decode each of the parameters individually.
        // OR: in url_query_string_decoded use as separator a control character that cannot appear in the URL.

        char *question_mark_start = strchr(path_and_query_string, '?');
        if (question_mark_start)
            url_decode_r(buffer, question_mark_start, NETDATA_WEB_REQUEST_URL_SIZE + 1);

        buffer[NETDATA_WEB_REQUEST_URL_SIZE + 1] = '\0';
        buffer_strcat(w->url_query_string_decoded, buffer);

        if (question_mark_start) {
            char c = *question_mark_start;
            *question_mark_start = '\0';
            url_decode_r(buffer, path_and_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1);
            *question_mark_start = c;
        } else
            url_decode_r(buffer, path_and_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1);

        buffer[NETDATA_WEB_REQUEST_URL_SIZE + 1] = '\0';
        buffer_strcat(w->url_path_decoded, buffer);
    }
}

#ifdef ENABLE_HTTPS
void web_client_reuse_ssl(struct web_client *w) {
    if (netdata_ssl_srv_ctx) {
        if (w->ssl.conn) {
            SSL_SESSION *session = SSL_get_session(w->ssl.conn);
            SSL *old = w->ssl.conn;
            w->ssl.conn = SSL_new(netdata_ssl_srv_ctx);
            if (session) {
#if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_111
                if (SSL_SESSION_is_resumable(session))
#endif
                    SSL_set_session(w->ssl.conn, session);
            }
            SSL_free(old);
        }
    }
}
#endif

void web_client_zero(struct web_client *w) {
    // zero everything about it - but keep the buffers

    web_client_reset_allocations(w, false);

    // remember the pointers to the buffers
    BUFFER *b1 = w->response.data;
    BUFFER *b2 = w->response.header;
    BUFFER *b3 = w->response.header_output;
    BUFFER *b4 = w->url_path_decoded;
    BUFFER *b5 = w->url_as_received;
    BUFFER *b6 = w->url_query_string_decoded;

#ifdef ENABLE_HTTPS
    web_client_reuse_ssl(w);
    SSL *ssl = w->ssl.conn;
#endif

    size_t use_count = w->use_count;
    size_t *statistics_memory_accounting = w->statistics.memory_accounting;

    // zero everything
    memset(w, 0, sizeof(struct web_client));

    w->ifd = w->ofd = -1;
    w->statistics.memory_accounting = statistics_memory_accounting;
    w->use_count = use_count;

#ifdef ENABLE_HTTPS
    w->ssl.conn = ssl;
    w->ssl.flags = NETDATA_SSL_START;
    debug(D_WEB_CLIENT_ACCESS,"Reusing SSL structure with (w->ssl = NULL, w->accepted = %u)", w->ssl.flags);
#endif

    // restore the pointers of the buffers
    w->response.data = b1;
    w->response.header = b2;
    w->response.header_output = b3;
    w->url_path_decoded = b4;
    w->url_as_received = b5;
    w->url_query_string_decoded = b6;
}

struct web_client *web_client_create(size_t *statistics_memory_accounting) {
    struct web_client *w = (struct web_client *)callocz(1, sizeof(struct web_client));
    w->use_count = 1;
    w->statistics.memory_accounting = statistics_memory_accounting;

    w->url_as_received = buffer_create(NETDATA_WEB_DECODED_URL_INITIAL_SIZE, w->statistics.memory_accounting);
    w->url_path_decoded = buffer_create(NETDATA_WEB_DECODED_URL_INITIAL_SIZE, w->statistics.memory_accounting);
    w->url_query_string_decoded = buffer_create(NETDATA_WEB_DECODED_URL_INITIAL_SIZE, w->statistics.memory_accounting);
    w->response.data = buffer_create(NETDATA_WEB_RESPONSE_INITIAL_SIZE, w->statistics.memory_accounting);
    w->response.header = buffer_create(NETDATA_WEB_RESPONSE_HEADER_INITIAL_SIZE, w->statistics.memory_accounting);
    w->response.header_output = buffer_create(NETDATA_WEB_RESPONSE_HEADER_INITIAL_SIZE, w->statistics.memory_accounting);

    __atomic_add_fetch(w->statistics.memory_accounting, sizeof(struct web_client), __ATOMIC_RELAXED);

    return w;
}

void web_client_free(struct web_client *w) {
    web_client_reset_allocations(w, true);

    __atomic_sub_fetch(w->statistics.memory_accounting, sizeof(struct web_client), __ATOMIC_RELAXED);
    freez(w);
}

inline void web_client_timeout_checkpoint_init(struct web_client *w) {
    now_monotonic_high_precision_timeval(&w->timings.tv_in);
}

inline void web_client_timeout_checkpoint_set(struct web_client *w, int timeout_ms) {
    w->timings.timeout_ut = timeout_ms * USEC_PER_MS;

    if(!w->timings.tv_in.tv_sec)
        web_client_timeout_checkpoint_init(w);

    if(!w->timings.tv_timeout_last_checkpoint.tv_sec)
        w->timings.tv_timeout_last_checkpoint = w->timings.tv_in;
}

inline usec_t web_client_timeout_checkpoint(struct web_client *w) {
    struct timeval now;
    now_monotonic_high_precision_timeval(&now);

    if (!w->timings.tv_timeout_last_checkpoint.tv_sec)
        w->timings.tv_timeout_last_checkpoint = w->timings.tv_in;

    usec_t since_last_check_ut = dt_usec(&w->timings.tv_timeout_last_checkpoint, &now);

    w->timings.tv_timeout_last_checkpoint = now;

    return since_last_check_ut;
}

inline usec_t web_client_timeout_checkpoint_response_ready(struct web_client *w, usec_t *usec_since_last_checkpoint) {
    usec_t since_last_check_ut = web_client_timeout_checkpoint(w);
    if(usec_since_last_checkpoint)
        *usec_since_last_checkpoint = since_last_check_ut;

    w->timings.tv_ready = w->timings.tv_timeout_last_checkpoint;

    // return the total time of the query
    return dt_usec(&w->timings.tv_in, &w->timings.tv_ready);
}

inline bool web_client_timeout_checkpoint_and_check(struct web_client *w, usec_t *usec_since_last_checkpoint) {

    usec_t since_last_check_ut = web_client_timeout_checkpoint(w);
    if(usec_since_last_checkpoint)
        *usec_since_last_checkpoint = since_last_check_ut;

    if(!w->timings.timeout_ut)
        return false;

    usec_t since_reception_ut = dt_usec(&w->timings.tv_in, &w->timings.tv_timeout_last_checkpoint);
    if (since_reception_ut >= w->timings.timeout_ut) {
        buffer_flush(w->response.data);
        buffer_strcat(w->response.data, "Query timeout exceeded");
        w->response.code = HTTP_RESP_BACKEND_FETCH_FAILED;
        return true;
    }

    return false;
}