1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
24 Debug the form generator stand-alone by compiling this source file with:
26 gcc -DHAVE_CONFIG_H -I../ -g -D_FORM_DEBUG -DCURLDEBUG -o formdata \
27 -I../include formdata.c strequal.c memdebug.c mprintf.c strerror.c
29 (depending on circumstances you may need further externals added)
31 run the 'formdata' executable the output should end with:
32 All Tests seem to have worked ...
33 and the following parts should be there:
35 Content-Disposition: form-data; name="simple_COPYCONTENTS"
36 value for simple COPYCONTENTS
38 Content-Disposition: form-data; name="COPYCONTENTS_+_CONTENTTYPE"
39 Content-Type: image/gif
40 value for COPYCONTENTS + CONTENTTYPE
42 Content-Disposition: form-data; name="PRNAME_+_NAMELENGTH_+_COPYNAME_+_CONTENTSLENGTH"
43 vlue for PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH
44 (or you might see P^@RNAME and v^@lue at the start)
46 Content-Disposition: form-data; name="simple_PTRCONTENTS"
47 value for simple PTRCONTENTS
49 Content-Disposition: form-data; name="PTRCONTENTS_+_CONTENTSLENGTH"
50 vlue for PTRCONTENTS + CONTENTSLENGTH
51 (or you might see v^@lue at the start)
53 Content-Disposition: form-data; name="PTRCONTENTS_+_CONTENTSLENGTH_+_CONTENTTYPE"
54 Content-Type: application/octet-stream
55 vlue for PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE
56 (or you might see v^@lue at the start)
58 Content-Disposition: form-data; name="FILE1_+_CONTENTTYPE"; filename="formdata.h"
59 Content-Type: text/html
62 Content-Disposition: form-data; name="FILE1_+_FILE2"
63 Content-Type: multipart/mixed, boundary=curlz1s0dkticx49MV1KGcYP5cvfSsz
65 Content-Disposition: attachment; filename="formdata.h"
66 Content-Type: application/octet-stream
68 Content-Disposition: attachment; filename="Makefile.b32"
69 Content-Type: application/octet-stream
72 Content-Disposition: form-data; name="FILE1_+_FILE2_+_FILE3"
73 Content-Type: multipart/mixed, boundary=curlirkYPmPwu6FrJ1vJ1u1BmtIufh1
75 Content-Disposition: attachment; filename="formdata.h"
76 Content-Type: application/octet-stream
78 Content-Disposition: attachment; filename="Makefile.b32"
79 Content-Type: application/octet-stream
81 Content-Disposition: attachment; filename="formdata.h"
82 Content-Type: application/octet-stream
86 Content-Disposition: form-data; name="ARRAY: FILE1_+_FILE2_+_FILE3"
87 Content-Type: multipart/mixed, boundary=curlirkYPmPwu6FrJ1vJ1u1BmtIufh1
89 Content-Disposition: attachment; filename="formdata.h"
90 Content-Type: application/octet-stream
92 Content-Disposition: attachment; filename="Makefile.b32"
93 Content-Type: application/octet-stream
95 Content-Disposition: attachment; filename="formdata.h"
96 Content-Type: application/octet-stream
99 Content-Disposition: form-data; name="FILECONTENT"
105 #include <curl/curl.h>
107 /* Length of the random boundary string. */
108 #define BOUNDARY_LENGTH 40
110 #if !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY)
117 #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
120 #include "urldata.h" /* for struct SessionHandle */
121 #include "easyif.h" /* for Curl_convert_... prototypes */
122 #include "formdata.h"
123 #include "curl_rand.h"
124 #include "strequal.h"
125 #include "curl_memory.h"
128 #define _MPRINTF_REPLACE /* use our functions only */
129 #include <curl/mprintf.h>
131 /* The last #include file should be: */
132 #include "memdebug.h"
134 #endif /* !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY) */
136 #ifndef CURL_DISABLE_HTTP
138 #ifndef HAVE_BASENAME
139 static char *Curl_basename(char *path);
140 #define basename(x) Curl_basename((x))
143 static size_t readfromfile(struct Form *form, char *buffer, size_t size);
145 /* What kind of Content-Type to use on un-specified files with unrecognized
147 #define HTTPPOST_CONTENTTYPE_DEFAULT "application/octet-stream"
149 #define FORM_FILE_SEPARATOR ','
150 #define FORM_TYPE_SEPARATOR ';'
152 /***************************************************************************
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.
159 * Returns newly allocated HttpPost on success and NULL if malloc failed.
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,
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)
174 struct curl_httppost *post;
175 post = calloc(1, sizeof(struct curl_httppost));
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;
193 /* now, point our 'more' to the original 'more' */
194 post->more = parent_post->more;
196 /* then move the original 'more' to point to ourselves */
197 parent_post->more = post;
200 /* make the previous point to this */
202 (*last_post)->next = post;
211 /***************************************************************************
215 * Adds a FormInfo structure to the list presented by parent_form_info.
217 * Returns newly allocated FormInfo on success and NULL if malloc failed/
218 * parent_form_info is NULL.
220 ***************************************************************************/
221 static FormInfo * AddFormInfo(char *value,
223 FormInfo *parent_form_info)
226 form_info = calloc(1, sizeof(struct FormInfo));
229 form_info->value = value;
231 form_info->contenttype = contenttype;
232 form_info->flags = HTTPPOST_FILENAME;
237 if(parent_form_info) {
238 /* now, point our 'more' to the original 'more' */
239 form_info->more = parent_form_info->more;
241 /* then move the original 'more' to point to ourselves */
242 parent_form_info->more = form_info;
250 /***************************************************************************
252 * ContentTypeForFilename()
254 * Provides content type for filename if one of the known types (else
255 * (either the prevtype or the default is returned).
257 * Returns some valid contenttype for filename.
259 ***************************************************************************/
260 static const char * ContentTypeForFilename (const char *filename,
261 const char *prevtype)
263 const char *contenttype = NULL;
266 * No type was specified, we scan through a few well-known
267 * extensions and pick the first we match!
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"}
283 /* default to the previously set/used! */
284 contenttype = prevtype;
286 contenttype = HTTPPOST_CONTENTTYPE_DEFAULT;
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;
300 /* we have a contenttype by now */
304 /***************************************************************************
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
312 * Returns the new pointer or NULL on failure.
314 ***************************************************************************/
315 static char *memdup(const char *src, size_t buffer_length)
322 length = buffer_length;
324 length = strlen(src);
328 /* no length and a NULL src pointer! */
331 buffer = malloc(length+add);
333 return NULL; /* fail */
335 memcpy(buffer, src, length);
337 /* if length unknown do null termination */
339 buffer[length] = '\0';
344 /***************************************************************************
348 * Stores a formpost parameter and builds the appropriate linked list.
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
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).
361 * Simple name/value pair with copied contents:
362 * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
363 * CURLFORM_COPYCONTENTS, "value", CURLFORM_END);
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)
370 * storing a filename (CONTENTTYPE is optional!):
371 * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
372 * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text",
375 * storing multiple filenames:
376 * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
377 * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END);
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
391 ***************************************************************************/
394 CURLFORMcode FormAdd(struct curl_httppost **httppost,
395 struct curl_httppost **last_post,
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 */
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;
412 * We need to allocate the first struct to fill in.
414 first_form = calloc(1, sizeof(struct FormInfo));
416 return CURL_FORMADD_MEMORY;
418 current_form = first_form;
421 * Loop through all the options set. Break if we have an error to report.
423 while(return_value == CURL_FORMADD_OK) {
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;
431 forms++; /* advance this to next entry */
432 if(CURLFORM_END == option) {
433 /* end of array state */
439 /* This is not array-state, get next option */
440 option = va_arg(params, CURLformoption);
441 if(CURLFORM_END == option)
448 /* we don't support an array from within an array */
449 return_value = CURL_FORMADD_ILLEGAL_ARRAY;
451 forms = va_arg(params, struct curl_forms *);
455 return_value = CURL_FORMADD_NULL;
460 * Set the Name property.
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 */
467 current_form->flags |= HTTPPOST_PTRNAME; /* fall through */
469 case CURLFORM_COPYNAME:
470 if(current_form->name)
471 return_value = CURL_FORMADD_OPTION_TWICE;
473 char *name = array_state?
474 array_value:va_arg(params, char *);
476 current_form->name = name; /* store for the moment */
478 return_value = CURL_FORMADD_NULL;
481 case CURLFORM_NAMELENGTH:
482 if(current_form->namelength)
483 return_value = CURL_FORMADD_OPTION_TWICE;
485 current_form->namelength =
486 array_state?(size_t)array_value:(size_t)va_arg(params, long);
490 * Set the contents property.
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;
499 array_state?array_value:va_arg(params, char *);
501 current_form->value = value; /* store for the moment */
503 return_value = CURL_FORMADD_NULL;
506 case CURLFORM_CONTENTSLENGTH:
507 if(current_form->contentslength)
508 return_value = CURL_FORMADD_OPTION_TWICE;
510 current_form->contentslength =
511 array_state?(size_t)array_value:(size_t)va_arg(params, long);
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;
519 const char *filename = array_state?
520 array_value:va_arg(params, char *);
522 current_form->value = strdup(filename);
523 if(!current_form->value)
524 return_value = CURL_FORMADD_MEMORY;
526 current_form->flags |= HTTPPOST_READFILE;
527 current_form->value_alloc = TRUE;
531 return_value = CURL_FORMADD_NULL;
535 /* We upload a file */
538 const char *filename = array_state?array_value:
539 va_arg(params, char *);
541 if(current_form->value) {
542 if(current_form->flags & HTTPPOST_FILENAME) {
544 if((current_form = AddFormInfo(strdup(filename),
545 NULL, current_form)) == NULL)
546 return_value = CURL_FORMADD_MEMORY;
549 return_value = CURL_FORMADD_NULL;
552 return_value = CURL_FORMADD_OPTION_TWICE;
556 current_form->value = strdup(filename);
557 if(!current_form->value)
558 return_value = CURL_FORMADD_MEMORY;
560 current_form->flags |= HTTPPOST_FILENAME;
561 current_form->value_alloc = TRUE;
565 return_value = CURL_FORMADD_NULL;
570 case CURLFORM_BUFFER:
572 const char *filename = array_state?array_value:
573 va_arg(params, char *);
575 if(current_form->value) {
576 if(current_form->flags & HTTPPOST_BUFFER) {
578 if((current_form = AddFormInfo(strdup(filename),
579 NULL, current_form)) == NULL)
580 return_value = CURL_FORMADD_MEMORY;
583 return_value = CURL_FORMADD_NULL;
586 return_value = CURL_FORMADD_OPTION_TWICE;
590 current_form->value = strdup(filename);
591 if(!current_form->value)
592 return_value = CURL_FORMADD_MEMORY;
595 return_value = CURL_FORMADD_NULL;
596 current_form->flags |= HTTPPOST_BUFFER;
601 case CURLFORM_BUFFERPTR:
602 current_form->flags |= HTTPPOST_PTRBUFFER;
603 if(current_form->buffer)
604 return_value = CURL_FORMADD_OPTION_TWICE;
607 array_state?array_value:va_arg(params, char *);
609 current_form->buffer = buffer; /* store for the moment */
611 return_value = CURL_FORMADD_NULL;
615 case CURLFORM_BUFFERLENGTH:
616 if(current_form->bufferlength)
617 return_value = CURL_FORMADD_OPTION_TWICE;
619 current_form->bufferlength =
620 array_state?(size_t)array_value:(size_t)va_arg(params, long);
623 case CURLFORM_STREAM:
624 current_form->flags |= HTTPPOST_CALLBACK;
625 if(current_form->userp)
626 return_value = CURL_FORMADD_OPTION_TWICE;
629 array_state?array_value:va_arg(params, char *);
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 */
638 return_value = CURL_FORMADD_NULL;
642 case CURLFORM_CONTENTTYPE:
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) {
649 if((current_form = AddFormInfo(NULL,
651 current_form)) == NULL)
652 return_value = CURL_FORMADD_MEMORY;
655 return_value = CURL_FORMADD_NULL;
658 return_value = CURL_FORMADD_OPTION_TWICE;
662 current_form->contenttype = strdup(contenttype);
663 if(!current_form->contenttype)
664 return_value = CURL_FORMADD_MEMORY;
666 current_form->contenttype_alloc = TRUE;
669 return_value = CURL_FORMADD_NULL;
673 case CURLFORM_CONTENTHEADER:
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*);
681 if( current_form->contentheader )
682 return_value = CURL_FORMADD_OPTION_TWICE;
684 current_form->contentheader = list;
688 case CURLFORM_FILENAME:
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;
695 current_form->showfilename = strdup(filename);
696 if(!current_form->showfilename)
697 return_value = CURL_FORMADD_MEMORY;
699 current_form->showfilename_alloc = TRUE;
704 return_value = CURL_FORMADD_UNKNOWN_OPTION;
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 */
713 for(form = first_form;
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) ) ||
723 (form->flags & HTTPPOST_BUFFER) &&
724 (form->flags & HTTPPOST_PTRBUFFER) ) ||
726 ( (form->flags & HTTPPOST_READFILE) &&
727 (form->flags & HTTPPOST_PTRCONTENTS) )
729 return_value = CURL_FORMADD_INCOMPLETE;
733 if( ((form->flags & HTTPPOST_FILENAME) ||
734 (form->flags & HTTPPOST_BUFFER)) &&
735 !form->contenttype ) {
736 /* our contenttype is missing */
738 = strdup(ContentTypeForFilename(form->value, prevtype));
739 if(!form->contenttype) {
740 return_value = CURL_FORMADD_MEMORY;
743 form->contenttype_alloc = TRUE;
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. */
750 /* copy name (without strdup; possibly contains null characters) */
751 form->name = memdup(form->name, form->namelength);
753 return_value = CURL_FORMADD_MEMORY;
756 form->name_alloc = TRUE;
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);
764 return_value = CURL_FORMADD_MEMORY;
767 form->value_alloc = TRUE;
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,
779 return_value = CURL_FORMADD_MEMORY;
783 if(form->contenttype)
784 prevtype = form->contenttype;
790 /* we return on error, free possibly allocated fields */
796 if(form->value_alloc)
798 if(form->contenttype_alloc)
799 free(form->contenttype);
800 if(form->showfilename_alloc)
801 free(form->showfilename);
805 /* always delete the allocated memory before returning */
807 while(form != NULL) {
808 FormInfo *delete_form;
819 * curl_formadd() is a public API to add a section to the multipart formpost.
822 CURLFORMcode curl_formadd(struct curl_httppost **httppost,
823 struct curl_httppost **last_post,
828 va_start(arg, last_post);
829 result = FormAdd(httppost, last_post, arg);
835 * AddFormData() adds a chunk of data to the FormData linked list.
837 * size is incremented by the chunk length, unless it is NULL
839 static CURLcode AddFormData(struct FormData **formp,
845 struct FormData *newform = malloc(sizeof(struct FormData));
847 return CURLE_OUT_OF_MEMORY;
848 newform->next = NULL;
850 if(type <= FORM_CONTENT) {
851 /* we make it easier for plain strings: */
853 length = strlen((char *)line);
855 newform->line = malloc(length+1);
858 return CURLE_OUT_OF_MEMORY;
860 memcpy(newform->line, line, length);
861 newform->length = length;
862 newform->line[length]=0; /* zero terminate for easier debugging */
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;
869 newform->type = type;
872 (*formp)->next = newform;
879 if(type != FORM_FILE)
880 /* for static content as well as callback data we add the size given
884 /* Since this is a file to be uploaded here, add the size of the actual
886 if(!strequal("-", newform->line)) {
888 if(!stat(newform->line, &file)) {
889 *size += file.st_size;
898 * AddFormDataf() adds printf()-style formatted data to the formdata chain.
901 static CURLcode AddFormDataf(struct FormData **formp,
903 const char *fmt, ...)
908 vsnprintf(s, sizeof(s), fmt, ap);
911 return AddFormData(formp, FORM_DATA, s, 0, size);
915 * Curl_formclean() is used from http.c, this cleans a built FormData linked
918 void Curl_formclean(struct FormData **form_ptr)
920 struct FormData *next, *form;
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 */
932 } while((form = next) != NULL); /* continue */
937 #ifdef CURL_DOES_CONVERSIONS
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.
943 CURLcode Curl_formconvert(struct SessionHandle *data, struct FormData *form)
945 struct FormData *next;
952 return CURLE_BAD_FUNCTION_ARGUMENT;
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 */
962 } while((form = next) != NULL); /* continue */
965 #endif /* CURL_DOES_CONVERSIONS */
969 * Serialize a curl_httppost struct.
970 * Returns 0 on success.
972 int curl_formget(struct curl_httppost *form, void *arg,
973 curl_formget_callback append)
977 struct FormData *data, *ptr;
979 rc = Curl_getformdata(NULL, &data, form, NULL, &size);
983 for (ptr = data; ptr; ptr = ptr->next) {
984 if(ptr->type == FORM_FILE) {
989 Curl_FormInit(&temp, ptr);
992 nread = readfromfile(&temp, buffer, sizeof(buffer));
993 if((nread == (size_t) -1) || (nread != append(arg, buffer, nread))) {
997 Curl_formclean(&data);
1000 } while(nread == sizeof(buffer));
1003 if(ptr->length != append(arg, ptr->line, ptr->length)) {
1004 Curl_formclean(&data);
1009 Curl_formclean(&data);
1014 * curl_formfree() is an external function to free up a whole form post
1017 void curl_formfree(struct curl_httppost *form)
1019 struct curl_httppost *next;
1022 /* no form to free, just get out of this */
1026 next=form->next; /* the following form line */
1028 /* recurse to sub-contents */
1030 curl_formfree(form->more);
1032 if( !(form->flags & HTTPPOST_PTRNAME) && form->name)
1033 free(form->name); /* free the name */
1034 if( !(form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_CALLBACK)) &&
1036 free(form->contents); /* free the contents */
1037 if(form->contenttype)
1038 free(form->contenttype); /* free the content type */
1039 if(form->showfilename)
1040 free(form->showfilename); /* free the faked file name */
1041 free(form); /* free the struct */
1043 } while((form = next) != NULL); /* continue */
1046 #ifndef HAVE_BASENAME
1048 (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004
1051 The basename() function shall take the pathname pointed to by path and
1052 return a pointer to the final component of the pathname, deleting any
1053 trailing '/' characters.
1055 If the string pointed to by path consists entirely of the '/' character,
1056 basename() shall return a pointer to the string "/". If the string pointed
1057 to by path is exactly "//", it is implementation-defined whether '/' or "//"
1060 If path is a null pointer or points to an empty string, basename() shall
1061 return a pointer to the string ".".
1063 The basename() function may modify the string pointed to by path, and may
1064 return a pointer to static storage that may then be overwritten by a
1065 subsequent call to basename().
1067 The basename() function need not be reentrant. A function that is not
1068 required to be reentrant is not required to be thread-safe.
1071 static char *Curl_basename(char *path)
1073 /* Ignore all the details above for now and make a quick and simple
1074 implementaion here */
1078 s1=strrchr(path, '/');
1079 s2=strrchr(path, '\\');
1082 path = (s1 > s2? s1 : s2)+1;
1093 static char *strippath(const char *fullfile)
1097 filename = strdup(fullfile); /* duplicate since basename() may ruin the
1098 buffer it works on */
1101 base = strdup(basename(filename));
1103 free(filename); /* free temporary buffer */
1105 return base; /* returns an allocated string or NULL ! */
1109 * Curl_getformdata() converts a linked list of "meta data" into a complete
1110 * (possibly huge) multipart formdata. The input list is in 'post', while the
1111 * output resulting linked lists gets stored in '*finalform'. *sizep will get
1112 * the total size of the whole POST.
1113 * A multipart/form_data content-type is built, unless a custom content-type
1114 * is passed in 'custom_content_type'.
1116 * This function will not do a failf() for the potential memory failures but
1117 * should for all other errors it spots. Just note that this function MAY get
1118 * a NULL pointer in the 'data' argument.
1121 CURLcode Curl_getformdata(struct SessionHandle *data,
1122 struct FormData **finalform,
1123 struct curl_httppost *post,
1124 const char *custom_content_type,
1127 struct FormData *form = NULL;
1128 struct FormData *firstform;
1129 struct curl_httppost *file;
1130 CURLcode result = CURLE_OK;
1132 curl_off_t size=0; /* support potentially ENORMOUS formposts */
1134 char *fileboundary=NULL;
1135 struct curl_slist* curList;
1137 *finalform=NULL; /* default form is empty */
1140 return result; /* no input => no output! */
1142 boundary = Curl_FormBoundary();
1144 return CURLE_OUT_OF_MEMORY;
1146 /* Make the first line of the output */
1147 result = AddFormDataf(&form, NULL,
1148 "%s; boundary=%s\r\n",
1149 custom_content_type?custom_content_type:
1150 "Content-Type: multipart/form-data",
1157 /* we DO NOT include that line in the total size of the POST, since it'll be
1158 part of the header! */
1165 result = AddFormDataf(&form, &size, "\r\n");
1171 result = AddFormDataf(&form, &size, "--%s\r\n", boundary);
1175 /* Maybe later this should be disabled when a custom_content_type is
1176 passed, since Content-Disposition is not meaningful for all multipart
1179 result = AddFormDataf(&form, &size,
1180 "Content-Disposition: form-data; name=\"");
1184 result = AddFormData(&form, FORM_DATA, post->name, post->namelength,
1189 result = AddFormDataf(&form, &size, "\"");
1194 /* If used, this is a link to more file names, we must then do
1195 the magic to include several files with the same field name */
1197 fileboundary = Curl_FormBoundary();
1199 result = AddFormDataf(&form, &size,
1200 "\r\nContent-Type: multipart/mixed,"
1211 /* If 'showfilename' is set, that is a faked name passed on to us
1212 to use to in the formpost. If that is not set, the actually used
1213 local file name should be added. */
1216 /* if multiple-file */
1217 char *filebasename= NULL;
1218 if(!file->showfilename) {
1219 filebasename = strippath(file->contents);
1221 Curl_formclean(&firstform);
1223 return CURLE_OUT_OF_MEMORY;
1227 result = AddFormDataf(&form, &size,
1228 "\r\n--%s\r\nContent-Disposition: "
1229 "attachment; filename=\"%s\"",
1231 (file->showfilename?file->showfilename:
1238 else if(post->flags & (HTTPPOST_FILENAME|HTTPPOST_BUFFER|
1239 HTTPPOST_CALLBACK)) {
1240 /* it should be noted that for the HTTPPOST_FILENAME and
1241 HTTPPOST_CALLBACK cases the ->showfilename struct member is always
1242 assigned at this point */
1244 (!post->showfilename)?strippath(post->contents):NULL;
1246 result = AddFormDataf(&form, &size,
1247 "; filename=\"%s\"",
1248 (post->showfilename?post->showfilename:
1257 if(file->contenttype) {
1258 /* we have a specified type */
1259 result = AddFormDataf(&form, &size,
1260 "\r\nContent-Type: %s",
1266 curList = file->contentheader;
1268 /* Process the additional headers specified for this form */
1269 result = AddFormDataf( &form, &size, "\r\n%s", curList->data );
1272 curList = curList->next;
1275 Curl_formclean(&firstform);
1280 result = AddFormDataf(&form, &size, "\r\n\r\n");
1284 if((post->flags & HTTPPOST_FILENAME) ||
1285 (post->flags & HTTPPOST_READFILE)) {
1286 /* we should include the contents from the specified file */
1289 fileread = strequal("-", file->contents)?
1290 stdin:fopen(file->contents, "rb"); /* binary read for win32 */
1293 * VMS: This only allows for stream files on VMS. Stream files are
1294 * OK, as are FIXED & VAR files WITHOUT implied CC For implied CC,
1295 * every record needs to have a \n appended & 1 added to SIZE
1299 if(fileread != stdin) {
1300 /* close the file again */
1302 /* add the file name only - for later reading from this */
1303 result = AddFormData(&form, FORM_FILE, file->contents, 0, &size);
1306 /* When uploading from stdin, we can't know the size of the file,
1307 * thus must read the full file as before. We *could* use chunked
1308 * transfer-encoding, but that only works for HTTP 1.1 and we
1309 * can't be sure we work with such a server.
1313 while((nread = fread(buffer, 1, sizeof(buffer), fileread)) != 0) {
1314 result = AddFormData(&form, FORM_CONTENT, buffer, nread, &size);
1322 failf(data, "couldn't open file \"%s\"\n", file->contents);
1324 result = CURLE_READ_ERROR;
1327 else if(post->flags & HTTPPOST_BUFFER)
1328 /* include contents of buffer */
1329 result = AddFormData(&form, FORM_CONTENT, post->buffer,
1330 post->bufferlength, &size);
1331 else if(post->flags & HTTPPOST_CALLBACK)
1332 /* the contents should be read with the callback and the size
1333 is set with the contentslength */
1334 result = AddFormData(&form, FORM_CALLBACK, post->userp,
1335 post->contentslength, &size);
1337 /* include the contents we got */
1338 result = AddFormData(&form, FORM_CONTENT, post->contents,
1339 post->contentslength, &size);
1342 } while(file && !result); /* for each specified file for this field */
1345 Curl_formclean(&firstform);
1351 /* this was a multiple-file inclusion, make a termination file
1353 result = AddFormDataf(&form, &size,
1361 } while((post = post->next) != NULL); /* for each field */
1363 Curl_formclean(&firstform);
1368 /* end-boundary for everything */
1369 result = AddFormDataf(&form, &size,
1373 Curl_formclean(&firstform);
1382 *finalform=firstform;
1388 * Curl_FormInit() inits the struct 'form' points to with the 'formdata'
1389 * and resets the 'sent' counter.
1391 int Curl_FormInit(struct Form *form, struct FormData *formdata )
1394 return 1; /* error */
1396 form->data = formdata;
1399 form->fread_func = ZERO_NULL;
1404 static size_t readfromfile(struct Form *form, char *buffer,
1408 bool callback = (bool)(form->data->type == FORM_CALLBACK);
1411 nread = form->fread_func(buffer, 1, size, form->data->line);
1414 /* this file hasn't yet been opened */
1415 form->fp = fopen(form->data->line, "rb"); /* b is for binary */
1417 return (size_t)-1; /* failure */
1419 nread = fread(buffer, 1, size, form->fp);
1421 if(!nread || nread > size) {
1422 /* this is the last chunk from the file, move on */
1427 form->data = form->data->next;
1434 * Curl_FormReader() is the fread() emulation function that will be used to
1435 * deliver the formdata to the transfer loop and then sent away to the peer.
1437 size_t Curl_FormReader(char *buffer,
1446 form=(struct Form *)mydata;
1448 wantedsize = size * nitems;
1451 return 0; /* nothing, error, empty */
1453 if((form->data->type == FORM_FILE) ||
1454 (form->data->type == FORM_CALLBACK)) {
1455 gotsize = readfromfile(form, buffer, wantedsize);
1458 /* If positive or -1, return. If zero, continue! */
1463 if( (form->data->length - form->sent ) > wantedsize - gotsize) {
1465 memcpy(buffer + gotsize , form->data->line + form->sent,
1466 wantedsize - gotsize);
1468 form->sent += wantedsize-gotsize;
1473 memcpy(buffer+gotsize,
1474 form->data->line + form->sent,
1475 (form->data->length - form->sent) );
1476 gotsize += form->data->length - form->sent;
1480 form->data = form->data->next; /* advance */
1482 } while(form->data && (form->data->type < FORM_CALLBACK));
1483 /* If we got an empty line and we have more data, we proceed to the next
1484 line immediately to avoid returning zero before we've reached the end. */
1490 * Curl_formpostheader() returns the first line of the formpost, the
1491 * request-header part (which is not part of the request-body like the rest of
1494 char *Curl_formpostheader(void *formp, size_t *len)
1497 struct Form *form=(struct Form *)formp;
1500 return 0; /* nothing, ERROR! */
1502 header = form->data->line;
1503 *len = form->data->length;
1505 form->data = form->data->next; /* advance */
1512 int FormAddTest(const char * errormsg,
1513 struct curl_httppost **httppost,
1514 struct curl_httppost **last_post,
1519 va_start(arg, last_post);
1520 if((result = FormAdd(httppost, last_post, arg)))
1521 fprintf (stderr, "ERROR doing FormAdd ret: %d action: %s\n", result,
1528 int main(int argc, argv_item_t argv[])
1530 char name1[] = "simple_COPYCONTENTS";
1531 char name2[] = "COPYCONTENTS_+_CONTENTTYPE";
1532 char name3[] = "PTRNAME_+_NAMELENGTH_+_COPYNAME_+_CONTENTSLENGTH";
1533 char name4[] = "simple_PTRCONTENTS";
1534 char name5[] = "PTRCONTENTS_+_CONTENTSLENGTH";
1535 char name6[] = "PTRCONTENTS_+_CONTENTSLENGTH_+_CONTENTTYPE";
1536 char name7[] = "FILE1_+_CONTENTTYPE";
1537 char name8[] = "FILE1_+_FILE2";
1538 char name9[] = "FILE1_+_FILE2_+_FILE3";
1539 char name10[] = "ARRAY: FILE1_+_FILE2_+_FILE3";
1540 char name11[] = "FILECONTENT";
1541 char value1[] = "value for simple COPYCONTENTS";
1542 char value2[] = "value for COPYCONTENTS + CONTENTTYPE";
1543 char value3[] = "value for PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH";
1544 char value4[] = "value for simple PTRCONTENTS";
1545 char value5[] = "value for PTRCONTENTS + CONTENTSLENGTH";
1546 char value6[] = "value for PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE";
1547 char value7[] = "formdata.h";
1548 char value8[] = "Makefile.b32";
1549 char type2[] = "image/gif";
1550 char type6[] = "text/plain";
1551 char type7[] = "text/html";
1552 int name3length = strlen(name3);
1553 int value3length = strlen(value3);
1554 int value5length = strlen(value5);
1555 int value6length = strlen(value6);
1561 struct curl_httppost *httppost=NULL;
1562 struct curl_httppost *last_post=NULL;
1563 struct curl_forms forms[4];
1565 struct FormData *form;
1566 struct Form formread;
1571 Curl_srand(); /* Because we do not call curl_global_init() here. */
1573 if(FormAddTest("simple COPYCONTENTS test", &httppost, &last_post,
1574 CURLFORM_COPYNAME, name1, CURLFORM_COPYCONTENTS, value1,
1577 if(FormAddTest("COPYCONTENTS + CONTENTTYPE test", &httppost, &last_post,
1578 CURLFORM_COPYNAME, name2, CURLFORM_COPYCONTENTS, value2,
1579 CURLFORM_CONTENTTYPE, type2, CURLFORM_END))
1581 /* make null character at start to check that contentslength works
1585 if(FormAddTest("PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH test",
1586 &httppost, &last_post,
1587 CURLFORM_PTRNAME, name3, CURLFORM_COPYCONTENTS, value3,
1588 CURLFORM_CONTENTSLENGTH, value3length,
1589 CURLFORM_NAMELENGTH, name3length, CURLFORM_END))
1591 if(FormAddTest("simple PTRCONTENTS test", &httppost, &last_post,
1592 CURLFORM_COPYNAME, name4, CURLFORM_PTRCONTENTS, value4,
1595 /* make null character at start to check that contentslength works
1598 if(FormAddTest("PTRCONTENTS + CONTENTSLENGTH test", &httppost, &last_post,
1599 CURLFORM_COPYNAME, name5, CURLFORM_PTRCONTENTS, value5,
1600 CURLFORM_CONTENTSLENGTH, value5length, CURLFORM_END))
1602 /* make null character at start to check that contentslength works
1605 if(FormAddTest("PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE test",
1606 &httppost, &last_post,
1607 CURLFORM_COPYNAME, name6, CURLFORM_PTRCONTENTS, value6,
1608 CURLFORM_CONTENTSLENGTH, value6length,
1609 CURLFORM_CONTENTTYPE, type6, CURLFORM_END))
1611 if(FormAddTest("FILE + CONTENTTYPE test", &httppost, &last_post,
1612 CURLFORM_COPYNAME, name7, CURLFORM_FILE, value7,
1613 CURLFORM_CONTENTTYPE, type7, CURLFORM_END))
1615 if(FormAddTest("FILE1 + FILE2 test", &httppost, &last_post,
1616 CURLFORM_COPYNAME, name8, CURLFORM_FILE, value7,
1617 CURLFORM_FILE, value8, CURLFORM_END))
1619 if(FormAddTest("FILE1 + FILE2 + FILE3 test", &httppost, &last_post,
1620 CURLFORM_COPYNAME, name9, CURLFORM_FILE, value7,
1621 CURLFORM_FILE, value8, CURLFORM_FILE, value7, CURLFORM_END))
1623 forms[0].option = CURLFORM_FILE;
1624 forms[0].value = value7;
1625 forms[1].option = CURLFORM_FILE;
1626 forms[1].value = value8;
1627 forms[2].option = CURLFORM_FILE;
1628 forms[2].value = value7;
1629 forms[3].option = CURLFORM_END;
1630 if(FormAddTest("FILE1 + FILE2 + FILE3 ARRAY test", &httppost, &last_post,
1631 CURLFORM_COPYNAME, name10, CURLFORM_ARRAY, forms,
1634 if(FormAddTest("FILECONTENT test", &httppost, &last_post,
1635 CURLFORM_COPYNAME, name11, CURLFORM_FILECONTENT, value7,
1639 rc = Curl_getformdata(NULL, &form, httppost, NULL, &size);
1640 if(rc != CURLE_OK) {
1641 if(rc != CURLE_READ_ERROR) {
1642 const char *errortext = curl_easy_strerror(rc);
1643 fprintf(stdout, "\n==> Curl_getformdata error: %s\n", errortext);
1648 Curl_FormInit(&formread, form);
1651 nread = Curl_FormReader(buffer, 1, sizeof(buffer),
1656 fwrite(buffer, nread, 1, stdout);
1659 fprintf(stdout, "size: ");
1660 fprintf(stdout, "%" FORMAT_OFF_T, size);
1661 fprintf(stdout, "\n");
1663 fprintf(stdout, "\n==> %d Test(s) failed!\n", errors);
1665 fprintf(stdout, "\nAll Tests seem to have worked (please check output)\n");
1670 #endif /* _FORM_DEBUG */
1672 #else /* CURL_DISABLE_HTTP */
1673 CURLFORMcode curl_formadd(struct curl_httppost **httppost,
1674 struct curl_httppost **last_post,
1679 return CURL_FORMADD_DISABLED;
1682 int curl_formget(struct curl_httppost *form, void *arg,
1683 curl_formget_callback append)
1688 return CURL_FORMADD_DISABLED;
1691 void curl_formfree(struct curl_httppost *form)
1694 /* does nothing HTTP is disabled */
1697 #endif /* CURL_DISABLE_HTTP */
1699 #if !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY)
1702 * Curl_FormBoundary() creates a suitable boundary string and returns an
1703 * allocated one. This is also used by SSL-code so it must be present even
1704 * if HTTP is disabled!
1706 char *Curl_FormBoundary(void)
1711 static const char table16[]="0123456789abcdef";
1713 retstring = malloc(BOUNDARY_LENGTH+1);
1716 return NULL; /* failed */
1718 strcpy(retstring, "----------------------------");
1720 for(i=strlen(retstring); i<BOUNDARY_LENGTH; i++)
1721 retstring[i] = table16[Curl_rand()%16];
1723 /* 28 dashes and 12 hexadecimal digits makes 12^16 (184884258895036416)
1725 retstring[BOUNDARY_LENGTH]=0; /* zero terminate */
1730 #endif /* !defined(CURL_DISABLE_HTTP) || defined(USE_SSLEAY) */