4 * This is a really bad attempt at writing a parser to handle multipart
5 * messages -- in the case of WebCit, a form containing uploaded files.
12 #include <sys/types.h>
19 * Take a part, figure out its length, and do something with it
21 void process_part(char *content, int part_length) {
24 static char partno = 0;
27 int crlf = 0; /* set to 1 for crlf-style newlines */
30 fprintf(stderr, "MIME: process_part() called with a length o' %d\n",
33 /* Strip off any leading blank lines. */
35 while ((!strncmp(start, "\r", 1)) || (!strncmp(start, "\n", 1))) {
40 /* At this point all we have left is the headers and the content. */
44 buf[strlen(buf)+1] = 0;
45 strncpy(&buf[strlen(buf)], start, 1);
48 } while((buf[strlen(buf)-1] != 10) && (part_length>0));
49 if (part_length <= 0) return;
50 buf[strlen(buf)-1] = 0;
51 if (buf[strlen(buf)-1]==13) {
52 buf[strlen(buf)-1] = 0;
55 fprintf(stderr, "MIME: <%s>\n", buf);
56 } while (strlen(buf)>0);
57 fprintf(stderr, "MIME: done processing headers\n");
59 if (crlf) actual_length = part_length - 2;
60 else actual_length = part_length - 1;
62 sprintf(filename, "content.%04x.%04x", getpid(), ++partno);
63 fp = fopen(filename, "wb");
64 fwrite(start, actual_length, 1, fp);
70 * Main function of parser
72 void mime_parser(char *content, int ContentLength, char *ContentType) {
75 int have_boundary = 0;
79 int bytes_processed = 0;
82 fprintf(stderr, "MIME: ContentLength: %d, ContentType: %s\n",
83 ContentLength, ContentType);
85 /* Figure out what the boundary is */
86 strcpy(boundary, ContentType);
87 for (a=0; a<strlen(boundary); ++a) {
88 if (!strncasecmp(&boundary[a], "boundary=", 9)) {
91 strcpy(&boundary[2], &boundary[a+9]);
95 if ((boundary[a]==13) || (boundary[a]==10)) {
100 /* We can't process multipart messages without a boundary. */
101 if (have_boundary == 0) return;
102 strcpy(endary, boundary);
103 strcat(endary, "--");
104 fprintf(stderr, "MIME: boundary is %s\n", boundary);
105 fprintf(stderr, "MIME: endary is %s\n", endary);
109 /* Seek to the beginning of the next boundary */
110 while (bytes_processed < ContentLength) {
111 /* && (strncasecmp(ptr, boundary, strlen(boundary))) ) { */
113 if (strncasecmp(ptr, boundary, strlen(boundary))) {
118 /* See if we're at the end */
119 if (!strncasecmp(ptr, endary, strlen(endary))) {
120 fprintf(stderr, "MIME: the end.\n");
124 /* Seek to the end of the boundary string */
125 if (!strncasecmp(ptr, boundary, strlen(boundary))) {
126 fprintf(stderr, "MIME: founda bounda\n");
127 while ( (bytes_processed < ContentLength)
128 && (strncasecmp(ptr, "\n", 1)) ) {
134 while ( (bytes_processed < ContentLength)
135 && (strncasecmp(ptr, boundary, strlen(boundary))) ) {
140 process_part(beginning, part_length);
141 /* Back off so we can see the next boundary */