-
Notifications
You must be signed in to change notification settings - Fork 96
/
cgic.c
2576 lines (2452 loc) · 55.9 KB
/
cgic.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* cgicTempDir is the only setting you are likely to need
to change in this file. */
/* Used only in Unix environments, in conjunction with mkstemp().
Elsewhere (Windows), temporary files go where the tmpnam()
function suggests. If this behavior does not work for you,
modify the getTempFile() function to suit your needs. */
#define cgicTempDir "/tmp"
#define cgicMaxTempSize 1073741824
#if CGICDEBUG
#define CGICDEBUGSTART \
{ \
FILE *dout; \
dout = fopen("/home/boutell/public_html/debug", "a"); \
#define CGICDEBUGEND \
fclose(dout); \
}
#else /* CGICDEBUG */
#define CGICDEBUGSTART
#define CGICDEBUGEND
#endif /* CGICDEBUG */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
#include <io.h>
/* cgic 2.01 */
#include <fcntl.h>
#else
#include <unistd.h>
#endif /* WIN32 */
#include "cgic.h"
#define cgiStrEq(a, b) (!strcmp((a), (b)))
char *cgiServerSoftware;
char *cgiServerName;
char *cgiGatewayInterface;
char *cgiServerProtocol;
char *cgiServerPort;
char *cgiRequestMethod;
char *cgiPathInfo;
char *cgiPathTranslated;
char *cgiScriptName;
char *cgiQueryString;
char *cgiRemoteHost;
char *cgiRemoteAddr;
char *cgiAuthType;
char *cgiRemoteUser;
char *cgiRemoteIdent;
char cgiContentTypeData[1024];
char *cgiContentType = cgiContentTypeData;
char *cgiMultipartBoundary;
char *cgiCookie;
int cgiContentLength;
char *cgiAccept;
char *cgiUserAgent;
char *cgiReferrer;
FILE *cgiIn;
FILE *cgiOut;
/* True if CGI environment was restored from a file. */
static int cgiRestored = 0;
static void cgiGetenv(char **s, char *var);
typedef enum {
cgiParseSuccess,
cgiParseMemory,
cgiParseIO
} cgiParseResultType;
/* One form entry, consisting of an attribute-value pair,
and an optional filename and content type. All of
these are guaranteed to be valid null-terminated strings,
which will be of length zero in the event that the
field is not present, with the exception of tfileName
which will be null when 'in' is null. DO NOT MODIFY THESE
VALUES. Make local copies if modifications are desired. */
typedef struct cgiFormEntryStruct {
char *attr;
/* value is populated for regular form fields only.
For file uploads, it points to an empty string, and file
upload data should be read from the file tfileName. */
char *value;
/* When fileName is not an empty string, tfileName is not null,
and 'value' points to an empty string. */
/* Valid for both files and regular fields; does not include
terminating null of regular fields. */
int valueLength;
char *fileName;
char *contentType;
/* Temporary file descriptor for working storage of file uploads. */
FILE *tFile;
struct cgiFormEntryStruct *next;
} cgiFormEntry;
/* The first form entry. */
static cgiFormEntry *cgiFormEntryFirst;
static cgiParseResultType cgiParseGetFormInput();
static cgiParseResultType cgiParsePostFormInput();
static cgiParseResultType cgiParsePostMultipartInput();
static cgiParseResultType cgiParseFormInput(char *data, int length);
static void cgiSetupConstants();
static void cgiFreeResources();
static int cgiStrEqNc(char *s1, char *s2);
static int cgiStrBeginsNc(char *s1, char *s2);
#ifdef UNIT_TEST
static int unitTest();
#endif
int main(int argc, char *argv[]) {
int result;
char *cgiContentLengthString;
char *e;
cgiSetupConstants();
cgiGetenv(&cgiServerSoftware, "SERVER_SOFTWARE");
cgiGetenv(&cgiServerName, "SERVER_NAME");
cgiGetenv(&cgiGatewayInterface, "GATEWAY_INTERFACE");
cgiGetenv(&cgiServerProtocol, "SERVER_PROTOCOL");
cgiGetenv(&cgiServerPort, "SERVER_PORT");
cgiGetenv(&cgiRequestMethod, "REQUEST_METHOD");
cgiGetenv(&cgiPathInfo, "PATH_INFO");
cgiGetenv(&cgiPathTranslated, "PATH_TRANSLATED");
cgiGetenv(&cgiScriptName, "SCRIPT_NAME");
cgiGetenv(&cgiQueryString, "QUERY_STRING");
cgiGetenv(&cgiRemoteHost, "REMOTE_HOST");
cgiGetenv(&cgiRemoteAddr, "REMOTE_ADDR");
cgiGetenv(&cgiAuthType, "AUTH_TYPE");
cgiGetenv(&cgiRemoteUser, "REMOTE_USER");
cgiGetenv(&cgiRemoteIdent, "REMOTE_IDENT");
/* 2.0: the content type string needs to be parsed and modified, so
copy it to a buffer. */
e = getenv("CONTENT_TYPE");
if (e) {
if (strlen(e) < sizeof(cgiContentTypeData)) {
strcpy(cgiContentType, e);
} else {
/* Truncate safely in the event of what is almost certainly
a hack attempt */
strncpy(cgiContentType, e, sizeof(cgiContentTypeData));
cgiContentType[sizeof(cgiContentTypeData) - 1] = '\0';
}
} else {
cgiContentType[0] = '\0';
}
/* Never null */
cgiMultipartBoundary = "";
/* 2.0: parse semicolon-separated additional parameters of the
content type. The one we're interested in is 'boundary'.
We discard the rest to make cgiContentType more useful
to the typical programmer. */
if (strchr(cgiContentType, ';')) {
char *sat = strchr(cgiContentType, ';');
while (sat) {
*sat = '\0';
sat++;
while (isspace(*sat)) {
sat++;
}
if (cgiStrBeginsNc(sat, "boundary=")) {
char *s;
cgiMultipartBoundary = sat + strlen("boundary=");
s = cgiMultipartBoundary;
while ((*s) && (!isspace(*s))) {
s++;
}
*s = '\0';
break;
} else {
sat = strchr(sat, ';');
}
}
}
cgiGetenv(&cgiContentLengthString, "CONTENT_LENGTH");
cgiContentLength = atoi(cgiContentLengthString);
cgiGetenv(&cgiAccept, "HTTP_ACCEPT");
cgiGetenv(&cgiUserAgent, "HTTP_USER_AGENT");
cgiGetenv(&cgiReferrer, "HTTP_REFERER");
cgiGetenv(&cgiCookie, "HTTP_COOKIE");
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "%d\n", cgiContentLength);
fprintf(dout, "%s\n", cgiRequestMethod);
fprintf(dout, "%s\n", cgiContentType);
CGICDEBUGEND
#endif /* CGICDEBUG */
#ifdef WIN32
/* 1.07: Must set stdin and stdout to binary mode */
/* 2.0: this is particularly crucial now and must not be removed */
_setmode( _fileno( stdin ), _O_BINARY );
_setmode( _fileno( stdout ), _O_BINARY );
#endif /* WIN32 */
cgiFormEntryFirst = 0;
cgiIn = stdin;
cgiOut = stdout;
cgiRestored = 0;
/* These five lines keep compilers from
producing warnings that argc and argv
are unused. They have no actual function. */
if (argc) {
if (argv[0]) {
cgiRestored = 0;
}
}
if (cgiStrEqNc(cgiRequestMethod, "post")) {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "POST recognized\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
if (cgiStrEqNc(cgiContentType, "application/x-www-form-urlencoded")) {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "Calling PostFormInput\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
if (cgiParsePostFormInput() != cgiParseSuccess) {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "PostFormInput failed\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
cgiHeaderStatus(500, "Error reading form data");
cgiFreeResources();
return -1;
}
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "PostFormInput succeeded\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
} else if (cgiStrEqNc(cgiContentType, "multipart/form-data")) {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "Calling PostMultipartInput\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
if (cgiParsePostMultipartInput() != cgiParseSuccess) {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "PostMultipartInput failed\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
cgiHeaderStatus(500, "Error reading form data");
cgiFreeResources();
return -1;
}
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "PostMultipartInput succeeded\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
}
} else if (cgiStrEqNc(cgiRequestMethod, "get")) {
/* The spec says this should be taken care of by
the server, but... it isn't */
cgiContentLength = strlen(cgiQueryString);
if (cgiParseGetFormInput() != cgiParseSuccess) {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "GetFormInput failed\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
cgiHeaderStatus(500, "Error reading form data");
cgiFreeResources();
return -1;
} else {
#ifdef CGICDEBUG
CGICDEBUGSTART
fprintf(dout, "GetFormInput succeeded\n");
CGICDEBUGEND
#endif /* CGICDEBUG */
}
}
#ifdef UNIT_TEST
unitTest();
cgiFreeResources();
return 0;
#else
result = cgiMain();
return result;
#endif
}
static void cgiGetenv(char **s, char *var){
*s = getenv(var);
if (!(*s)) {
*s = "";
}
}
static cgiParseResultType cgiParsePostFormInput() {
char *input;
cgiParseResultType result;
if (!cgiContentLength) {
return cgiParseSuccess;
}
input = (char *) malloc(cgiContentLength);
if (!input) {
return cgiParseMemory;
}
if (((int) fread(input, 1, cgiContentLength, cgiIn))
!= cgiContentLength)
{
return cgiParseIO;
}
result = cgiParseFormInput(input, cgiContentLength);
free(input);
return result;
}
/* 2.0: A virtual datastream supporting putback of
enough characters to handle multipart boundaries easily.
A simple memset(&mp, 0, sizeof(mp)) is suitable initialization. */
typedef struct {
/* Buffer for putting characters back */
char putback[1024];
/* Position in putback from which next character will be read.
If readPos == writePos, then next character should
come from cgiIn. */
int readPos;
/* Position in putback to which next character will be put back.
If writePos catches up to readPos, as opposed to the other
way around, the stream no longer functions properly.
Calling code must guarantee that no more than
sizeof(putback) bytes are put back at any given time. */
int writePos;
/* Offset in the virtual datastream; can be compared
to cgiContentLength */
int offset;
} mpStream, *mpStreamPtr;
int mpRead(mpStreamPtr mpp, char *buffer, int len)
{
int ilen = len;
int got = 0;
/* Refuse to read past the declared length in order to
avoid deadlock */
if (len > (cgiContentLength - mpp->offset)) {
len = cgiContentLength - mpp->offset;
}
while (len) {
if (mpp->readPos != mpp->writePos) {
*buffer++ = mpp->putback[mpp->readPos++];
mpp->readPos %= sizeof(mpp->putback);
got++;
len--;
} else {
break;
}
}
if (len) {
int fgot = fread(buffer, 1, len, cgiIn);
if (fgot >= 0) {
mpp->offset += (got + fgot);
return got + fgot;
} else if (got > 0) {
mpp->offset += got;
return got;
} else {
/* EOF or error */
return fgot;
}
} else if (got) {
mpp->offset += got;
return got;
} else if (ilen) {
return EOF;
} else {
/* 2.01 */
return 0;
}
}
void mpPutBack(mpStreamPtr mpp, char *data, int len)
{
mpp->offset -= len;
while (len) {
mpp->putback[mpp->writePos++] = *data++;
mpp->writePos %= sizeof(mpp->putback);
len--;
}
}
/* This function copies the body to outf if it is not null, otherwise to
a newly allocated character buffer at *outP, which will be null
terminated; if both outf and outP are null the body is not stored.
If bodyLengthP is not null, the size of the body in bytes is stored
to *bodyLengthP, not including any terminating null added to *outP.
If 'first' is nonzero, a preceding newline is not expected before
the boundary. If 'first' is zero, a preceding newline is expected.
Upon return mpp is positioned after the boundary and its trailing
newline, if any; if the boundary is followed by -- the next two
characters read after this function returns will be --. Upon error,
if outP is not null, *outP is a null pointer; *bodyLengthP
is set to zero. Returns cgiParseSuccess, cgiParseMemory
or cgiParseIO. */
static cgiParseResultType afterNextBoundary(mpStreamPtr mpp,
FILE *outf,
char **outP,
int *bodyLengthP,
int first
);
static int readHeaderLine(
mpStreamPtr mpp,
char *attr,
int attrSpace,
char *value,
int valueSpace);
static void decomposeValue(char *value,
char *mvalue, int mvalueSpace,
char **argNames,
char **argValues,
int argValueSpace);
static cgiParseResultType getTempFile(FILE **tFile);
static cgiParseResultType cgiParsePostMultipartInput() {
cgiParseResultType result;
cgiFormEntry *n = 0, *l = 0;
int got;
FILE *outf = 0;
char *out = 0;
mpStream mp;
mpStreamPtr mpp = ∓
memset(&mp, 0, sizeof(mp));
if (!cgiContentLength) {
return cgiParseSuccess;
}
/* Read first boundary, including trailing newline */
result = afterNextBoundary(mpp, 0, 0, 0, 1);
if (result == cgiParseIO) {
/* An empty submission is not necessarily an error */
return cgiParseSuccess;
} else if (result != cgiParseSuccess) {
return result;
}
while (1) {
char d[1024];
char fvalue[1024];
char fname[1024];
int bodyLength = 0;
char ffileName[1024];
char fcontentType[1024];
char attr[1024];
char value[1024];
fvalue[0] = 0;
fname[0] = 0;
ffileName[0] = 0;
fcontentType[0] = 0;
out = 0;
outf = 0;
/* Check for EOF */
got = mpRead(mpp, d, 2);
if (got < 2) {
/* Crude EOF */
break;
}
if ((d[0] == '-') && (d[1] == '-')) {
/* Graceful EOF */
break;
}
mpPutBack(mpp, d, 2);
/* Read header lines until end of header */
while (readHeaderLine(
mpp, attr, sizeof(attr), value, sizeof(value)))
{
char *argNames[3];
char *argValues[2];
/* Content-Disposition: form-data;
name="test"; filename="googley.gif" */
if (cgiStrEqNc(attr, "Content-Disposition")) {
argNames[0] = "name";
argNames[1] = "filename";
argNames[2] = 0;
argValues[0] = fname;
argValues[1] = ffileName;
decomposeValue(value,
fvalue, sizeof(fvalue),
argNames,
argValues,
1024);
} else if (cgiStrEqNc(attr, "Content-Type")) {
argNames[0] = 0;
decomposeValue(value,
fcontentType, sizeof(fcontentType),
argNames,
0,
0);
}
}
if (!cgiStrEqNc(fvalue, "form-data")) {
/* Not form data */
result = afterNextBoundary(mpp, 0, 0, 0, 0);
if (result != cgiParseSuccess) {
/* Lack of a boundary here is an error. */
return result;
}
continue;
}
/* Body is everything from here until the next
boundary. So, set it aside and move past boundary.
If a filename was submitted as part of the
disposition header, store to a temporary file.
Otherwise, store to a memory buffer (it is
presumably a regular form field). */
if (strlen(ffileName)) {
if (getTempFile(&outf) != cgiParseSuccess) {
return cgiParseIO;
}
} else {
outf = 0;
}
result = afterNextBoundary(mpp, outf, &out, &bodyLength, 0);
if (result != cgiParseSuccess) {
/* Lack of a boundary here is an error. */
if (outf) {
fclose(outf);
}
if (out) {
free(out);
}
return result;
}
/* OK, we have a new pair, add it to the list. */
n = (cgiFormEntry *) malloc(sizeof(cgiFormEntry));
if (!n) {
goto outOfMemory;
}
memset(n, 0, sizeof(cgiFormEntry));
/* 2.01: one of numerous new casts required
to please C++ compilers */
n->attr = (char *) malloc(strlen(fname) + 1);
if (!n->attr) {
goto outOfMemory;
}
strcpy(n->attr, fname);
if (out) {
n->value = out;
out = 0;
} else if (outf) {
n->value = (char *) malloc(1);
if (!n->value) {
goto outOfMemory;
}
n->value[0] = '\0';
}
n->valueLength = bodyLength;
n->next = 0;
if (!l) {
cgiFormEntryFirst = n;
} else {
l->next = n;
}
n->fileName = (char *) malloc(strlen(ffileName) + 1);
if (!n->fileName) {
goto outOfMemory;
}
strcpy(n->fileName, ffileName);
n->contentType = (char *) malloc(strlen(fcontentType) + 1);
if (!n->contentType) {
goto outOfMemory;
}
strcpy(n->contentType, fcontentType);
if(outf)
{
n->tFile = fdopen (dup (fileno (outf)), "w+b");
fclose(outf);
}
l = n;
}
return cgiParseSuccess;
outOfMemory:
if (n) {
if (n->attr) {
free(n->attr);
}
if (n->value) {
free(n->value);
}
if (n->fileName) {
free(n->fileName);
}
if (n->tFile) {
fclose(n->tFile);
}
if (n->contentType) {
free(n->contentType);
}
free(n);
}
if (out) {
free(out);
}
if (outf) {
fclose(outf);
}
return cgiParseMemory;
}
static cgiParseResultType getTempFile(FILE **tFile)
{
/* tfileName must be 1024 bytes to ensure adequacy on
win32 (1024 exceeds the maximum path length and
certainly exceeds observed behavior of _tmpnam).
May as well also be 1024 bytes on Unix, although actual
length is strlen(cgiTempDir) + a short unique pattern. */
char tfileName[1024];
#ifndef WIN32
/* Unix. Use the robust 'mkstemp' function to create
a temporary file that is truly unique, with
permissions that are truly safe. The
fopen-for-write destroys any bogus information
written by potential hackers during the brief
window between the file's creation and the
chmod call (glibc 2.0.6 and lower might
otherwise have allowed this). */
int outfd;
strcpy(tfileName, cgicTempDir "/cgicXXXXXX");
outfd = mkstemp(tfileName);
if (outfd == -1) {
return cgiParseIO;
}
close(outfd);
/* Fix the permissions */
if (chmod(tfileName, 0600) != 0) {
unlink(tfileName);
return cgiParseIO;
}
#else
/* Non-Unix. Do what we can. */
if (!tmpnam(tfileName)) {
return cgiParseIO;
}
#endif
*tFile = fopen(tfileName, "w+b");
unlink(tfileName);
return cgiParseSuccess;
}
#define APPEND(string, char) \
{ \
if ((string##Len + 1) < string##Space) { \
string[string##Len++] = (char); \
} \
}
#define RAPPEND(string, ch) \
{ \
if ((string##Len + 1) == string##Space) { \
char *sold = string; \
string##Space *= 2; \
string = (char *) realloc(string, string##Space); \
if (!string) { \
string = sold; \
goto outOfMemory; \
} \
} \
string[string##Len++] = (ch); \
}
#define BAPPEND(ch) \
{ \
if (outf) { \
putc(ch, outf); \
outLen++; \
} else if (out) { \
RAPPEND(out, ch); \
} \
}
cgiParseResultType afterNextBoundary(mpStreamPtr mpp, FILE *outf, char **outP,
int *bodyLengthP, int first)
{
int outLen = 0;
int outSpace = 256;
char *out = 0;
cgiParseResultType result;
int boffset;
int got;
char d[2];
/* This is large enough, because the buffer into which the
original boundary string is fetched is shorter by more
than four characters due to the space required for
the attribute name */
char workingBoundaryData[1024];
char *workingBoundary = workingBoundaryData;
int workingBoundaryLength;
if ((!outf) && (outP)) {
out = (char *) malloc(outSpace);
if (!out) {
goto outOfMemory;
}
}
boffset = 0;
sprintf(workingBoundaryData, "\r\n--%s", cgiMultipartBoundary);
if (first) {
workingBoundary = workingBoundaryData + 2;
}
workingBoundaryLength = strlen(workingBoundary);
while (1) {
got = mpRead(mpp, d, 1);
if (got != 1) {
/* 2.01: cgiParseIO, not cgiFormIO */
result = cgiParseIO;
goto error;
}
if (d[0] == workingBoundary[boffset]) {
/* We matched the next byte of the boundary.
Keep track of our progress into the
boundary and don't emit anything. */
boffset++;
if (boffset == workingBoundaryLength) {
break;
}
} else if (boffset > 0) {
/* We matched part, but not all, of the
boundary. Now we have to be careful:
put back all except the first
character and try again. The
real boundary could begin in the
middle of a false match. We can
emit the first character only so far. */
BAPPEND(workingBoundary[0]);
mpPutBack(mpp,
workingBoundary + 1, boffset - 1);
mpPutBack(mpp, d, 1);
boffset = 0;
} else {
/* Not presently in the middle of a boundary
match; just emit the character. */
BAPPEND(d[0]);
}
if(outLen > cgicMaxTempSize) {
goto outOfMemory;
}
}
/* Read trailing newline or -- EOF marker. A literal EOF here
would be an error in the input stream. */
got = mpRead(mpp, d, 2);
if (got != 2) {
result = cgiParseIO;
goto error;
}
if ((d[0] == '\r') && (d[1] == '\n')) {
/* OK, EOL */
} else if (d[0] == '-') {
/* Probably EOF, but we check for
that later */
mpPutBack(mpp, d, 2);
}
if (out && outSpace) {
char *oout = out;
out[outLen] = '\0';
out = (char *) realloc(out, outLen + 1);
if (!out) {
/* Surprising if it happens; and not fatal! We were
just trying to give some space back. We can
keep it if we have to. */
out = oout;
}
*outP = out;
}
if (bodyLengthP) {
*bodyLengthP = outLen;
}
return cgiParseSuccess;
outOfMemory:
result = cgiParseMemory;
if (outP) {
if (out) {
free(out);
}
*outP = 0;
}
error:
if (bodyLengthP) {
*bodyLengthP = 0;
}
if (out) {
free(out);
}
if (outP) {
*outP = 0;
}
return result;
}
static void decomposeValue(char *value,
char *mvalue, int mvalueSpace,
char **argNames,
char **argValues,
int argValueSpace)
{
char argName[1024];
int argNameSpace = sizeof(argName);
int argNameLen = 0;
int mvalueLen = 0;
char *argValue;
int argNum = 0;
while (argNames[argNum]) {
if (argValueSpace) {
argValues[argNum][0] = '\0';
}
argNum++;
}
while (isspace(*value)) {
value++;
}
/* Quoted mvalue */
if (*value == '\"') {
value++;
while ((*value) && (*value != '\"')) {
APPEND(mvalue, *value);
value++;
}
while ((*value) && (*value != ';')) {
value++;
}
} else {
/* Unquoted mvalue */
while ((*value) && (*value != ';')) {
APPEND(mvalue, *value);
value++;
}
}
if (mvalueSpace) {
mvalue[mvalueLen] = '\0';
}
while (*value == ';') {
int argNum;
int argValueLen = 0;
/* Skip the ; between parameters */
value++;
/* Now skip leading whitespace */
while ((*value) && (isspace(*value))) {
value++;
}
/* Now read the parameter name */
argNameLen = 0;
while ((*value) && (isalnum(*value))) {
APPEND(argName, *value);
value++;
}
if (argNameSpace) {
argName[argNameLen] = '\0';
}
while ((*value) && isspace(*value)) {
value++;
}
if (*value != '=') {
/* Malformed line */
return;
}
value++;
while ((*value) && isspace(*value)) {
value++;
}
/* Find the parameter in the argument list, if present */
argNum = 0;
argValue = 0;
while (argNames[argNum]) {
if (cgiStrEqNc(argName, argNames[argNum])) {
argValue = argValues[argNum];
break;
}
argNum++;
}
/* Finally, read the parameter value */
if (*value == '\"') {
value++;
while ((*value) && (*value != '\"')) {
if (argValue) {
APPEND(argValue, *value);
}
value++;
}
while ((*value) && (*value != ';')) {
value++;
}
} else {
/* Unquoted value */
while ((*value) && (*value != ';')) {
if (argNames[argNum]) {
APPEND(argValue, *value);
}
value++;
}
}
if (argValueSpace) {
if (argValue) {
argValue[argValueLen] = '\0';
}
}
}
}
static int readHeaderLine(
mpStreamPtr mpp,
char *attr,
int attrSpace,
char *value,
int valueSpace)
{
int attrLen = 0;
int valueLen = 0;
int valueFound = 0;
while (1) {
char d[1];
int got = mpRead(mpp, d, 1);
if (got != 1) {
return 0;
}
if (d[0] == '\r') {
got = mpRead(mpp, d, 1);
if (got == 1) {
if (d[0] == '\n') {
/* OK */
} else {
mpPutBack(mpp, d, 1);
}
}
break;
} else if (d[0] == '\n') {
break;
} else if ((d[0] == ':') && attrLen) {
valueFound = 1;
while (mpRead(mpp, d, 1) == 1) {
if (!isspace(d[0])) {
mpPutBack(mpp, d, 1);
break;
}
}
} else if (!valueFound) {
if (!isspace(*d)) {
if (attrLen < (attrSpace - 1)) {
attr[attrLen++] = *d;
}
}
} else if (valueFound) {
if (valueLen < (valueSpace - 1)) {
value[valueLen++] = *d;
}
}
}
if (attrSpace) {
attr[attrLen] = '\0';
}
if (valueSpace) {
value[valueLen] = '\0';
}
if (attrLen && valueLen) {
return 1;
} else {
return 0;
}
}
static cgiParseResultType cgiParseGetFormInput() {
return cgiParseFormInput(cgiQueryString, cgiContentLength);
}
typedef enum {
cgiEscapeRest,
cgiEscapeFirst,
cgiEscapeSecond
} cgiEscapeState;
typedef enum {
cgiUnescapeSuccess,
cgiUnescapeMemory