forked from netdata/netdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_client.c
1984 lines (1633 loc) · 68.2 KB
/
web_client.c
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
// 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->contenttype = 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) {
#ifdef TCP_CORK
if(likely(web_client_is_corkable(w) && !w->tcp_cork && w->ofd != -1)) {
w->tcp_cork = 1;
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 = 0;
return -1;
}
}
#else
(void)w;
#endif /* TCP_CORK */
return 0;
}
static inline int web_client_uncrock_socket(struct web_client *w) {
#ifdef TCP_CORK
if(likely(w->tcp_cork && w->ofd != -1)) {
w->tcp_cork = 0;
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 = 1;
return -1;
}
}
#else
(void)w;
#endif /* TCP_CORK */
return 0;
}
static inline char *strip_control_characters(char *url) {
char *s = url;
if(!s) return "";
if(iscntrl(*s)) *s = ' ';
while(*++s) {
if(iscntrl(*s)) *s = ' ';
}
return url;
}
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(w->last_url[0])) {
struct timeval tv;
now_realtime_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
finished_web_request_statistics(dt_usec(&tv, &w->tv_in),
w->stats_received_bytes,
w->stats_sent_bytes,
size,
sent);
w->stats_received_bytes = 0;
w->stats_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_NORMAL:
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) ? ((size - sent) / (double) size * 100.0) : 0.0)
, dt_usec(&w->tv_ready, &w->tv_in) / 1000.0
, dt_usec(&tv, &w->tv_ready) / 1000.0
, dt_usec(&tv, &w->tv_in) / 1000.0
, w->response.code
, strip_control_characters(w->last_url)
);
}
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;
}
}
w->last_url[0] = '\0';
w->cookie1[0] = '\0';
w->cookie2[0] = '\0';
w->origin[0] = '*';
w->origin[1] = '\0';
freez(w->user_agent); w->user_agent = NULL;
if (w->auth_bearer_token) {
freez(w->auth_bearer_token);
w->auth_bearer_token = NULL;
}
w->mode = WEB_CLIENT_MODE_NORMAL;
w->tcp_cork = 0;
web_client_disable_donottrack(w);
web_client_disable_tracking_required(w);
web_client_disable_keepalive(w);
w->decoded_url[0] = '\0';
buffer_reset(w->response.header_output);
buffer_reset(w->response.header);
buffer_reset(w->response.data);
w->response.rlen = 0;
w->response.sent = 0;
w->response.code = 0;
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.zoutput = 0;
// if we had enabled compression, release it
#ifdef NETDATA_WITH_ZLIB
if(w->response.zinitialized) {
debug(D_DEFLATE, "%llu: Freeing compression resources.", w->id);
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 = 0;
}
#endif // NETDATA_WITH_ZLIB
}
uid_t web_files_uid(void) {
static char *web_owner = NULL;
static uid_t owner_uid = 0;
if(unlikely(!web_owner)) {
// getpwuid() is not thread safe,
// but we have called this function once
// while single threaded
struct passwd *pw = getpwuid(geteuid());
web_owner = config_get(CONFIG_SECTION_WEB, "web files owner", (pw)?(pw->pw_name?pw->pw_name:""):"");
if(!web_owner || !*web_owner)
owner_uid = geteuid();
else {
// getpwnam() is not thread safe,
// but we have called this function once
// while single threaded
pw = getpwnam(web_owner);
if(!pw) {
error("User '%s' is not present. Ignoring option.", web_owner);
owner_uid = geteuid();
}
else {
debug(D_WEB_CLIENT, "Web files owner set to %s.", web_owner);
owner_uid = pw->pw_uid;
}
}
}
return(owner_uid);
}
gid_t web_files_gid(void) {
static char *web_group = NULL;
static gid_t owner_gid = 0;
if(unlikely(!web_group)) {
// getgrgid() is not thread safe,
// but we have called this function once
// while single threaded
struct group *gr = getgrgid(getegid());
web_group = config_get(CONFIG_SECTION_WEB, "web files group", (gr)?(gr->gr_name?gr->gr_name:""):"");
if(!web_group || !*web_group)
owner_gid = getegid();
else {
// getgrnam() is not thread safe,
// but we have called this function once
// while single threaded
gr = getgrnam(web_group);
if(!gr) {
error("Group '%s' is not present. Ignoring option.", web_group);
owner_gid = getegid();
}
else {
debug(D_WEB_CLIENT, "Web files group set to %s.", web_group);
owner_gid = gr->gr_gid;
}
}
}
return(owner_gid);
}
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->contenttype = 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->contenttype = 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 .. 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->contenttype = 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->contenttype = 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);
}
// check if the file is owned by expected user
if (statbuf.st_uid != web_files_uid()) {
error("%llu: File '%s' is owned by user %u (expected user %u). Access Denied.", w->id, webfilename, statbuf.st_uid, web_files_uid());
return access_to_file_is_not_permitted(w, webfilename);
}
// check if the file is owned by expected group
if (statbuf.st_gid != web_files_gid()) {
error("%llu: File '%s' is owned by group %u (expected group %u). Access Denied.", w->id, webfilename, statbuf.st_gid, web_files_gid());
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->contenttype = 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->contenttype = 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->contenttype = contenttype_for_filename(webfilename);
debug(D_WEB_CLIENT_ACCESS, "%llu: Sending file '%s' (%ld bytes, ifd %d, ofd %d).", w->id, webfilename, 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 = 1;
w->response.zinitialized = 1;
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");
}
}
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 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 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)
{
// get the api version
char *tok = mystrsep(&url, "/");
if(tok && *tok) {
debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
if(strcmp(tok, "v1") == 0)
return web_client_api_request_v1(host, w, url);
else {
buffer_flush(w->response.data);
w->response.data->contenttype = 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(uint8_t contenttype) {
switch(contenttype) {
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;
#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");
}
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"))
strncpyz(w->origin, v, NETDATA_WEB_REQUEST_ORIGIN_HEADER_SIZE);
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")){
strncpyz(w->server_host, v, ((size_t)(ve - v) < sizeof(w->server_host)-1 ? (size_t)(ve - v) : sizeof(w->server_host)-1));
}
#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 */
*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_NORMAL;
}
else if(!strncmp(s, "OPTIONS ", 8)) {
s = &s[8];
w->mode = WEB_CLIENT_MODE_OPTIONS;
}
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 = 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 encrypt connection, please enable the SSL on slave with hostname '%s'.",hostname);
s = NULL;
}
#endif
w->mode = WEB_CLIENT_MODE_STREAM;
}
else {
s = NULL;
}
return s;
}
/**
* Set Path Query
*
* Set the pointers to the path and query string according to the input.
*
* @param w is the structure with the client request
* @param s is the first address of the string.
* @param ptr is the address of the separator.
*/
static void web_client_set_path_query(struct web_client *w, char *s, char *ptr) {
w->url_path_length = (size_t)(ptr -s);
w->url_search_path = ptr;
}
/**
* Split path query
*
* Do the separation between path and query string
*
* @param w is the structure with the client request
* @param s is the string to parse
*/
void web_client_split_path_query(struct web_client *w, char *s) {
//I am assuming here that the separator character(?) is not encoded
char *ptr = strchr(s, '?');
if(ptr) {
w->separator = '?';
web_client_set_path_query(w, s, ptr);
return;
}
//Here I test the second possibility, the URL is completely encoded by the user.
//I am not using the strcasestr, because it is fastest to check %3f and compare
//the next character.
//We executed some tests with "encodeURI(uri);" described in https://www.w3schools.com/jsref/jsref_encodeuri.asp
//on July 1st, 2019, that show us that URLs won't have '?','=' and '&' encoded, but we decided to move in front
//with the next part, because users can develop their own encoded that won't follow this rule.
char *moveme = s;
while (moveme) {
ptr = strchr(moveme, '%');
if(ptr) {
char *test = (ptr+1);
if (!strncmp(test, "3f", 2) || !strncmp(test, "3F", 2)) {
w->separator = *ptr;
web_client_set_path_query(w, s, ptr);
return;
}
ptr++;
}
moveme = ptr;
}
w->separator = 0x00;
w->url_path_length = strlen(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);
if(!is_it_valid) {
if(w->header_parse_tries > 10) {
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_NOT_SUPPORTED;
}
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);
}
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_NOT_SUPPORTED;
}
}