-
Notifications
You must be signed in to change notification settings - Fork 103
/
http_parser.c
10558 lines (9555 loc) · 304 KB
/
http_parser.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
/**
* Tempesta FW
*
* Copyright (C) 2014 NatSys Lab. (info@natsys-lab.com).
* Copyright (C) 2015-2022 Tempesta Technologies, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/ctype.h>
#include <linux/kernel.h>
#undef DEBUG
#if DBG_HTTP_PARSER > 0
#define DEBUG DBG_HTTP_PARSER
#endif
#include "gfsm.h"
#include "http_msg.h"
#include "htype.h"
#include "http_sess.h"
#include "hpack.h"
#include "lib/str.h"
/*
* ------------------------------------------------------------------------
* Common HTTP parsing routines
* ------------------------------------------------------------------------
*/
/**
* The following __data_{} macros help to reduce the amount of direct
* @data/@len manipulations.
*/
#define __data_off(pos) (size_t)((pos) - data)
#define __data_processed(pos) __data_off(pos)
#define __data_remain(pos) (len - __data_off(pos))
#define __data_available(pos, num) (num <= __data_remain(pos))
/**
* The following set of macros is for use in generic field processing.
* @__msg_field_open macro is used for field opening, @__msg_field_fixup
* is used for updating, and @__msg_field_finish is used when the field
* is finished. The latter means that the TfwStr{} flag TFW_STR_COMPLETE
* must be raised. The behavior of macros with @_pos suffixes differ from
* the ones specified above in the sense that they fixate the field chunk
* with respect to an explicitly defined pointer (instead of only relative
* start of the data).
*/
#define __msg_field_open(field, pos) \
tfw_http_msg_set_str_data(msg, field, pos)
#define __msg_field_fixup(field, pos) \
do { \
if (unlikely(tfw_http_msg_add_str_data(msg, field, data, \
__data_off(pos)))) \
return CSTR_NEQ; \
} while (0)
#define __msg_field_finish(field, pos) \
do { \
__msg_field_fixup(field, pos); \
(field)->flags |= TFW_STR_COMPLETE; \
} while (0)
#define __msg_field_fixup_pos(field, data, len) \
do { \
if (unlikely(tfw_http_msg_add_str_data(msg, field, data, len))) \
return CSTR_NEQ; \
} while (0)
#define __msg_field_finish_pos(field, data, len) \
do { \
__msg_field_fixup_pos(field, data, len); \
(field)->flags |= TFW_STR_COMPLETE; \
} while (0)
#define __msg_field_chunk_flags(field, flag) \
do { \
T_DBG3("parser: add chunk flags: %u\n", flag); \
TFW_STR_CURR(field)->flags |= flag; \
} while (0)
#define __msg_chunk_flags(flag) \
__msg_field_chunk_flags(&msg->stream->parser.hdr, flag)
/*
* The macro is frequently used for headers opened by tfw_http_msg_hdr_open().
* It sets the header's TfwStr->data to the current chunk pointer,
* but leaves TfwStr->len = 0. This TfwStr->data value is used latter when
* the parser will be reading "n" bytes of data using a pointer variable "p".
* The underlying __tfw_http_msg_add_str_data() detects TfwStr->len == 0 and
* sets the current TfwStr's length to p + n - TfwStr->data i.e. the final
* string will effectively point to the original chunk's start and will contain
* every parsed byte counting from the chunk's start.
*/
#define __msg_hdr_chunk_fixup(data, len) \
do { \
if (unlikely(tfw_http_msg_add_str_data(msg, \
&msg->stream->parser.hdr, data, len))) \
return CSTR_NEQ; \
} while (0)
#define __msg_hdr_set_hpack_index(idx) \
parser->hdr.hpack_idx = idx;
/**
* GCC still does a poor work on memory reusage of automatic local
* variables in nested blocks, so we declare all required temporal variables
* used in the defines below here to reduce stack frame usage.
* Since the variables are global now, be careful with them.
*
* objtool understands jump table, but our direct jumps are still opaque for it,
* so use compiler barrier to avoid stack manipulations after jumps.
*
* @parser - stores FSM state across multiple chunk processing.
* @p - current parser's position within the current @data chunk.
* @c - current character at @p. Should preferably be assigned by
* __FSM_STATE label.
* @__fsm_n and
* @__fsm_sz - mostly just two local integer values of different
* types. Usually one of them is used to store __data_remaining(p),
* and the other one is a return value indicating actually parsed
* character count.
* @chunk - one of FSM states used by __try_str() and derrivatives
* (TRY_STR_LAMBDA_fixup(), TRY_STR(), etc) to match a multi-character
* string. Initialized by TRY_STR_INIT() before the matching.
*/
#define __FSM_DECLARE_VARS(ptr) \
TfwHttpMsg *msg = (TfwHttpMsg *)(ptr); \
TfwHttpParser *parser = &msg->stream->parser; \
unsigned char *p = data; \
unsigned char c = *p; \
int __maybe_unused __fsm_n; \
size_t __maybe_unused __fsm_sz; \
TfwStr __maybe_unused *chunk = &parser->_tmp_chunk; \
barrier();
/**
* The function prints the problem place of an HTTP message whenever there
* is not enough functionality in our parser or there is an attack.
* We need to give more context about the case, so we print the data with
* 8 bytes (at most) backward offset and 48 bytes (at most) length.
* The standard format printing deals with non-printable characters, so it's
* safe to print the attack payload as is.
*/
#define TFW_PARSER_BLOCK(st) \
do { \
register unsigned int __p_o = min_t(unsigned int, 8, p - data); \
register unsigned int __p_n = min_t(unsigned int, 48, \
data + len + __p_o - p); \
T_WARN("Parser error: state=" #st " input(-%d)=%#x('%.*s')" \
" data_len=%lu off=%lu\n", \
__p_o, (char)c, __p_n, p - __p_o, len, p - data); \
return TFW_BLOCK; \
} while (0)
#define __FSM_START(s) \
T_DBG3("enter FSM at state %pK\n", s); \
if (unlikely(s)) \
goto *s; /* Fall through to the first state otherwise. */
#define __FSM_START_ALT(s) \
T_DBG3("enter FSM at state %pK\n", s); \
if (s == __I_EoL) \
goto I_EoL; \
if (s) \
goto *s; /* Fall through to the first state otherwise. */
#define __FSM_STATE(st, ...) \
barrier(); \
st: __attribute__((unused, __VA_ARGS__)) \
c = *p; \
T_DBG3("parser at " #st ": c=%#x(%c), p_off=%ld\n", \
c, isprint(c) ? c : '.', p - data);
#define __FSM_EXIT(ret) \
do { \
r = ret; \
goto done; \
} while (0)
#define FSM_EXIT(ret) \
do { \
p += 1; /* eat current character */ \
__FSM_EXIT(ret); \
} while (0)
#define __FSM_FINISH(m) \
done: \
if (r == TFW_PASS) \
__set_bit(TFW_HTTP_B_FULLY_PARSED, msg->flags); \
/* Remaining number of bytes to process in the data chunk. */ \
*parsed = __data_off(p);
#define __FSM_MOVE_nofixup_n(to, n) \
do { \
p += n; \
if (unlikely(__data_off(p) >= len)) { \
parser->state = &&to; /* start from state @to next time */\
__FSM_EXIT(TFW_POSTPONE); \
} \
goto to; \
} while (0)
#define __FSM_MOVE_nf(to, n, field) \
do { \
p += n; \
if (unlikely(__data_off(p) >= len)) { \
parser->state = &&to; /* start from state @to next time */\
/* Close currently parsed field chunk. */ \
BUG_ON(!(field)->data); \
__msg_field_fixup(field, data + len); \
__FSM_EXIT(TFW_POSTPONE); \
} \
goto to; \
} while (0)
#define __FSM_MOVE_nofixup(to) __FSM_MOVE_nofixup_n(to, 1)
#define __FSM_MOVE_n(to, n) \
__FSM_MOVE_nf(to, n, &msg->stream->parser.hdr)
#define __FSM_MOVE_f(to, field) __FSM_MOVE_nf(to, 1, field)
#define __FSM_MOVE(to) \
__FSM_MOVE_nf(to, 1, &msg->stream->parser.hdr)
/* The same as __FSM_MOVE_n(), but exactly for jumps w/o data moving. */
#define __FSM_JMP(to) do { goto to; } while (0)
#define __FSM_MATCH_MOVE_fixup_pos(alphabet, to, field, flag, fixup_pos) \
do { \
__fsm_n = __data_remain(p); \
__fsm_sz = tfw_match_##alphabet(p, __fsm_n); \
if (unlikely(__fsm_sz == __fsm_n)) { \
/* Continue field processing on next skb. */ \
BUG_ON(!(field)->data); \
if (fixup_pos) \
__msg_field_fixup_pos(field, p, __fsm_sz); \
else \
__msg_field_fixup(field, data + len); \
__msg_field_chunk_flags(field, flag); \
parser->state = &&to; \
p += __fsm_sz; \
__FSM_EXIT(TFW_POSTPONE); \
} \
} while (0)
/* Fixups p + __fsm_sz on chunk exhaustion */
#define __FSM_MATCH_MOVE_pos_f(alphabet, to, field, flag) \
__FSM_MATCH_MOVE_fixup_pos(alphabet, to, field, flag, true)
/* Fixups data + len on chunk exhaustion */
#define __FSM_MATCH_MOVE(alphabet, to, flag) \
__FSM_MATCH_MOVE_fixup_pos(alphabet, to, &msg->stream->parser.hdr, \
flag, false)
#define __FSM_MOVE_hdr_fixup(to, n) \
do { \
__msg_hdr_chunk_fixup(p, n); \
p += n; \
if (unlikely(__data_off(p) >= len)) { \
parser->state = &&to; \
__FSM_EXIT(TFW_POSTPONE); \
} \
goto to; \
} while (0)
/*
* __FSM_I_* macros are intended to help with parsing of message
* header values. That is done with separate, nested, or interior
* FSMs, and so _I_ in the name means "interior" FSM.
*/
#define __FSM_I_field_chunk_flags(field, flag) \
__msg_field_chunk_flags(field, flag)
#define __FSM_I_chunk_flags(flag) \
__msg_chunk_flags(flag)
#define __FSM_I_MOVE_BY_REF_n(to, n, flag) \
do { \
BUG_ON(n < 0); \
parser->_i_st = to; \
p += n; \
if (unlikely(__data_off(p) >= len)) { \
/* Close currently parsed field chunk. */ \
__msg_hdr_chunk_fixup(data, len); \
if (flag) \
__msg_chunk_flags(flag); \
__FSM_EXIT(TFW_POSTPONE); \
} \
goto *to; \
} while (0)
/* These four macroses fixup by data + len on chunk exhaustion */
#define __FSM_I_MOVE_n(to, n) \
__FSM_I_MOVE_BY_REF_n(&&to, n, 0)
#define __FSM_I_MOVE_flag(to, flag) \
__FSM_I_MOVE_BY_REF_n(&&to, 1, flag)
#define __FSM_I_MOVE_BY_REF(to) \
__FSM_I_MOVE_BY_REF_n(to, 1, 0)
#define __FSM_I_MOVE(to) __FSM_I_MOVE_n(to, 1)
/* The same as __FSM_I_MOVE_n(), but exactly for jumps w/o data moving. */
#define __FSM_I_JMP(to) goto to
#define __FSM_I_MATCH_MOVE_finish(alphabet, to, finish) \
do { \
__fsm_n = __data_remain(p); \
__fsm_sz = tfw_match_##alphabet(p, __fsm_n); \
if (unlikely(__fsm_sz == __fsm_n)) { \
__msg_hdr_chunk_fixup(data, len); \
parser->_i_st = &&to; \
r = TFW_POSTPONE; \
finish; \
__FSM_EXIT(r); /* let finish update the @r */ \
} \
} while (0)
#define __FSM_I_MATCH_MOVE(alphabet, n) \
__FSM_I_MATCH_MOVE_finish(alphabet, n, {})
/*
* __FSM_I_MOVE_fixup_xxx() and __FSM_I_MATCH_fixup_xxx() family macroses
* fixup p + n and p + __fsm_sz appropriately. They are to be used for explicit
* fine-grained control of chunking within a string:
* i.e. a caller can explicitly chop an ingress contiguous string
* into multiple chunks thus generating efficient key/value pairs.
* These explicit fixups should not be mixed with regular fixups
* (__FSM_I_MOVE and others).
*/
/*
* Fixup the current chunk that starts at the current data pointer
* @p and has the size @n. Move forward to just after the chunk.
* We have at least @n bytes as we parsed them before the fixup.
* p+n should never exceed data+len i.e. we can fixup data
* from the current chunk only.
*/
#define __FSM_I_MOVE_fixup_f(to, n, field, flag) \
do { \
BUG_ON(!(field)->data); \
BUG_ON(n < 0); \
__msg_field_fixup_pos(field, p, n); \
__FSM_I_field_chunk_flags(field, flag); \
parser->_i_st = &&to; \
p += n; \
if (unlikely(__data_off(p) >= len)) \
__FSM_EXIT(TFW_POSTPONE); \
goto to; \
} while (0)
#define __FSM_I_MOVE_fixup(to, n, flag) \
__FSM_I_MOVE_fixup_f(to, n, &msg->stream->parser.hdr, flag)
#define __FSM_I_MATCH_MOVE_fixup_finish(alphabet, to, flag, finish) \
do { \
__fsm_n = __data_remain(p); \
__fsm_sz = tfw_match_##alphabet(p, __fsm_n); \
if (unlikely(__fsm_sz == __fsm_n)) { \
__msg_hdr_chunk_fixup(p, __fsm_sz); \
__FSM_I_chunk_flags(flag); \
parser->_i_st = &&to; \
r = TFW_POSTPONE; \
finish; \
__FSM_EXIT(r); \
} \
} while (0)
#define __FSM_I_MATCH_MOVE_fixup(alphabet, to, flag) \
__FSM_I_MATCH_MOVE_fixup_finish(alphabet, to, flag, {})
/* Conditional transition from state @st to @st_next. */
#define __FSM_TX_COND(st, condition, st_next, field, ...) \
__FSM_STATE(st, __VA_ARGS__) { \
if (likely(condition)) \
__FSM_MOVE_f(st_next, field); \
TFW_PARSER_BLOCK(st); \
}
#define __FSM_TX_COND_nofixup(st, condition, st_next, ...) \
__FSM_STATE(st, __VA_ARGS__) { \
if (likely(condition)) \
__FSM_MOVE_nofixup(st_next); \
TFW_PARSER_BLOCK(st); \
}
/* Automaton transition from state @st to @st_next on character @ch. */
#define __FSM_TX(st, ch, st_next, ...) \
__FSM_TX_COND(st, c == (ch), st_next, &parser->hdr, __VA_ARGS__)
#define __FSM_TX_nofixup(st, ch, st_next, ...) \
__FSM_TX_COND_nofixup(st, c == (ch), st_next, __VA_ARGS__)
/* Case-insensitive version of __FSM_TX(). */
#define __FSM_TX_LC(st, ch, st_next, field, ...) \
__FSM_TX_COND(st, TFW_LC(c) == (ch), st_next, field, __VA_ARGS__)
#define __FSM_TX_LC_nofixup(st, ch, st_next, ...) \
__FSM_TX_COND_nofixup(st, TFW_LC(c) == (ch), st_next, __VA_ARGS__)
/*
* Automaton transition with alphabet checking and fallback state.
* Improbable states only, so cold label.
*/
#define __FSM_TX_AF(st, ch, st_next) \
__FSM_STATE(st, cold) { \
if (likely(TFW_LC(c) == ch)) \
__FSM_MOVE(st_next); \
/* It should be checked in st_fallback if `c` is allowed */ \
__FSM_JMP(RGen_HdrOtherN); \
}
/*
* As above, but reads OWS through transitional state. Note, that header
* name, colon, LWS and value are stored in different chunks.
*/
#define __FSM_TX_AF_OWS(st, st_next) \
__FSM_STATE(st, cold) { \
if (likely(c == ':')) { \
__msg_hdr_chunk_fixup(data, __data_off(p)); \
parser->_i_st = &&st_next; \
__FSM_MOVE_hdr_fixup(RGen_LWS, 1); \
} \
/* It should be checked in st_fallback if `c` is allowed */ \
__FSM_JMP(RGen_HdrOtherN); \
}
/* As above, but with HPACK static index setting. */
#define __FSM_TX_AF_OWS_HP(st, st_next, hp_idx) \
__FSM_STATE(st, cold) { \
if (likely(c == ':')) { \
__msg_hdr_chunk_fixup(data, __data_off(p)); \
parser->_i_st = &&st_next; \
__msg_hdr_set_hpack_index(hp_idx); \
__FSM_MOVE_hdr_fixup(RGen_LWS, 1); \
} \
/* It should be checked in st_fallback if `c` is allowed */ \
__FSM_JMP(RGen_HdrOtherN); \
}
/* Used for improbable states only, so use cold label. */
#define __FSM_METH_MOVE(st, ch, st_next) \
__FSM_STATE(st, cold) { \
if (likely(c == (ch))) \
__FSM_MOVE_nofixup(st_next); \
__FSM_JMP(Req_MethodUnknown); \
}
#define __FSM_METH_MOVE_finish(st, ch, m_type) \
__FSM_STATE(st, cold) { \
if (unlikely(c != (ch))) \
__FSM_JMP(Req_MethodUnknown); \
req->method = (m_type); \
__FSM_MOVE_nofixup(Req_MUSpace); \
}
#define __FSM_REQUIRE(st, st_next, predicate) \
__FSM_STATE(st) { \
if (unlikely(!predicate)) \
return CSTR_NEQ; \
parser->_i_st = &&st_next; \
}
#define __FSM_REQUIRE_FIRST_DIGIT(st, st_next) \
__FSM_REQUIRE(st, st_next, isdigit(c))
/* 4-byte (Integer) access to a string Pointer. */
#define PI(p) (*(unsigned int *)(p))
/**
* Little endian.
* These two at the below can be used for characters only.
*/
#define TFW_LC_INT 0x20202020
#define TFW_LC_INT3 0x00202020
#define TFW_LC_LONG 0x2020202020202020UL
#define TFW_LC_LONG7 0x0020202020202020UL
#define TFW_CHAR4_INT(a, b, c, d) \
((d << 24) | (c << 16) | (b << 8) | a)
#define TFW_CHAR8_INT(a, b, c, d, e, f, g, h) \
(((long)h << 56) | ((long)g << 48) | ((long)f << 40) \
| ((long)e << 32) | (d << 24) | (c << 16) | (b << 8) | a)
#define TFW_P2LCINT(p) (PI(p) | TFW_LC_INT)
/*
* Match 4 or 8 characters with conversion to lower case of 3, 4, 7, or
* 8 first characters and type conversion to int or long type.
*/
#define C4_INT_LCM(p, a, b, c, d) \
!((PI(p) | TFW_LC_INT) ^ TFW_CHAR4_INT(a, b, c, d))
#define C8_INT_LCM(p, a, b, c, d, e, f, g, h) \
!((*(unsigned long *)(p) | TFW_LC_LONG) \
^ TFW_CHAR8_INT(a, b, c, d, e, f, g, h))
#define C4_INT3_LCM(p, a, b, c, d) \
!((PI(p) | TFW_LC_INT3) ^ TFW_CHAR4_INT(a, b, c, d))
#define C8_INT7_LCM(p, a, b, c, d, e, f, g, h) \
!((*(unsigned long *)(p) | TFW_LC_LONG7) \
^ TFW_CHAR8_INT(a, b, c, d, e, f, g, h))
/*
* Matching 4 to 8 characters without conversion to lower case (applicable
* for HTTP/2 headers name comparison).
*/
#define C4_INT(p, a, b, c, d) \
!(PI(p) ^ TFW_CHAR4_INT(a, b, c, d))
#define C8_INT(p, a, b, c, d, e, f, g, h) \
!(*(unsigned long *)(p) ^ TFW_CHAR8_INT(a, b, c, d, e, f, g, h))
#define IN_ALPHABET(c, a) (a[c >> 6] & (1UL << (c & 0x3f)))
#define CSTR_EQ 0
#define CSTR_POSTPONE TFW_POSTPONE /* -1 */
#define CSTR_NEQ TFW_BLOCK /* -2 */
#define CSTR_BADLEN -3
/**
* Compare a mixed pair of strings with the string @str of length @str_len where
* the first string is a part of the header @hdr which is being processed and
* the second string is yet unhandled data of length @len starting from @p. The
* @chunk->data is used to refer to the start of the first string within the
* @hdr, while the @chunk->len is used to track gathered length.
*
* @str is always in lower case.
*
* @return
* CSTR_NEQ: not equal
* > 0: (partial) equal
*/
static int
__try_str(TfwStr *hdr, TfwStr* chunk, unsigned char *p, size_t len,
const unsigned char *str, size_t str_len)
{
size_t offset = chunk->len;
if (unlikely(offset > str_len || TFW_LC(*p) != str[offset]))
return CSTR_NEQ;
len = min(len, str_len - offset);
if (tfw_cstricmp_2lc(p, str + offset, len) ||
(chunk->len && !tfw_str_eq_cstr_pos(hdr, chunk->data, str,
chunk->len, TFW_STR_EQ_CASEI)))
return CSTR_NEQ;
chunk->len += len;
return len;
}
/**
* Parse probably chunked string representation of an decimal integer.
* @return number of parsed bytes.
*/
static __always_inline int
__parse_ulong(unsigned char *__restrict data, size_t len,
const unsigned long *__restrict delimiter_a,
unsigned long *__restrict acc, unsigned long limit)
{
unsigned char *p;
for (p = data; p - data < len; ++p) {
T_DBG3("__parse_ulong: acc=%lu p=%c len=%zu limit=%lu\n",
*acc, *p, len, limit);
if (unlikely(IN_ALPHABET(*p, delimiter_a)))
return p - data;
if (unlikely(!isdigit(*p)))
return CSTR_NEQ;
if (unlikely(__builtin_uaddl_overflow(*acc * 10, *p - '0', acc)
|| *acc > limit))
return CSTR_BADLEN;
}
return CSTR_POSTPONE;
}
/**
* Parse an integer followed by a white space.
*/
static __always_inline int
__parse_ulong_ws(unsigned char *__restrict data, size_t len,
unsigned long *__restrict acc, unsigned long limit)
{
/*
* Standard white-space characters are:
* ' ' (0x20) space (SPC)
* '\t' (0x09) horizontal tab (TAB)
* '\n' (0x0a) newline (LF)
* '\v' (0x0b) vertical tab (VT)
* '\f' (0x0c) feed (FF)
* '\r' (0x0d) carriage return (CR)
*/
static const unsigned long whitespace_a[] ____cacheline_aligned = {
0x0000000100003e00UL, 0, 0, 0
};
return __parse_ulong(data, len, whitespace_a, acc, limit);
}
#define parse_int_ws(data, len, acc) \
__parse_ulong_ws(data, len, acc, UINT_MAX)
#define parse_long_ws(data, len, acc) \
__parse_ulong_ws(data, len, acc, LONG_MAX)
/**
* Parse an integer as part of HTTP list.
*/
static inline int
parse_ulong_list(unsigned char *data, size_t len, unsigned long *acc,
unsigned long limit)
{
/*
* Standard white-space plus comma characters are:
* '\t' (0x09) horizontal tab (TAB)
* '\n' (0x0a) newline (LF)
* '\v' (0x0b) vertical tab (VT)
* '\f' (0x0c) feed (FF)
* '\r' (0x0d) carriage return (CR)
* ' ' (0x20) space (SPC)
* ',' (0x2c) comma
*/
static const unsigned long ws_comma_a[] ____cacheline_aligned = {
0x0000100100003e00UL, 0, 0, 0
};
return __parse_ulong(data, len, ws_comma_a, acc, limit);
}
#define parse_uint_list(data, len, acc) \
parse_ulong_list(data, len, acc, UINT_MAX)
/**
* Parse probably chunked string representation of an hexadecimal integer.
* @return number of parsed bytes.
*/
static int
parse_int_hex(unsigned char *data, size_t len, unsigned long *acc, unsigned short *cnt)
{
unsigned char *p;
for (p = data; p - data < len; ++p) {
if (unlikely(IS_CRLF(*p) || (*p == ';'))) {
if (unlikely(*acc > LONG_MAX))
return CSTR_BADLEN;
return p - data;
}
if (unlikely(!isxdigit(*p)))
return CSTR_NEQ;
if (unlikely(*cnt >= (sizeof(long) * 2)))
return CSTR_BADLEN;
*acc = (*acc << 4) + (*p & 0xf) + (*p >> 6) * 9;
++*cnt;
}
return CSTR_POSTPONE;
}
/**
* Parse OWS, i.e. the space or horizontal tab characters which
* can exist before or after the header's value.
* @return number of parsed bytes or CSTR_POSTPONE if all @len bytes
* are parsed.
*/
static __always_inline int
parse_ows(unsigned char *__restrict data, size_t len)
{
unsigned char *p;
for (p = data; p - data < len; ++p) {
if (!IS_WS(*p))
return p - data;
}
return CSTR_POSTPONE;
}
/**
* Mark existing spec headers of http message @hm as hop-by-hop if they were
* listed in Connection header or in @tfw_http_init_parser_* function.
*/
static void
mark_spec_hbh(TfwHttpMsg *hm)
{
TfwHttpHbhHdrs *hbh_hdrs = &hm->stream->parser.hbh_parser;
unsigned int id;
for (id = 0; id < TFW_HTTP_HDR_RAW; ++id) {
TfwStr *hdr = &hm->h_tbl->tbl[id];
if ((hbh_hdrs->spec & (0x1 << id)) && (!TFW_STR_EMPTY(hdr)))
hdr->flags |= TFW_STR_HBH_HDR;
}
}
/**
* Mark raw header @hdr as hop-by-hop if its name was listed in Connection
* header
*/
static void
mark_raw_hbh(TfwHttpMsg *hm, TfwStr *hdr)
{
TfwHttpHbhHdrs *hbh = &hm->stream->parser.hbh_parser;
unsigned int i;
/*
* Multiple headers with the same name are saved to the same TfwStr,
* so once we bumped into the first of the headers and marked it with
* TFW_STR_HBH_HDR flag no need to keep comparing the header name to
* every other header in message.
*
* Unset TFW_STR_HBH_HDR flag for header name to indicate that
* corresponding hop-by-hop header was found.
*/
for (i = 0; i < hbh->off; ++i) {
TfwStr *hbh_name = &hbh->raw[i];
if ((hbh_name->flags & TFW_STR_HBH_HDR)
&& !(tfw_stricmpspn(&hbh->raw[i], hdr, ':')))
{
hdr->flags |= TFW_STR_HBH_HDR;
hbh_name->flags = hbh_name->flags &
~(unsigned int)TFW_STR_HBH_HDR;
break;
}
}
}
/**
* Lookup for the header @hdr in already collected headers table @ht,
* and mark it as hop-by-hop. The lookup is performed until ':', so header
* name only is enough in @hdr.
*
* @return true if @hdr was found and marked as hop-by-hop
*/
static bool
__mark_hbh_hdr(TfwHttpMsg *hm, TfwStr *hdr)
{
TfwHttpHdrTbl *ht = hm->h_tbl;
unsigned int hid = tfw_http_msg_hdr_lookup(hm, hdr);
/*
* This function is called before hm->h_tbl is fully parsed,
* if header is empty, don't touch it
*/
if ((hid >= ht->off) || (TFW_STR_EMPTY(&ht->tbl[hid])))
return false;
ht->tbl[hid].flags |= TFW_STR_HBH_HDR;
return true;
}
/**
* Add header name listed in Connection header to hop-by-hop table of raw headers.
* If @last is true then (@data, @len) represents last chunk of header name and
* chunk with ':' will be added to the end. Otherwize last header in table stays
* open to add more data.
*
* After name of hop-by-hop header was completed, will search for headers
* with that name and mark them as hop-by-hop.
*
* NOTE: Most of the headers listed in RFC 7231 are end-to-end and must not
* be listed in the header. Instead of comparing connection tokens to all
* end-to-end headers names compare only to headers parsed by
* TFW_HTTP_PARSE_RAWHDR_VAL macro.
*/
static int
__hbh_parser_add_data(TfwHttpMsg *hm, char *data, unsigned long len, bool finalize_item)
{
TfwStr *hbh_hdr, *append;
TfwHttpHbhHdrs *hbh = &hm->stream->parser.hbh_parser;
static const TfwStr block[] = {
/* End-to-end spec and raw headers */
TFW_STR_STRING("age:"),
TFW_STR_STRING("authorization:"),
TFW_STR_STRING("cache-control:"),
TFW_STR_STRING("connection:"),
TFW_STR_STRING("content-length:"),
TFW_STR_STRING("content-type:"),
TFW_STR_STRING("cookie:"),
TFW_STR_STRING("date:"),
TFW_STR_STRING("etag:"),
TFW_STR_STRING("expires:"),
TFW_STR_STRING("host:"),
TFW_STR_STRING("pragma:"),
TFW_STR_STRING("server:"),
TFW_STR_STRING("transfer-encoding:"),
TFW_STR_STRING("user-agent:"),
TFW_STR_STRING("x-forwarded-for:"),
};
if (hbh->off == TFW_HBH_TOKENS_MAX)
return CSTR_NEQ;
hbh_hdr = &hbh->raw[hbh->off];
if (!TFW_STR_EMPTY(hbh_hdr)) {
append = tfw_str_add_compound(hm->pool, hbh_hdr);
}
else {
append = (TfwStr *)tfw_pool_alloc(hm->pool, sizeof(TfwStr));
hbh_hdr->chunks = append;
hbh_hdr->nchunks = 1;
}
if (!append)
return -ENOMEM;
append->len = len;
append->data = data;
hbh_hdr->len += len;
if (finalize_item) {
TfwStr s_colon = { .data = ":", .len = 1 };
append = tfw_str_add_compound(hm->pool, hbh_hdr);
if (!append)
return -ENOMEM;
*append = s_colon;
hbh_hdr->len += s_colon.len;
++hbh->off;
if (tfw_http_msg_find_hdr(hbh_hdr, block))
return CSTR_NEQ;
/*
* Don't set TFW_STR_HBH_HDR flag if such header was already
* parsed. See comment in mark_raw_hbh()
*/
if (!__mark_hbh_hdr(hm, hbh_hdr))
hbh_hdr->flags |= TFW_STR_HBH_HDR;
};
return 0;
}
static int
process_trailer_hdr(TfwHttpMsg *hm, TfwStr *hdr, unsigned int id)
{
if (!(hm->crlf.flags & TFW_STR_COMPLETE))
return CSTR_EQ;
/*
* RFC 7230 4.1.2:
*
* A sender MUST NOT generate a trailer that contains a field necessary
* for message framing (e.g., Transfer-Encoding and Content-Length),
* routing (e.g., Host), request modifiers (e.g., controls and
* conditionals in Section 5 of [RFC7231]), authentication (e.g., see
* [RFC7235] and [RFC6265]), response control data (e.g., see Section
* 7.1 of [RFC7231]), or determining how to process the payload (e.g.,
* Content-Encoding, Content-Type, Content-Range, and Trailer).
*/
switch (id) {
case TFW_HTTP_HDR_HOST:
case TFW_HTTP_HDR_CONTENT_LENGTH:
case TFW_HTTP_HDR_CONTENT_TYPE:
case TFW_HTTP_HDR_COOKIE: // and TFW_HTTP_HDR_SET_COOKIE
case TFW_HTTP_HDR_IF_NONE_MATCH:
case TFW_HTTP_HDR_X_FORWARDED_FOR:
case TFW_HTTP_HDR_TRANSFER_ENCODING:
return CSTR_NEQ;
}
hdr->flags |= TFW_STR_TRAILER;
__set_bit(TFW_HTTP_B_CHUNKED_TRAILER, hm->flags);
return CSTR_EQ;
}
/*
* Helping state identifiers used to define which jump address an FSM should
* set as the entry point.
* Don't introduce too much of such identifies!
*/
#define __I_EoL (void *)1
/* Initialize TRY_STR parsing context */
#define TRY_STR_INIT() TFW_STR_INIT(chunk)
/**
* Parsing helpers.
* TRY_STR_* macros are supposed to be used without explicit fixups, so the
* whole data + len chunk will be fixed up on chunk exhaustion.
* @str in TRY_STR_LAMBDA must be in lower case.
* @lambda is called on successfull match.
* @finish is called when the current data+len chunk is exhausted.
*/
#define TRY_STR_LAMBDA_BY_REF_finish(str, lambda, finish, state) \
if (!chunk->data) \
chunk->data = p; \
__fsm_n = __try_str(&parser->hdr, chunk, p, __data_remain(p), \
str, sizeof(str) - 1); \
if (__fsm_n > 0) { \
if (chunk->len == sizeof(str) - 1) { \
lambda; \
TRY_STR_INIT(); \
__FSM_I_MOVE_BY_REF_n(state, __fsm_n, 0); \
} \
/* Here __fsm_n == __data_remain(p) i.e. chunk exhausted */ \
__msg_hdr_chunk_fixup(data, len); \
finish; \
return CSTR_POSTPONE; \
}
#define TRY_STR_LAMBDA_finish(str, lambda, finish, state) \
TRY_STR_LAMBDA_BY_REF_finish(str, lambda, finish, &&state)
/*
* Store current state if we're going to exit in waiting for new data
* (POSTPONE). We store current parser state only when we return from the
* parser FSM - it's better that to store the state on each transition.
*/
#define TRY_STR_LAMBDA(str, lambda, curr_st, next_st) \
TRY_STR_LAMBDA_finish(str, lambda, { \
parser->_i_st = &&curr_st; \
}, next_st)
#define TRY_STR(str, curr_st, next_st) \
TRY_STR_LAMBDA_finish(str, { }, { \
parser->_i_st = &&curr_st; \
}, next_st)
#define TRY_STR_BY_REF(str, curr_st, next_st) \
TRY_STR_LAMBDA_BY_REF_finish(str, { }, { \
parser->_i_st = curr_st; \
}, next_st)
/**
* The same as @TRY_STR_LAMBDA_finish(), but @str must be of plain
* @TfwStr{} type and variable @field is used (instead of hard coded
* header field); besides, @finish parameter is not used in this macro.
* xxx_fixup() family of functions is used to explicit chunking of strings.
*/
#define TRY_STR_LAMBDA_fixup(str, field, lambda, curr_st, next_st) \
BUG_ON(!TFW_STR_PLAIN(str)); \
if (!chunk->data) \
chunk->data = p; \
__fsm_n = __try_str(field, chunk, p, __data_remain(p), \
(str)->data, (str)->len); \
if (__fsm_n > 0) { \
if (chunk->len == (str)->len) { \
lambda; \
TRY_STR_INIT(); \
__FSM_I_MOVE_fixup_f(next_st, __fsm_n, field, 0);\
} \
__msg_field_fixup_pos(field, p, __fsm_n); \
parser->_i_st = &&curr_st; \
return CSTR_POSTPONE; \
}
#define TRY_STR_fixup(str, curr_st, next_st) \
TRY_STR_LAMBDA_fixup(str, &parser->hdr, { }, curr_st, next_st)
/*
* Headers EOL processing. Allow only LF and CRLF as a newline delimiters.
*
* Note also, that according to RFC 7230, HTTP-headers may appear in two
* cases. The first one is header section (3.2) and the second one is
* chunked-body trailer-part (4.1).
*/
#define RGEN_EOL() \
__FSM_STATE(RGen_EoL, hot) { \
if (c == '\r') \
__FSM_MOVE_nofixup(RGen_CR); \
if (c == '\n') { \
if (parser->hdr.data) { \
tfw_str_set_eolen(&parser->hdr, 1); \
if (tfw_http_msg_hdr_close(msg)) \
TFW_PARSER_BLOCK(RGen_EoL); \
} \
__FSM_MOVE_nofixup(RGen_Hdr); \
} \
TFW_PARSER_BLOCK(RGen_EoL); \
} \
__FSM_STATE(RGen_CR, hot) { \
if (unlikely(c != '\n')) \
TFW_PARSER_BLOCK(RGen_CR); \
if (parser->hdr.data) { \
tfw_str_set_eolen(&parser->hdr, 2); \
if (tfw_http_msg_hdr_close(msg)) \
TFW_PARSER_BLOCK(RGen_CR); \
} \
/* Process next header if any. */ \
__FSM_MOVE_nofixup(RGen_Hdr); \
}
/*
* Process the final CRLF, i.e. the end of the headers part or the whole
* HTTP message. We may get here after trailing-part headers. In that
* case @msg->crlf is already set and there is nothing to do.
*/
#define TFW_HTTP_PARSE_CRLF() \
do { \
if (unlikely(c == '\r')) { \
if (msg->crlf.flags & TFW_STR_COMPLETE) \
__FSM_MOVE_nofixup(RGen_CRLFCR); \
if (!msg->crlf.data) \
/* The end of the headers part. */ \
tfw_http_msg_set_str_data(msg, &msg->crlf, p); \
__FSM_MOVE_f(RGen_CRLFCR, &msg->crlf); \
} \
if (c == '\n') { \
if (!msg->crlf.data) { \