aboutsummaryrefslogtreecommitdiff
path: root/picohttp.c
blob: 3bc918a5fcaa3103ba97e4a4bc62998585fee2f3 (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
/*
    picoweb / litheweb -- a web server and application framework
                          for resource constraint systems.

    Copyright (C) 2012 - 2014 Wolfgang Draxinger

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "picohttp.h"
#include "picohttp_debug.h"

#include <alloca.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

#include "picohttp_base64.h"

static char const PICOHTTP_STR_CRLF[] = "\r\n";
static char const PICOHTTP_STR_CLSP[] = ": ";
static char const PICOHTTP_STR_HTTP_[] = "HTTP/";
static char const PICOHTTP_STR_HOST[] = "Host";
static char const PICOHTTP_STR_SERVER[] = "Server";
static char const PICOHTTP_STR_PICOWEB[] = "picoweb/0.1";

static char const PICOHTTP_STR_ACCEPT[]    = "Accept";
static char const PICOHTTP_STR_TRANSFER[]  = "Transfer";

static char const PICOHTTP_STR__ENCODING[] = "-Encoding";

static char const PICOHTTP_STR_CONTENT[] = "Content";
static char const PICOHTTP_STR__TYPE[]   = "-Type";
static char const PICOHTTP_STR__LENGTH[] = "-Length";
static char const PICOHTTP_STR__CODING[] = "-Coding";
static char const PICOHTTP_STR__DISPOSITION[] = "-Disposition";

static char const PICOHTTP_STR_APPLICATION_[] = "application/";
static char const PICOHTTP_STR_TEXT_[] = "text/";
static char const PICOHTTP_STR_MULTIPART_[] = "multipart/";

static char const PICOHTTP_STR_FORMDATA[] = "form-data";

static char const PICOHTTP_STR_CACHECONTROL[] = "Cache-Control";

static char const PICOHTTP_STR_CONNECTION[] = "Connection";
static char const PICOHTTP_STR_CLOSE[] = "close";

static char const PICOHTTP_STR_DATE[] = "Date";
static char const PICOHTTP_STR_EXPECT[] = "Expect";

static char const PICOHTTP_STR_BOUNDARY[] = " boundary=";
static char const PICOHTTP_STR_NAME__[] = " name=\"";

static char const PICOHTTP_STR_CHUNKED[] = "chunked";

static char const PICOHTTP_STR_WWW_AUTHENTICATE[] = "WWW-Authenticate";
static char const PICOHTTP_STR_AUTHORIZATION[] = "Authorization";
static char const PICOHTTP_STR_BASIC_[] = "Basic ";
static char const PICOHTTP_STR_DIGEST_[] = "Digest ";
static char const PICOHTTP_STR_REALM__[] = "realm=\"";
static char const PICOHTTP_STR_USERNAME__[] = "username=\"";
static char const PICOHTTP_STR_QOP_[] = "qop=";
static char const PICOHTTP_STR_NC_[] = "nc=";

/* compilation unit local function forward declarations */
static int picohttpProcessHeaders (
	struct picohttpRequest * const req,
	size_t const hvbuflen,
	char * const headervalue,
	picohttpHeaderFieldCallback headerfieldcallback,
	void * const data,
	int ch );

/* compilation unit local helper functions */
#if !defined(PICOHTTP_CONFIG_HAVE_LIBDJB)
/* Number formating functions modified from libdjb by
 * Daniel J. Bernstein, packaged at http://www.fefe.de/djb/
 */
static size_t picohttp_fmt_uint(char *dest, unsigned int i)
{
	register unsigned int len, tmp, len2;
	/* first count the number of bytes needed */
	for(len = 1, tmp = i;
	    tmp > 9;
	    ++len )
		tmp/=10;

	if( dest )
		for(tmp = i, dest += len, len2 = len+1;
		    --len2;
		    tmp /= 10 )
			*--dest = ( tmp % 10 ) + '0';
	return len;
}

#if 0
static size_t picohttp_fmt_int(char *dest,int i) {
	if( i < 0 ) {
		if( dest )
			*dest++='-';
		return picohttp_fmt_uint(dest, -i) + 1;
	}
	return picohttp_fmt_uint(dest, i);
}
#endif

#else
#include <djb/byte/fmt.h>
#define picohttp_fmt_uint fmt_ulong
#define picohttp_fmt_int fmt_long
#endif

static char const *picohttpStatusString(int code)
{
	switch(code) {
	case 200:
		return "OK";
	case 400:
		return "Bad Request";
	case 401:
		return "Unauthorized";
	case 403:
		return "Forbidden";
	case 404:
		return "Not Found";
	case 414:
		return "Request URI Too Long";
	case 422:
		return "Unprocessable Entity";
	case 500:
		return "Internal Server Error";
	case 501:
		return "Not Implemented";
	case 505:
		return "HTTP Version Not Supported";
	}
	return "...";
}

void picohttpStatusResponse(
	struct picohttpRequest *req, int status )
{
	req->status = status;
	char const * const c = picohttpStatusString(req->status);
	picohttpResponseWrite(req, strlen(c), c);
}

void picohttpAuthRequired(
	struct picohttpRequest *req,
	char const * const realm )
{
	/* FIXME: Fits only for Basic Auth!
	 *        Adjust this for Digest Auth header */
	size_t const www_authenticate_maxlen = 1 + /* terminating 0 */
		sizeof(PICOHTTP_STR_BASIC_)-1 +
		sizeof(PICOHTTP_STR_REALM__)-1 +
		strlen(realm) +
		1; /* closing '"' */
#ifdef PICOWEB_CONFIG_USE_C99VARARRAY	
	char www_authenticate[www_authenticate_maxlen+1];
#else
	char *www_authenticate = alloca(www_authenticate_maxlen+1);
#endif
	memset(www_authenticate, 0, www_authenticate_maxlen);

	char *c = www_authenticate;
	memcpy(c, PICOHTTP_STR_BASIC_, sizeof(PICOHTTP_STR_BASIC_)-1);
	c += sizeof(PICOHTTP_STR_BASIC_)-1;
	memcpy(c, PICOHTTP_STR_REALM__, sizeof(PICOHTTP_STR_REALM__)-1);
	c += sizeof(PICOHTTP_STR_REALM__)-1;
	for(size_t i=0; realm[i]; i++) {
		*c++ = realm[i];
	}
	*c = '"';

	req->response.www_authenticate = www_authenticate;

	picohttpStatusResponse(req, PICOHTTP_STATUS_401_UNAUTHORIZED);
}

static inline bool picohttpIsCRLF(int ch)
{
	return '\r' == ch
	    || '\n' == ch;
}

static inline bool picohttpIsLWS(int ch)
{
	return picohttpIsCRLF(ch)
	    || ' '  == ch
	    || '\t' == ch;
}

static int picohttpIoSkipSpace (
	struct picohttpIoOps const * const ioops,
	int ch)
{
	for(;;ch = -1) {
		if( 0 > ch ) {
			ch = picohttpIoGetch(ioops);
		}

		if( 0 > ch
		 || ( ' ' != ch && '\t' != ch ) )
			break;
	}
	return ch;
}

static int picohttpIoSkipOverCRLF (
	struct picohttpIoOps const * const ioops,
	int ch)
{
	for(;;ch = -1) {
		if(0 > ch) {
			ch = picohttpIoGetch(ioops);
		}

		if( 0 > ch ) {
			return -1;
		}

		if( '\n' == ch ) {
			break;
		}
		if( '\r' == ch ) {
			ch = picohttpIoGetch(ioops);
			if( 0 > ch ) {
				return -1;
			}
			if( '\n' != ch ) {
				return 0;
			}
			break;
		}
	}
	ch = picohttpIoGetch(ioops);
	return ch;
}

static int picohttpIoB10ToU8 (
	uint8_t *i,
	struct picohttpIoOps const * const ioops,
	int ch )
{
	if( 0 > ch )
		ch = picohttpIoGetch(ioops);

	while( '0' <= ch && '9' >= ch ) {
		*i *= 10;
		*i += (ch & 0x0f);
		ch = picohttpIoGetch(ioops);
	}

	return ch;
}

static int picohttpIoB10ToU64 (
	uint64_t *i,
	struct picohttpIoOps const * const ioops,
	int ch )
{
	if( 0 > ch )
		ch = picohttpIoGetch(ioops);

	while( '0' <= ch && '9' >= ch ) {
		*i *= 10;
		*i += (ch & 0x0f);
		ch = picohttpIoGetch(ioops);
	}

	return ch;
}

static int picohttpIoGetPercentCh(
	struct picohttpIoOps const * const ioops )
{
	char ch=0;
	int chr;
	if( 0 > (chr = picohttpIoGetch(ioops)))
		return chr;

	chr |= 0x20;
	if( '0' <= chr && '9' >= chr ) {
		ch = ((chr)&0x0f)<<4;
	} else
	if( 'a' <= chr && 'f' >= chr ) {
		ch = (((chr)&0x0f) + 9)<<4;
	}

	if( 0 > (chr = picohttpIoGetch(ioops)))
		return chr;

	chr |= 0x20;
	if( '0' <= chr && '9' >= chr ) {
		ch |= ((chr)&0x0f);
	} else
	if( 'a' <= chr && 'f' >= chr ) {
		ch |= (((chr)&0x0f) + 9);
	}

	return ch;
}

int picohttpGetch(struct picohttpRequest * const req)
{
	int ch;
	/* skipping over Chunked Transfer Boundaries
	 * if Chunked Transfer Encoding is used */
	if(req->query.transferencoding == PICOHTTP_CODING_CHUNKED ) {
		if( !req->query.chunklength ) {
			/* this is a new chunk;
			 * read the length and skip to after <CR><LF> */
			if( 0 > (ch = picohttpIoGetch(req->ioops)) ) {
				return -1;
			}
			uint64_t len;
			if( 0 > (ch = picohttpIoB10ToU64(
					&len,
					req->ioops,
					ch))
			) {
				return ch;
			}
			if( 0 > (ch = picohttpIoSkipOverCRLF(req->ioops, ch)) ) {
				return ch;
			}
			req->query.chunklength = len;
			return ch;
		}

		if( req->query.chunklength <= req->received_octets ) {
			/* If this happens the data is corrupted, or
			 * the client is nonconforming, or an attack is
			 * underway, or something entierely different,
			 * or all of that.
			 * Abort processing the query!
			 */
			return -1;
		}
	}

	if( 0 <= (ch = picohttpIoGetch(req->ioops)) ) {
		req->received_octets++;
	} else {
		return ch;
	}

	if(req->query.transferencoding == PICOHTTP_CODING_CHUNKED ) {
		if( !req->query.chunklength <= req->received_octets ) {
			/* end of chunk;
			 * skip over <CR><LF>, make sure the trailing '0' is
			 * there and read the headers, err, I mean footers
			 * (whatever, the header processing code will do for 
			 * chunk footers just fine).
			 */
			if( '0' != (ch = picohttpIoGetch(req->ioops)) ) {
				return -1;
			}
			if( 0 > (ch = picohttpIoGetch(req->ioops)) ) {
				return -1;
			}
			if( 0 > (ch = picohttpProcessHeaders(
					req,
					0, NULL,
					NULL, NULL,
					ch))
			) {
				return ch;
			}
			
			req->received_octets =
			req->query.chunklength = 0;
		}
	}

	return ch;
}

int picohttpRead(struct picohttpRequest * const req, size_t len, char * const buf)
{
	/* skipping over Chunked Transfer Boundaries
	 * if Chunked Transfer Encoding is used */
	if(req->query.transferencoding == PICOHTTP_CODING_CHUNKED ) {
		if( !req->query.chunklength ) {
			int ch;
			/* this is a new chunk;
			 * read the length and skip to after <CR><LF> */
			if( 0 > (ch = picohttpIoGetch(req->ioops)) ) {
				return -1;
			}
			uint64_t len;
			if( 0 > (ch = picohttpIoB10ToU64(
					&len,
					req->ioops,
					ch))
			) {
				return ch;
			}
			if( 0 > (ch = picohttpIoSkipOverCRLF(req->ioops, ch)) ) {
				return ch;
			}
			req->query.chunklength = len;
			return ch;
		}

		if( req->query.chunklength <= req->received_octets ) {
			/* If this happens the data is corrupted, or
			 * the client is nonconforming, or an attack is
			 * underway, or something entierely different,
			 * or all of that.
			 * Abort processing the query!
			 */
			return -1;
		}
	}

	if( req->received_octets + len > req->query.chunklength ) {
		len = req->query.chunklength - req->received_octets;
	}

	int r = picohttpIoRead(req->ioops, len, buf);

	if(req->query.transferencoding == PICOHTTP_CODING_CHUNKED ) {
		if( !req->query.chunklength <= req->received_octets ) {
			int ch;
			/* end of chunk;
			 * skip over <CR><LF>, make sure the trailing '0' is
			 * there and read the headers, err, I mean footers
			 * (whatever, the header processing code will do for 
			 * chunk footers just fine).
			 */
			if( '0' != (ch = picohttpIoGetch(req->ioops)) ) {
				return -1;
			}
			if( 0 > (ch = picohttpIoGetch(req->ioops)) ) {
				return -1;
			}
			if( 0 > (ch = picohttpProcessHeaders(
					req,
					0, NULL,
					NULL, NULL,
					ch))
			) {
				return ch;
			}
			
			req->received_octets =
			req->query.chunklength = 0;
		}
	}

	return r;
}

/* TODO:
 * It is possible to do in-place pattern matching on the route definition
 * array, without first reading in the URL and then processing it here.
 *
 * Implement this to improve memory footprint reduction.
 */
static size_t picohttpMatchURL(
	char const * const urlhead,
	char const * const url )
{
	size_t len_urlhead = strlen(urlhead);
	size_t j;
	for(j = 0; j < len_urlhead; j++) {
		if( '|' == urlhead[j] ) {
			/* hard URL termination */
			if( url[j] ) {
				return 0;
			}
			break;
		}

		if( '\\' == urlhead[j] ) {
			/* soft URL termination, i.e. URL may be terminated
			 * by an optional '/' character */
			if( url[j] && !( url[j] == '/' && !url[j+1] ) ) {
				return 0;
			}
			break;
		}

		if( urlhead[j] != url[j] ) {
			return 0;
		}
	}
	if( url[j] && url[j] != '/' ) {
		return 0;
	}
	return j;
}

static int picohttpMatchRoute(
	struct picohttpRequest * const req,
	struct picohttpURLRoute const * const routes )
{
	struct picohttpURLRoute const *r;
	for(size_t i = 0; (r = routes + i)->urlhead; i++) {
		size_t l;
		if( (l = picohttpMatchURL(r->urlhead, req->url)) && 
		    req->method & r->allowed_methods ) {
			req->route = r;
			req->urltail = req->url[l] ? req->url+l : 0;
			return 1;
		}
	}	
	return 0;
}

static int picohttpProcessRequestMethod (
	struct picohttpIoOps const * const ioops )
{
	int method = 0;

	/* Poor man's string matching tree; trade RAM for code */
	switch( picohttpIoGetch(ioops) ) {
	case 'H': switch( picohttpIoGetch(ioops) ) {
		case 'E': switch( picohttpIoGetch(ioops) ) {
			case 'A': switch( picohttpIoGetch(ioops) ) {
				case 'D':
					method = PICOHTTP_METHOD_HEAD;
					break;
				case -1:
					method = -1;
					break;
				} break;
			case -1:
				method = -1;
				break;
			} break;
		case -1:
			method = -1;
			break;
		} break;
	case 'G': switch( picohttpIoGetch(ioops) ) {
		case 'E': switch( picohttpIoGetch(ioops) ) {
			case 'T':
				method = PICOHTTP_METHOD_GET;
				break;
			case -1:
				method = -1;
				break;
			} break;
		case -1:
			method = -1;
			break;
		} break;
	case 'P': switch( picohttpIoGetch(ioops) ) {
		case 'O': switch( picohttpIoGetch(ioops) ) {
			case 'S': switch( picohttpIoGetch(ioops) ) {
				case 'T':
					method = PICOHTTP_METHOD_POST;
					break;
				case -1:
					method = -1;
					break;
				} break;
			case -1:
				method = -1;
				break;
			} break;
		case -1:
			method = -1;
			break;
		} break;
	case -1:
		method = -1;
		break;
	}
	return method;
}

static int picohttpProcessURL (
	struct picohttpRequest * const req,
	size_t const url_max_length,
	int ch )
{
	/* copy url up to the first query component; note that this is not
	 * fully compliant to RFC 3986, which permits query components in each
	 * path component (i.e. between '/'-s).
	 * picohttp terminates the path once it encounters the first query 
	 * component.
	 */
	/* Deliberately discarding const qualifier! */
	for(char *urliter = req->url ;; urliter++) {
		if( 0 > ch ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}
		if( '?' == ch ||
		    picohttpIsLWS(ch) ) {
			break;
		}
		if( '%' == ch ) {
			ch = picohttpIoGetPercentCh(req->ioops);
			if( ch < 0 ) {
				return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
			}
		}
		if( !ch ) {
			return -PICOHTTP_STATUS_400_BAD_REQUEST;
		}

		if( (size_t)(urliter - req->url) >= url_max_length ) {
			return -PICOHTTP_STATUS_414_REQUEST_URI_TOO_LONG;
		}
		*urliter = ch;
		ch = picohttpIoGetch(req->ioops);
	}
	return ch;
}

static int picohttpProcessQuery (
	struct picohttpRequest * const req,
	int ch )
{
	size_t var_max_length = 0;
	if(req->route->get_vars) {
		for(size_t j = 0; req->route->get_vars[j].name; j++) {
			size_t var_length = strlen(
				req->route->get_vars[j].name );
			if( var_length > var_max_length ) {
				var_max_length = var_length;
			}
		}
	}
#ifdef PICOWEB_CONFIG_USE_C99VARARRAY
	char var[var_max_length+1];
#else
	char *var = alloca(var_max_length+1);
#endif

	while('?' == ch || '&' == ch) {
		memset(var, 0, var_max_length+1);
		ch = picohttpIoGetch(req->ioops);

		if( 0 > ch ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}
		if( '&' == ch )
			continue;


		for(char *variter = var ;; variter++) {
			if( 0 > ch) {
				return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
			}
			if( '='  == ch ||
			    '#'  == ch ||
			    '&'  == ch ||
			    picohttpIsLWS(ch) ) {
				break;
			}
			if( '%' == ch ) {
				ch = picohttpIoGetPercentCh(req->ioops);
				if( ch < 0 ) {
					return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
				}
			}
			if( !ch ) {
				return -PICOHTTP_STATUS_400_BAD_REQUEST;
			}

			if( (size_t)(variter - var) >= var_max_length ) {
/* variable name in request longer than longest
 * variable name accepted by route --> skip to next variable */
				do {
					ch = picohttpIoGetch(req->ioops);
					if( ch < 0 ) {
						return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
					}
				} while(!( '&' == ch ||
				           picohttpIsLWS(ch) ));
				continue;
			}
			*variter = ch;

			ch = picohttpIoGetch(req->ioops);
		}
		if( '=' == ch ) {
			debug_printf("set variable '%s'\r\n", var);
		} else {
		}
	}
	if( 0 > (ch = picohttpIoSkipSpace(req->ioops, ch)) ) {
		return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
	}

	return ch;
}

static int picohttpProcessHTTPVersion (
	struct picohttpRequest * const req,
	int ch )
{

	if( !picohttpIsCRLF(ch) ) {
		for(uint8_t i = 0; i < 5; i++) {
			if(PICOHTTP_STR_HTTP_[i] != (char)ch ) {
				if( 0 > ch ) {
					return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
				}
				return -PICOHTTP_STATUS_400_BAD_REQUEST;
			}
			ch = picohttpIoGetch(req->ioops);
		}

		req->httpversion.major = 0;
		req->httpversion.minor = 0;
		ch = picohttpIoB10ToU8(
			&req->httpversion.major,
			req->ioops,
			ch );
		if( 0 > ch ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}
		if( '.' != ch ) {
			return -PICOHTTP_STATUS_400_BAD_REQUEST;
		}
		ch = picohttpIoB10ToU8(
			&req->httpversion.minor,
			req->ioops,
			-1 );
		if( 0 > ch ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}

		ch = picohttpIoSkipSpace(req->ioops, ch);
		if( 0 > ch ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}
	}
	ch = picohttpIoSkipOverCRLF(req->ioops, ch);
	if( 0 > ch ) {
		return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
	}
	if( !ch ) {
		return -PICOHTTP_STATUS_400_BAD_REQUEST;
	}

	return ch;
}

static int picohttpProcessContentType(
	char const **contenttype)
{
	int ct = 0;
	if(!strncmp(*contenttype,
	            PICOHTTP_STR_APPLICATION_, sizeof(PICOHTTP_STR_APPLICATION_)-1)) {
		ct = PICOHTTP_CONTENTTYPE_APPLICATION;
	}

	if(!strncmp(*contenttype,
	            PICOHTTP_STR_TEXT_, sizeof(PICOHTTP_STR_TEXT_)-1)) {
		ct = PICOHTTP_CONTENTTYPE_TEXT;
	}

	if(!strncmp(*contenttype, PICOHTTP_STR_MULTIPART_,
	            sizeof(PICOHTTP_STR_MULTIPART_)-1)) {
		ct = PICOHTTP_CONTENTTYPE_MULTIPART;
		*contenttype += sizeof(PICOHTTP_STR_MULTIPART_)-1;

		if(!strncmp(*contenttype,PICOHTTP_STR_FORMDATA,
		            sizeof(PICOHTTP_STR_FORMDATA)-1)) {
			*contenttype += sizeof(PICOHTTP_STR_FORMDATA)-1;

			ct = PICOHTTP_CONTENTTYPE_MULTIPART_FORMDATA;
		}
	}

	return ct;
}

static void picohttpProcessHeaderContentType(
	struct picohttpRequest * const req,
	char const *contenttype )
{
	req->query.contenttype = picohttpProcessContentType(&contenttype);

	if( PICOHTTP_CONTENTTYPE_MULTIPART == (req->query.contenttype & 0xf000) ) {
		char *boundary = strstr(contenttype, PICOHTTP_STR_BOUNDARY);
		if(boundary) {
			/* see RFC1521 regarding maximum length of boundary */
			memset(req->query.multipartboundary, 0,
			       PICOHTTP_MULTIPARTBOUNDARY_MAX_LEN+1);
			memcpy(req->query.multipartboundary, "\r\n--", 4);
			strncpy(req->query.multipartboundary+4,
			        boundary + sizeof(PICOHTTP_STR_BOUNDARY)-1,
				PICOHTTP_MULTIPARTBOUNDARY_MAX_LEN);
		}
	}
}

static void picohttpProcessHeaderAuthorization(
	struct picohttpRequest * const req,
	char const *authorization )
{
	if(!strncmp(authorization,
	            PICOHTTP_STR_BASIC_,
		    sizeof(PICOHTTP_STR_BASIC_)-1)) {
		authorization += sizeof(PICOHTTP_STR_BASIC_)-1;
		/* HTTP RFC-2617 Basic Auth */

		if( !req->query.auth
		 || !req->query.auth->username 
		 || !req->query.auth->pwresponse ) {
			return;
		}
		size_t user_password_max_len = 
			req->query.auth->username_maxlen +
			req->query.auth->pwresponse_maxlen;

#ifdef PICOWEB_CONFIG_USE_C99VARARRAY
			
		char user_password[user_password_max_len+1];
#else
		char *user_password = alloca(user_password_max_len+1);
#endif
		char const *a = authorization;
		size_t i = 0;
		while(*a && i < user_password_max_len) {
			phb64enc_t e = {0,0,0,0};
			for(size_t j=0; *a && j < 4; j++) {
				e[j] = *a++;
			}
			phb64raw_t r;
			size_t l = phb64decode(e, r);
			if( !l ) {
				/* invalid chunk => abort the whole header */
				return;
			}
			for(size_t j=0;
			       j < l
			    && i < user_password_max_len;
			    j++, i++) {
				user_password[i] = r[j];
			}
		}
		user_password[i] = 0;

		debug_printf(
			"[picohttp] user_password='%s'\r\n",
			user_password);

		char *c;
		for(c = user_password; *c && ':' != *c; c++);
		if( !*c 
		 || ((size_t)(c - user_password) >= user_password_max_len)
		 || ((size_t)(c - user_password) > req->query.auth->username_maxlen)
		 || (strlen(c+1) > req->query.auth->pwresponse_maxlen) ) {
			/* no colon found, or colon is last character in string
			 * or username part doesn't fit into auth.username field
			 */
			return;
		}
		memset(req->query.auth->username, 0,
		       req->query.auth->username_maxlen);
		memset(req->query.auth->pwresponse, 0,
		       req->query.auth->pwresponse_maxlen);

		memcpy( req->query.auth->username, 
		        user_password,
			c - user_password );
		if(*(++c)) {
			strncpy(req->query.auth->pwresponse,
				c,
				req->query.auth->pwresponse_maxlen);
		}
		debug_printf(
			"[picohttp] Basic Auth: username='%s', password='%s'\r\n",
			req->query.auth->username,
			req->query.auth->pwresponse);
		return;
	}

	if(!strncmp(authorization,
	            PICOHTTP_STR_DIGEST_,
		    sizeof(PICOHTTP_STR_DIGEST_)-1)) {
		return;
	}
}

static void picohttpProcessHeaderField(
	void * const data,
	char const *headername,
	char const *headervalue)
{
	struct picohttpRequest * const req = data;
	debug_printf("[picohttp] %s: %s\r\n", headername, headervalue);
	if(!strncmp(headername,
		    PICOHTTP_STR_CONTENT,
		    sizeof(PICOHTTP_STR_CONTENT)-1)) {
		headername += sizeof(PICOHTTP_STR_CONTENT)-1;
		/* Content Length */
		if(!strncmp(headername,
			    PICOHTTP_STR__LENGTH, sizeof(PICOHTTP_STR__LENGTH)-1)) {
			req->query.contentlength = atol(headervalue);
			return;
		}

		/* Content Type */
		if(!strncmp(headername,
			    PICOHTTP_STR__TYPE, sizeof(PICOHTTP_STR__TYPE)-1)) {
			picohttpProcessHeaderContentType(req, headervalue);
			return;
		}
		return;
	}

	if(!strncmp(headername,
	            PICOHTTP_STR_TRANSFER,
		    sizeof(PICOHTTP_STR_TRANSFER)-1)) {
		headername += sizeof(PICOHTTP_STR_TRANSFER)-1;
		/* Transfer Encoding */
		if(!strncmp(headername,
			    PICOHTTP_STR__ENCODING, sizeof(PICOHTTP_STR__ENCODING)-1)) {
			if(!strncmp(headervalue,
			            PICOHTTP_STR_CHUNKED,
			            sizeof(PICOHTTP_STR_CHUNKED)-1)) {
				req->query.transferencoding = PICOHTTP_CODING_CHUNKED;
				req->query.chunklength = 0;
			}
			return;
		}
		return;
	}

	if(!strncmp(headername,
	            PICOHTTP_STR_AUTHORIZATION,
		    sizeof(PICOHTTP_STR_AUTHORIZATION)-1)) {
		picohttpProcessHeaderAuthorization(req, headervalue);
		return;
	}
}

static int picohttpProcessHeaders (
	struct picohttpRequest * const req,
	size_t const headervalue_maxlen,
	char * const headervalue,
	picohttpHeaderFieldCallback headerfieldcallback,
	void * const cb_data,
	int ch )
{
#define PICOHTTP_HEADERNAME_MAX_LEN 32
	char headername[PICOHTTP_HEADERNAME_MAX_LEN+1] = {0,};

#if 0
#define PICOHTTP_HEADERVALUE_MAX_LEN 224
	char headervalue[PICOHTTP_HEADERVALUE_MAX_LEN+1] = {0,};
#endif

	char *hn = headername;
	char *hv = headervalue;

	/* TODO: Add Header handling here */
	while( !picohttpIsCRLF(ch) ) {
		/* Beginning of new header line */
		if( 0 < ch && !picohttpIsCRLF(ch) ){
			/* new header field OR field continuation */
			if( picohttpIsLWS(ch) ) {
				/* continuation */
				/* skip space */
				if( 0 > (ch = picohttpIoSkipSpace(req->ioops, ch)) )
					return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;

				/* read until EOL */
				for(;
				    0 < ch && !picohttpIsCRLF(ch);
				    hv = (size_t)(hv - headervalue) <
				         (headervalue_maxlen-1) ?
					     hv+1 : 0 ) {
					/* add to header field content */

					if(hv)
						*hv = ch;

					ch = picohttpIoGetch(req->ioops);
				}
			} else {
				if( *headername && *headervalue && headerfieldcallback )
					headerfieldcallback(
						cb_data,
						headername,
						headervalue );
				/* new header field */
				memset(headername, 0, PICOHTTP_HEADERNAME_MAX_LEN+1);
				hn = headername;

				memset(headervalue, 0, headervalue_maxlen);
				hv = headervalue;
				/* read until ':' or EOL */
				for(;
				    0 < ch && ':' != ch && !picohttpIsCRLF(ch);
				    hn = (hn - headername) <
				          PICOHTTP_HEADERNAME_MAX_LEN ?
					      hn+1 : 0 ) {
					/* add to header name */
					if(hn)
						*hn = ch;

					ch = picohttpIoGetch(req->ioops);
				}
			}
		} 
		if( 0 > ch  ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}
		if( picohttpIsCRLF(ch) )
			ch = picohttpIoSkipOverCRLF(req->ioops, ch);
		else
			ch = picohttpIoGetch(req->ioops);
		if( 0 > ch ) {
			return -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		}
		if( !ch ) {
			return -PICOHTTP_STATUS_400_BAD_REQUEST;
		}
	}
	if( *headername && *headervalue && headerfieldcallback)
		headerfieldcallback(
			cb_data,
			headername,
			headervalue );

	return ch;
}

/* This wraps picohttpProcessHeaders with a *large* header value buffer
 * so that we can process initial headers of a HTTP request, with loads
 * of content. Most importantly Digest authentication, which can push quite
 * some data.
 *
 * By calling this function from picohttpProcessRequest the allocation
 * stays within the stack frame of this function. After the function
 * returns, the stack gets available for the actual request handler.
 */
static int picohttp_wrap_request_prochdrs (
	struct picohttpRequest * const req,
	int ch )
{
#if PICOHTTP_NO_DIGEST_AUTH
	size_t const headervalue_maxlen = 256;
#else
	size_t const headervalue_maxlen = 768;
#endif
	char headervalue[headervalue_maxlen];

	memset(headervalue, 0, headervalue_maxlen);

	return picohttpProcessHeaders(
		req,
		headervalue_maxlen,
		headervalue,
		picohttpProcessHeaderField,
		req,
		ch );
}

size_t picohttpRoutesMaxUrlLength(
	struct picohttpURLRoute const * const routes )
{
	size_t url_max_length = 0;
	for(size_t i = 0; routes[i].urlhead; i++) {
		size_t url_length =
			strlen(routes[i].urlhead) +
			routes[i].max_urltail_len;

		if(url_length > url_max_length)
			url_max_length = url_length;
	}
	return url_max_length;
}

void picohttpProcessRequest (
	struct picohttpIoOps const * const ioops,
	struct picohttpURLRoute const * const routes,
	struct picohttpAuthData * const authdata,
	void *userdata)
{

	int ch;
	struct picohttpRequest request;
	memset(&request, 0, sizeof(request));

	size_t const url_max_length = picohttpRoutesMaxUrlLength(routes);
#ifdef PICOWEB_CONFIG_USE_C99VARARRAY
	char url[url_max_length+1];
#else
	char *url = alloca(url_max_length+1);
#endif
	memset(url, 0, url_max_length+1);

	request.url = url;
	request.urltail = 0;
	request.ioops = ioops;
	request.method = 0;
	request.httpversion.major = 1;
	request.httpversion.minor = 0;
	request.sent.header = 0;
	request.sent.octets = 0;
	request.received_octets = 0;
	request.userdata = userdata;
	request.query.auth = authdata;

	request.method = picohttpProcessRequestMethod(ioops);
	if( !request.method ) {
		ch = -PICOHTTP_STATUS_501_NOT_IMPLEMENTED;
		goto http_error;
	}
	if( 0 > request.method ) {
		ch = -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		goto http_error;
	}

	if( 0 > (ch = picohttpIoSkipSpace(ioops, -1)) ) {
		ch = -PICOHTTP_STATUS_500_INTERNAL_SERVER_ERROR;
		goto http_error;
	}

	if( 0 > (ch = picohttpProcessURL(&request, url_max_length, ch)) )
		goto http_error;

	if( !picohttpMatchRoute(&request, routes) || !request.route ) {
		ch = -PICOHTTP_STATUS_404_NOT_FOUND;
		goto http_error;
	}
	if( !(request.route->allowed_methods & request.method) ) {
		ch = -PICOHTTP_STATUS_405_METHOD_NOT_ALLOWED;
		goto http_error;
	}

	if( 0 > (ch = picohttpProcessQuery(&request, ch)) )
		goto http_error;

	if( 0 > (ch = picohttpProcessHTTPVersion (&request, ch)) )
		goto http_error;

	if( request.httpversion.major > 1 ||
	    request.httpversion.minor > 1 ) {
		ch = -PICOHTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
		goto http_error;
	}

	if( 0 > (ch = picohttp_wrap_request_prochdrs(&request, ch)) )
		goto http_error;

	if( '\r' == ch ) {	
		if( 0 > (ch = picohttpIoGetch(ioops)) )
			goto http_error;
		if( '\n' != ch ) {
			ch = -PICOHTTP_STATUS_400_BAD_REQUEST;
			goto http_error;
		}
	}

	request.status = PICOHTTP_STATUS_200_OK;
	request.route->handler(&request);

	picohttpIoFlush(request.ioops);
	return;

http_error:

	picohttpStatusResponse(&request, -ch);
	picohttpIoFlush(request.ioops);
}

int picohttpResponseSendHeaders (
	struct picohttpRequest * const req )
{
#define picohttpIO_WRITE_STATIC_STR(x) \
	(picohttpIoWrite(req->ioops, sizeof(x)-1, x))

	char tmp[16] = {0,};
	char const *c;
	int e;

	if(req->sent.header)
		return 0;

	if(!req->response.contenttype) {
		req->response.contenttype = "text/plain";
	}

#if defined(PICOHTTP_CONFIG_USE_SNPRINTF)
	snprintf(tmp, sizeof(tmp)-1, "%s%d.%d %d ",
	         PICOHTTP_STR_HTTP_,
	         req->httpversion.major,
		 req->httpversion.minor,
		 req->status);
#else
	if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_HTTP_)) )
		return e;

	size_t p = 0;
	p += picohttp_fmt_uint(tmp+p, req->httpversion.major);
	tmp[p] = '.'; p++;
	p += picohttp_fmt_uint(tmp+p, req->httpversion.minor);
	tmp[p] = ' '; p++;
	p += picohttp_fmt_uint(tmp+p, req->status);
	tmp[p] = ' '; p++;
	/* assert(p < sizeof(tmp)-1); */
#endif
	/* HTTP status line */
	c = picohttpStatusString(req->status);
	if( 0 > (e = picohttpIoWrite(req->ioops, strlen(tmp), tmp)) ||
	    0 > (e = picohttpIoWrite(req->ioops, strlen(c), c)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
		return e;

	/* Server header */
	if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_SERVER)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLSP)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_PICOWEB)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
		return e;

	/* Connection header -- for now this is "Connection: close" */
	if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CONNECTION)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLSP)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLOSE)) ||
	    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
		return e;

	if(req->response.contenttype) {
		/* Content-Type header */
		if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CONTENT)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR__TYPE)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLSP)) ||
		    0 > (e = picohttpIoWrite(
				req->ioops, strlen(req->response.contenttype),
				req->response.contenttype))  ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
			return e;
	}

	if(req->response.disposition) {
		/* Content-Type header */
		if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CONTENT)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR__DISPOSITION)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLSP)) ||
		    0 > (e = picohttpIoWrite(
				req->ioops, strlen(req->response.disposition),
				req->response.disposition))  ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
			return e;
	}

	/* Content-Length header */
	if( req->response.contentlength ){
		p = picohttp_fmt_uint(tmp, req->response.contentlength);
		if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CONTENT)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR__LENGTH)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLSP)) ||
		    0 > (e = picohttpIoWrite(req->ioops, p, tmp))  ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
			return e;
	}

	/* WWW-Authenticate header */
	if( req->response.www_authenticate ){
		if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_WWW_AUTHENTICATE)) ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CLSP)) ||
		    0 > (e = picohttpIoWrite(
				req->ioops, strlen(req->response.www_authenticate),
				req->response.www_authenticate))  ||
		    0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
			return e;
	}

	if( 0 > (e = picohttpIO_WRITE_STATIC_STR(PICOHTTP_STR_CRLF)) )
		return e;

	return req->sent.header = 1;

#undef picohttpIO_WRITE_STATIC_STR
}

int picohttpResponseWrite (
	struct picohttpRequest * const req,
	size_t len,
	void const *buf )
{
	int e;

	if( !req->sent.header )
		picohttpResponseSendHeaders(req);

	if( req->response.contentlength > 0 ) {
		if(req->sent.octets >= req->response.contentlength)
			return -1;

		if(req->sent.octets + len < req->sent.octets) /* int overflow */
			return -2;

		if(req->sent.octets + len >= req->response.contentlength)
			len = req->response.contentlength - req->sent.octets;
	}
	
	if( PICOHTTP_METHOD_HEAD == req->method )
		return 0;

	if( 0 > (e = picohttpIoWrite(req->ioops, len, buf)) )
		return e;

	req->sent.octets += len;
	return len;
}

int picohttpMultipartGetch(
	struct picohttpMultipart * const mp)
{
	int ch;
	if( mp->finished ) {
		return -1;
	} else
	if( 0 <= mp->mismatch ) {
replay:
		if( mp->replayhead < mp->replay ) {
			ch = mp->req->query.multipartboundary[mp->replayhead];
			mp->replayhead++;
			return ch;
		} else {
			ch = mp->mismatch;
			mp->mismatch = -1;
			mp->replayhead = 0;
			return ch;
		}
	} else {
		ch = picohttpGetch(mp->req);

	/* picohttp's query and header parsing is forgiving
	 * regarding line termination. <CR><LF> or just <LF>
	 * are accepted.
	 * However multipart boundaries are to start with
	 * a <CR><LF> sequence.
	 */

		while( 0 <= ch ) {

			if( mp->req->query.multipartboundary[mp->in_boundary] == ch ) {
				if( 0 == mp->req->query.multipartboundary[mp->in_boundary+1] ) {
					mp->in_boundary = 0;
					/* matched boundary */
					int trail[2] = {0, 0};
					for(int i=0; i<2; i++) {
						trail[i] = picohttpGetch(mp->req);
						if( 0 > trail[i] )
							return -1;
					}
				
					if(trail[0] == '\r' && trail[1] == '\n') {
						mp->finished = 1;
					}

				/* TODO: Technically the last boundary is followed by a
				 * terminating <CR><LF> sequence... we should check for
				 * this as well, just for completeness
				 */
					if(trail[0] == '-' && trail[1] == '-') {
						mp->finished = 2;
					}

					return -1;
				} 
				mp->in_boundary++;
			} else {
				if( mp->in_boundary ) 
				{
					if( '\r' == ch ) {
						mp->replay = mp->in_boundary-1;
						mp->mismatch = mp->req->query.multipartboundary[mp->replay];
						mp->in_boundary = 1;
					} else {
						mp->mismatch = ch;
						mp->replay = mp->in_boundary;
						mp->in_boundary = 0;
					} 

					goto replay;

				} 
				return ch;
			}
			ch = picohttpGetch(mp->req);
		}
	}
	return ch;
} 

int picohttpMultipartRead(
	struct picohttpMultipart * const mp,
	size_t len,
	char * const buf)
{
/* TODO: Replace this with a dedicated variant processing whole buffers?
 *       Probably a lot of code would be shared with the ...Getch variant
 *       and could be placed into a commonly used function.
 */
	if( mp->finished ) {
		return -1;
	}

	int ch;
	size_t i;
	for(i = 0; i < len; i++) {
		if( 0 > (ch = picohttpMultipartGetch(mp)) ) {
			if( mp->finished )
				return i;
			else
				return ch;
		}

		buf[i] = ch;
	}
	return i;
}

static void picohttpProcessMultipartContentType(
	struct picohttpMultipart * const mp,
	char const *contenttype )
{
	mp->contenttype = picohttpProcessContentType(&contenttype);

	if( PICOHTTP_CONTENTTYPE_MULTIPART == (mp->contenttype & 0xf000) ) {
	}
}

static void picohttpProcessMultipartContentDisposition(
	struct picohttpMultipart * const mp,
	char const *disposition )
{
	char const *name = strstr(disposition, PICOHTTP_STR_NAME__);
	if(name) {
		name += sizeof(PICOHTTP_STR_NAME__)-1;
		char const * const nameend = strchr(name, '"');
		if(nameend) {
			size_t len = nameend - name;
			if( PICOHTTP_DISPOSITION_NAME_MAX < len )
				len = PICOHTTP_DISPOSITION_NAME_MAX;

			strncpy(mp->disposition.name, name, len);
		}
	}
}

static void picohttpMultipartHeaderField(
	void * const data,
	char const *headername,
	char const *headervalue)
{
	struct picohttpMultipart * const mp = data;
	if(!strncmp(headername,
		    PICOHTTP_STR_CONTENT,
		    sizeof(PICOHTTP_STR_CONTENT)-1)) {
		headername += sizeof(PICOHTTP_STR_CONTENT)-1;
		/* Content Length
		 * TODO: Is this a header actually defined for multipart bodies?
		 *       Anyway, even if it's not defined, this has not negative
		 *       side effects, so why care about it. Worst it can do it
		 *       be usefull later.
		 */
		if(!strncmp(headername,
			    PICOHTTP_STR__LENGTH, sizeof(PICOHTTP_STR__LENGTH)-1)) {
			return;
		}

		/* Content Disposition */
		if(!strncmp(headername,
			    PICOHTTP_STR__DISPOSITION, sizeof(PICOHTTP_STR__DISPOSITION)-1)) {
			picohttpProcessMultipartContentDisposition(mp, headervalue);
			return;
		}

		/* Content Type */
		if(!strncmp(headername,
			    PICOHTTP_STR__TYPE, sizeof(PICOHTTP_STR__TYPE)-1)) {
			picohttpProcessMultipartContentType(mp, headervalue);
			return;
		}
		return;
	}
}

struct picohttpMultipart picohttpMultipartStart(
	struct picohttpRequest * const req)
{
	struct picohttpMultipart mp = {
		.req = req,
		.finished = 0,
		.contenttype = 0,
		.disposition = { .name = {0,} },
		.in_boundary = 2,
		.replayhead = 2,
		.mismatch = -1,
	};

	return mp;
}

int picohttpMultipartNext(
	struct picohttpMultipart * const mp)
{
	if( 2 == mp->finished ) {
		return -1;
	} 

	char headervalbuf[224];

	for(;;) {
		int ch = picohttpMultipartGetch(mp);
		if( 0 > ch ) {
			if( 2 == mp->finished ) {
				return -1;
			}

			if( 1 == mp->finished ) {
				mp->finished = 0;

				if( 0 > (ch = picohttpGetch(mp->req)) )
					return ch;

				memset(headervalbuf, 0, sizeof(headervalbuf));
				if( 0 > (ch = picohttpProcessHeaders(
						mp->req,
						sizeof(headervalbuf),
						headervalbuf,
						picohttpMultipartHeaderField,
						mp,
						ch)) )
					return ch;

				if( '\r' == ch ) {	
					if( 0 > (ch = picohttpIoGetch(mp->req->ioops)) )
						return ch;
					if( '\n' != ch ) {
						return -1;
					}
				}
				mp->mismatch = -1;
				mp->in_boundary = 
				mp->replayhead = 0;

				return 0;
			}
		}

	}

	return -1;
}