Check for basename() is now done the same as other function checks
[platform/upstream/curl.git] / lib / formdata.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 /*
25   Debug the form generator stand-alone by compiling this source file with:
26
27   gcc -DHAVE_CONFIG_H -I../ -g -D_FORM_DEBUG -DCURLDEBUG -o formdata \
28     -I../include formdata.c strequal.c memdebug.c mprintf.c strerror.c
29
30   (depending on circumstances you may need further externals added)
31
32   run the 'formdata' executable the output should end with:
33   All Tests seem to have worked ...
34   and the following parts should be there:
35
36 Content-Disposition: form-data; name="simple_COPYCONTENTS"
37 value for simple COPYCONTENTS
38
39 Content-Disposition: form-data; name="COPYCONTENTS_+_CONTENTTYPE"
40 Content-Type: image/gif
41 value for COPYCONTENTS + CONTENTTYPE
42
43 Content-Disposition: form-data; name="PRNAME_+_NAMELENGTH_+_COPYNAME_+_CONTENTSLENGTH"
44 vlue for PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH
45 (or you might see P^@RNAME and v^@lue at the start)
46
47 Content-Disposition: form-data; name="simple_PTRCONTENTS"
48 value for simple PTRCONTENTS
49
50 Content-Disposition: form-data; name="PTRCONTENTS_+_CONTENTSLENGTH"
51 vlue for PTRCONTENTS + CONTENTSLENGTH
52 (or you might see v^@lue at the start)
53
54 Content-Disposition: form-data; name="PTRCONTENTS_+_CONTENTSLENGTH_+_CONTENTTYPE"
55 Content-Type: application/octet-stream
56 vlue for PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE
57 (or you might see v^@lue at the start)
58
59 Content-Disposition: form-data; name="FILE1_+_CONTENTTYPE"; filename="formdata.h"
60 Content-Type: text/html
61 ...
62
63 Content-Disposition: form-data; name="FILE1_+_FILE2"
64 Content-Type: multipart/mixed, boundary=curlz1s0dkticx49MV1KGcYP5cvfSsz
65 ...
66 Content-Disposition: attachment; filename="formdata.h"
67 Content-Type: application/octet-stream
68 ...
69 Content-Disposition: attachment; filename="Makefile.b32"
70 Content-Type: application/octet-stream
71 ...
72
73 Content-Disposition: form-data; name="FILE1_+_FILE2_+_FILE3"
74 Content-Type: multipart/mixed, boundary=curlirkYPmPwu6FrJ1vJ1u1BmtIufh1
75 ...
76 Content-Disposition: attachment; filename="formdata.h"
77 Content-Type: application/octet-stream
78 ...
79 Content-Disposition: attachment; filename="Makefile.b32"
80 Content-Type: application/octet-stream
81 ...
82 Content-Disposition: attachment; filename="formdata.h"
83 Content-Type: application/octet-stream
84 ...
85
86
87 Content-Disposition: form-data; name="ARRAY: FILE1_+_FILE2_+_FILE3"
88 Content-Type: multipart/mixed, boundary=curlirkYPmPwu6FrJ1vJ1u1BmtIufh1
89 ...
90 Content-Disposition: attachment; filename="formdata.h"
91 Content-Type: application/octet-stream
92 ...
93 Content-Disposition: attachment; filename="Makefile.b32"
94 Content-Type: application/octet-stream
95 ...
96 Content-Disposition: attachment; filename="formdata.h"
97 Content-Type: application/octet-stream
98 ...
99
100 Content-Disposition: form-data; name="FILECONTENT"
101 ...
102
103  */
104
105 #include "setup.h"
106 #include <curl/curl.h>
107
108 /* Length of the random boundary string. */
109 #define BOUNDARY_LENGTH 40
110
111 #if !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY)
112
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <stdarg.h>
117 #include <time.h>
118 #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
119 #include <libgen.h>
120 #endif
121 #include "urldata.h" /* for struct SessionHandle */
122 #include "easyif.h" /* for Curl_convert_... prototypes */
123 #include "formdata.h"
124 #include "curl_rand.h"
125 #include "strequal.h"
126 #include "curl_memory.h"
127
128 #define _MPRINTF_REPLACE /* use our functions only */
129 #include <curl/mprintf.h>
130
131 /* The last #include file should be: */
132 #include "memdebug.h"
133
134 #endif  /* !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY) */
135
136 #ifndef CURL_DISABLE_HTTP
137
138 #ifndef HAVE_BASENAME
139 static char *Curl_basename(char *path);
140 #define basename(x)  Curl_basename((x))
141 #endif
142
143 static size_t readfromfile(struct Form *form, char *buffer, size_t size);
144
145 /* What kind of Content-Type to use on un-specified files with unrecognized
146    extensions. */
147 #define HTTPPOST_CONTENTTYPE_DEFAULT "application/octet-stream"
148
149 #define FORM_FILE_SEPARATOR ','
150 #define FORM_TYPE_SEPARATOR ';'
151
152 /***************************************************************************
153  *
154  * AddHttpPost()
155  *
156  * Adds a HttpPost structure to the list, if parent_post is given becomes
157  * a subpost of parent_post instead of a direct list element.
158  *
159  * Returns newly allocated HttpPost on success and NULL if malloc failed.
160  *
161  ***************************************************************************/
162 static struct curl_httppost *
163 AddHttpPost(char *name, size_t namelength,
164             char *value, size_t contentslength,
165             char *buffer, size_t bufferlength,
166             char *contenttype,
167             long flags,
168             struct curl_slist* contentHeader,
169             char *showfilename, char *userp,
170             struct curl_httppost *parent_post,
171             struct curl_httppost **httppost,
172             struct curl_httppost **last_post)
173 {
174   struct curl_httppost *post;
175   post = calloc(sizeof(struct curl_httppost), 1);
176   if(post) {
177     post->name = name;
178     post->namelength = (long)(name?(namelength?namelength:strlen(name)):0);
179     post->contents = value;
180     post->contentslength = (long)contentslength;
181     post->buffer = buffer;
182     post->bufferlength = (long)bufferlength;
183     post->contenttype = contenttype;
184     post->contentheader = contentHeader;
185     post->showfilename = showfilename;
186     post->userp = userp,
187     post->flags = flags;
188   }
189   else
190     return NULL;
191
192   if(parent_post) {
193     /* now, point our 'more' to the original 'more' */
194     post->more = parent_post->more;
195
196     /* then move the original 'more' to point to ourselves */
197     parent_post->more = post;
198   }
199   else {
200     /* make the previous point to this */
201     if(*last_post)
202       (*last_post)->next = post;
203     else
204       (*httppost) = post;
205
206     (*last_post) = post;
207   }
208   return post;
209 }
210
211 /***************************************************************************
212  *
213  * AddFormInfo()
214  *
215  * Adds a FormInfo structure to the list presented by parent_form_info.
216  *
217  * Returns newly allocated FormInfo on success and NULL if malloc failed/
218  * parent_form_info is NULL.
219  *
220  ***************************************************************************/
221 static FormInfo * AddFormInfo(char *value,
222                               char *contenttype,
223                               FormInfo *parent_form_info)
224 {
225   FormInfo *form_info;
226   form_info = calloc(sizeof(FormInfo), 1);
227   if(form_info) {
228     if(value)
229       form_info->value = value;
230     if(contenttype)
231       form_info->contenttype = contenttype;
232     form_info->flags = HTTPPOST_FILENAME;
233   }
234   else
235     return NULL;
236
237   if(parent_form_info) {
238     /* now, point our 'more' to the original 'more' */
239     form_info->more = parent_form_info->more;
240
241     /* then move the original 'more' to point to ourselves */
242     parent_form_info->more = form_info;
243   }
244   else
245     return NULL;
246
247   return form_info;
248 }
249
250 /***************************************************************************
251  *
252  * ContentTypeForFilename()
253  *
254  * Provides content type for filename if one of the known types (else
255  * (either the prevtype or the default is returned).
256  *
257  * Returns some valid contenttype for filename.
258  *
259  ***************************************************************************/
260 static const char * ContentTypeForFilename (const char *filename,
261                                             const char *prevtype)
262 {
263   const char *contenttype = NULL;
264   unsigned int i;
265   /*
266    * No type was specified, we scan through a few well-known
267    * extensions and pick the first we match!
268    */
269   struct ContentType {
270     char extension[6];
271     const char *type;
272   };
273   static const struct ContentType ctts[]={
274     {".gif",  "image/gif"},
275     {".jpg",  "image/jpeg"},
276     {".jpeg", "image/jpeg"},
277     {".txt",  "text/plain"},
278     {".html", "text/html"},
279     {".xml", "application/xml"}
280   };
281
282   if(prevtype)
283     /* default to the previously set/used! */
284     contenttype = prevtype;
285   else
286     contenttype = HTTPPOST_CONTENTTYPE_DEFAULT;
287
288   if(filename) { /* in case a NULL was passed in */
289     for(i=0; i<sizeof(ctts)/sizeof(ctts[0]); i++) {
290       if(strlen(filename) >= strlen(ctts[i].extension)) {
291         if(strequal(filename +
292                     strlen(filename) - strlen(ctts[i].extension),
293                     ctts[i].extension)) {
294           contenttype = ctts[i].type;
295           break;
296         }
297       }
298     }
299   }
300   /* we have a contenttype by now */
301   return contenttype;
302 }
303
304 /***************************************************************************
305  *
306  * memdup()
307  *
308  * Copies the 'source' data to a newly allocated buffer buffer (that is
309  * returned). Uses buffer_length if not null, else uses strlen to determine
310  * the length of the buffer to be copied
311  *
312  * Returns the new pointer or NULL on failure.
313  *
314  ***************************************************************************/
315 static char *memdup(const char *src, size_t buffer_length)
316 {
317   size_t length;
318   bool add = FALSE;
319   char *buffer;
320
321   if(buffer_length)
322     length = buffer_length;
323   else if(src) {
324     length = strlen(src);
325     add = TRUE;
326   }
327   else
328     /* no length and a NULL src pointer! */
329     return strdup("");
330
331   buffer = malloc(length+add);
332   if(!buffer)
333     return NULL; /* fail */
334
335   memcpy(buffer, src, length);
336
337   /* if length unknown do null termination */
338   if(add)
339     buffer[length] = '\0';
340
341   return buffer;
342 }
343
344 /***************************************************************************
345  *
346  * FormAdd()
347  *
348  * Stores a formpost parameter and builds the appropriate linked list.
349  *
350  * Has two principal functionalities: using files and byte arrays as
351  * post parts. Byte arrays are either copied or just the pointer is stored
352  * (as the user requests) while for files only the filename and not the
353  * content is stored.
354  *
355  * While you may have only one byte array for each name, multiple filenames
356  * are allowed (and because of this feature CURLFORM_END is needed after
357  * using CURLFORM_FILE).
358  *
359  * Examples:
360  *
361  * Simple name/value pair with copied contents:
362  * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
363  * CURLFORM_COPYCONTENTS, "value", CURLFORM_END);
364  *
365  * name/value pair where only the content pointer is remembered:
366  * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
367  * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END);
368  * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used)
369  *
370  * storing a filename (CONTENTTYPE is optional!):
371  * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
372  * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text",
373  * CURLFORM_END);
374  *
375  * storing multiple filenames:
376  * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
377  * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END);
378  *
379  * Returns:
380  * CURL_FORMADD_OK             on success
381  * CURL_FORMADD_MEMORY         if the FormInfo allocation fails
382  * CURL_FORMADD_OPTION_TWICE   if one option is given twice for one Form
383  * CURL_FORMADD_NULL           if a null pointer was given for a char
384  * CURL_FORMADD_MEMORY         if the allocation of a FormInfo struct failed
385  * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
386  * CURL_FORMADD_INCOMPLETE     if the some FormInfo is not complete (or an error)
387  * CURL_FORMADD_MEMORY         if a HttpPost struct cannot be allocated
388  * CURL_FORMADD_MEMORY         if some allocation for string copying failed.
389  * CURL_FORMADD_ILLEGAL_ARRAY  if an illegal option is used in an array
390  *
391  ***************************************************************************/
392
393 static
394 CURLFORMcode FormAdd(struct curl_httppost **httppost,
395                      struct curl_httppost **last_post,
396                      va_list params)
397 {
398   FormInfo *first_form, *current_form, *form = NULL;
399   CURLFORMcode return_value = CURL_FORMADD_OK;
400   const char *prevtype = NULL;
401   struct curl_httppost *post = NULL;
402   CURLformoption option;
403   struct curl_forms *forms = NULL;
404   char *array_value=NULL; /* value read from an array */
405
406   /* This is a state variable, that if TRUE means that we're parsing an
407      array that we got passed to us. If FALSE we're parsing the input
408      va_list arguments. */
409   bool array_state = FALSE;
410
411   /*
412    * We need to allocate the first struct to fill in.
413    */
414   first_form = calloc(sizeof(struct FormInfo), 1);
415   if(!first_form)
416     return CURL_FORMADD_MEMORY;
417
418   current_form = first_form;
419
420   /*
421    * Loop through all the options set. Break if we have an error to report.
422    */
423   while(return_value == CURL_FORMADD_OK) {
424
425     /* first see if we have more parts of the array param */
426     if( array_state && forms ) {
427       /* get the upcoming option from the given array */
428       option = forms->option;
429       array_value = (char *)forms->value;
430
431       forms++; /* advance this to next entry */
432       if(CURLFORM_END == option) {
433         /* end of array state */
434         array_state = FALSE;
435         continue;
436       }
437     }
438     else {
439       /* This is not array-state, get next option */
440       option = va_arg(params, CURLformoption);
441       if(CURLFORM_END == option)
442         break;
443     }
444
445     switch (option) {
446     case CURLFORM_ARRAY:
447       if(array_state)
448         /* we don't support an array from within an array */
449         return_value = CURL_FORMADD_ILLEGAL_ARRAY;
450       else {
451         forms = va_arg(params, struct curl_forms *);
452         if(forms)
453           array_state = TRUE;
454         else
455           return_value = CURL_FORMADD_NULL;
456       }
457       break;
458
459       /*
460        * Set the Name property.
461        */
462     case CURLFORM_PTRNAME:
463 #ifdef CURL_DOES_CONVERSIONS
464       /* treat CURLFORM_PTR like CURLFORM_COPYNAME so we'll
465          have safe memory for the eventual conversion */
466 #else
467       current_form->flags |= HTTPPOST_PTRNAME; /* fall through */
468 #endif
469     case CURLFORM_COPYNAME:
470       if(current_form->name)
471         return_value = CURL_FORMADD_OPTION_TWICE;
472       else {
473         char *name = array_state?
474           array_value:va_arg(params, char *);
475         if(name)
476           current_form->name = name; /* store for the moment */
477         else
478           return_value = CURL_FORMADD_NULL;
479       }
480       break;
481     case CURLFORM_NAMELENGTH:
482       if(current_form->namelength)
483         return_value = CURL_FORMADD_OPTION_TWICE;
484       else
485         current_form->namelength =
486           array_state?(size_t)array_value:(size_t)va_arg(params, long);
487       break;
488
489       /*
490        * Set the contents property.
491        */
492     case CURLFORM_PTRCONTENTS:
493       current_form->flags |= HTTPPOST_PTRCONTENTS; /* fall through */
494     case CURLFORM_COPYCONTENTS:
495       if(current_form->value)
496         return_value = CURL_FORMADD_OPTION_TWICE;
497       else {
498         char *value =
499           array_state?array_value:va_arg(params, char *);
500         if(value)
501           current_form->value = value; /* store for the moment */
502         else
503           return_value = CURL_FORMADD_NULL;
504       }
505       break;
506     case CURLFORM_CONTENTSLENGTH:
507       if(current_form->contentslength)
508         return_value = CURL_FORMADD_OPTION_TWICE;
509       else
510         current_form->contentslength =
511           array_state?(size_t)array_value:(size_t)va_arg(params, long);
512       break;
513
514       /* Get contents from a given file name */
515     case CURLFORM_FILECONTENT:
516       if(current_form->flags != 0)
517         return_value = CURL_FORMADD_OPTION_TWICE;
518       else {
519         const char *filename = array_state?
520           array_value:va_arg(params, char *);
521         if(filename) {
522           current_form->value = strdup(filename);
523           if(!current_form->value)
524             return_value = CURL_FORMADD_MEMORY;
525           else {
526             current_form->flags |= HTTPPOST_READFILE;
527             current_form->value_alloc = TRUE;
528           }
529         }
530         else
531           return_value = CURL_FORMADD_NULL;
532       }
533       break;
534
535       /* We upload a file */
536     case CURLFORM_FILE:
537       {
538         const char *filename = array_state?array_value:
539           va_arg(params, char *);
540
541         if(current_form->value) {
542           if(current_form->flags & HTTPPOST_FILENAME) {
543             if(filename) {
544               if((current_form = AddFormInfo(strdup(filename),
545                                               NULL, current_form)) == NULL)
546                 return_value = CURL_FORMADD_MEMORY;
547             }
548             else
549               return_value = CURL_FORMADD_NULL;
550           }
551           else
552             return_value = CURL_FORMADD_OPTION_TWICE;
553         }
554         else {
555           if(filename) {
556             current_form->value = strdup(filename);
557             if(!current_form->value)
558               return_value = CURL_FORMADD_MEMORY;
559             else {
560               current_form->flags |= HTTPPOST_FILENAME;
561               current_form->value_alloc = TRUE;
562             }
563           }
564           else
565             return_value = CURL_FORMADD_NULL;
566         }
567         break;
568       }
569
570     case CURLFORM_BUFFER:
571       {
572         const char *filename = array_state?array_value:
573           va_arg(params, char *);
574
575         if(current_form->value) {
576           if(current_form->flags & HTTPPOST_BUFFER) {
577             if(filename) {
578               if((current_form = AddFormInfo(strdup(filename),
579                                               NULL, current_form)) == NULL)
580                 return_value = CURL_FORMADD_MEMORY;
581             }
582             else
583               return_value = CURL_FORMADD_NULL;
584           }
585           else
586             return_value = CURL_FORMADD_OPTION_TWICE;
587         }
588         else {
589           if(filename) {
590             current_form->value = strdup(filename);
591             if(!current_form->value)
592               return_value = CURL_FORMADD_MEMORY;
593           }
594           else
595             return_value = CURL_FORMADD_NULL;
596           current_form->flags |= HTTPPOST_BUFFER;
597         }
598         break;
599       }
600
601     case CURLFORM_BUFFERPTR:
602       current_form->flags |= HTTPPOST_PTRBUFFER;
603       if(current_form->buffer)
604         return_value = CURL_FORMADD_OPTION_TWICE;
605       else {
606         char *buffer =
607           array_state?array_value:va_arg(params, char *);
608         if(buffer)
609           current_form->buffer = buffer; /* store for the moment */
610         else
611           return_value = CURL_FORMADD_NULL;
612       }
613       break;
614
615     case CURLFORM_BUFFERLENGTH:
616       if(current_form->bufferlength)
617         return_value = CURL_FORMADD_OPTION_TWICE;
618       else
619         current_form->bufferlength =
620           array_state?(size_t)array_value:(size_t)va_arg(params, long);
621       break;
622
623     case CURLFORM_STREAM:
624       current_form->flags |= HTTPPOST_CALLBACK;
625       if(current_form->userp)
626         return_value = CURL_FORMADD_OPTION_TWICE;
627       else {
628         char *userp =
629           array_state?array_value:va_arg(params, char *);
630         if(userp) {
631           current_form->userp = userp;
632           current_form->value = userp; /* this isn't strictly true but we
633                                           derive a value from this later on
634                                           and we need this non-NULL to be
635                                           accepted as a fine form part */
636         }
637         else
638           return_value = CURL_FORMADD_NULL;
639       }
640       break;
641
642     case CURLFORM_CONTENTTYPE:
643       {
644         const char *contenttype =
645           array_state?array_value:va_arg(params, char *);
646         if(current_form->contenttype) {
647           if(current_form->flags & HTTPPOST_FILENAME) {
648             if(contenttype) {
649               if((current_form = AddFormInfo(NULL,
650                                               strdup(contenttype),
651                                               current_form)) == NULL)
652                 return_value = CURL_FORMADD_MEMORY;
653             }
654             else
655               return_value = CURL_FORMADD_NULL;
656           }
657           else
658             return_value = CURL_FORMADD_OPTION_TWICE;
659         }
660         else {
661           if(contenttype) {
662             current_form->contenttype = strdup(contenttype);
663             if(!current_form->contenttype)
664               return_value = CURL_FORMADD_MEMORY;
665             else
666               current_form->contenttype_alloc = TRUE;
667           }
668           else
669             return_value = CURL_FORMADD_NULL;
670         }
671         break;
672       }
673     case CURLFORM_CONTENTHEADER:
674       {
675         /* this "cast increases required alignment of target type" but
676            we consider it OK anyway */
677         struct curl_slist* list = array_state?
678           (struct curl_slist*)array_value:
679           va_arg(params, struct curl_slist*);
680
681         if( current_form->contentheader )
682           return_value = CURL_FORMADD_OPTION_TWICE;
683         else
684           current_form->contentheader = list;
685
686         break;
687       }
688     case CURLFORM_FILENAME:
689       {
690         const char *filename = array_state?array_value:
691           va_arg(params, char *);
692         if( current_form->showfilename )
693           return_value = CURL_FORMADD_OPTION_TWICE;
694         else {
695           current_form->showfilename = strdup(filename);
696           if(!current_form->showfilename)
697             return_value = CURL_FORMADD_MEMORY;
698           else
699             current_form->showfilename_alloc = TRUE;
700         }
701         break;
702       }
703     default:
704       return_value = CURL_FORMADD_UNKNOWN_OPTION;
705     }
706   }
707
708   if(CURL_FORMADD_OK == return_value) {
709     /* go through the list, check for completeness and if everything is
710      * alright add the HttpPost item otherwise set return_value accordingly */
711
712     post = NULL;
713     for(form = first_form;
714         form != NULL;
715         form = form->more) {
716       if( ((!form->name || !form->value) && !post) ||
717           ( (form->contentslength) &&
718             (form->flags & HTTPPOST_FILENAME) ) ||
719           ( (form->flags & HTTPPOST_FILENAME) &&
720             (form->flags & HTTPPOST_PTRCONTENTS) ) ||
721
722           ( (!form->buffer) &&
723             (form->flags & HTTPPOST_BUFFER) &&
724             (form->flags & HTTPPOST_PTRBUFFER) ) ||
725
726           ( (form->flags & HTTPPOST_READFILE) &&
727             (form->flags & HTTPPOST_PTRCONTENTS) )
728         ) {
729         return_value = CURL_FORMADD_INCOMPLETE;
730         break;
731       }
732       else {
733         if( ((form->flags & HTTPPOST_FILENAME) ||
734               (form->flags & HTTPPOST_BUFFER)) &&
735              !form->contenttype ) {
736           /* our contenttype is missing */
737           form->contenttype
738             = strdup(ContentTypeForFilename(form->value, prevtype));
739           if(!form->contenttype) {
740             return_value = CURL_FORMADD_MEMORY;
741             break;
742           }
743           form->contenttype_alloc = TRUE;
744         }
745         if( !(form->flags & HTTPPOST_PTRNAME) &&
746              (form == first_form) ) {
747           /* Note that there's small risk that form->name is NULL here if the
748              app passed in a bad combo, so we better check for that first. */
749           if(form->name)
750             /* copy name (without strdup; possibly contains null characters) */
751             form->name = memdup(form->name, form->namelength);
752           if(!form->name) {
753             return_value = CURL_FORMADD_MEMORY;
754             break;
755           }
756           form->name_alloc = TRUE;
757         }
758         if( !(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE |
759                              HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER |
760                              HTTPPOST_CALLBACK)) ) {
761           /* copy value (without strdup; possibly contains null characters) */
762           form->value = memdup(form->value, form->contentslength);
763           if(!form->value) {
764             return_value = CURL_FORMADD_MEMORY;
765             break;
766           }
767           form->value_alloc = TRUE;
768         }
769         post = AddHttpPost(form->name, form->namelength,
770                            form->value, form->contentslength,
771                            form->buffer, form->bufferlength,
772                            form->contenttype, form->flags,
773                            form->contentheader, form->showfilename,
774                            form->userp,
775                            post, httppost,
776                            last_post);
777
778         if(!post) {
779           return_value = CURL_FORMADD_MEMORY;
780           break;
781         }
782
783         if(form->contenttype)
784           prevtype = form->contenttype;
785       }
786     }
787   }
788
789   if(return_value) {
790     /* we return on error, free possibly allocated fields */
791     if(!form)
792       form = current_form;
793     if(form) {
794       if(form->name_alloc)
795         free(form->name);
796       if(form->value_alloc)
797         free(form->value);
798       if(form->contenttype_alloc)
799         free(form->contenttype);
800       if(form->showfilename_alloc)
801         free(form->showfilename);
802     }
803   }
804
805   /* always delete the allocated memory before returning */
806   form = first_form;
807   while(form != NULL) {
808     FormInfo *delete_form;
809
810     delete_form = form;
811     form = form->more;
812     free (delete_form);
813   }
814
815   return return_value;
816 }
817
818 /*
819  * curl_formadd() is a public API to add a section to the multipart formpost.
820  */
821
822 CURLFORMcode curl_formadd(struct curl_httppost **httppost,
823                           struct curl_httppost **last_post,
824                           ...)
825 {
826   va_list arg;
827   CURLFORMcode result;
828   va_start(arg, last_post);
829   result = FormAdd(httppost, last_post, arg);
830   va_end(arg);
831   return result;
832 }
833
834 /*
835  * AddFormData() adds a chunk of data to the FormData linked list.
836  *
837  * size is incremented by the chunk length, unless it is NULL
838  */
839 static CURLcode AddFormData(struct FormData **formp,
840                             enum formtype type,
841                             const void *line,
842                             size_t length,
843                             curl_off_t *size)
844 {
845   struct FormData *newform = malloc(sizeof(struct FormData));
846   if(!newform)
847     return CURLE_OUT_OF_MEMORY;
848   newform->next = NULL;
849
850   if(type <= FORM_CONTENT) {
851     /* we make it easier for plain strings: */
852     if(!length)
853       length = strlen((char *)line);
854
855     newform->line = malloc(length+1);
856     if(!newform->line) {
857       free(newform);
858       return CURLE_OUT_OF_MEMORY;
859     }
860     memcpy(newform->line, line, length);
861     newform->length = length;
862     newform->line[length]=0; /* zero terminate for easier debugging */
863   }
864   else
865     /* For callbacks and files we don't have any actual data so we just keep a
866        pointer to whatever this points to */
867     newform->line = (char *)line;
868
869   newform->type = type;
870
871   if(*formp) {
872     (*formp)->next = newform;
873     *formp = newform;
874   }
875   else
876     *formp = newform;
877
878   if(size) {
879     if(type != FORM_FILE)
880       /* for static content as well as callback data we add the size given
881          as input argument */
882       *size += length;
883     else {
884       /* Since this is a file to be uploaded here, add the size of the actual
885          file */
886       if(!strequal("-", newform->line)) {
887         struct_stat file;
888         if(!stat(newform->line, &file)) {
889           *size += file.st_size;
890         }
891       }
892     }
893   }
894   return CURLE_OK;
895 }
896
897 /*
898  * AddFormDataf() adds printf()-style formatted data to the formdata chain.
899  */
900
901 static CURLcode AddFormDataf(struct FormData **formp,
902                              curl_off_t *size,
903                              const char *fmt, ...)
904 {
905   char s[4096];
906   va_list ap;
907   va_start(ap, fmt);
908   vsnprintf(s, sizeof(s), fmt, ap);
909   va_end(ap);
910
911   return AddFormData(formp, FORM_DATA, s, 0, size);
912 }
913
914 /*
915  * Curl_formclean() is used from http.c, this cleans a built FormData linked
916  * list
917  */
918 void Curl_formclean(struct FormData **form_ptr)
919 {
920   struct FormData *next, *form;
921
922   form = *form_ptr;
923   if(!form)
924     return;
925
926   do {
927     next=form->next;  /* the following form line */
928     if(form->type <= FORM_CONTENT)
929       free(form->line); /* free the line */
930     free(form);       /* free the struct */
931
932   } while((form = next) != NULL); /* continue */
933
934   *form_ptr = NULL;
935 }
936
937 #ifdef CURL_DOES_CONVERSIONS
938 /*
939  * Curl_formcovert() is used from http.c, this converts any
940    form items that need to be sent in the network encoding.
941    Returns CURLE_OK on success.
942  */
943 CURLcode Curl_formconvert(struct SessionHandle *data, struct FormData *form)
944 {
945   struct FormData *next;
946   CURLcode rc;
947
948   if(!form)
949     return CURLE_OK;
950
951   if(!data)
952     return CURLE_BAD_FUNCTION_ARGUMENT;
953
954   do {
955     next=form->next;  /* the following form line */
956     if(form->type == FORM_DATA) {
957       rc = Curl_convert_to_network(data, form->line, form->length);
958       /* Curl_convert_to_network calls failf if unsuccessful */
959       if(rc != CURLE_OK)
960         return rc;
961     }
962   } while((form = next) != NULL); /* continue */
963   return CURLE_OK;
964 }
965 #endif /* CURL_DOES_CONVERSIONS */
966
967 /*
968  * curl_formget()
969  * Serialize a curl_httppost struct.
970  * Returns 0 on success.
971  */
972 int curl_formget(struct curl_httppost *form, void *arg,
973                  curl_formget_callback append)
974 {
975   CURLcode rc;
976   curl_off_t size;
977   struct FormData *data, *ptr;
978
979   rc = Curl_getFormData(&data, form, NULL, &size);
980   if(rc != CURLE_OK)
981     return (int)rc;
982
983   for (ptr = data; ptr; ptr = ptr->next) {
984     if(ptr->type == FORM_FILE) {
985       char buffer[8192];
986       size_t nread;
987       struct Form temp;
988
989       Curl_FormInit(&temp, ptr);
990
991       do {
992         nread = readfromfile(&temp, buffer, sizeof(buffer));
993         if((nread == (size_t) -1) || (nread != append(arg, buffer, nread))) {
994           if(temp.fp) {
995             fclose(temp.fp);
996           }
997           Curl_formclean(&data);
998           return -1;
999         }
1000       } while(nread == sizeof(buffer));
1001     } else {
1002       if(ptr->length != append(arg, ptr->line, ptr->length)) {
1003         Curl_formclean(&data);
1004         return -1;
1005       }
1006     }
1007   }
1008   Curl_formclean(&data);
1009   return 0;
1010 }
1011
1012 /*
1013  * curl_formfree() is an external function to free up a whole form post
1014  * chain
1015  */
1016 void curl_formfree(struct curl_httppost *form)
1017 {
1018   struct curl_httppost *next;
1019
1020   if(!form)
1021     /* no form to free, just get out of this */
1022     return;
1023
1024   do {
1025     next=form->next;  /* the following form line */
1026
1027     /* recurse to sub-contents */
1028     if(form->more)
1029       curl_formfree(form->more);
1030
1031     if( !(form->flags & HTTPPOST_PTRNAME) && form->name)
1032       free(form->name); /* free the name */
1033     if( !(form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_CALLBACK)) &&
1034         form->contents)
1035       free(form->contents); /* free the contents */
1036     if(form->contenttype)
1037       free(form->contenttype); /* free the content type */
1038     if(form->showfilename)
1039       free(form->showfilename); /* free the faked file name */
1040     free(form);       /* free the struct */
1041
1042   } while((form = next) != NULL); /* continue */
1043 }
1044
1045 #ifndef HAVE_BASENAME
1046 /*
1047   (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004
1048   Edition)
1049
1050   The basename() function shall take the pathname pointed to by path and
1051   return a pointer to the final component of the pathname, deleting any
1052   trailing '/' characters.
1053
1054   If the string pointed to by path consists entirely of the '/' character,
1055   basename() shall return a pointer to the string "/". If the string pointed
1056   to by path is exactly "//", it is implementation-defined whether '/' or "//"
1057   is returned.
1058
1059   If path is a null pointer or points to an empty string, basename() shall
1060   return a pointer to the string ".".
1061
1062   The basename() function may modify the string pointed to by path, and may
1063   return a pointer to static storage that may then be overwritten by a
1064   subsequent call to basename().
1065
1066   The basename() function need not be reentrant. A function that is not
1067   required to be reentrant is not required to be thread-safe.
1068
1069 */
1070 static char *Curl_basename(char *path)
1071 {
1072   /* Ignore all the details above for now and make a quick and simple
1073      implementaion here */
1074   char *s1;
1075   char *s2;
1076
1077   s1=strrchr(path, '/');
1078   s2=strrchr(path, '\\');
1079
1080   if(s1 && s2) {
1081     path = (s1 > s2? s1 : s2)+1;
1082   }
1083   else if(s1)
1084     path = s1 + 1;
1085   else if(s2)
1086     path = s2 + 1;
1087
1088   return path;
1089 }
1090 #endif
1091
1092 static char *strippath(const char *fullfile)
1093 {
1094   char *filename;
1095   char *base;
1096   filename = strdup(fullfile); /* duplicate since basename() may ruin the
1097                                   buffer it works on */
1098   if(!filename)
1099     return NULL;
1100   base = strdup(basename(filename));
1101
1102   free(filename); /* free temporary buffer */
1103
1104   return base; /* returns an allocated string or NULL ! */
1105 }
1106
1107 /*
1108  * Curl_getFormData() converts a linked list of "meta data" into a complete
1109  * (possibly huge) multipart formdata. The input list is in 'post', while the
1110  * output resulting linked lists gets stored in '*finalform'. *sizep will get
1111  * the total size of the whole POST.
1112  * A multipart/form_data content-type is built, unless a custom content-type
1113  * is passed in 'custom_content_type'.
1114  */
1115
1116 CURLcode Curl_getFormData(struct FormData **finalform,
1117                           struct curl_httppost *post,
1118                           const char *custom_content_type,
1119                           curl_off_t *sizep)
1120 {
1121   struct FormData *form = NULL;
1122   struct FormData *firstform;
1123   struct curl_httppost *file;
1124   CURLcode result = CURLE_OK;
1125
1126   curl_off_t size=0; /* support potentially ENORMOUS formposts */
1127   char *boundary;
1128   char *fileboundary=NULL;
1129   struct curl_slist* curList;
1130
1131   *finalform=NULL; /* default form is empty */
1132
1133   if(!post)
1134     return result; /* no input => no output! */
1135
1136   boundary = Curl_FormBoundary();
1137   if(!boundary)
1138     return CURLE_OUT_OF_MEMORY;
1139
1140   /* Make the first line of the output */
1141   result = AddFormDataf(&form, NULL,
1142                         "%s; boundary=%s\r\n",
1143                         custom_content_type?custom_content_type:
1144                         "Content-Type: multipart/form-data",
1145                         boundary);
1146
1147   if(result) {
1148     free(boundary);
1149     return result;
1150   }
1151   /* we DO NOT include that line in the total size of the POST, since it'll be
1152      part of the header! */
1153
1154   firstform = form;
1155
1156   do {
1157
1158     if(size) {
1159       result = AddFormDataf(&form, &size, "\r\n");
1160       if(result)
1161         break;
1162     }
1163
1164     /* boundary */
1165     result = AddFormDataf(&form, &size, "--%s\r\n", boundary);
1166     if(result)
1167       break;
1168
1169     /* Maybe later this should be disabled when a custom_content_type is
1170        passed, since Content-Disposition is not meaningful for all multipart
1171        types.
1172     */
1173     result = AddFormDataf(&form, &size,
1174                           "Content-Disposition: form-data; name=\"");
1175     if(result)
1176       break;
1177
1178     result = AddFormData(&form, FORM_DATA, post->name, post->namelength,
1179                          &size);
1180     if(result)
1181       break;
1182
1183     result = AddFormDataf(&form, &size, "\"");
1184     if(result)
1185       break;
1186
1187     if(post->more) {
1188       /* If used, this is a link to more file names, we must then do
1189          the magic to include several files with the same field name */
1190
1191       fileboundary = Curl_FormBoundary();
1192
1193       result = AddFormDataf(&form, &size,
1194                             "\r\nContent-Type: multipart/mixed,"
1195                             " boundary=%s\r\n",
1196                             fileboundary);
1197       if(result)
1198         break;
1199     }
1200
1201     file = post;
1202
1203     do {
1204
1205       /* If 'showfilename' is set, that is a faked name passed on to us
1206          to use to in the formpost. If that is not set, the actually used
1207          local file name should be added. */
1208
1209       if(post->more) {
1210         /* if multiple-file */
1211         char *filebasename= NULL;
1212         if(!file->showfilename) {
1213           filebasename = strippath(file->contents);
1214           if(!filebasename) {
1215             Curl_formclean(&firstform);
1216             free(boundary);
1217             return CURLE_OUT_OF_MEMORY;
1218           }
1219         }
1220
1221         result = AddFormDataf(&form, &size,
1222                               "\r\n--%s\r\nContent-Disposition: "
1223                               "attachment; filename=\"%s\"",
1224                               fileboundary,
1225                               (file->showfilename?file->showfilename:
1226                                filebasename));
1227         if(filebasename)
1228           free(filebasename);
1229         if(result)
1230           break;
1231       }
1232       else if(post->flags & (HTTPPOST_FILENAME|HTTPPOST_BUFFER|
1233                              HTTPPOST_CALLBACK)) {
1234         /* it should be noted that for the HTTPPOST_FILENAME and
1235            HTTPPOST_CALLBACK cases the ->showfilename struct member is always
1236            assigned at this point */
1237         char *filebasename=
1238           (!post->showfilename)?strippath(post->contents):NULL;
1239
1240         result = AddFormDataf(&form, &size,
1241                               "; filename=\"%s\"",
1242                               (post->showfilename?post->showfilename:
1243                                filebasename));
1244         if(filebasename)
1245           free(filebasename);
1246
1247         if(result)
1248           break;
1249       }
1250
1251       if(file->contenttype) {
1252         /* we have a specified type */
1253         result = AddFormDataf(&form, &size,
1254                               "\r\nContent-Type: %s",
1255                               file->contenttype);
1256         if(result)
1257           break;
1258       }
1259
1260       curList = file->contentheader;
1261       while( curList ) {
1262         /* Process the additional headers specified for this form */
1263         result = AddFormDataf( &form, &size, "\r\n%s", curList->data );
1264         if(result)
1265           break;
1266         curList = curList->next;
1267       }
1268       if(result) {
1269         Curl_formclean(&firstform);
1270         free(boundary);
1271         return result;
1272       }
1273
1274 #if 0
1275       /* The header Content-Transfer-Encoding: seems to confuse some receivers
1276        * (like the built-in PHP engine). While I can't see any reason why it
1277        * should, I can just as well skip this to the benefit of the users who
1278        * are using such confused receivers.
1279        */
1280
1281       if(file->contenttype &&
1282          !checkprefix("text/", file->contenttype)) {
1283         /* this is not a text content, mention our binary encoding */
1284         result = AddFormDataf(&form, &size,
1285                               "\r\nContent-Transfer-Encoding: binary");
1286         if(result)
1287           break;
1288       }
1289 #endif
1290
1291       result = AddFormDataf(&form, &size, "\r\n\r\n");
1292       if(result)
1293         break;
1294
1295       if((post->flags & HTTPPOST_FILENAME) ||
1296          (post->flags & HTTPPOST_READFILE)) {
1297         /* we should include the contents from the specified file */
1298         FILE *fileread;
1299
1300         fileread = strequal("-", file->contents)?
1301           stdin:fopen(file->contents, "rb"); /* binary read for win32  */
1302
1303         /*
1304          * VMS: This only allows for stream files on VMS.  Stream files are
1305          * OK, as are FIXED & VAR files WITHOUT implied CC For implied CC,
1306          * every record needs to have a \n appended & 1 added to SIZE
1307          */
1308
1309         if(fileread) {
1310           if(fileread != stdin) {
1311             /* close the file again */
1312             fclose(fileread);
1313             /* add the file name only - for later reading from this */
1314             result = AddFormData(&form, FORM_FILE, file->contents, 0, &size);
1315           }
1316           else {
1317             /* When uploading from stdin, we can't know the size of the file,
1318              * thus must read the full file as before. We *could* use chunked
1319              * transfer-encoding, but that only works for HTTP 1.1 and we
1320              * can't be sure we work with such a server.
1321              */
1322             size_t nread;
1323             char buffer[512];
1324             while((nread = fread(buffer, 1, sizeof(buffer), fileread)) != 0) {
1325               result = AddFormData(&form, FORM_CONTENT, buffer, nread, &size);
1326               if(result)
1327                 break;
1328             }
1329           }
1330
1331           if(result) {
1332             Curl_formclean(&firstform);
1333             free(boundary);
1334             return result;
1335           }
1336
1337         }
1338         else {
1339 #ifdef _FORM_DEBUG
1340           fprintf(stderr,
1341                   "\n==> Curl_getFormData couldn't open/read \"%s\"\n",
1342                   file->contents);
1343 #endif
1344           Curl_formclean(&firstform);
1345           free(boundary);
1346           *finalform = NULL;
1347           return CURLE_READ_ERROR;
1348         }
1349
1350       }
1351       else if(post->flags & HTTPPOST_BUFFER) {
1352         /* include contents of buffer */
1353         result = AddFormData(&form, FORM_CONTENT, post->buffer,
1354                              post->bufferlength, &size);
1355           if(result)
1356             break;
1357       }
1358       else if(post->flags & HTTPPOST_CALLBACK) {
1359         /* the contents should be read with the callback and the size
1360            is set with the contentslength */
1361         result = AddFormData(&form, FORM_CALLBACK, post->userp,
1362                              post->contentslength, &size);
1363         if(result)
1364           break;
1365       }
1366       else {
1367         /* include the contents we got */
1368         result = AddFormData(&form, FORM_CONTENT, post->contents,
1369                              post->contentslength, &size);
1370         if(result)
1371           break;
1372       }
1373     } while((file = file->more) != NULL); /* for each specified file for this field */
1374     if(result) {
1375       Curl_formclean(&firstform);
1376       free(boundary);
1377       return result;
1378     }
1379
1380     if(post->more) {
1381       /* this was a multiple-file inclusion, make a termination file
1382          boundary: */
1383       result = AddFormDataf(&form, &size,
1384                            "\r\n--%s--",
1385                            fileboundary);
1386       free(fileboundary);
1387       if(result)
1388         break;
1389     }
1390
1391   } while((post = post->next) != NULL); /* for each field */
1392   if(result) {
1393     Curl_formclean(&firstform);
1394     free(boundary);
1395     return result;
1396   }
1397
1398   /* end-boundary for everything */
1399   result = AddFormDataf(&form, &size,
1400                        "\r\n--%s--\r\n",
1401                        boundary);
1402   if(result) {
1403     Curl_formclean(&firstform);
1404     free(boundary);
1405     return result;
1406   }
1407
1408   *sizep = size;
1409
1410   free(boundary);
1411
1412   *finalform=firstform;
1413
1414   return result;
1415 }
1416
1417 /*
1418  * Curl_FormInit() inits the struct 'form' points to with the 'formdata'
1419  * and resets the 'sent' counter.
1420  */
1421 int Curl_FormInit(struct Form *form, struct FormData *formdata )
1422 {
1423   if(!formdata)
1424     return 1; /* error */
1425
1426   form->data = formdata;
1427   form->sent = 0;
1428   form->fp = NULL;
1429   form->fread_func = ZERO_NULL;
1430
1431   return 0;
1432 }
1433
1434 static size_t readfromfile(struct Form *form, char *buffer,
1435                            size_t size)
1436 {
1437   size_t nread;
1438   bool callback = (bool)(form->data->type == FORM_CALLBACK);
1439
1440   if(callback)
1441     nread = form->fread_func(buffer, 1, size, form->data->line);
1442   else {
1443     if(!form->fp) {
1444       /* this file hasn't yet been opened */
1445       form->fp = fopen(form->data->line, "rb"); /* b is for binary */
1446       if(!form->fp)
1447         return (size_t)-1; /* failure */
1448     }
1449     nread = fread(buffer, 1, size, form->fp);
1450   }
1451   if(!nread || nread > size) {
1452     /* this is the last chunk from the file, move on */
1453     if(!callback) {
1454       fclose(form->fp);
1455       form->fp = NULL;
1456     }
1457     form->data = form->data->next;
1458   }
1459
1460   return nread;
1461 }
1462
1463 /*
1464  * Curl_FormReader() is the fread() emulation function that will be used to
1465  * deliver the formdata to the transfer loop and then sent away to the peer.
1466  */
1467 size_t Curl_FormReader(char *buffer,
1468                        size_t size,
1469                        size_t nitems,
1470                        FILE *mydata)
1471 {
1472   struct Form *form;
1473   size_t wantedsize;
1474   size_t gotsize = 0;
1475
1476   form=(struct Form *)mydata;
1477
1478   wantedsize = size * nitems;
1479
1480   if(!form->data)
1481     return 0; /* nothing, error, empty */
1482
1483   if((form->data->type == FORM_FILE) ||
1484      (form->data->type == FORM_CALLBACK)) {
1485     gotsize = readfromfile(form, buffer, wantedsize);
1486
1487     if(gotsize)
1488       /* If positive or -1, return. If zero, continue! */
1489       return gotsize;
1490   }
1491   do {
1492
1493     if( (form->data->length - form->sent ) > wantedsize - gotsize) {
1494
1495       memcpy(buffer + gotsize , form->data->line + form->sent,
1496              wantedsize - gotsize);
1497
1498       form->sent += wantedsize-gotsize;
1499
1500       return wantedsize;
1501     }
1502
1503     memcpy(buffer+gotsize,
1504            form->data->line + form->sent,
1505            (form->data->length - form->sent) );
1506     gotsize += form->data->length - form->sent;
1507
1508     form->sent = 0;
1509
1510     form->data = form->data->next; /* advance */
1511
1512   } while(form->data && (form->data->type < FORM_CALLBACK));
1513   /* If we got an empty line and we have more data, we proceed to the next
1514      line immediately to avoid returning zero before we've reached the end. */
1515
1516   return gotsize;
1517 }
1518
1519 /*
1520  * Curl_formpostheader() returns the first line of the formpost, the
1521  * request-header part (which is not part of the request-body like the rest of
1522  * the post).
1523  */
1524 char *Curl_formpostheader(void *formp, size_t *len)
1525 {
1526   char *header;
1527   struct Form *form=(struct Form *)formp;
1528
1529   if(!form->data)
1530     return 0; /* nothing, ERROR! */
1531
1532   header = form->data->line;
1533   *len = form->data->length;
1534
1535   form->data = form->data->next; /* advance */
1536
1537   return header;
1538 }
1539
1540
1541 #ifdef _FORM_DEBUG
1542 int FormAddTest(const char * errormsg,
1543                  struct curl_httppost **httppost,
1544                  struct curl_httppost **last_post,
1545                  ...)
1546 {
1547   int result;
1548   va_list arg;
1549   va_start(arg, last_post);
1550   if((result = FormAdd(httppost, last_post, arg)))
1551     fprintf (stderr, "ERROR doing FormAdd ret: %d action: %s\n", result,
1552              errormsg);
1553   va_end(arg);
1554   return result;
1555 }
1556
1557
1558 int main(int argc, argv_item_t argv[])
1559 {
1560   char name1[] = "simple_COPYCONTENTS";
1561   char name2[] = "COPYCONTENTS_+_CONTENTTYPE";
1562   char name3[] = "PTRNAME_+_NAMELENGTH_+_COPYNAME_+_CONTENTSLENGTH";
1563   char name4[] = "simple_PTRCONTENTS";
1564   char name5[] = "PTRCONTENTS_+_CONTENTSLENGTH";
1565   char name6[] = "PTRCONTENTS_+_CONTENTSLENGTH_+_CONTENTTYPE";
1566   char name7[] = "FILE1_+_CONTENTTYPE";
1567   char name8[] = "FILE1_+_FILE2";
1568   char name9[] = "FILE1_+_FILE2_+_FILE3";
1569   char name10[] = "ARRAY: FILE1_+_FILE2_+_FILE3";
1570   char name11[] = "FILECONTENT";
1571   char value1[] = "value for simple COPYCONTENTS";
1572   char value2[] = "value for COPYCONTENTS + CONTENTTYPE";
1573   char value3[] = "value for PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH";
1574   char value4[] = "value for simple PTRCONTENTS";
1575   char value5[] = "value for PTRCONTENTS + CONTENTSLENGTH";
1576   char value6[] = "value for PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE";
1577   char value7[] = "formdata.h";
1578   char value8[] = "Makefile.b32";
1579   char type2[] = "image/gif";
1580   char type6[] = "text/plain";
1581   char type7[] = "text/html";
1582   int name3length = strlen(name3);
1583   int value3length = strlen(value3);
1584   int value5length = strlen(value5);
1585   int value6length = strlen(value6);
1586   int errors = 0;
1587   CURLcode rc;
1588   curl_off_t size;
1589   size_t nread;
1590   char buffer[4096];
1591   struct curl_httppost *httppost=NULL;
1592   struct curl_httppost *last_post=NULL;
1593   struct curl_forms forms[4];
1594
1595   struct FormData *form;
1596   struct Form formread;
1597
1598   (void) argc;
1599   (void) argv;
1600
1601   Curl_srand();         /* Because we do not call curl_global_init() here. */
1602
1603   if(FormAddTest("simple COPYCONTENTS test", &httppost, &last_post,
1604                   CURLFORM_COPYNAME, name1, CURLFORM_COPYCONTENTS, value1,
1605                   CURLFORM_END))
1606     ++errors;
1607   if(FormAddTest("COPYCONTENTS  + CONTENTTYPE test", &httppost, &last_post,
1608                   CURLFORM_COPYNAME, name2, CURLFORM_COPYCONTENTS, value2,
1609                   CURLFORM_CONTENTTYPE, type2, CURLFORM_END))
1610     ++errors;
1611   /* make null character at start to check that contentslength works
1612      correctly */
1613   name3[1] = '\0';
1614   value3[1] = '\0';
1615   if(FormAddTest("PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH test",
1616                   &httppost, &last_post,
1617                   CURLFORM_PTRNAME, name3, CURLFORM_COPYCONTENTS, value3,
1618                   CURLFORM_CONTENTSLENGTH, value3length,
1619                   CURLFORM_NAMELENGTH, name3length, CURLFORM_END))
1620     ++errors;
1621   if(FormAddTest("simple PTRCONTENTS test", &httppost, &last_post,
1622                   CURLFORM_COPYNAME, name4, CURLFORM_PTRCONTENTS, value4,
1623                   CURLFORM_END))
1624     ++errors;
1625   /* make null character at start to check that contentslength works
1626      correctly */
1627   value5[1] = '\0';
1628   if(FormAddTest("PTRCONTENTS + CONTENTSLENGTH test", &httppost, &last_post,
1629                   CURLFORM_COPYNAME, name5, CURLFORM_PTRCONTENTS, value5,
1630                   CURLFORM_CONTENTSLENGTH, value5length, CURLFORM_END))
1631     ++errors;
1632   /* make null character at start to check that contentslength works
1633      correctly */
1634   value6[1] = '\0';
1635   if(FormAddTest("PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE test",
1636                   &httppost, &last_post,
1637                   CURLFORM_COPYNAME, name6, CURLFORM_PTRCONTENTS, value6,
1638                   CURLFORM_CONTENTSLENGTH, value6length,
1639                   CURLFORM_CONTENTTYPE, type6, CURLFORM_END))
1640     ++errors;
1641   if(FormAddTest("FILE + CONTENTTYPE test", &httppost, &last_post,
1642                   CURLFORM_COPYNAME, name7, CURLFORM_FILE, value7,
1643                   CURLFORM_CONTENTTYPE, type7, CURLFORM_END))
1644     ++errors;
1645   if(FormAddTest("FILE1 + FILE2 test", &httppost, &last_post,
1646                   CURLFORM_COPYNAME, name8, CURLFORM_FILE, value7,
1647                   CURLFORM_FILE, value8, CURLFORM_END))
1648     ++errors;
1649   if(FormAddTest("FILE1 + FILE2 + FILE3 test", &httppost, &last_post,
1650                   CURLFORM_COPYNAME, name9, CURLFORM_FILE, value7,
1651                   CURLFORM_FILE, value8, CURLFORM_FILE, value7, CURLFORM_END))
1652     ++errors;
1653   forms[0].option = CURLFORM_FILE;
1654   forms[0].value  = value7;
1655   forms[1].option = CURLFORM_FILE;
1656   forms[1].value  = value8;
1657   forms[2].option = CURLFORM_FILE;
1658   forms[2].value  = value7;
1659   forms[3].option  = CURLFORM_END;
1660   if(FormAddTest("FILE1 + FILE2 + FILE3 ARRAY test", &httppost, &last_post,
1661                   CURLFORM_COPYNAME, name10, CURLFORM_ARRAY, forms,
1662                   CURLFORM_END))
1663     ++errors;
1664   if(FormAddTest("FILECONTENT test", &httppost, &last_post,
1665                   CURLFORM_COPYNAME, name11, CURLFORM_FILECONTENT, value7,
1666                   CURLFORM_END))
1667     ++errors;
1668
1669   rc = Curl_getFormData(&form, httppost, NULL, &size);
1670   if(rc != CURLE_OK) {
1671     if(rc != CURLE_READ_ERROR) {
1672       const char *errortext = curl_easy_strerror(rc);
1673       fprintf(stdout, "\n==> Curl_getFormData error: %s\n", errortext);
1674     }
1675     return 0;
1676   }
1677
1678   Curl_FormInit(&formread, form);
1679
1680   do {
1681     nread = Curl_FormReader(buffer, 1, sizeof(buffer),
1682                             (FILE *)&formread);
1683
1684     if(nread < 1)
1685       break;
1686     fwrite(buffer, nread, 1, stdout);
1687   } while(1);
1688
1689   fprintf(stdout, "size: ");
1690   fprintf(stdout, "%" FORMAT_OFF_T, size);
1691   fprintf(stdout, "\n");
1692   if(errors)
1693     fprintf(stdout, "\n==> %d Test(s) failed!\n", errors);
1694   else
1695     fprintf(stdout, "\nAll Tests seem to have worked (please check output)\n");
1696
1697   return 0;
1698 }
1699
1700 #endif  /* _FORM_DEBUG */
1701
1702 #else  /* CURL_DISABLE_HTTP */
1703 CURLFORMcode curl_formadd(struct curl_httppost **httppost,
1704                           struct curl_httppost **last_post,
1705                           ...)
1706 {
1707   (void)httppost;
1708   (void)last_post;
1709   return CURL_FORMADD_DISABLED;
1710 }
1711
1712 int curl_formget(struct curl_httppost *form, void *arg,
1713                  curl_formget_callback append)
1714 {
1715   (void) form;
1716   (void) arg;
1717   (void) append;
1718   return CURL_FORMADD_DISABLED;
1719 }
1720
1721 void curl_formfree(struct curl_httppost *form)
1722 {
1723   (void)form;
1724   /* does nothing HTTP is disabled */
1725 }
1726
1727 #endif  /* CURL_DISABLE_HTTP */
1728
1729 #if !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY)
1730
1731 /*
1732  * Curl_FormBoundary() creates a suitable boundary string and returns an
1733  * allocated one. This is also used by SSL-code so it must be present even
1734  * if HTTP is disabled!
1735  */
1736 char *Curl_FormBoundary(void)
1737 {
1738   char *retstring;
1739   size_t i;
1740
1741   static const char table16[]="0123456789abcdef";
1742
1743   retstring = malloc(BOUNDARY_LENGTH+1);
1744
1745   if(!retstring)
1746     return NULL; /* failed */
1747
1748   strcpy(retstring, "----------------------------");
1749
1750   for(i=strlen(retstring); i<BOUNDARY_LENGTH; i++)
1751     retstring[i] = table16[Curl_rand()%16];
1752
1753   /* 28 dashes and 12 hexadecimal digits makes 12^16 (184884258895036416)
1754      combinations */
1755   retstring[BOUNDARY_LENGTH]=0; /* zero terminate */
1756
1757   return retstring;
1758 }
1759
1760 #endif  /* !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY) */