summaryrefslogtreecommitdiffstats
path: root/htp/htp_multipart.c
blob: ea73072dd6c75354a936bc27b4751fe47e0c54a1 (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
/***************************************************************************
 * Copyright (c) 2009-2010 Open Information Security Foundation
 * Copyright (c) 2010-2013 Qualys, Inc.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.

 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.

 * - Neither the name of the Qualys, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ***************************************************************************/

/**
 * @file
 * @author Ivan Ristic <ivanr@webkreator.com>
 */

#include "htp_config_auto.h"

#include "htp_private.h"

/**
 * Determines the type of a Content-Disposition parameter.
 *
 * @param[in] data
 * @param[in] startpos
 * @param[in] pos
 * @return CD_PARAM_OTHER, CD_PARAM_NAME or CD_PARAM_FILENAME.
 */
static int htp_mpartp_cd_param_type(unsigned char *data, size_t startpos, size_t endpos) {
    if ((endpos - startpos) == 4) {
        if (memcmp(data + startpos, "name", 4) == 0) return CD_PARAM_NAME;
    } else if ((endpos - startpos) == 8) {
        if (memcmp(data + startpos, "filename", 8) == 0) return CD_PARAM_FILENAME;
    }

    return CD_PARAM_OTHER;
}

htp_multipart_t *htp_mpartp_get_multipart(htp_mpartp_t *parser) {
    return &(parser->multipart);
}

/**
 * Decodes a C-D header value. This is impossible to do correctly without a
 * parsing personality because most browsers are broken:
 *  - Firefox encodes " as \", and \ is not encoded.
 *  - Chrome encodes " as %22.
 *  - IE encodes " as \", and \ is not encoded.
 *  - Opera encodes " as \" and \ as \\.
 * @param[in] b
 */
static void htp_mpart_decode_quoted_cd_value_inplace(bstr *b) {
    unsigned char *s = bstr_ptr(b);
    unsigned char *d = bstr_ptr(b);
    size_t len = bstr_len(b);
    size_t pos = 0;

    while (pos < len) {
        // Ignore \ when before \ or ".
        if ((*s == '\\')&&(pos + 1 < len)&&((*(s + 1) == '"')||(*(s + 1) == '\\'))) {
            s++;
            pos++;
        }

        *d++ = *s++;
        pos++;
    }

    bstr_adjust_len(b, len - (s - d));
}

/**
 * Parses the Content-Disposition part header.
 *
 * @param[in] part
 * @return HTP_OK on success (header found and parsed), HTP_DECLINED if there is no C-D header or if
 *         it could not be processed, and HTP_ERROR on fatal error.
 */
htp_status_t htp_mpart_part_parse_c_d(htp_multipart_part_t *part) {
    // Find the C-D header.
    htp_header_t *h = htp_table_get_c(part->headers, "content-disposition");
    if (h == NULL) {        
        part->parser->multipart.flags |= HTP_MULTIPART_PART_UNKNOWN;
        return HTP_DECLINED;
    }

    // Require "form-data" at the beginning of the header.
    if (bstr_index_of_c(h->value, "form-data") != 0) {        
        part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
        return HTP_DECLINED;
    }

    // The parsing starts here.
    unsigned char *data = bstr_ptr(h->value);
    size_t len = bstr_len(h->value);
    size_t pos = 9; // Start after "form-data"

    // Main parameter parsing loop (once per parameter).
    while (pos < len) {              
        // Ignore whitespace.
        while ((pos < len) && isspace(data[pos])) pos++;
        if (pos == len) {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }

        // Expecting a semicolon.
        if (data[pos] != ';') {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }
        pos++;

        // Go over the whitespace before parameter name.
        while ((pos < len) && isspace(data[pos])) pos++;
        if (pos == len) {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }

        // Found the starting position of the parameter name.
        size_t start = pos;

        // Look for the ending position.
        while ((pos < len) && (!isspace(data[pos]) && (data[pos] != '='))) pos++;
        if (pos == len) {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }

        // Ending position is in "pos" now.

        // Determine parameter type ("name", "filename", or other).
        int param_type = htp_mpartp_cd_param_type(data, start, pos);        

        // Ignore whitespace after parameter name, if any.
        while ((pos < len) && isspace(data[pos])) pos++;
        if (pos == len) {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }

        // Equals.
        if (data[pos] != '=') {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }
        pos++;

        // Go over the whitespace before the parameter value.
        while ((pos < len) && isspace(data[pos])) pos++;
        if (pos == len) {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }
        
        // Expecting a double quote.
        if (data[pos] != '"') {            
            // Bare string or non-standard quoting, which we don't like.
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }        

        pos++; // Over the double quote.

        // We have the starting position of the value.
        start = pos;

        // Find the end of the value.
        while ((pos < len) && (data[pos] != '"')) {
            // Check for escaping.
            if (data[pos] == '\\') {
                if (pos + 1 >= len) {
                    // A backslash as the last character in the C-D header.
                    part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
                    return HTP_DECLINED;
                }

                // Allow " and \ to be escaped.
                if ((data[pos + 1] == '"')||(data[pos + 1] == '\\')) {
                    // Go over the quoted character.
                    pos++;
                }
            }

            pos++;
        }

        // If we've reached the end of the string that means the
        // value was not terminated properly (the second double quote is missing).
        if (pos == len) {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }

        // Expecting the terminating double quote.
        if (data[pos] != '"') {            
            part->parser->multipart.flags |= HTP_MULTIPART_CD_SYNTAX_INVALID;
            return HTP_DECLINED;
        }

        pos++; // Over the terminating double quote.

        // Finally, process the parameter value.

        switch (param_type) {
            case CD_PARAM_NAME:
                // Check that we have not seen the name parameter already.
                if (part->name != NULL) {                    
                    part->parser->multipart.flags |= HTP_MULTIPART_CD_PARAM_REPEATED;
                    return HTP_DECLINED;
                }
                
                part->name = bstr_dup_mem(data + start, pos - start - 1);
                if (part->name == NULL) return HTP_ERROR;

                htp_mpart_decode_quoted_cd_value_inplace(part->name);

                break;

            case CD_PARAM_FILENAME:                
                // Check that we have not seen the filename parameter already.
                if (part->file != NULL) {                    
                    part->parser->multipart.flags |= HTP_MULTIPART_CD_PARAM_REPEATED;
                    return HTP_DECLINED;
                }
 
                part->file = calloc(1, sizeof (htp_file_t));
                if (part->file == NULL) return HTP_ERROR;

                part->file->fd = -1;
                part->file->source = HTP_FILE_MULTIPART;

                part->file->filename = bstr_dup_mem(data + start, pos - start - 1);
                if (part->file->filename == NULL) {
                    free(part->file);
                    return HTP_ERROR;
                }

                htp_mpart_decode_quoted_cd_value_inplace(part->file->filename);
                
                break;
                
            default:
                // Unknown parameter.                
                part->parser->multipart.flags |= HTP_MULTIPART_CD_PARAM_UNKNOWN;
                return HTP_DECLINED;
                break;
        }       

        // Continue to parse the next parameter, if any.
    }

    return HTP_OK;
}

/**
 * Parses the Content-Type part header, if present.
 *
 * @param[in] part
 * @return HTP_OK on success, HTP_DECLINED if the C-T header is not present, and HTP_ERROR on failure.
 */
static htp_status_t htp_mpart_part_parse_c_t(htp_multipart_part_t *part) {
    htp_header_t *h = (htp_header_t *) htp_table_get_c(part->headers, "content-type");
    if (h == NULL) return HTP_DECLINED;
    return htp_parse_ct_header(h->value, &part->content_type);
}

/**
 * Processes part headers.
 *
 * @param[in] part
 * @return HTP_OK on success, HTP_ERROR on failure.
 */
htp_status_t htp_mpart_part_process_headers(htp_multipart_part_t *part) {
    if (htp_mpart_part_parse_c_d(part) == HTP_ERROR) return HTP_ERROR;
    if (htp_mpart_part_parse_c_t(part) == HTP_ERROR) return HTP_ERROR;

    return HTP_OK;
}

/**
 * Parses one part header.
 *
 * @param[in] part
 * @param[in] data
 * @param[in] len
 * @return HTP_OK on success, HTP_DECLINED on parsing error, HTP_ERROR on fatal error.
 */
htp_status_t htp_mpartp_parse_header(htp_multipart_part_t *part, const unsigned char *data, size_t len) {
    size_t name_start, name_end;
    size_t value_start, value_end;
   
    // We do not allow NUL bytes here.
    if (memchr(data, '\0', len) != NULL) {        
        part->parser->multipart.flags |= HTP_MULTIPART_NUL_BYTE;
        return HTP_DECLINED;
    }

    name_start = 0;

    // Look for the starting position of the name first.
    size_t colon_pos = 0;

    while ((colon_pos < len)&&(htp_is_space(data[colon_pos]))) colon_pos++;
    if (colon_pos != 0) {
        // Whitespace before header name.
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_INVALID;
        return HTP_DECLINED;
    }

    // Now look for the colon.
    while ((colon_pos < len) && (data[colon_pos] != ':')) colon_pos++;

    if (colon_pos == len) {
        // Missing colon.
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_INVALID;
        return HTP_DECLINED;
    }

    if (colon_pos == 0) {
        // Empty header name.
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_INVALID;
        return HTP_DECLINED;
    }

    name_end = colon_pos;

    // Ignore LWS after header name.
    size_t prev = name_end;
    while ((prev > name_start) && (htp_is_lws(data[prev - 1]))) {
        prev--;
        name_end--;

        // LWS after field name. Not allowing for now.
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_INVALID;
        return HTP_DECLINED;
    }

    // Header value.

    value_start = colon_pos + 1;

    // Ignore LWS before value.
    while ((value_start < len) && (htp_is_lws(data[value_start]))) value_start++;

    if (value_start == len) {
        // No header value.
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_INVALID;
        return HTP_DECLINED;
    }   

    // Assume the value is at the end.
    value_end = len;

    // Check that the header name is a token.
    size_t i = name_start;
    while (i < name_end) {
        if (!htp_is_token(data[i])) {
            part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_INVALID;
            return HTP_DECLINED;
        }

        i++;
    }

    // Now extract the name and the value.
    htp_header_t *h = calloc(1, sizeof (htp_header_t));
    if (h == NULL) return HTP_ERROR;

    h->name = bstr_dup_mem(data + name_start, name_end - name_start);
    if (h->name == NULL) {
        free(h);
        return HTP_ERROR;
    }

    h->value = bstr_dup_mem(data + value_start, value_end - value_start);
    if (h->value == NULL) {
        bstr_free(h->name);
        free(h);
        return HTP_ERROR;
    }

    if ((bstr_cmp_c_nocase(h->name, "content-disposition") != 0) && (bstr_cmp_c_nocase(h->name, "content-type") != 0)) {
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_UNKNOWN;
    }

    // Check if the header already exists.
    htp_header_t * h_existing = htp_table_get(part->headers, h->name);
    if (h_existing != NULL) {
        // Add to the existing header.
        bstr *new_value = bstr_expand(h_existing->value, bstr_len(h_existing->value)
                + 2 + bstr_len(h->value));
        if (new_value == NULL) {
            bstr_free(h->name);
            bstr_free(h->value);
            free(h);
            return HTP_ERROR;
        }

        h_existing->value = new_value;
        bstr_add_mem_noex(h_existing->value, ", ", 2);
        bstr_add_noex(h_existing->value, h->value);

        // The header is no longer needed.
        bstr_free(h->name);
        bstr_free(h->value);
        free(h);

        // Keep track of same-name headers.
        h_existing->flags |= HTP_MULTIPART_PART_HEADER_REPEATED;
        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_REPEATED;
    } else {
        // Add as a new header.
        if (htp_table_add(part->headers, h->name, h) != HTP_OK) {
            bstr_free(h->value);
            bstr_free(h->name);
            free(h);
            return HTP_ERROR;
        }
    }

    return HTP_OK;
}

/**
 * Creates a new Multipart part.
 *
 * @param[in] parser
 * @return New part instance, or NULL on memory allocation failure.
 */
htp_multipart_part_t *htp_mpart_part_create(htp_mpartp_t *parser) {
    htp_multipart_part_t * part = calloc(1, sizeof (htp_multipart_part_t));
    if (part == NULL) return NULL;

    part->headers = htp_table_create(4);
    if (part->headers == NULL) {
        free(part);
        return NULL;
    }

    part->parser = parser;
    bstr_builder_clear(parser->part_data_pieces);
    bstr_builder_clear(parser->part_header_pieces);

    return part;
}

/**
 * Destroys a part.
 *
 * @param[in] part
 * @param[in] gave_up_data
 */
void htp_mpart_part_destroy(htp_multipart_part_t *part, int gave_up_data) {
    if (part == NULL) return;

    if (part->file != NULL) {
        bstr_free(part->file->filename);

        if (part->file->tmpname != NULL) {
            unlink(part->file->tmpname);
            free(part->file->tmpname);
        }

        free(part->file);
        part->file = NULL;
    }

    if ((!gave_up_data) || (part->type != MULTIPART_PART_TEXT)) {
        bstr_free(part->name);
        bstr_free(part->value);
    }

    bstr_free(part->content_type);

    if (part->headers != NULL) {
        htp_header_t *h = NULL;
        for (size_t i = 0, n = htp_table_size(part->headers); i < n; i++) {
            h = htp_table_get_index(part->headers, i, NULL);
            bstr_free(h->name);
            bstr_free(h->value);
            free(h);
        }

        htp_table_destroy(part->headers);
    }

    free(part);
}

/**
 * Finalizes part processing.
 *
 * @param[in] part
 * @return HTP_OK on success, HTP_ERROR on failure.
 */
htp_status_t htp_mpart_part_finalize_data(htp_multipart_part_t *part) {
    // Determine if this part is the epilogue.

    if (part->parser->multipart.flags & HTP_MULTIPART_SEEN_LAST_BOUNDARY) {
        if (part->type == MULTIPART_PART_UNKNOWN) {
            // Assume that the unknown part after the last boundary is the epilogue.            
            part->parser->current_part->type = MULTIPART_PART_EPILOGUE;

            // But if we've already seen a part we thought was the epilogue,
            // raise HTP_MULTIPART_PART_UNKNOWN. Multiple epilogues are not allowed.
            if (part->parser->multipart.flags & HTP_MULTIPART_HAS_EPILOGUE) {
                part->parser->multipart.flags |= HTP_MULTIPART_PART_UNKNOWN;
            }

            part->parser->multipart.flags |= HTP_MULTIPART_HAS_EPILOGUE;
        } else {
            part->parser->multipart.flags |= HTP_MULTIPART_PART_AFTER_LAST_BOUNDARY;
        }
    }

    // Sanity checks.

    // Have we seen complete part headers? If we have not, that means that the part ended prematurely.
    if ((part->parser->current_part->type != MULTIPART_PART_EPILOGUE) && (part->parser->current_part_mode != MODE_DATA)) {
        part->parser->multipart.flags |= HTP_MULTIPART_PART_INCOMPLETE;
    }

    // Have we been able to determine the part type? If not, this means
    // that the part did not contain the C-D header.
    if (part->type == MULTIPART_PART_UNKNOWN) {
        part->parser->multipart.flags |= HTP_MULTIPART_PART_UNKNOWN;
    }

    // Finalize part value.   

    if (part->type == MULTIPART_PART_FILE) {
        // Notify callbacks about the end of the file.
        htp_mpartp_run_request_file_data_hook(part, NULL, 0);

        // If we are storing the file to disk, close the file descriptor.
        if (part->file->fd != -1) {
            close(part->file->fd);
        }
    } else {
        // Combine value pieces into a single buffer.
        if (bstr_builder_size(part->parser->part_data_pieces) > 0) {
            part->value = bstr_builder_to_str(part->parser->part_data_pieces);
            bstr_builder_clear(part->parser->part_data_pieces);
        }
    }

    return HTP_OK;
}

htp_status_t htp_mpartp_run_request_file_data_hook(htp_multipart_part_t *part, const unsigned char *data, size_t len) {
    if (part->parser->cfg == NULL) return HTP_OK;

    // Keep track of the file length.
    part->file->len += len;

    // Package data for the callbacks.
    htp_file_data_t file_data;
    file_data.file = part->file;
    file_data.data = data;
    file_data.len = (const size_t) len;

    // Send data to callbacks
    htp_status_t rc = htp_hook_run_all(part->parser->cfg->hook_request_file_data, &file_data);
    if (rc != HTP_OK) return rc;

    return HTP_OK;
}

/**
 * Handles part data.
 *
 * @param[in] part
 * @param[in] data
 * @param[in] len
 * @param[in] is_line
 * @return HTP_OK on success, HTP_ERROR on failure.
 */
htp_status_t htp_mpart_part_handle_data(htp_multipart_part_t *part, const unsigned char *data, size_t len, int is_line) {
    #if HTP_DEBUG
    fprintf(stderr, "Part type %d mode %d is_line %d\n", part->type, part->parser->current_part_mode, is_line);
    fprint_raw_data(stderr, "htp_mpart_part_handle_data: data chunk", data, len);
    #endif

    // Keep track of raw part length.
    part->len += len;

    // If we're processing a part that came after the last boundary, then we're not sure if it
    // is the epilogue part or some other part (in case of evasion attempt). For that reason we
    // will keep all its data in the part_data_pieces structure. If it ends up not being the
    // epilogue, this structure will be cleared.
    if ((part->parser->multipart.flags & HTP_MULTIPART_SEEN_LAST_BOUNDARY) && (part->type == MULTIPART_PART_UNKNOWN)) {
        bstr_builder_append_mem(part->parser->part_data_pieces, data, len);
    }

    if (part->parser->current_part_mode == MODE_LINE) {
        // Line mode.       

        if (is_line) {
            // End of the line.

            bstr *line = NULL;

            // If this line came to us in pieces, combine them now into a single buffer.
            if (bstr_builder_size(part->parser->part_header_pieces) > 0) {
                bstr_builder_append_mem(part->parser->part_header_pieces, data, len);
                line = bstr_builder_to_str(part->parser->part_header_pieces);
                if (line == NULL) return HTP_ERROR;
                bstr_builder_clear(part->parser->part_header_pieces);

                data = bstr_ptr(line);
                len = bstr_len(line);
            }

            // Ignore the line endings.
            if (len > 1) {
                if (data[len - 1] == LF) len--;
                if (data[len - 1] == CR) len--;
            } else if (len > 0) {
                if (data[len - 1] == LF) len--;
            }

            // Is it an empty line?
            if (len == 0) {
                // Empty line; process headers and switch to data mode.

                // Process the pending header, if any.
                if (part->parser->pending_header_line != NULL) {
                    if (htp_mpartp_parse_header(part, bstr_ptr(part->parser->pending_header_line),
                            bstr_len(part->parser->pending_header_line)) == HTP_ERROR)
                    {
                        bstr_free(line);
                        return HTP_ERROR;
                    }

                    bstr_free(part->parser->pending_header_line);
                    part->parser->pending_header_line = NULL;
                }

                if (htp_mpart_part_process_headers(part) == HTP_ERROR) {
                    bstr_free(line);
                    return HTP_ERROR;
                }

                part->parser->current_part_mode = MODE_DATA;
                bstr_builder_clear(part->parser->part_header_pieces);

                if (part->file != NULL) {
                    // Changing part type because we have a filename.
                    part->type = MULTIPART_PART_FILE;

                    if ((part->parser->extract_files) && (part->parser->file_count < part->parser->extract_limit)) {
                        char buf[255];
                        
                        strncpy(buf, part->parser->extract_dir, 254);
                        strncat(buf, "/libhtp-multipart-file-XXXXXX", 254 - strlen(buf));

                        part->file->tmpname = strdup(buf);
                        if (part->file->tmpname == NULL) {
                            bstr_free(line);
                            return HTP_ERROR;
                        }

                        mode_t previous_mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
                        part->file->fd = mkstemp(part->file->tmpname);
                        umask(previous_mask);

                        if (part->file->fd < 0) {
                            bstr_free(line);
                            return HTP_ERROR;
                        }

                        part->parser->file_count++;
                    }
                } else if (part->name != NULL) {
                    // Changing part type because we have a name.
                    part->type = MULTIPART_PART_TEXT;
                    bstr_builder_clear(part->parser->part_data_pieces);
                } else {
                    // Do nothing; the type stays MULTIPART_PART_UNKNOWN.
                }
            } else {
                // Not an empty line.

                // Is there a pending header?
                if (part->parser->pending_header_line == NULL) {
                    if (line != NULL) {
                        part->parser->pending_header_line = line;
                        line = NULL;
                    } else {
                        part->parser->pending_header_line = bstr_dup_mem(data, len);
                        if (part->parser->pending_header_line == NULL) return HTP_ERROR;
                    }
                } else {
                    // Is this a folded line?
                    if (isspace(data[0])) {
                        // Folding; add to the existing line.
                        part->parser->multipart.flags |= HTP_MULTIPART_PART_HEADER_FOLDING;
                        part->parser->pending_header_line = bstr_add_mem(part->parser->pending_header_line, data, len);
                        if (part->parser->pending_header_line == NULL) {
                            bstr_free(line);
                            return HTP_ERROR;
                        }
                    } else {
                        // Process the pending header line.                        
                        if (htp_mpartp_parse_header(part, bstr_ptr(part->parser->pending_header_line),
                                bstr_len(part->parser->pending_header_line)) == HTP_ERROR)
                        {
                            bstr_free(line);
                            return HTP_ERROR;
                        }
                        
                        bstr_free(part->parser->pending_header_line);

                        if (line != NULL) {
                            part->parser->pending_header_line = line;
                            line = NULL;
                        } else {
                            part->parser->pending_header_line = bstr_dup_mem(data, len);
                            if (part->parser->pending_header_line == NULL) return HTP_ERROR;
                        }
                    }
                }
            }

            bstr_free(line);
            line = NULL;
        } else {
            // Not end of line; keep the data chunk for later.
            bstr_builder_append_mem(part->parser->part_header_pieces, data, len);
        }
    } else {
        // Data mode; keep the data chunk for later (but not if it is a file).
        switch (part->type) {
            case MULTIPART_PART_EPILOGUE:
            case MULTIPART_PART_PREAMBLE:
            case MULTIPART_PART_TEXT:
            case MULTIPART_PART_UNKNOWN:
                // Make a copy of the data in RAM.
                bstr_builder_append_mem(part->parser->part_data_pieces, data, len);
                break;

            case MULTIPART_PART_FILE:
                // Invoke file data callbacks.
                htp_mpartp_run_request_file_data_hook(part, data, len);

                // Optionally, store the data in a file.
                if (part->file->fd != -1) {
                    if (write(part->file->fd, data, len) < 0) {
                        return HTP_ERROR;
                    }
                }
                break;
                
            default:
                // Internal error.
                return HTP_ERROR;
                break;
        }
    }

    return HTP_OK;
}

/**
 * Handles data, creating new parts as necessary.
 *
 * @param[in] mpartp
 * @param[in] data
 * @param[in] len
 * @param[in] is_line
 * @return HTP_OK on success, HTP_ERROR on failure.
 */
static htp_status_t htp_mpartp_handle_data(htp_mpartp_t *parser, const unsigned char *data, size_t len, int is_line) {
    if (len == 0) return HTP_OK;

    // Do we have a part already?
    if (parser->current_part == NULL) {
        // Create a new part.
        parser->current_part = htp_mpart_part_create(parser);
        if (parser->current_part == NULL) return HTP_ERROR;

        if (parser->multipart.boundary_count == 0) {
            // We haven't seen a boundary yet, so this must be the preamble part.
            parser->current_part->type = MULTIPART_PART_PREAMBLE;
            parser->multipart.flags |= HTP_MULTIPART_HAS_PREAMBLE;
            parser->current_part_mode = MODE_DATA;
        } else {
            // Part after preamble.
            parser->current_part_mode = MODE_LINE;
        }

        // Add part to the list.        
        htp_list_push(parser->multipart.parts, parser->current_part);

        #ifdef HTP_DEBUG
        fprintf(stderr, "Created new part type %d\n", parser->current_part->type);
        #endif
    }

    // Send data to the part.
    return htp_mpart_part_handle_data(parser->current_part, data, len, is_line);
}

/**
 * Handles a boundary event, which means that it will finalize a part if one exists.
 *
 * @param[in] mpartp
 * @return HTP_OK on success, HTP_ERROR on failure.
 */
static htp_status_t htp_mpartp_handle_boundary(htp_mpartp_t *parser) {
    #if HTP_DEBUG
    fprintf(stderr, "htp_mpartp_handle_boundary\n");
    #endif

    if (parser->current_part != NULL) {
        if (htp_mpart_part_finalize_data(parser->current_part) != HTP_OK) {
            return HTP_ERROR;
        }

        // We're done with this part
        parser->current_part = NULL;

        // Revert to line mode
        parser->current_part_mode = MODE_LINE;
    }

    return HTP_OK;
}

static htp_status_t htp_mpartp_init_boundary(htp_mpartp_t *parser, unsigned char *data, size_t len) {
    if ((parser == NULL) || (data == NULL)) return HTP_ERROR;

    // Copy the boundary and convert it to lowercase.

    parser->multipart.boundary_len = len + 4;
    parser->multipart.boundary = malloc(parser->multipart.boundary_len + 1);
    if (parser->multipart.boundary == NULL) return HTP_ERROR;

    parser->multipart.boundary[0] = CR;
    parser->multipart.boundary[1] = LF;
    parser->multipart.boundary[2] = '-';
    parser->multipart.boundary[3] = '-';

    for (size_t i = 0; i < len; i++) {
        parser->multipart.boundary[i + 4] = data[i];
    }

    parser->multipart.boundary[parser->multipart.boundary_len] = '\0';

    // We're starting in boundary-matching mode. The first boundary can appear without the
    // CRLF, and our starting state expects that. If we encounter non-boundary data, the
    // state will switch to data mode. Then, if the data is CRLF or LF, we will go back
    // to boundary matching. Thus, we handle all the possibilities.

    parser->parser_state = STATE_BOUNDARY;
    parser->boundary_match_pos = 2;

    return HTP_OK;
}

htp_mpartp_t *htp_mpartp_create(htp_cfg_t *cfg, bstr *boundary, uint64_t flags) {
    if ((cfg == NULL) || (boundary == NULL)) return NULL;

    htp_mpartp_t *parser = calloc(1, sizeof (htp_mpartp_t));
    if (parser == NULL) return NULL;

    parser->cfg = cfg;

    parser->boundary_pieces = bstr_builder_create();
    if (parser->boundary_pieces == NULL) {
        htp_mpartp_destroy(parser);
        return NULL;
    }

    parser->part_data_pieces = bstr_builder_create();
    if (parser->part_data_pieces == NULL) {
        htp_mpartp_destroy(parser);
        return NULL;
    }

    parser->part_header_pieces = bstr_builder_create();
    if (parser->part_header_pieces == NULL) {
        htp_mpartp_destroy(parser);
        return NULL;
    }

    parser->multipart.parts = htp_list_create(64);
    if (parser->multipart.parts == NULL) {
        htp_mpartp_destroy(parser);
        return NULL;
    }

    parser->multipart.flags = flags;
    parser->parser_state = STATE_INIT;
    parser->extract_files = cfg->extract_request_files;
    parser->extract_dir = cfg->tmpdir;
    if (cfg->extract_request_files_limit >= 0) {
        parser->extract_limit = cfg->extract_request_files_limit;
    } else {
        parser->extract_limit = DEFAULT_FILE_EXTRACT_LIMIT;
    }
    parser->handle_data = htp_mpartp_handle_data;
    parser->handle_boundary = htp_mpartp_handle_boundary;

    // Initialize the boundary.
    htp_status_t rc = htp_mpartp_init_boundary(parser, bstr_ptr(boundary), bstr_len(boundary));
    if (rc != HTP_OK) {
        htp_mpartp_destroy(parser);
        return NULL;
    }

    // On success, the ownership of the boundary parameter
    // is transferred to us. We made a copy, and so we
    // don't need it any more.
    bstr_free(boundary);

    return parser;
}

void htp_mpartp_destroy(htp_mpartp_t *parser) {
    if (parser == NULL) return;

    if (parser->multipart.boundary != NULL) {
        free(parser->multipart.boundary);
    }

    bstr_builder_destroy(parser->boundary_pieces);
    bstr_builder_destroy(parser->part_header_pieces);
    bstr_free(parser->pending_header_line);
    bstr_builder_destroy(parser->part_data_pieces);

    // Free the parts.
    if (parser->multipart.parts != NULL) {
        for (size_t i = 0, n = htp_list_size(parser->multipart.parts); i < n; i++) {
            htp_multipart_part_t * part = htp_list_get(parser->multipart.parts, i);
            htp_mpart_part_destroy(part, parser->gave_up_data);
        }

        htp_list_destroy(parser->multipart.parts);
    }

    free(parser);
}

/**
 * Processes set-aside data.
 *
 * @param[in] mpartp
 * @param[in] data
 * @param[in] pos
 * @param[in] startpos
 * @param[in] return_pos
 * @param[in] matched
 * @return HTP_OK on success, HTP_ERROR on failure.
 */
static htp_status_t htp_martp_process_aside(htp_mpartp_t *parser, int matched) {
    // The stored data pieces can contain up to one line. If we're in data mode and there
    // was no boundary match, things are straightforward -- we process everything as data.
    // If there was a match, we need to take care to not send the line ending as data, nor
    // anything that follows (because it's going to be a part of the boundary). Similarly,
    // when we are in line mode, we need to split the first data chunk, processing the first
    // part as line and the second part as data.

    #ifdef HTP_DEBUG
    fprintf(stderr, "mpartp_process_aside matched %d current_part_mode %d\n", matched, parser->current_part_mode);
    #endif

    // Do we need to do any chunk splitting?
    if (matched || (parser->current_part_mode == MODE_LINE)) {
        // Line mode or boundary match

        // Process the CR byte, if set aside.
        if ((!matched) && (parser->cr_aside)) {
            // Treat as part data, when there is not a match.
            parser->handle_data(parser, (unsigned char *) &"\r", 1, /* not a line */ 0);
            parser->cr_aside = 0;
        } else {
            // Treat as boundary, when there is a match.
            parser->cr_aside = 0;
        }

        // We know that we went to match a boundary because
        // we saw a new line. Now we have to find that line and
        // process it. It's either going to be in the current chunk,
        // or in the first stored chunk.
        if (bstr_builder_size(parser->boundary_pieces) > 0) {
            int first = 1;
            for (size_t i = 0, n = htp_list_size(parser->boundary_pieces->pieces); i < n; i++) {
                bstr *b = htp_list_get(parser->boundary_pieces->pieces, i);

                if (first) {
                    first = 0;

                    // Split the first chunk.

                    if (!matched) {
                        // In line mode, we are OK with line endings.
                        parser->handle_data(parser, bstr_ptr(b), parser->boundary_candidate_pos, /* line */ 1);
                    } else {
                        // But if there was a match, the line ending belongs to the boundary.
                        unsigned char *dx = bstr_ptr(b);
                        size_t lx = parser->boundary_candidate_pos;

                        // Remove LF or CRLF.
                        if ((lx > 0) && (dx[lx - 1] == LF)) {
                            lx--;
                            // Remove CR.
                            if ((lx > 0) && (dx[lx - 1] == CR)) {
                                lx--;
                            }
                        }

                        parser->handle_data(parser, dx, lx, /* not a line */ 0);
                    }

                    // The second part of the split chunks belongs to the boundary
                    // when matched, data otherwise.
                    if (!matched) {
                        parser->handle_data(parser, bstr_ptr(b) + parser->boundary_candidate_pos,
                                bstr_len(b) - parser->boundary_candidate_pos, /* not a line */ 0);
                    }
                } else {
                    // Do not send data if there was a boundary match. The stored
                    // data belongs to the boundary.
                    if (!matched) {
                        parser->handle_data(parser, bstr_ptr(b), bstr_len(b), /* not a line */ 0);
                    }
                }
            }

            bstr_builder_clear(parser->boundary_pieces);
        }
    } else {
        // Data mode and no match.       

        // In data mode, we process the lone CR byte as data.
        if (parser->cr_aside) {
            parser->handle_data(parser, (const unsigned char *)&"\r", 1, /* not a line */ 0);
            parser->cr_aside = 0;
        }

        // We then process any pieces that we might have stored, also as data.
        if (bstr_builder_size(parser->boundary_pieces) > 0) {
            for (size_t i = 0, n = htp_list_size(parser->boundary_pieces->pieces); i < n; i++) {
                bstr *b = htp_list_get(parser->boundary_pieces->pieces, i);
                parser->handle_data(parser, bstr_ptr(b), bstr_len(b), /* not a line */ 0);
            }

            bstr_builder_clear(parser->boundary_pieces);
        }
    }

    return HTP_OK;
}

htp_status_t htp_mpartp_finalize(htp_mpartp_t *parser) {
    if (parser->current_part != NULL) {
        // Process buffered data, if any.
        htp_martp_process_aside(parser, 0);

        // Finalize the last part.
        if (htp_mpart_part_finalize_data(parser->current_part) != HTP_OK) return HTP_ERROR;

        // It is OK to end abruptly in the epilogue part, but not in any other.
        if (parser->current_part->type != MULTIPART_PART_EPILOGUE) {
            parser->multipart.flags |= HTP_MULTIPART_INCOMPLETE;
        }
    }

    bstr_builder_clear(parser->boundary_pieces);

    return HTP_OK;
}

htp_status_t htp_mpartp_parse(htp_mpartp_t *parser, const void *_data, size_t len) {
    unsigned char *data = (unsigned char *) _data;

    // The current position in the entire input buffer.
    size_t pos = 0;

    // The position of the first unprocessed byte of data. We split the
    // input buffer into smaller chunks, according to their purpose. Once
    // an entire such smaller chunk is processed, we move to the next
    // and update startpos.
    size_t startpos = 0;

    // The position of the (possible) boundary. We investigate for possible
    // boundaries whenever we encounter CRLF or just LF. If we don't find a
    // boundary we need to go back, and this is what data_return_pos helps with.
    size_t data_return_pos = 0;

    #if HTP_DEBUG
    fprint_raw_data(stderr, "htp_mpartp_parse: data chunk", data, len);
    #endif

    // While there's data in the input buffer.

    while (pos < len) {

STATE_SWITCH:
        #if HTP_DEBUG        
        fprintf(stderr, "htp_mpartp_parse: state %d pos %zd startpos %zd\n", parser->parser_state, pos, startpos);
        #endif

        switch (parser->parser_state) {

            case STATE_INIT:
                // Incomplete initialization.
                return HTP_ERROR;
                break;

            case STATE_DATA: // Handle part data.

                // While there's data in the input buffer.

                while (pos < len) {
                    // Check for a CRLF-terminated line.
                    if (data[pos] == CR) {
                        // We have a CR byte.

                        // Is this CR the last byte in the input buffer?
                        if (pos + 1 == len) {
                            // We have CR as the last byte in input. We are going to process
                            // what we have in the buffer as data, except for the CR byte,
                            // which we're going to leave for later. If it happens that a
                            // CR is followed by a LF and then a boundary, the CR is going
                            // to be discarded.
                            pos++; // Advance over CR.
                            parser->cr_aside = 1;
                        } else {
                            // We have CR and at least one more byte in the buffer, so we
                            // are able to test for the LF byte too.
                            if (data[pos + 1] == LF) {
                                pos += 2; // Advance over CR and LF.

                                parser->multipart.flags |= HTP_MULTIPART_CRLF_LINE;

                                // Prepare to switch to boundary testing.
                                data_return_pos = pos;
                                parser->boundary_candidate_pos = pos - startpos;
                                parser->boundary_match_pos = 2; // After LF; position of the first dash.
                                parser->parser_state = STATE_BOUNDARY;

                                goto STATE_SWITCH;
                            } else {
                                // This is not a new line; advance over the
                                // byte and clear the CR set-aside flag.
                                pos++;
                                parser->cr_aside = 0;
                            }
                        }
                    } else if (data[pos] == LF) { // Check for a LF-terminated line.
                        pos++; // Advance over LF.

                        // Did we have a CR in the previous input chunk?
                        if (parser->cr_aside == 0) {
                            parser->multipart.flags |= HTP_MULTIPART_LF_LINE;
                        } else {
                            parser->multipart.flags |= HTP_MULTIPART_CRLF_LINE;
                        }

                        // Prepare to switch to boundary testing.
                        data_return_pos = pos;
                        parser->boundary_candidate_pos = pos - startpos;
                        parser->boundary_match_pos = 2; // After LF; position of the first dash.
                        parser->parser_state = STATE_BOUNDARY;

                        goto STATE_SWITCH;
                    } else {
                        // Take one byte from input
                        pos++;

                        // Earlier we might have set aside a CR byte not knowing if the next
                        // byte is a LF. Now we know that it is not, and so we can release the CR.
                        if (parser->cr_aside) {
                            parser->handle_data(parser, (unsigned char *) &"\r", 1, /* not a line */ 0);
                            parser->cr_aside = 0;
                        }
                    }
                } // while               

                // No more data in the input buffer; process the data chunk.
                parser->handle_data(parser, data + startpos, pos - startpos - parser->cr_aside, /* not a line */ 0);

                break;

            case STATE_BOUNDARY: // Handle a possible boundary.
                while (pos < len) {
                    #ifdef HTP_DEBUG
                    fprintf(stderr, "boundary (len %zd pos %zd char %d) data char %d\n", parser->multipart.boundary_len,
                            parser->boundary_match_pos, parser->multipart.boundary[parser->boundary_match_pos], tolower(data[pos]));
                    #endif                   

                    // Check if the bytes match.
                    if (!(data[pos] == parser->multipart.boundary[parser->boundary_match_pos])) {
                        // Boundary mismatch.

                        // Process stored (buffered) data.
                        htp_martp_process_aside(parser, /* no match */ 0);

                        // Return back where data parsing left off.
                        if (parser->current_part_mode == MODE_LINE) {
                            // In line mode, we process the line.
                            parser->handle_data(parser, data + startpos, data_return_pos - startpos, /* line */ 1);
                            startpos = data_return_pos;
                        } else {
                            // In data mode, we go back where we left off.
                            pos = data_return_pos;
                        }

                        parser->parser_state = STATE_DATA;

                        goto STATE_SWITCH;
                    }

                    // Consume one matched boundary byte
                    pos++;
                    parser->boundary_match_pos++;

                    // Have we seen all boundary bytes?
                    if (parser->boundary_match_pos == parser->multipart.boundary_len) {
                        // Boundary match!

                        // Process stored (buffered) data.
                        htp_martp_process_aside(parser, /* boundary match */ 1);

                        // Process data prior to the boundary in the current input buffer.
                        // Because we know this is the last chunk before boundary, we can
                        // remove the line endings.
                        size_t dlen = data_return_pos - startpos;
                        if ((dlen > 0) && (data[startpos + dlen - 1] == LF)) dlen--;
                        if ((dlen > 0) && (data[startpos + dlen - 1] == CR)) dlen--;
                        parser->handle_data(parser, data + startpos, dlen, /* line */ 1);

                        // Keep track of how many boundaries we've seen.
                        parser->multipart.boundary_count++;

                        if (parser->multipart.flags & HTP_MULTIPART_SEEN_LAST_BOUNDARY) {
                            parser->multipart.flags |= HTP_MULTIPART_PART_AFTER_LAST_BOUNDARY;
                        }

                        // Run boundary match.
                        parser->handle_boundary(parser);

                        // We now need to check if this is the last boundary in the payload
                        parser->parser_state = STATE_BOUNDARY_IS_LAST2;

                        goto STATE_SWITCH;
                    }
                } // while

                // No more data in the input buffer; store (buffer) the unprocessed
                // part for later, for after we find out if this is a boundary.
                bstr_builder_append_mem(parser->boundary_pieces, data + startpos, len - startpos);

                break;

            case STATE_BOUNDARY_IS_LAST2:
                // Examine the first byte after the last boundary character. If it is
                // a dash, then we maybe processing the last boundary in the payload. If
                // it is not, move to eat all bytes until the end of the line.

                if (data[pos] == '-') {
                    // Found one dash, now go to check the next position.
                    pos++;
                    parser->parser_state = STATE_BOUNDARY_IS_LAST1;
                } else {
                    // This is not the last boundary. Change state but
                    // do not advance the position, allowing the next
                    // state to process the byte.
                    parser->parser_state = STATE_BOUNDARY_EAT_LWS;
                }
                break;

            case STATE_BOUNDARY_IS_LAST1:
                // Examine the byte after the first dash; expected to be another dash.
                // If not, eat all bytes until the end of the line.

                if (data[pos] == '-') {
                    // This is indeed the last boundary in the payload.
                    pos++;
                    parser->multipart.flags |= HTP_MULTIPART_SEEN_LAST_BOUNDARY;
                    parser->parser_state = STATE_BOUNDARY_EAT_LWS;
                } else {
                    // The second character is not a dash, and so this is not
                    // the final boundary. Raise the flag for the first dash,
                    // and change state to consume the rest of the boundary line.
                    parser->multipart.flags |= HTP_MULTIPART_BBOUNDARY_NLWS_AFTER;
                    parser->parser_state = STATE_BOUNDARY_EAT_LWS;
                }
                break;

            case STATE_BOUNDARY_EAT_LWS:
                if (data[pos] == CR) {
                    // CR byte, which could indicate a CRLF line ending.
                    pos++;
                    parser->parser_state = STATE_BOUNDARY_EAT_LWS_CR;
                } else if (data[pos] == LF) {
                    // LF line ending; we're done with boundary processing; data bytes follow.
                    pos++;
                    startpos = pos;
                    parser->multipart.flags |= HTP_MULTIPART_LF_LINE;
                    parser->parser_state = STATE_DATA;
                } else {
                    if (htp_is_lws(data[pos])) {
                        // Linear white space is allowed here.
                        parser->multipart.flags |= HTP_MULTIPART_BBOUNDARY_LWS_AFTER;
                        pos++;
                    } else {
                        // Unexpected byte; consume, but remain in the same state.
                        parser->multipart.flags |= HTP_MULTIPART_BBOUNDARY_NLWS_AFTER;
                        pos++;
                    }
                }
                break;

            case STATE_BOUNDARY_EAT_LWS_CR:
                if (data[pos] == LF) {
                    // CRLF line ending; we're done with boundary processing; data bytes follow.
                    pos++;
                    startpos = pos;
                    parser->multipart.flags |= HTP_MULTIPART_CRLF_LINE;
                    parser->parser_state = STATE_DATA;
                } else {
                    // Not a line ending; start again, but do not process this byte.
                    parser->multipart.flags |= HTP_MULTIPART_BBOUNDARY_NLWS_AFTER;
                    parser->parser_state = STATE_BOUNDARY_EAT_LWS;
                }
                break;
        } // switch
    }

    return HTP_OK;
}

static void htp_mpartp_validate_boundary(bstr *boundary, uint64_t *flags) {
    /*

    RFC 1341:

    The only mandatory parameter for the multipart  Content-Type
    is  the  boundary  parameter,  which  consists  of  1  to 70
    characters from a set of characters known to be very  robust
    through  email  gateways,  and  NOT ending with white space.
    (If a boundary appears to end with white  space,  the  white
    space  must be presumed to have been added by a gateway, and
    should  be  deleted.)   It  is  formally  specified  by  the
    following BNF:

    boundary := 0*69<bchars> bcharsnospace

    bchars := bcharsnospace / " "

    bcharsnospace :=    DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_"
                          / "," / "-" / "." / "/" / ":" / "=" / "?"
     */

    /*
     Chrome: Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryT4AfwQCOgIxNVwlD
    Firefox: Content-Type: multipart/form-data; boundary=---------------------------21071316483088
       MSIE: Content-Type: multipart/form-data; boundary=---------------------------7dd13e11c0452
      Opera: Content-Type: multipart/form-data; boundary=----------2JL5oh7QWEDwyBllIRc7fh
     Safari: Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryre6zL3b0BelnTY5S
     */

    unsigned char *data = bstr_ptr(boundary);
    size_t len = bstr_len(boundary);

    // The RFC allows up to 70 characters. In real life,
    // boundaries tend to be shorter.
    if ((len == 0) || (len > 70)) {
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
    }

    // Check boundary characters. This check is stricter than the
    // RFC, which seems to allow many separator characters.
    size_t pos = 0;
    while (pos < len) {
        if (!(((data[pos] >= '0') && (data[pos] <= '9'))
                || ((data[pos] >= 'a') && (data[pos] <= 'z'))
                || ((data[pos] >= 'A') && (data[pos] <= 'Z'))
                || (data[pos] == '-'))) {

            switch (data[pos]) {
                case '\'':
                case '(':
                case ')':
                case '+':
                case '_':
                case ',':
                case '.':
                case '/':
                case ':':
                case '=':
                case '?':
                    // These characters are allowed by the RFC, but not common.
                    *flags |= HTP_MULTIPART_HBOUNDARY_UNUSUAL;
                    break;
                    
                default:
                    // Invalid character.
                    *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
                    break;
            }
        }

        pos++;
    }
}

static void htp_mpartp_validate_content_type(bstr *content_type, uint64_t *flags) {
    unsigned char *data = bstr_ptr(content_type);
    size_t len = bstr_len(content_type);
    size_t counter = 0;

    while (len > 0) {
        int i = bstr_util_mem_index_of_c_nocase(data, len, "boundary");
        if (i == -1) break;

        data = data + i;
        len = len - i;

        // In order to work around the fact that WebKit actually uses
        // the word "boundary" in their boundary, we also require one
        // equals character the follow the words.
        // "multipart/form-data; boundary=----WebKitFormBoundaryT4AfwQCOgIxNVwlD"
        if (memchr(data, '=', len) == NULL) break;

        counter++;

        // Check for case variations.        
        for (size_t j = 0; j < 8; j++) {
            if (!((*data >= 'a') && (*data <= 'z'))) {
                *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
            }

            data++;
            len--;
        }
    }

    // How many boundaries have we seen?
    if (counter > 1) {
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
    }
}

htp_status_t htp_mpartp_find_boundary(bstr *content_type, bstr **boundary, uint64_t *flags) {
    if ((content_type == NULL) || (boundary == NULL) || (flags == NULL)) return HTP_ERROR;

    // Our approach is to ignore the MIME type and instead just look for
    // the boundary. This approach is more reliable in the face of various
    // evasion techniques that focus on submitting invalid MIME types.

    // Reset flags.
    *flags = 0;

    // Look for the boundary, case insensitive.
    int i = bstr_index_of_c_nocase(content_type, "boundary");
    if (i == -1) return HTP_DECLINED;

    unsigned char *data = bstr_ptr(content_type) + i + 8;
    size_t len = bstr_len(content_type) - i - 8;

    // Look for the boundary value.
    size_t pos = 0;
    while ((pos < len) && (data[pos] != '=')) {
        if (htp_is_space(data[pos])) {
            // It is unusual to see whitespace before the equals sign.
            *flags |= HTP_MULTIPART_HBOUNDARY_UNUSUAL;
        } else {
            // But seeing a non-whitespace character may indicate evasion.
            *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
        }

        pos++;
    }

    if (pos >= len) {
        // No equals sign in the header.
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
        return HTP_DECLINED;
    }

    // Go over the '=' character.
    pos++;

    // Ignore any whitespace after the equals sign.
    while ((pos < len) && (htp_is_space(data[pos]))) {
        if (htp_is_space(data[pos])) {
            // It is unusual to see whitespace after
            // the equals sign.
            *flags |= HTP_MULTIPART_HBOUNDARY_UNUSUAL;
        }

        pos++;
    }

    if (pos >= len) {
        // No value after the equals sign.
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
        return HTP_DECLINED;
    }

    if (data[pos] == '"') {
        // Quoted boundary.

        // Possibly not very unusual, but let's see.
        *flags |= HTP_MULTIPART_HBOUNDARY_UNUSUAL;

        pos++; // Over the double quote.
        size_t startpos = pos; // Starting position of the boundary.

        // Look for the terminating double quote.
        while ((pos < len) && (data[pos] != '"')) pos++;

        if (pos >= len) {
            // Ran out of space without seeing
            // the terminating double quote.
            *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;

            // Include the starting double quote in the boundary.
            startpos--;
        }

        *boundary = bstr_dup_mem(data + startpos, pos - startpos);
        if (*boundary == NULL) return HTP_ERROR;

        pos++; // Over the double quote.
    } else {
        // Boundary not quoted.

        size_t startpos = pos;

        // Find the end of the boundary. For the time being, we replicate
        // the behavior of PHP 5.4.x. This may result with a boundary that's
        // closer to what would be accepted in real life. Our subsequent
        // checks of boundary characters will catch irregularities.
        while ((pos < len) && (data[pos] != ',') && (data[pos] != ';') && (!htp_is_space(data[pos]))) pos++;

        *boundary = bstr_dup_mem(data + startpos, pos - startpos);
        if (*boundary == NULL) return HTP_ERROR;
    }

    // Check for a zero-length boundary.
    if (bstr_len(*boundary) == 0) {
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
        bstr_free(*boundary);
        *boundary = NULL;
        return HTP_DECLINED;
    }

    // Allow only whitespace characters after the boundary.
    int seen_space = 0, seen_non_space = 0;

    while (pos < len) {
        if (!htp_is_space(data[pos])) {
            seen_non_space = 1;
        } else {
            seen_space = 1;
        }

        pos++;
    }

    // Raise INVALID if we see any non-space characters,
    // but raise UNUSUAL if we see _only_ space characters.
    if (seen_non_space) {
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
    } else if (seen_space) {
        *flags |= HTP_MULTIPART_HBOUNDARY_UNUSUAL;
    }

    #ifdef HTP_DEBUG
    fprint_bstr(stderr, "Multipart boundary", *boundary);
    #endif   

    // Validate boundary characters.
    htp_mpartp_validate_boundary(*boundary, flags);

    // Correlate with the MIME type. This might be a tad too
    // sensitive because it may catch non-browser access with sloppy
    // implementations, but let's go with it for now.    
    if (bstr_begins_with_c(content_type, "multipart/form-data;") == 0) {
        *flags |= HTP_MULTIPART_HBOUNDARY_INVALID;
    }

    htp_mpartp_validate_content_type(content_type, flags);

    return HTP_OK;
}