-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmultipart.cc
1781 lines (1523 loc) · 61.6 KB
/
multipart.cc
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
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* You may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address [email protected].
*
*/
#include "src/request_body_processor/multipart.h"
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef WIN32
#include <unistd.h>
#else
#include <io.h>
#include "src/compat/msvc.h"
#endif
#include <list>
#include <iostream>
#include <string>
#include <utility>
#include "modsecurity/rules_set.h"
#include "modsecurity/collection/collections.h"
#include "src/utils/string.h"
namespace modsecurity {
namespace RequestBodyProcessor {
static const char* mime_charset_special = "!#$%&+-^_`{}~";
static const char* attr_char_special = "!#$&+-.^_`~";
MultipartPartTmpFile::~MultipartPartTmpFile() {
if (!m_tmp_file_name.empty() && m_delete) {
/* make sure it is closed first */
if (m_tmp_file_fd > 0) {
Close();
}
const int unlink_rc = unlink(m_tmp_file_name.c_str());
if (unlink_rc < 0) {
ms_dbg_a(m_transaction, 1, "Multipart: Failed to delete file (part) \"" \
+ m_tmp_file_name + "\" because " \
+ std::to_string(errno) + "(" \
+ strerror(errno) + ")");
} else {
ms_dbg_a(m_transaction, 4, "Multipart: file deleted successfully (part) \"" \
+ m_tmp_file_name + "\"");
}
}
}
void MultipartPartTmpFile::Open() {
time_t tt = time(nullptr);
struct tm timeinfo;
localtime_r(&tt, &timeinfo);
char tstr[std::size("/yyyymmdd-hhmmss")];
strftime(tstr, std::size(tstr), "/%Y%m%d-%H%M%S", &timeinfo);
std::string path = m_transaction->m_rules->m_uploadDirectory.m_value;
path = path + tstr + "-" + m_transaction->m_id;
path += "-file-XXXXXX";
#ifndef WIN32
m_tmp_file_fd = mkstemp(path.data());
#else
_mktemp_s(path.data(), path.length()+1);
m_tmp_file_fd = _open(path.c_str(), _O_CREAT | _O_EXCL | _O_RDWR);
#endif
m_tmp_file_name = path;
ms_dbg_a(m_transaction, 4, "MultipartPartTmpFile: Create filename= " + m_tmp_file_name);
int mode = m_transaction->m_rules->m_uploadFileMode.m_value;
if ((m_tmp_file_fd != -1) && (mode != 0)) {
#ifndef WIN32
if (fchmod(m_tmp_file_fd, mode) == -1) {
#else
if (_chmod(m_tmp_file_name.c_str(), mode) == -1) {
#endif
m_tmp_file_fd = -1;
}
}
}
void MultipartPartTmpFile::Close() {
close(m_tmp_file_fd);
m_tmp_file_fd = -1;
}
Multipart::Multipart(const std::string &header, Transaction *transaction)
: m_reqbody_no_files_length(0),
m_nfiles(0),
m_boundary_count(0),
m_buf{0},
m_buf_contains_line(0),
m_bufptr(NULL),
m_bufleft(0),
m_buf_offset(0),
m_crlf_state(0),
m_crlf_state_buf_end(0),
m_mpp(NULL),
m_mpp_state(0),
m_mpp_substate_part_data_read(0),
m_reserve{0},
m_seen_data(0),
m_is_complete(0),
m_flag_error(0),
m_flag_data_before(0),
m_flag_data_after(0),
m_flag_header_folding(0),
m_flag_boundary_quoted(0),
m_flag_lf_line(0),
m_flag_crlf_line(0),
m_flag_unmatched_boundary(0),
m_flag_boundary_whitespace(0),
m_flag_missing_semicolon(0),
m_flag_invalid_quoting(0),
m_flag_invalid_part(0),
m_flag_invalid_header_folding(0),
m_flag_file_limit_exceeded(0),
m_header(header),
m_transaction(transaction) { }
Multipart::~Multipart() {
ms_dbg_a(m_transaction, 4,
"Multipart: Cleanup started (keep files set to " \
+ RulesSetProperties::configBooleanString(
m_transaction->m_rules->m_uploadKeepFiles) \
+ ")");
if (m_transaction->m_rules->m_uploadKeepFiles
!= RulesSetProperties::TrueConfigBoolean) {
for (MultipartPart *m : m_parts) {
if ((m->m_type == MULTIPART_FILE) && (m->m_tmp_file)) {
// only mark for deletion for now; the file should stay on disk until
// the transaction is complete
ms_dbg_a(m_transaction, 9, "Multipart: Marking temporary file for deletion: " \
+ m->m_tmp_file->getFilename());
m->m_tmp_file->setDelete();
}
}
}
while (m_parts.empty() == false) {
auto *a = m_parts.back();
m_parts.pop_back();
delete a;
}
if (m_mpp != NULL) {
delete m_mpp;
m_mpp = NULL;
}
}
int Multipart::is_token_char(unsigned char c) {
/* ENH Is the performance important at all? We could use a table instead. */
/* CTLs not allowed */
if ((c <= 32) || (c >= 127)) {
return 0;
}
switch (c) {
case '(' :
case ')' :
case '<' :
case '>' :
case '@' :
case ',' :
case ';' :
case ':' :
case '\\' :
case '"' :
case '/' :
case '[' :
case ']' :
case '?' :
case '=' :
return 0;
}
return 1;
}
int Multipart::boundary_characters_valid(const char *boundary) {
const unsigned char *p = (unsigned char *)boundary;
unsigned char c;
if (p == NULL) {
return -1;
}
while ((c = *p) != '\0') {
// Check against allowed list defined in RFC2046 page 22
if (!(
('0' <= c && c <= '9')
|| ('A' <= c && c <= 'Z')
|| ('a' <= c && c <= 'z')
|| (c == ' ' && *(p + 1) != '\0') // space allowed, but not as last character
|| c == '\''
|| c == '('
|| c == ')'
|| c == '+'
|| c == '_'
|| c == ','
|| c == '-'
|| c == '.'
|| c == '/'
|| c == ':'
|| c == '='
|| c == '?'
)) {
return 0;
}
p++;
}
return 1;
}
void Multipart::validate_quotes(const char *data, char quote) {
int len;
if (data == NULL)
return;
// if the value was enclosed in double quotes, then we don't care about
// a single quote character within the name.
if (quote == '"') {
return;
}
len = strlen(data);
for (int i = 0;i < len;i++) {
if (data[i] == '\'') {
ms_dbg_a(m_transaction, 9,
"Multipart: Invalid quoting detected: " \
+ std::string(data) + " length " \
+ std::to_string(len) + " bytes");
m_flag_invalid_quoting = 1;
}
}
}
int Multipart::parse_content_disposition(const char *c_d_value, int offset) {
const char *p = NULL;
std::string filenameStar;
/* accept only what we understand */
if (strncmp(c_d_value, "form-data", 9) != 0) {
return -1;
}
/* see if there are any other parts to parse */
p = c_d_value + 9;
while ((*p == '\t') || (*p == ' ')) p++;
if (*p == '\0') {
return 1; /* this is OK */
}
if (*p != ';') {
return -2;
}
p++;
/* parse the appended parts */
while (*p != '\0') {
const char *start = NULL;
std::string name;
std::string value;
/* go over the whitespace */
while ((*p == '\t') || (*p == ' ')) {
p++;
}
if (*p == '\0') {
return -3;
}
start = p;
while ((*p != '\0') && (*p != '=') && (*p != '\t') && (*p != ' ')) {
p++;
}
if (*p == '\0') {
return -4;
}
name = std::string(start, (p - start));
while ((*p == '\t') || (*p == ' ')) {
p++;
}
if (*p == '\0') {
return -5;
}
if (*p != '=') {
return -13;
}
p++;
while ((*p == '\t') || (*p == ' ')) {
p++;
}
if (*p == '\0') {
return -6;
}
char quote = '\0';
if (name == "filename*") {
/* filename*=charset'[optional-language]'filename */
/* Read beyond the charset and the optional language*/
const char* start_of_charset = p;
while ((*p != '\0') && (isalnum(*p) || (strchr(mime_charset_special, *p)))) {
p++;
}
if ((*p != '\'') || (p == start_of_charset)) {
return -16; // Must be at least one legit char before ' for start of language
}
p++;
while ((*p != '\0') && (*p != '\'')) {
p++;
}
if (*p != '\'') {
return -17; // Single quote for end-of-language not found
}
p++;
/* Now read what should be the actual filename */
const char* start_of_filename = p;
while ((*p != '\0') && (*p != ';')) {
if (*p == '%') {
if ((*(p+1) == '\0') || (!isxdigit(*(p+1))) || (!isxdigit(*(p+2)))) {
return -18;
}
p += 3;
} else if (isalnum(*p) || strchr(attr_char_special, *p)) {
p++;
} else {
return -19;
}
}
value.assign(start_of_filename, p - start_of_filename);
} else if ((*p == '"') || (*p == '\'')) {
/* Accept both quotes as some backends will accept them, but
* technically "'" is invalid and so flag_invalid_quoting is
* set so the user can deal with it in the rules if they so wish.
*/
quote = *p; // remember which quote character was used for the value
if (quote == '\'') {
m_flag_invalid_quoting = 1;
}
p++;
if (*p == '\0') {
return -7;
}
while (*p != '\0') {
if (*p == '\\') {
if (*(p + 1) == '\0') {
/* improper escaping */
return -8;
}
/* only quote and \ can be escaped */
if ((*(p + 1) == quote) || (*(p + 1) == '\\')) {
p++;
} else {
/* improper escaping */
/* We allow for now because IE sends
* improperly escaped content and there's
* nothing we can do about it.
*
* return -9;
*/
}
} else if (*p == quote) {
break;
}
value.append((p++), 1);
}
p++; /* go over the quote at the end */
} else {
/* not quoted */
start = p;
while ((*p != '\0') && (is_token_char(*p))) {
p++;
}
value.assign(start, p - start);
}
/* evaluate part */
if (name == "name") {
validate_quotes(value.c_str(), quote);
m_transaction->m_variableMultipartName.set(value, value,
offset + ((p - c_d_value) - value.size()));
if (!m_mpp->m_name.empty()) {
ms_dbg_a(m_transaction, 4,
"Multipart: Warning: Duplicate Content-Disposition " \
"name: " + value + ". Previously: " + m_mpp->m_name + "");
return -14;
}
m_mpp->m_name.assign(value);
m_mpp->m_nameOffset = offset + ((p - c_d_value) - value.size());
ms_dbg_a(m_transaction, 9,
"Multipart: Content-Disposition name: " + value + ".");
} else if (name == "filename") {
validate_quotes(value.c_str(), quote);
m_transaction->m_variableMultipartFileName.set(value, value, \
offset + ((p - c_d_value) - value.size()));
if (!m_mpp->m_filename.empty()) {
ms_dbg_a(m_transaction, 4,
"Multipart: Warning: Duplicate Content-Disposition " \
"filename: " + value + ".");
return -15;
}
m_mpp->m_filename.assign(value);
m_mpp->m_filenameOffset = offset + ((p - c_d_value) - value.size());
ms_dbg_a(m_transaction, 9,
"Multipart: Content-Disposition filename: " + value + ".");
} else if (name == "filename*") {
if (!filenameStar.empty()) {
ms_dbg_a(m_transaction, 4,
"Multipart: Warning: Duplicate Content-Disposition " \
"filename*: " + value + ".");
return -20;
}
filenameStar.assign(value);
ms_dbg_a(m_transaction, 9,
"Multipart: Content-Disposition filename*: " + value + ".");
} else {
return -11;
}
if (*p != '\0') {
while ((*p == '\t') || (*p == ' ')) {
p++;
}
/* the next character must be a zero or a semi-colon */
if (*p == '\0') {
// Just let the 'while' condition end the loop
} else {
if (*p != ';') {
p--;
if (*p == '\'' || *p == '\"') {
ms_dbg_a(m_transaction, 9,
"Multipart: Invalid quoting detected: " \
+ std::string(p) + " length " \
+ std::to_string(strlen(p)) + " bytes");
m_flag_invalid_quoting = 1;
}
/* p++; */
return -12;
}
p++; /* move over the semi-colon */
}
}
/* loop will stop when (*p == '\0') */
}
if (!filenameStar.empty() && m_mpp->m_filename.empty()) {
ms_dbg_a(m_transaction, 4,
"Multipart: Warning: no filename= but filename*:" \
+ filenameStar + ".");
return -21;
}
return 1;
}
int Multipart::process_part_data(std::string *error, size_t offset) {
char *p = m_buf + (MULTIPART_BUF_SIZE - m_bufleft);
char localreserve[2] = { '\0', '\0' }; /* initialized to quiet warning */
int bytes_reserved = 0;
m_mpp_substate_part_data_read = 1;
/* Preserve some bytes for later. */
if (((MULTIPART_BUF_SIZE - m_bufleft) >= 1) && (*(p - 1) == '\n')) {
if (((MULTIPART_BUF_SIZE - m_bufleft) >= 2) && (*(p - 2) == '\r')) {
/* Two bytes. */
bytes_reserved = 2;
localreserve[0] = *(p - 2);
localreserve[1] = *(p - 1);
m_bufleft += 2;
*(p - 2) = 0;
} else {
/* Only one byte. */
bytes_reserved = 1;
localreserve[0] = *(p - 1);
localreserve[1] = 0;
m_bufleft += 1;
*(p - 1) = 0;
}
}
/* add data to the part we are building */
if (m_mpp->m_type == MULTIPART_FILE) {
bool extract = m_transaction->m_rules->m_uploadKeepFiles \
== RulesSetProperties::TrueConfigBoolean \
|| m_transaction->m_rules->m_tmpSaveUploadedFiles \
== RulesSetProperties::TrueConfigBoolean;
/* remember where we started */
if (m_mpp->m_length == 0) {
m_mpp->m_offset = m_buf_offset;
}
/* check if the file limit has been reached */
if (extract && m_transaction->m_rules->m_uploadFileLimit.m_value
&& (m_nfiles >=
m_transaction->m_rules->m_uploadFileLimit.m_value)) {
if (m_flag_file_limit_exceeded == 0) {
ms_dbg_a(m_transaction, 1,
"Multipart: Upload file limit exceeded " \
+ std::to_string(
m_transaction->m_rules->m_uploadFileLimit.m_value) \
+ ". Use SecUploadFileLimit to change the limit.");
error->assign("Multipart: Upload file limit exceeded " \
+ std::to_string(
m_transaction->m_rules->m_uploadFileLimit.m_value) \
+ ". Use SecUploadFileLimit to change the limit.");
m_flag_file_limit_exceeded = 1;
}
extract = 0;
}
/* only store individual files on disk if we are going
* to keep them or if we need to have them approved later
*/
if (extract) {
/* first create a temporary file if we don't have it already */
if (!m_mpp->m_tmp_file || !m_mpp->m_tmp_file->isValid()) {
m_mpp->m_tmp_file = std::make_shared<RequestBodyProcessor::MultipartPartTmpFile>(m_transaction);
m_transaction->m_multipartPartTmpFiles.push_back(m_mpp->m_tmp_file);
m_mpp->m_tmp_file->Open();
/* do we have an opened file? */
if (!m_mpp->m_tmp_file || m_mpp->m_tmp_file->getFd() < 0) {
ms_dbg_a(m_transaction, 1,
"Multipart: Failed to create file: " \
+ m_mpp->m_tmp_file->getFilename());
error->assign("Multipart: Failed to create file: " \
+ m_mpp->m_tmp_file->getFilename());
return -1;
}
/* keep track of the files count */
m_nfiles++;
ms_dbg_a(m_transaction, 4,
"Multipart: Created temporary file " \
+ std::to_string(m_nfiles) + " (mode o" + std::to_string(m_transaction->m_rules->m_uploadFileMode.m_value) + "): " \
+ m_mpp->m_tmp_file->getFilename());
}
/* write the reserve first */
if (m_reserve[0] != 0) {
if (write(m_mpp->m_tmp_file->getFd(), &m_reserve[1], m_reserve[0])
!= m_reserve[0]) {
ms_dbg_a(m_transaction, 1,
"Multipart: writing to \"" \
+ m_mpp->m_tmp_file->getFilename() + "\" failed");
error->assign("Multipart: writing to \"" \
+ m_mpp->m_tmp_file->getFilename() + "\" failed");
return -1;
}
m_mpp->m_tmp_file_size.first += m_reserve[0];
if (m_mpp->m_tmp_file_size.second == 0) {
m_mpp->m_tmp_file_size.second = offset \
- m_mpp->m_tmp_file_size.first;
}
m_mpp->m_length += m_reserve[0];
}
/* write data to the file */
if (write(m_mpp->m_tmp_file->getFd(), m_buf,
MULTIPART_BUF_SIZE - m_bufleft)
!= (MULTIPART_BUF_SIZE - m_bufleft)) {
ms_dbg_a(m_transaction, 1,
"Multipart: writing to \"" \
+ m_mpp->m_tmp_file->getFilename() + "\" failed");
error->assign("Multipart: writing to \"" \
+ m_mpp->m_tmp_file->getFilename() + "\" failed");
return -1;
}
m_mpp->m_value.append(std::string(m_buf,
MULTIPART_BUF_SIZE - m_bufleft));
m_mpp->m_valueOffset = offset - (MULTIPART_BUF_SIZE - m_bufleft);
m_mpp->m_tmp_file_size.first += (MULTIPART_BUF_SIZE - m_bufleft);
if (m_mpp->m_tmp_file_size.second == 0) {
m_mpp->m_tmp_file_size.second = offset \
- m_mpp->m_tmp_file_size.first;
}
m_mpp->m_length += (MULTIPART_BUF_SIZE - m_bufleft);
} else {
/* just keep track of the file size */
m_mpp->m_tmp_file_size.first += (MULTIPART_BUF_SIZE - m_bufleft) \
+ m_reserve[0];
if (m_mpp->m_tmp_file_size.second == 0) {
m_mpp->m_tmp_file_size.second = offset \
- m_mpp->m_tmp_file_size.first;
}
m_mpp->m_length += (MULTIPART_BUF_SIZE - m_bufleft) + m_reserve[0];
}
} else if (m_mpp->m_type == MULTIPART_FORMDATA) {
std::string d;
/* The buffer contains data so increase the data length counter. */
m_reqbody_no_files_length += (MULTIPART_BUF_SIZE - m_bufleft) \
+ m_reserve[0];
/* add this part to the list of parts */
/* remember where we started */
if (m_mpp->m_length == 0) {
m_mpp->m_offset = m_buf_offset;
}
if (m_reserve[0] != 0) {
d.assign(&(m_reserve[1]), m_reserve[0]);
d.assign(m_buf, MULTIPART_BUF_SIZE - m_bufleft);
m_mpp->m_length += d.size();
} else {
d.assign(m_buf, MULTIPART_BUF_SIZE - m_bufleft);
m_mpp->m_length += d.size();
}
m_mpp->m_value_parts.push_back(std::make_pair(d, m_buf_offset));
ms_dbg_a(m_transaction, 9,
"Multipart: Added data to variable: " + d);
} else {
ms_dbg_a(m_transaction, 1,
"Multipart: unknown part type: " \
+ std::to_string(m_mpp->m_type));
error->assign("Multipart: unknown part type: " \
+ std::to_string(m_mpp->m_type));
return false;
}
/* store the reserved bytes to the multipart
* context so that they don't get lost
*/
if (bytes_reserved) {
m_reserve[0] = bytes_reserved;
m_reserve[1] = localreserve[0];
m_reserve[2] = localreserve[1];
m_buf_offset += bytes_reserved;
} else {
m_buf_offset -= m_reserve[0];
m_reserve[0] = 0;
}
return true;
}
int Multipart::process_part_header(std::string *error, int offset) {
int i, len;
/* Check for nul bytes. */
len = MULTIPART_BUF_SIZE - m_bufleft;
int len_without_termination = len - 1;
for (i = 0; i < len; i++) {
if (m_buf[i] == '\0') {
ms_dbg_a(m_transaction, 1,
"Multipart: Nul byte in part headers.");
error->assign("Multipart: Nul byte in part headers.");
return false;
}
}
i = 0;
/* The buffer is data so increase the data length counter. */
m_reqbody_no_files_length += (MULTIPART_BUF_SIZE - m_bufleft);
if (len > 1) {
if (m_buf[len - 2] == '\r') {
m_flag_crlf_line = 1;
len_without_termination--;
} else {
m_flag_lf_line = 1;
}
} else {
m_flag_lf_line = 1;
}
/* Is this an empty line? */
if (((m_buf[0] == '\r') && (m_buf[1] == '\n') && (m_buf[2] == '\0'))
|| ((m_buf[0] == '\n') && (m_buf[1] == '\0'))) { /* Empty line. */
std::string header_value("");
int rc;
/* record the previous completed header */
if (!m_mpp->m_last_header_line.empty()) {
m_mpp->m_header_lines.push_back(std::make_pair(
offset-m_mpp->m_last_header_line.length(), m_mpp->m_last_header_line));
m_mpp->m_last_header_line.assign("");
}
if (m_mpp->m_headers.count("Content-Disposition") == 0) {
ms_dbg_a(m_transaction, 1,
"Multipart: Part missing Content-Disposition header.");
error->assign("Multipart: Part missing " \
"Content-Disposition header.");
return false;
}
header_value = m_mpp->m_headers.at("Content-Disposition").second;
try {
rc = parse_content_disposition(header_value.c_str(),
m_mpp->m_headers.at("Content-Disposition").first);
} catch (...) {
ms_dbg_a(m_transaction, 1,
"Multipart: Unexpected error parsing Content-Disposition header.");
rc = -99;
}
if (rc < 0) {
ms_dbg_a(m_transaction, 1,
"Multipart: Invalid Content-Disposition header ("
+ std::to_string(rc) + "): " + header_value);
error->assign("Multipart: Invalid Content-Disposition header ("
+ std::to_string(rc) + "): " + header_value);
return false;
}
if (m_mpp->m_name.empty()) {
ms_dbg_a(m_transaction, 1,
"Multipart: Content-Disposition header missing " \
"name field.");
error->assign("Multipart: Content-Disposition header missing " \
"name field.");
return false;
}
if (!m_mpp->m_filename.empty()) {
/* Some parsers use crude methods to extract the name and filename
* values from the C-D header. We need to check for the case where they
* didn't understand C-D but we did.
*/
if (strstr(header_value.c_str(), "filename=") == NULL) {
ms_dbg_a(m_transaction, 1,
"Multipart: Invalid Content-Disposition " \
"header (filename).");
error->assign("Multipart: Invalid Content-Disposition " \
"header (filename).");
return false;
}
m_mpp->m_type = MULTIPART_FILE;
} else {
m_mpp->m_type = MULTIPART_FORMDATA;
}
m_mpp_state = 1;
m_mpp_substate_part_data_read = 0;
m_mpp->m_last_header_name.assign("");
} else { /* Header line. */
if (isspace(m_buf[0])) {
std::string header_value;
char *data;
std::string new_value;
/* header folding, add data to the header we are building */
m_flag_header_folding = 1;
/* RFC-2557 states header folding is SP / HTAB, but PHP and
* perhaps others will take any whitespace. So, we accept,
* but with a flag set.
*/
if ((m_buf[0] != '\t') && (m_buf[0] != ' ')) {
m_flag_invalid_header_folding = 1;
}
if (m_mpp->m_last_header_name.empty()) {
/* we are not building a header at this moment */
ms_dbg_a(m_transaction, 1,
"Multipart: Invalid part header (folding error).");
error->assign("Multipart: Invalid part header " \
"(folding error).");
return false;
}
/* locate the beginning of data */
data = m_buf;
while (isspace(*data)) {
/* Flag invalid header folding if an invalid RFC-2557
* character is used anywhere in the folding prefix.
*/
if ((*data != '\t') && (*data != ' ')) {
m_flag_invalid_header_folding = 1;
}
data++;
i++;
}
new_value = std::string(data);
utils::string::chomp(new_value);
/* update the header value in the table */
header_value = m_mpp->m_headers.at(
m_mpp->m_last_header_name).second;
new_value = header_value + " " + new_value;
m_mpp->m_headers.at(m_mpp->m_last_header_name).second = new_value;
ms_dbg_a(m_transaction, 9,
"Multipart: Continued folder header \"" \
+ m_mpp->m_last_header_name + "\" with \"" \
+ std::string(data) + "\"");
if (new_value.size() > MULTIPART_BUF_SIZE) {
ms_dbg_a(m_transaction, 1, "Multipart: Part header too long.");
error->assign("Multipart: Part header too long.");
return false;
}
m_mpp->m_last_header_line = m_mpp->m_last_header_name + ": " + new_value;
} else {
char *data;
std::string header_value;
std::string header_name;
/* new header */
/* record the previous completed header */
if (!m_mpp->m_last_header_line.empty()) {
m_mpp->m_header_lines.push_back(std::make_pair(
offset-m_mpp->m_last_header_line.length(), m_mpp->m_last_header_line));
m_mpp->m_last_header_line.assign("");
}
data = m_buf;
while ((*data != ':') && (*data != '\0')) {
data++;
i++;
}
if (*data == '\0') {
ms_dbg_a(m_transaction, 1,
"Multipart: Invalid part header (colon missing): " \
+ std::string(m_buf));
error->assign("Multipart: Invalid part header " \
"(colon missing): " + std::string(m_buf));
return false;
}
/* extract header name */
header_name = std::string(m_buf, data - m_buf);
if (data == m_buf) {
ms_dbg_a(m_transaction, 1,
"Multipart: Invalid part header " \
"(header name missing).");
error->assign("Multipart: Invalid part header " \
"(header name missing).");
return false;
}
/* check if multipart header contains any invalid characters */
for (const auto& ch : header_name) {
if (ch < 33 || ch > 126) {
ms_dbg_a(m_transaction, 1,
"Multipart: Invalid part header " \
"(contains invalid character).");
error->assign("Multipart: Invalid part header "\
"(contains invalid character).");
return false;
}
}
/* extract the value value */
data++;
i++;
while ((*data == '\t') || (*data == ' ')) {
data++;
i++;
}
header_value = std::string(data);
utils::string::chomp(header_value);
/* error if the name already exists */
if (m_mpp->m_headers.count(header_name) > 0) {
ms_dbg_a(m_transaction, 1,
"Multipart: Duplicate part header: " \
+ header_name + ".");
return false;
}
m_mpp->m_last_header_name.assign(header_name);
m_mpp->m_headers.emplace(
std::string(header_name), std::make_pair(offset - len + i,
std::string(header_value)));
ms_dbg_a(m_transaction, 9,
"Multipart: Added part header \"" + header_name \
+ "\" \"" + header_value + "\".");
if (len_without_termination > 0) {
m_mpp->m_last_header_line.assign(m_buf, len_without_termination);
} else {
m_mpp->m_last_header_line.assign("");
}
}
}
return true;
}
int Multipart::process_boundary(int last_part) {
/* if there was a part being built finish it */
if (m_mpp != NULL) {
/* record all the part header lines from the part into the transaction collection */
for (const auto& header_line : m_mpp->m_header_lines) {
m_transaction->m_variableMultipartPartHeaders.set(m_mpp->m_name,
header_line.second, header_line.first);
ms_dbg_a(m_transaction, 9, "Multipart: Added part header line:" + header_line.second );
}
/* close the temp file */
if ((m_mpp->m_type == MULTIPART_FILE) && (m_mpp->m_tmp_file)
&& (m_mpp->m_tmp_file->isValid())) {
m_mpp->m_tmp_file->Close();
}
if (m_mpp->m_type != MULTIPART_FILE) {
/* now construct a single string out of the parts */
for (const auto &i : m_mpp->m_value_parts) {
if (m_mpp->m_valueOffset == 0) {
m_mpp->m_valueOffset = i.second;
}
m_mpp->m_value.append(i.first);
}
}
if (m_mpp->m_name.empty() == false) {
/* add the part to the list of parts */
m_parts.push_back(m_mpp);