• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2019, 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 https://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  ***************************************************************************/
22 
23 #include "curl_setup.h"
24 
25 #include <curl/curl.h>
26 
27 #include "mime.h"
28 #include "non-ascii.h"
29 #include "urldata.h"
30 #include "sendf.h"
31 
32 #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
33     !defined(CURL_DISABLE_IMAP)
34 
35 #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
36 #include <libgen.h>
37 #endif
38 
39 #include "rand.h"
40 #include "slist.h"
41 #include "strcase.h"
42 /* The last 3 #include files should be in this order */
43 #include "curl_printf.h"
44 #include "curl_memory.h"
45 #include "memdebug.h"
46 
47 #ifdef WIN32
48 # ifndef R_OK
49 #  define R_OK 4
50 # endif
51 #endif
52 
53 
54 #define READ_ERROR                      ((size_t) -1)
55 
56 /* Encoders. */
57 static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
58                                 curl_mimepart *part);
59 static curl_off_t encoder_nop_size(curl_mimepart *part);
60 static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
61                                 curl_mimepart *part);
62 static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
63                                 curl_mimepart *part);
64 static curl_off_t encoder_base64_size(curl_mimepart *part);
65 static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
66                               curl_mimepart *part);
67 static curl_off_t encoder_qp_size(curl_mimepart *part);
68 
69 static const mime_encoder encoders[] = {
70   {"binary", encoder_nop_read, encoder_nop_size},
71   {"8bit", encoder_nop_read, encoder_nop_size},
72   {"7bit", encoder_7bit_read, encoder_nop_size},
73   {"base64", encoder_base64_read, encoder_base64_size},
74   {"quoted-printable", encoder_qp_read, encoder_qp_size},
75   {ZERO_NULL, ZERO_NULL, ZERO_NULL}
76 };
77 
78 /* Base64 encoding table */
79 static const char base64[] =
80   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
81 
82 /* Quoted-printable character class table.
83  *
84  * We cannot rely on ctype functions since quoted-printable input data
85  * is assumed to be ascii-compatible, even on non-ascii platforms. */
86 #define QP_OK           1       /* Can be represented by itself. */
87 #define QP_SP           2       /* Space or tab. */
88 #define QP_CR           3       /* Carriage return. */
89 #define QP_LF           4       /* Line-feed. */
90 static const unsigned char qp_class[] = {
91  0,     0,     0,     0,     0,     0,     0,     0,            /* 00 - 07 */
92  0,     QP_SP, QP_LF, 0,     0,     QP_CR, 0,     0,            /* 08 - 0F */
93  0,     0,     0,     0,     0,     0,     0,     0,            /* 10 - 17 */
94  0,     0,     0,     0,     0,     0,     0,     0,            /* 18 - 1F */
95  QP_SP, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 20 - 27 */
96  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 28 - 2F */
97  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 30 - 37 */
98  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0    , QP_OK, QP_OK,        /* 38 - 3F */
99  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 40 - 47 */
100  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 48 - 4F */
101  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 50 - 57 */
102  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 58 - 5F */
103  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 60 - 67 */
104  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 68 - 6F */
105  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 70 - 77 */
106  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0,            /* 78 - 7F */
107  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* 80 - 8F */
108  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* 90 - 9F */
109  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* A0 - AF */
110  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* B0 - BF */
111  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* C0 - CF */
112  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* D0 - DF */
113  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* E0 - EF */
114  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0                 /* F0 - FF */
115 };
116 
117 
118 /* Binary --> hexadecimal ASCII table. */
119 static const char aschex[] =
120   "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46";
121 
122 
123 
124 #ifndef __VMS
125 #define filesize(name, stat_data) (stat_data.st_size)
126 #define fopen_read fopen
127 
128 #else
129 
130 #include <fabdef.h>
131 /*
132  * get_vms_file_size does what it takes to get the real size of the file
133  *
134  * For fixed files, find out the size of the EOF block and adjust.
135  *
136  * For all others, have to read the entire file in, discarding the contents.
137  * Most posted text files will be small, and binary files like zlib archives
138  * and CD/DVD images should be either a STREAM_LF format or a fixed format.
139  *
140  */
VmsRealFileSize(const char * name,const struct_stat * stat_buf)141 curl_off_t VmsRealFileSize(const char *name,
142                            const struct_stat *stat_buf)
143 {
144   char buffer[8192];
145   curl_off_t count;
146   int ret_stat;
147   FILE * file;
148 
149   file = fopen(name, FOPEN_READTEXT); /* VMS */
150   if(file == NULL)
151     return 0;
152 
153   count = 0;
154   ret_stat = 1;
155   while(ret_stat > 0) {
156     ret_stat = fread(buffer, 1, sizeof(buffer), file);
157     if(ret_stat != 0)
158       count += ret_stat;
159   }
160   fclose(file);
161 
162   return count;
163 }
164 
165 /*
166  *
167  *  VmsSpecialSize checks to see if the stat st_size can be trusted and
168  *  if not to call a routine to get the correct size.
169  *
170  */
VmsSpecialSize(const char * name,const struct_stat * stat_buf)171 static curl_off_t VmsSpecialSize(const char *name,
172                                  const struct_stat *stat_buf)
173 {
174   switch(stat_buf->st_fab_rfm) {
175   case FAB$C_VAR:
176   case FAB$C_VFC:
177     return VmsRealFileSize(name, stat_buf);
178     break;
179   default:
180     return stat_buf->st_size;
181   }
182 }
183 
184 #define filesize(name, stat_data) VmsSpecialSize(name, &stat_data)
185 
186 /*
187  * vmsfopenread
188  *
189  * For upload to work as expected on VMS, different optional
190  * parameters must be added to the fopen command based on
191  * record format of the file.
192  *
193  */
vmsfopenread(const char * file,const char * mode)194 static FILE * vmsfopenread(const char *file, const char *mode)
195 {
196   struct_stat statbuf;
197   int result;
198 
199   result = stat(file, &statbuf);
200 
201   switch(statbuf.st_fab_rfm) {
202   case FAB$C_VAR:
203   case FAB$C_VFC:
204   case FAB$C_STMCR:
205     return fopen(file, FOPEN_READTEXT); /* VMS */
206     break;
207   default:
208     return fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm");
209   }
210 }
211 
212 #define fopen_read vmsfopenread
213 #endif
214 
215 
216 #ifndef HAVE_BASENAME
217 /*
218   (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004
219   Edition)
220 
221   The basename() function shall take the pathname pointed to by path and
222   return a pointer to the final component of the pathname, deleting any
223   trailing '/' characters.
224 
225   If the string pointed to by path consists entirely of the '/' character,
226   basename() shall return a pointer to the string "/". If the string pointed
227   to by path is exactly "//", it is implementation-defined whether '/' or "//"
228   is returned.
229 
230   If path is a null pointer or points to an empty string, basename() shall
231   return a pointer to the string ".".
232 
233   The basename() function may modify the string pointed to by path, and may
234   return a pointer to static storage that may then be overwritten by a
235   subsequent call to basename().
236 
237   The basename() function need not be reentrant. A function that is not
238   required to be reentrant is not required to be thread-safe.
239 
240 */
Curl_basename(char * path)241 static char *Curl_basename(char *path)
242 {
243   /* Ignore all the details above for now and make a quick and simple
244      implementation here */
245   char *s1;
246   char *s2;
247 
248   s1 = strrchr(path, '/');
249   s2 = strrchr(path, '\\');
250 
251   if(s1 && s2) {
252     path = (s1 > s2? s1 : s2) + 1;
253   }
254   else if(s1)
255     path = s1 + 1;
256   else if(s2)
257     path = s2 + 1;
258 
259   return path;
260 }
261 
262 #define basename(x)  Curl_basename((x))
263 #endif
264 
265 
266 /* Set readback state. */
mimesetstate(mime_state * state,enum mimestate tok,void * ptr)267 static void mimesetstate(mime_state *state, enum mimestate tok, void *ptr)
268 {
269   state->state = tok;
270   state->ptr = ptr;
271   state->offset = 0;
272 }
273 
274 
275 /* Escape header string into allocated memory. */
escape_string(const char * src)276 static char *escape_string(const char *src)
277 {
278   size_t bytecount = 0;
279   size_t i;
280   char *dst;
281 
282   for(i = 0; src[i]; i++)
283     if(src[i] == '"' || src[i] == '\\')
284       bytecount++;
285 
286   bytecount += i;
287   dst = malloc(bytecount + 1);
288   if(!dst)
289     return NULL;
290 
291   for(i = 0; *src; src++) {
292     if(*src == '"' || *src == '\\')
293       dst[i++] = '\\';
294     dst[i++] = *src;
295   }
296 
297   dst[i] = '\0';
298   return dst;
299 }
300 
301 /* Check if header matches. */
match_header(struct curl_slist * hdr,const char * lbl,size_t len)302 static char *match_header(struct curl_slist *hdr, const char *lbl, size_t len)
303 {
304   char *value = NULL;
305 
306   if(strncasecompare(hdr->data, lbl, len) && hdr->data[len] == ':')
307     for(value = hdr->data + len + 1; *value == ' '; value++)
308       ;
309   return value;
310 }
311 
312 /* Get a header from an slist. */
search_header(struct curl_slist * hdrlist,const char * hdr)313 static char *search_header(struct curl_slist *hdrlist, const char *hdr)
314 {
315   size_t len = strlen(hdr);
316   char *value = NULL;
317 
318   for(; !value && hdrlist; hdrlist = hdrlist->next)
319     value = match_header(hdrlist, hdr, len);
320 
321   return value;
322 }
323 
strippath(const char * fullfile)324 static char *strippath(const char *fullfile)
325 {
326   char *filename;
327   char *base;
328   filename = strdup(fullfile); /* duplicate since basename() may ruin the
329                                   buffer it works on */
330   if(!filename)
331     return NULL;
332   base = strdup(basename(filename));
333 
334   free(filename); /* free temporary buffer */
335 
336   return base; /* returns an allocated string or NULL ! */
337 }
338 
339 /* Initialize data encoder state. */
cleanup_encoder_state(mime_encoder_state * p)340 static void cleanup_encoder_state(mime_encoder_state *p)
341 {
342   p->pos = 0;
343   p->bufbeg = 0;
344   p->bufend = 0;
345 }
346 
347 
348 /* Dummy encoder. This is used for 8bit and binary content encodings. */
encoder_nop_read(char * buffer,size_t size,bool ateof,curl_mimepart * part)349 static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
350                                curl_mimepart *part)
351 {
352   mime_encoder_state *st = &part->encstate;
353   size_t insize = st->bufend - st->bufbeg;
354 
355   (void) ateof;
356 
357   if(size > insize)
358     size = insize;
359   if(size)
360     memcpy(buffer, st->buf, size);
361   st->bufbeg += size;
362   return size;
363 }
364 
encoder_nop_size(curl_mimepart * part)365 static curl_off_t encoder_nop_size(curl_mimepart *part)
366 {
367   return part->datasize;
368 }
369 
370 
371 /* 7bit encoder: the encoder is just a data validity check. */
encoder_7bit_read(char * buffer,size_t size,bool ateof,curl_mimepart * part)372 static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
373                                 curl_mimepart *part)
374 {
375   mime_encoder_state *st = &part->encstate;
376   size_t cursize = st->bufend - st->bufbeg;
377 
378   (void) ateof;
379 
380   if(size > cursize)
381     size = cursize;
382 
383   for(cursize = 0; cursize < size; cursize++) {
384     *buffer = st->buf[st->bufbeg];
385     if(*buffer++ & 0x80)
386       return cursize? cursize: READ_ERROR;
387     st->bufbeg++;
388   }
389 
390   return cursize;
391 }
392 
393 
394 /* Base64 content encoder. */
encoder_base64_read(char * buffer,size_t size,bool ateof,curl_mimepart * part)395 static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
396                                 curl_mimepart *part)
397 {
398   mime_encoder_state *st = &part->encstate;
399   size_t cursize = 0;
400   int i;
401   char *ptr = buffer;
402 
403   while(st->bufbeg < st->bufend) {
404     /* Line full ? */
405     if(st->pos > MAX_ENCODED_LINE_LENGTH - 4) {
406       /* Yes, we need 2 characters for CRLF. */
407       if(size < 2)
408         break;
409       *ptr++ = '\r';
410       *ptr++ = '\n';
411       st->pos = 0;
412       cursize += 2;
413       size -= 2;
414     }
415 
416     /* Be sure there is enough space and input data for a base64 group. */
417     if(size < 4 || st->bufend - st->bufbeg < 3)
418       break;
419 
420     /* Encode three bytes as four characters. */
421     i = st->buf[st->bufbeg++] & 0xFF;
422     i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
423     i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
424     *ptr++ = base64[(i >> 18) & 0x3F];
425     *ptr++ = base64[(i >> 12) & 0x3F];
426     *ptr++ = base64[(i >> 6) & 0x3F];
427     *ptr++ = base64[i & 0x3F];
428     cursize += 4;
429     st->pos += 4;
430     size -= 4;
431   }
432 
433   /* If at eof, we have to flush the buffered data. */
434   if(ateof && size >= 4) {
435     /* Buffered data size can only be 0, 1 or 2. */
436     ptr[2] = ptr[3] = '=';
437     i = 0;
438     switch(st->bufend - st->bufbeg) {
439     case 2:
440       i = (st->buf[st->bufbeg + 1] & 0xFF) << 8;
441       /* FALLTHROUGH */
442     case 1:
443       i |= (st->buf[st->bufbeg] & 0xFF) << 16;
444       ptr[0] = base64[(i >> 18) & 0x3F];
445       ptr[1] = base64[(i >> 12) & 0x3F];
446       if(++st->bufbeg != st->bufend) {
447         ptr[2] = base64[(i >> 6) & 0x3F];
448         st->bufbeg++;
449       }
450       cursize += 4;
451       st->pos += 4;
452       break;
453     }
454   }
455 
456 #ifdef CURL_DOES_CONVERSIONS
457   /* This is now textual data, Convert character codes. */
458   if(part->easy && cursize) {
459     CURLcode result = Curl_convert_to_network(part->easy, buffer, cursize);
460     if(result)
461       return READ_ERROR;
462   }
463 #endif
464 
465   return cursize;
466 }
467 
encoder_base64_size(curl_mimepart * part)468 static curl_off_t encoder_base64_size(curl_mimepart *part)
469 {
470   curl_off_t size = part->datasize;
471 
472   if(size <= 0)
473     return size;    /* Unknown size or no data. */
474 
475   /* Compute base64 character count. */
476   size = 4 * (1 + (size - 1) / 3);
477 
478   /* Effective character count must include CRLFs. */
479   return size + 2 * ((size - 1) / MAX_ENCODED_LINE_LENGTH);
480 }
481 
482 
483 /* Quoted-printable lookahead.
484  *
485  * Check if a CRLF or end of data is in input buffer at current position + n.
486  * Return -1 if more data needed, 1 if CRLF or end of data, else 0.
487  */
qp_lookahead_eol(mime_encoder_state * st,int ateof,size_t n)488 static int qp_lookahead_eol(mime_encoder_state *st, int ateof, size_t n)
489 {
490   n += st->bufbeg;
491   if(n >= st->bufend && ateof)
492     return 1;
493   if(n + 2 > st->bufend)
494     return ateof? 0: -1;
495   if(qp_class[st->buf[n] & 0xFF] == QP_CR &&
496      qp_class[st->buf[n + 1] & 0xFF] == QP_LF)
497     return 1;
498   return 0;
499 }
500 
501 /* Quoted-printable encoder. */
encoder_qp_read(char * buffer,size_t size,bool ateof,curl_mimepart * part)502 static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
503                               curl_mimepart *part)
504 {
505   mime_encoder_state *st = &part->encstate;
506   char *ptr = buffer;
507   size_t cursize = 0;
508   int softlinebreak;
509   char buf[4];
510 
511   /* On all platforms, input is supposed to be ASCII compatible: for this
512      reason, we use hexadecimal ASCII codes in this function rather than
513      character constants that can be interpreted as non-ascii on some
514      platforms. Preserve ASCII encoding on output too. */
515   while(st->bufbeg < st->bufend) {
516     size_t len = 1;
517     size_t consumed = 1;
518     int i = st->buf[st->bufbeg];
519     buf[0] = (char) i;
520     buf[1] = aschex[(i >> 4) & 0xF];
521     buf[2] = aschex[i & 0xF];
522 
523     switch(qp_class[st->buf[st->bufbeg] & 0xFF]) {
524     case QP_OK:          /* Not a special character. */
525       break;
526     case QP_SP:          /* Space or tab. */
527       /* Spacing must be escaped if followed by CRLF. */
528       switch(qp_lookahead_eol(st, ateof, 1)) {
529       case -1:          /* More input data needed. */
530         return cursize;
531       case 0:           /* No encoding needed. */
532         break;
533       default:          /* CRLF after space or tab. */
534         buf[0] = '\x3D';    /* '=' */
535         len = 3;
536         break;
537       }
538       break;
539     case QP_CR:         /* Carriage return. */
540       /* If followed by a line-feed, output the CRLF pair.
541          Else escape it. */
542       switch(qp_lookahead_eol(st, ateof, 0)) {
543       case -1:          /* Need more data. */
544         return cursize;
545       case 1:           /* CRLF found. */
546         buf[len++] = '\x0A';    /* Append '\n'. */
547         consumed = 2;
548         break;
549       default:          /* Not followed by LF: escape. */
550         buf[0] = '\x3D';    /* '=' */
551         len = 3;
552         break;
553       }
554       break;
555     default:            /* Character must be escaped. */
556       buf[0] = '\x3D';    /* '=' */
557       len = 3;
558       break;
559     }
560 
561     /* Be sure the encoded character fits within maximum line length. */
562     if(buf[len - 1] != '\x0A') {    /* '\n' */
563       softlinebreak = st->pos + len > MAX_ENCODED_LINE_LENGTH;
564       if(!softlinebreak && st->pos + len == MAX_ENCODED_LINE_LENGTH) {
565         /* We may use the current line only if end of data or followed by
566            a CRLF. */
567         switch(qp_lookahead_eol(st, ateof, consumed)) {
568         case -1:        /* Need more data. */
569           return cursize;
570           break;
571         case 0:         /* Not followed by a CRLF. */
572           softlinebreak = 1;
573           break;
574         }
575       }
576       if(softlinebreak) {
577         strcpy(buf, "\x3D\x0D\x0A");    /* "=\r\n" */
578         len = 3;
579         consumed = 0;
580       }
581     }
582 
583     /* If the output buffer would overflow, do not store. */
584     if(len > size)
585       break;
586 
587     /* Append to output buffer. */
588     memcpy(ptr, buf, len);
589     cursize += len;
590     ptr += len;
591     size -= len;
592     st->pos += len;
593     if(buf[len - 1] == '\x0A')    /* '\n' */
594       st->pos = 0;
595     st->bufbeg += consumed;
596   }
597 
598   return cursize;
599 }
600 
encoder_qp_size(curl_mimepart * part)601 static curl_off_t encoder_qp_size(curl_mimepart *part)
602 {
603   /* Determining the size can only be done by reading the data: unless the
604      data size is 0, we return it as unknown (-1). */
605   return part->datasize? -1: 0;
606 }
607 
608 
609 /* In-memory data callbacks. */
610 /* Argument is a pointer to the mime part. */
mime_mem_read(char * buffer,size_t size,size_t nitems,void * instream)611 static size_t mime_mem_read(char *buffer, size_t size, size_t nitems,
612                             void *instream)
613 {
614   curl_mimepart *part = (curl_mimepart *) instream;
615   size_t sz = (size_t) part->datasize - part->state.offset;
616   (void) size;   /* Always 1.*/
617 
618   if(sz > nitems)
619     sz = nitems;
620 
621   if(sz)
622     memcpy(buffer, (char *) &part->data[part->state.offset], sz);
623 
624   part->state.offset += sz;
625   return sz;
626 }
627 
mime_mem_seek(void * instream,curl_off_t offset,int whence)628 static int mime_mem_seek(void *instream, curl_off_t offset, int whence)
629 {
630   curl_mimepart *part = (curl_mimepart *) instream;
631 
632   switch(whence) {
633   case SEEK_CUR:
634     offset += part->state.offset;
635     break;
636   case SEEK_END:
637     offset += part->datasize;
638     break;
639   }
640 
641   if(offset < 0 || offset > part->datasize)
642     return CURL_SEEKFUNC_FAIL;
643 
644   part->state.offset = (size_t) offset;
645   return CURL_SEEKFUNC_OK;
646 }
647 
mime_mem_free(void * ptr)648 static void mime_mem_free(void *ptr)
649 {
650   Curl_safefree(((curl_mimepart *) ptr)->data);
651 }
652 
653 
654 /* Named file callbacks. */
655 /* Argument is a pointer to the mime part. */
mime_open_file(curl_mimepart * part)656 static int mime_open_file(curl_mimepart * part)
657 {
658   /* Open a MIMEKIND_FILE part. */
659 
660   if(part->fp)
661     return 0;
662   part->fp = fopen_read(part->data, "rb");
663   return part->fp? 0: -1;
664 }
665 
mime_file_read(char * buffer,size_t size,size_t nitems,void * instream)666 static size_t mime_file_read(char *buffer, size_t size, size_t nitems,
667                              void *instream)
668 {
669   curl_mimepart *part = (curl_mimepart *) instream;
670 
671   if(mime_open_file(part))
672     return READ_ERROR;
673 
674   return fread(buffer, size, nitems, part->fp);
675 }
676 
mime_file_seek(void * instream,curl_off_t offset,int whence)677 static int mime_file_seek(void *instream, curl_off_t offset, int whence)
678 {
679   curl_mimepart *part = (curl_mimepart *) instream;
680 
681   if(whence == SEEK_SET && !offset && !part->fp)
682     return CURL_SEEKFUNC_OK;   /* Not open: implicitly already at BOF. */
683 
684   if(mime_open_file(part))
685     return CURL_SEEKFUNC_FAIL;
686 
687   return fseek(part->fp, (long) offset, whence)?
688                CURL_SEEKFUNC_CANTSEEK: CURL_SEEKFUNC_OK;
689 }
690 
mime_file_free(void * ptr)691 static void mime_file_free(void *ptr)
692 {
693   curl_mimepart *part = (curl_mimepart *) ptr;
694 
695   if(part->fp) {
696     fclose(part->fp);
697     part->fp = NULL;
698   }
699   Curl_safefree(part->data);
700   part->data = NULL;
701 }
702 
703 
704 /* Subparts callbacks. */
705 /* Argument is a pointer to the mime structure. */
706 
707 /* Readback a byte string segment. */
readback_bytes(mime_state * state,char * buffer,size_t bufsize,const char * bytes,size_t numbytes,const char * trail)708 static size_t readback_bytes(mime_state *state,
709                              char *buffer, size_t bufsize,
710                              const char *bytes, size_t numbytes,
711                              const char *trail)
712 {
713   size_t sz;
714 
715   if(numbytes > state->offset) {
716     sz = numbytes - state->offset;
717     bytes += state->offset;
718   }
719   else {
720     size_t tsz = strlen(trail);
721 
722     sz = state->offset - numbytes;
723     if(sz >= tsz)
724       return 0;
725     bytes = trail + sz;
726     sz = tsz - sz;
727   }
728 
729   if(sz > bufsize)
730     sz = bufsize;
731 
732   memcpy(buffer, bytes, sz);
733   state->offset += sz;
734   return sz;
735 }
736 
737 /* Read a non-encoded part content. */
read_part_content(curl_mimepart * part,char * buffer,size_t bufsize)738 static size_t read_part_content(curl_mimepart *part,
739                                 char *buffer, size_t bufsize)
740 {
741   size_t sz = 0;
742 
743   if(part->readfunc)
744     sz = part->readfunc(buffer, 1, bufsize, part->arg);
745   return sz;
746 }
747 
748 /* Read and encode part content. */
read_encoded_part_content(curl_mimepart * part,char * buffer,size_t bufsize)749 static size_t read_encoded_part_content(curl_mimepart *part,
750                                         char *buffer, size_t bufsize)
751 {
752   mime_encoder_state *st = &part->encstate;
753   size_t cursize = 0;
754   size_t sz;
755   bool ateof = FALSE;
756 
757   while(bufsize) {
758     if(st->bufbeg < st->bufend || ateof) {
759       /* Encode buffered data. */
760       sz = part->encoder->encodefunc(buffer, bufsize, ateof, part);
761       switch(sz) {
762       case 0:
763         if(ateof)
764           return cursize;
765         break;
766       case CURL_READFUNC_ABORT:
767       case CURL_READFUNC_PAUSE:
768       case READ_ERROR:
769         return cursize? cursize: sz;
770       default:
771         cursize += sz;
772         buffer += sz;
773         bufsize -= sz;
774         continue;
775       }
776     }
777 
778     /* We need more data in input buffer. */
779     if(st->bufbeg) {
780       size_t len = st->bufend - st->bufbeg;
781 
782       if(len)
783         memmove(st->buf, st->buf + st->bufbeg, len);
784       st->bufbeg = 0;
785       st->bufend = len;
786     }
787     if(st->bufend >= sizeof(st->buf))
788       return cursize? cursize: READ_ERROR;    /* Buffer full. */
789     sz = read_part_content(part, st->buf + st->bufend,
790                            sizeof(st->buf) - st->bufend);
791     switch(sz) {
792     case 0:
793       ateof = TRUE;
794       break;
795     case CURL_READFUNC_ABORT:
796     case CURL_READFUNC_PAUSE:
797     case READ_ERROR:
798       return cursize? cursize: sz;
799     default:
800       st->bufend += sz;
801       break;
802     }
803   }
804 
805   return cursize;
806 }
807 
808 /* Readback a mime part. */
readback_part(curl_mimepart * part,char * buffer,size_t bufsize)809 static size_t readback_part(curl_mimepart *part,
810                             char *buffer, size_t bufsize)
811 {
812   size_t cursize = 0;
813 #ifdef CURL_DOES_CONVERSIONS
814   char *convbuf = buffer;
815 #endif
816 
817   /* Readback from part. */
818 
819   while(bufsize) {
820     size_t sz = 0;
821     struct curl_slist *hdr = (struct curl_slist *) part->state.ptr;
822     switch(part->state.state) {
823     case MIMESTATE_BEGIN:
824       mimesetstate(&part->state, part->flags & MIME_BODY_ONLY? MIMESTATE_BODY:
825                                  MIMESTATE_CURLHEADERS, part->curlheaders);
826       break;
827     case MIMESTATE_USERHEADERS:
828       if(!hdr) {
829         mimesetstate(&part->state, MIMESTATE_EOH, NULL);
830         break;
831       }
832       if(match_header(hdr, "Content-Type", 12)) {
833         mimesetstate(&part->state, MIMESTATE_USERHEADERS, hdr->next);
834         break;
835       }
836       /* FALLTHROUGH */
837     case MIMESTATE_CURLHEADERS:
838       if(!hdr)
839         mimesetstate(&part->state, MIMESTATE_USERHEADERS, part->userheaders);
840       else {
841         sz = readback_bytes(&part->state, buffer, bufsize,
842                             hdr->data, strlen(hdr->data), "\r\n");
843         if(!sz)
844           mimesetstate(&part->state, part->state.state, hdr->next);
845       }
846       break;
847     case MIMESTATE_EOH:
848       sz = readback_bytes(&part->state, buffer, bufsize, "\r\n", 2, "");
849       if(!sz)
850         mimesetstate(&part->state, MIMESTATE_BODY, NULL);
851       break;
852     case MIMESTATE_BODY:
853 #ifdef CURL_DOES_CONVERSIONS
854       if(part->easy && convbuf < buffer) {
855         CURLcode result = Curl_convert_to_network(part->easy, convbuf,
856                                                   buffer - convbuf);
857         if(result)
858           return READ_ERROR;
859         convbuf = buffer;
860       }
861 #endif
862       cleanup_encoder_state(&part->encstate);
863       mimesetstate(&part->state, MIMESTATE_CONTENT, NULL);
864       break;
865     case MIMESTATE_CONTENT:
866       if(part->encoder)
867         sz = read_encoded_part_content(part, buffer, bufsize);
868       else
869         sz = read_part_content(part, buffer, bufsize);
870       switch(sz) {
871       case 0:
872         mimesetstate(&part->state, MIMESTATE_END, NULL);
873         /* Try sparing open file descriptors. */
874         if(part->kind == MIMEKIND_FILE && part->fp) {
875           fclose(part->fp);
876           part->fp = NULL;
877         }
878         /* FALLTHROUGH */
879       case CURL_READFUNC_ABORT:
880       case CURL_READFUNC_PAUSE:
881       case READ_ERROR:
882         return cursize? cursize: sz;
883       }
884       break;
885     case MIMESTATE_END:
886       return cursize;
887     default:
888       break;    /* Other values not in part state. */
889     }
890 
891     /* Bump buffer and counters according to read size. */
892     cursize += sz;
893     buffer += sz;
894     bufsize -= sz;
895   }
896 
897 #ifdef CURL_DOES_CONVERSIONS
898       if(part->easy && convbuf < buffer &&
899          part->state.state < MIMESTATE_BODY) {
900         CURLcode result = Curl_convert_to_network(part->easy, convbuf,
901                                                   buffer - convbuf);
902         if(result)
903           return READ_ERROR;
904       }
905 #endif
906 
907   return cursize;
908 }
909 
910 /* Readback from mime. */
mime_subparts_read(char * buffer,size_t size,size_t nitems,void * instream)911 static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems,
912                                  void *instream)
913 {
914   curl_mime *mime = (curl_mime *) instream;
915   size_t cursize = 0;
916 #ifdef CURL_DOES_CONVERSIONS
917   char *convbuf = buffer;
918 #endif
919 
920   (void) size;   /* Always 1. */
921 
922   while(nitems) {
923     size_t sz = 0;
924     curl_mimepart *part = mime->state.ptr;
925     switch(mime->state.state) {
926     case MIMESTATE_BEGIN:
927     case MIMESTATE_BODY:
928 #ifdef CURL_DOES_CONVERSIONS
929       convbuf = buffer;
930 #endif
931       mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, mime->firstpart);
932       /* The first boundary always follows the header termination empty line,
933          so is always preceded by a CRLK. We can then spare 2 characters
934          by skipping the leading CRLF in boundary. */
935       mime->state.offset += 2;
936       break;
937     case MIMESTATE_BOUNDARY1:
938       sz = readback_bytes(&mime->state, buffer, nitems, "\r\n--", 4, "");
939       if(!sz)
940         mimesetstate(&mime->state, MIMESTATE_BOUNDARY2, part);
941       break;
942     case MIMESTATE_BOUNDARY2:
943       sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary,
944                           strlen(mime->boundary), part? "\r\n": "--\r\n");
945       if(!sz) {
946 #ifdef CURL_DOES_CONVERSIONS
947         if(mime->easy && convbuf < buffer) {
948           CURLcode result = Curl_convert_to_network(mime->easy, convbuf,
949                                                     buffer - convbuf);
950           if(result)
951             return READ_ERROR;
952           convbuf = buffer;
953         }
954 #endif
955         mimesetstate(&mime->state, MIMESTATE_CONTENT, part);
956       }
957       break;
958     case MIMESTATE_CONTENT:
959       if(!part) {
960         mimesetstate(&mime->state, MIMESTATE_END, NULL);
961         break;
962       }
963       sz = readback_part(part, buffer, nitems);
964       switch(sz) {
965       case CURL_READFUNC_ABORT:
966       case CURL_READFUNC_PAUSE:
967       case READ_ERROR:
968         return cursize? cursize: sz;
969       case 0:
970 #ifdef CURL_DOES_CONVERSIONS
971         convbuf = buffer;
972 #endif
973         mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, part->nextpart);
974         break;
975       }
976       break;
977     case MIMESTATE_END:
978       return cursize;
979     default:
980       break;    /* other values not used in mime state. */
981     }
982 
983     /* Bump buffer and counters according to read size. */
984     cursize += sz;
985     buffer += sz;
986     nitems -= sz;
987   }
988 
989 #ifdef CURL_DOES_CONVERSIONS
990       if(mime->easy && convbuf < buffer &&
991          mime->state.state <= MIMESTATE_CONTENT) {
992         CURLcode result = Curl_convert_to_network(mime->easy, convbuf,
993                                                   buffer - convbuf);
994         if(result)
995           return READ_ERROR;
996       }
997 #endif
998 
999   return cursize;
1000 }
1001 
mime_part_rewind(curl_mimepart * part)1002 static int mime_part_rewind(curl_mimepart *part)
1003 {
1004   int res = CURL_SEEKFUNC_OK;
1005   enum mimestate targetstate = MIMESTATE_BEGIN;
1006 
1007   if(part->flags & MIME_BODY_ONLY)
1008     targetstate = MIMESTATE_BODY;
1009   cleanup_encoder_state(&part->encstate);
1010   if(part->state.state > targetstate) {
1011     res = CURL_SEEKFUNC_CANTSEEK;
1012     if(part->seekfunc) {
1013       res = part->seekfunc(part->arg, (curl_off_t) 0, SEEK_SET);
1014       switch(res) {
1015       case CURL_SEEKFUNC_OK:
1016       case CURL_SEEKFUNC_FAIL:
1017       case CURL_SEEKFUNC_CANTSEEK:
1018         break;
1019       case -1:    /* For fseek() error. */
1020         res = CURL_SEEKFUNC_CANTSEEK;
1021         break;
1022       default:
1023         res = CURL_SEEKFUNC_FAIL;
1024         break;
1025       }
1026     }
1027   }
1028 
1029   if(res == CURL_SEEKFUNC_OK)
1030     mimesetstate(&part->state, targetstate, NULL);
1031 
1032   return res;
1033 }
1034 
mime_subparts_seek(void * instream,curl_off_t offset,int whence)1035 static int mime_subparts_seek(void *instream, curl_off_t offset, int whence)
1036 {
1037   curl_mime *mime = (curl_mime *) instream;
1038   curl_mimepart *part;
1039   int result = CURL_SEEKFUNC_OK;
1040 
1041   if(whence != SEEK_SET || offset)
1042     return CURL_SEEKFUNC_CANTSEEK;    /* Only support full rewind. */
1043 
1044   if(mime->state.state == MIMESTATE_BEGIN)
1045    return CURL_SEEKFUNC_OK;           /* Already rewound. */
1046 
1047   for(part = mime->firstpart; part; part = part->nextpart) {
1048     int res = mime_part_rewind(part);
1049     if(res != CURL_SEEKFUNC_OK)
1050       result = res;
1051   }
1052 
1053   if(result == CURL_SEEKFUNC_OK)
1054     mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
1055 
1056   return result;
1057 }
1058 
1059 /* Release part content. */
cleanup_part_content(curl_mimepart * part)1060 static void cleanup_part_content(curl_mimepart *part)
1061 {
1062   if(part->freefunc)
1063     part->freefunc(part->arg);
1064 
1065   part->readfunc = NULL;
1066   part->seekfunc = NULL;
1067   part->freefunc = NULL;
1068   part->arg = (void *) part;          /* Defaults to part itself. */
1069   part->data = NULL;
1070   part->fp = NULL;
1071   part->datasize = (curl_off_t) 0;    /* No size yet. */
1072   cleanup_encoder_state(&part->encstate);
1073   part->kind = MIMEKIND_NONE;
1074 }
1075 
mime_subparts_free(void * ptr)1076 static void mime_subparts_free(void *ptr)
1077 {
1078   curl_mime *mime = (curl_mime *) ptr;
1079 
1080   if(mime && mime->parent) {
1081     mime->parent->freefunc = NULL;  /* Be sure we won't be called again. */
1082     cleanup_part_content(mime->parent);  /* Avoid dangling pointer in part. */
1083   }
1084   curl_mime_free(mime);
1085 }
1086 
1087 /* Do not free subparts: unbind them. This is used for the top level only. */
mime_subparts_unbind(void * ptr)1088 static void mime_subparts_unbind(void *ptr)
1089 {
1090   curl_mime *mime = (curl_mime *) ptr;
1091 
1092   if(mime && mime->parent) {
1093     mime->parent->freefunc = NULL;  /* Be sure we won't be called again. */
1094     cleanup_part_content(mime->parent);  /* Avoid dangling pointer in part. */
1095     mime->parent = NULL;
1096   }
1097 }
1098 
1099 
Curl_mime_cleanpart(curl_mimepart * part)1100 void Curl_mime_cleanpart(curl_mimepart *part)
1101 {
1102   cleanup_part_content(part);
1103   curl_slist_free_all(part->curlheaders);
1104   if(part->flags & MIME_USERHEADERS_OWNER)
1105     curl_slist_free_all(part->userheaders);
1106   Curl_safefree(part->mimetype);
1107   Curl_safefree(part->name);
1108   Curl_safefree(part->filename);
1109   Curl_mime_initpart(part, part->easy);
1110 }
1111 
1112 /* Recursively delete a mime handle and its parts. */
curl_mime_free(curl_mime * mime)1113 void curl_mime_free(curl_mime *mime)
1114 {
1115   curl_mimepart *part;
1116 
1117   if(mime) {
1118     mime_subparts_unbind(mime);  /* Be sure it's not referenced anymore. */
1119     while(mime->firstpart) {
1120       part = mime->firstpart;
1121       mime->firstpart = part->nextpart;
1122       Curl_mime_cleanpart(part);
1123       free(part);
1124     }
1125     free(mime);
1126   }
1127 }
1128 
Curl_mime_duppart(curl_mimepart * dst,const curl_mimepart * src)1129 CURLcode Curl_mime_duppart(curl_mimepart *dst, const curl_mimepart *src)
1130 {
1131   curl_mime *mime;
1132   curl_mimepart *d;
1133   const curl_mimepart *s;
1134   CURLcode res = CURLE_OK;
1135 
1136   /* Duplicate content. */
1137   switch(src->kind) {
1138   case MIMEKIND_NONE:
1139     break;
1140   case MIMEKIND_DATA:
1141     res = curl_mime_data(dst, src->data, (size_t) src->datasize);
1142     break;
1143   case MIMEKIND_FILE:
1144     res = curl_mime_filedata(dst, src->data);
1145     /* Do not abort duplication if file is not readable. */
1146     if(res == CURLE_READ_ERROR)
1147       res = CURLE_OK;
1148     break;
1149   case MIMEKIND_CALLBACK:
1150     res = curl_mime_data_cb(dst, src->datasize, src->readfunc,
1151                             src->seekfunc, src->freefunc, src->arg);
1152     break;
1153   case MIMEKIND_MULTIPART:
1154     /* No one knows about the cloned subparts, thus always attach ownership
1155        to the part. */
1156     mime = curl_mime_init(dst->easy);
1157     res = mime? curl_mime_subparts(dst, mime): CURLE_OUT_OF_MEMORY;
1158 
1159     /* Duplicate subparts. */
1160     for(s = ((curl_mime *) src->arg)->firstpart; !res && s; s = s->nextpart) {
1161       d = curl_mime_addpart(mime);
1162       res = d? Curl_mime_duppart(d, s): CURLE_OUT_OF_MEMORY;
1163     }
1164     break;
1165   default:  /* Invalid kind: should not occur. */
1166     res = CURLE_BAD_FUNCTION_ARGUMENT;  /* Internal error? */
1167     break;
1168   }
1169 
1170   /* Duplicate headers. */
1171   if(!res && src->userheaders) {
1172     struct curl_slist *hdrs = Curl_slist_duplicate(src->userheaders);
1173 
1174     if(!hdrs)
1175       res = CURLE_OUT_OF_MEMORY;
1176     else {
1177       /* No one but this procedure knows about the new header list,
1178          so always take ownership. */
1179       res = curl_mime_headers(dst, hdrs, TRUE);
1180       if(res)
1181         curl_slist_free_all(hdrs);
1182     }
1183   }
1184 
1185   /* Duplicate other fields. */
1186   if(dst != NULL)
1187     dst->encoder = src->encoder;
1188   else
1189     res = CURLE_WRITE_ERROR;
1190   if(!res)
1191     res = curl_mime_type(dst, src->mimetype);
1192   if(!res)
1193     res = curl_mime_name(dst, src->name);
1194   if(!res)
1195     res = curl_mime_filename(dst, src->filename);
1196 
1197   /* If an error occurred, rollback. */
1198   if(res && dst)
1199     Curl_mime_cleanpart(dst);
1200 
1201   return res;
1202 }
1203 
1204 /*
1205  * Mime build functions.
1206  */
1207 
1208 /* Create a mime handle. */
curl_mime_init(struct Curl_easy * easy)1209 curl_mime *curl_mime_init(struct Curl_easy *easy)
1210 {
1211   curl_mime *mime;
1212 
1213   mime = (curl_mime *) malloc(sizeof(*mime));
1214 
1215   if(mime) {
1216     mime->easy = easy;
1217     mime->parent = NULL;
1218     mime->firstpart = NULL;
1219     mime->lastpart = NULL;
1220 
1221     memset(mime->boundary, '-', 24);
1222     if(Curl_rand_hex(easy, (unsigned char *) &mime->boundary[24],
1223                      MIME_RAND_BOUNDARY_CHARS + 1)) {
1224       /* failed to get random separator, bail out */
1225       free(mime);
1226       return NULL;
1227     }
1228     mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
1229   }
1230 
1231   return mime;
1232 }
1233 
1234 /* Initialize a mime part. */
Curl_mime_initpart(curl_mimepart * part,struct Curl_easy * easy)1235 void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy)
1236 {
1237   memset((char *) part, 0, sizeof(*part));
1238   part->easy = easy;
1239   mimesetstate(&part->state, MIMESTATE_BEGIN, NULL);
1240 }
1241 
1242 /* Create a mime part and append it to a mime handle's part list. */
curl_mime_addpart(curl_mime * mime)1243 curl_mimepart *curl_mime_addpart(curl_mime *mime)
1244 {
1245   curl_mimepart *part;
1246 
1247   if(!mime)
1248     return NULL;
1249 
1250   part = (curl_mimepart *) malloc(sizeof(*part));
1251 
1252   if(part) {
1253     Curl_mime_initpart(part, mime->easy);
1254     part->parent = mime;
1255 
1256     if(mime->lastpart)
1257       mime->lastpart->nextpart = part;
1258     else
1259       mime->firstpart = part;
1260 
1261     mime->lastpart = part;
1262   }
1263 
1264   return part;
1265 }
1266 
1267 /* Set mime part name. */
curl_mime_name(curl_mimepart * part,const char * name)1268 CURLcode curl_mime_name(curl_mimepart *part, const char *name)
1269 {
1270   if(!part)
1271     return CURLE_BAD_FUNCTION_ARGUMENT;
1272 
1273   Curl_safefree(part->name);
1274   part->name = NULL;
1275 
1276   if(name) {
1277     part->name = strdup(name);
1278     if(!part->name)
1279       return CURLE_OUT_OF_MEMORY;
1280   }
1281 
1282   return CURLE_OK;
1283 }
1284 
1285 /* Set mime part remote file name. */
curl_mime_filename(curl_mimepart * part,const char * filename)1286 CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
1287 {
1288   if(!part)
1289     return CURLE_BAD_FUNCTION_ARGUMENT;
1290 
1291   Curl_safefree(part->filename);
1292   part->filename = NULL;
1293 
1294   if(filename) {
1295     part->filename = strdup(filename);
1296     if(!part->filename)
1297       return CURLE_OUT_OF_MEMORY;
1298   }
1299 
1300   return CURLE_OK;
1301 }
1302 
1303 /* Set mime part content from memory data. */
curl_mime_data(curl_mimepart * part,const char * data,size_t datasize)1304 CURLcode curl_mime_data(curl_mimepart *part,
1305                         const char *data, size_t datasize)
1306 {
1307   if(!part)
1308     return CURLE_BAD_FUNCTION_ARGUMENT;
1309 
1310   cleanup_part_content(part);
1311 
1312   if(data) {
1313     if(datasize == CURL_ZERO_TERMINATED)
1314       datasize = strlen(data);
1315 
1316     part->data = malloc(datasize + 1);
1317     if(!part->data)
1318       return CURLE_OUT_OF_MEMORY;
1319 
1320     part->datasize = datasize;
1321 
1322     if(datasize)
1323       memcpy(part->data, data, datasize);
1324     part->data[datasize] = '\0';    /* Set a nul terminator as sentinel. */
1325 
1326     part->readfunc = mime_mem_read;
1327     part->seekfunc = mime_mem_seek;
1328     part->freefunc = mime_mem_free;
1329     part->kind = MIMEKIND_DATA;
1330   }
1331 
1332   return CURLE_OK;
1333 }
1334 
1335 /* Set mime part content from named local file. */
curl_mime_filedata(curl_mimepart * part,const char * filename)1336 CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
1337 {
1338   CURLcode result = CURLE_OK;
1339 
1340   if(!part)
1341     return CURLE_BAD_FUNCTION_ARGUMENT;
1342 
1343   cleanup_part_content(part);
1344 
1345   if(filename) {
1346     char *base;
1347     struct_stat sbuf;
1348 
1349     if(stat(filename, &sbuf) || access(filename, R_OK))
1350       result = CURLE_READ_ERROR;
1351 
1352     part->data = strdup(filename);
1353     if(!part->data)
1354       result = CURLE_OUT_OF_MEMORY;
1355 
1356     part->datasize = -1;
1357     if(!result && S_ISREG(sbuf.st_mode)) {
1358       part->datasize = filesize(filename, sbuf);
1359       part->seekfunc = mime_file_seek;
1360     }
1361 
1362     part->readfunc = mime_file_read;
1363     part->freefunc = mime_file_free;
1364     part->kind = MIMEKIND_FILE;
1365 
1366     /* As a side effect, set the filename to the current file's base name.
1367        It is possible to withdraw this by explicitly calling
1368        curl_mime_filename() with a NULL filename argument after the current
1369        call. */
1370     base = strippath(filename);
1371     if(!base)
1372       result = CURLE_OUT_OF_MEMORY;
1373     else {
1374       CURLcode res = curl_mime_filename(part, base);
1375 
1376       if(res)
1377         result = res;
1378       free(base);
1379     }
1380   }
1381   return result;
1382 }
1383 
1384 /* Set mime part type. */
curl_mime_type(curl_mimepart * part,const char * mimetype)1385 CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
1386 {
1387   if(!part)
1388     return CURLE_BAD_FUNCTION_ARGUMENT;
1389 
1390   Curl_safefree(part->mimetype);
1391   part->mimetype = NULL;
1392 
1393   if(mimetype) {
1394     part->mimetype = strdup(mimetype);
1395     if(!part->mimetype)
1396       return CURLE_OUT_OF_MEMORY;
1397   }
1398 
1399   return CURLE_OK;
1400 }
1401 
1402 /* Set mime data transfer encoder. */
curl_mime_encoder(curl_mimepart * part,const char * encoding)1403 CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
1404 {
1405   CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
1406   const mime_encoder *mep;
1407 
1408   if(!part)
1409     return result;
1410 
1411   part->encoder = NULL;
1412 
1413   if(!encoding)
1414     return CURLE_OK;    /* Removing current encoder. */
1415 
1416   for(mep = encoders; mep->name; mep++)
1417     if(strcasecompare(encoding, mep->name)) {
1418       part->encoder = mep;
1419       result = CURLE_OK;
1420     }
1421 
1422   return result;
1423 }
1424 
1425 /* Set mime part headers. */
curl_mime_headers(curl_mimepart * part,struct curl_slist * headers,int take_ownership)1426 CURLcode curl_mime_headers(curl_mimepart *part,
1427                            struct curl_slist *headers, int take_ownership)
1428 {
1429   if(!part)
1430     return CURLE_BAD_FUNCTION_ARGUMENT;
1431 
1432   if(part->flags & MIME_USERHEADERS_OWNER) {
1433     if(part->userheaders != headers)  /* Allow setting twice the same list. */
1434       curl_slist_free_all(part->userheaders);
1435     part->flags &= ~MIME_USERHEADERS_OWNER;
1436   }
1437   part->userheaders = headers;
1438   if(headers && take_ownership)
1439     part->flags |= MIME_USERHEADERS_OWNER;
1440   return CURLE_OK;
1441 }
1442 
1443 /* Set mime part content from callback. */
curl_mime_data_cb(curl_mimepart * part,curl_off_t datasize,curl_read_callback readfunc,curl_seek_callback seekfunc,curl_free_callback freefunc,void * arg)1444 CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize,
1445                            curl_read_callback readfunc,
1446                            curl_seek_callback seekfunc,
1447                            curl_free_callback freefunc, void *arg)
1448 {
1449   if(!part)
1450     return CURLE_BAD_FUNCTION_ARGUMENT;
1451 
1452   cleanup_part_content(part);
1453 
1454   if(readfunc) {
1455     part->readfunc = readfunc;
1456     part->seekfunc = seekfunc;
1457     part->freefunc = freefunc;
1458     part->arg = arg;
1459     part->datasize = datasize;
1460     part->kind = MIMEKIND_CALLBACK;
1461   }
1462 
1463   return CURLE_OK;
1464 }
1465 
1466 /* Set mime part content from subparts. */
Curl_mime_set_subparts(curl_mimepart * part,curl_mime * subparts,int take_ownership)1467 CURLcode Curl_mime_set_subparts(curl_mimepart *part,
1468                                 curl_mime *subparts, int take_ownership)
1469 {
1470   curl_mime *root;
1471 
1472   if(!part)
1473     return CURLE_BAD_FUNCTION_ARGUMENT;
1474 
1475   /* Accept setting twice the same subparts. */
1476   if(part->kind == MIMEKIND_MULTIPART && part->arg == subparts)
1477     return CURLE_OK;
1478 
1479   cleanup_part_content(part);
1480 
1481   if(subparts) {
1482     /* Must belong to the same data handle. */
1483     if(part->easy && subparts->easy && part->easy != subparts->easy)
1484       return CURLE_BAD_FUNCTION_ARGUMENT;
1485 
1486     /* Should not have been attached already. */
1487     if(subparts->parent)
1488       return CURLE_BAD_FUNCTION_ARGUMENT;
1489 
1490     /* Should not be the part's root. */
1491     root = part->parent;
1492     if(root) {
1493       while(root->parent && root->parent->parent)
1494         root = root->parent->parent;
1495       if(subparts == root) {
1496         if(part->easy)
1497           failf(part->easy, "Can't add itself as a subpart!");
1498         return CURLE_BAD_FUNCTION_ARGUMENT;
1499       }
1500     }
1501 
1502     subparts->parent = part;
1503     part->readfunc = mime_subparts_read;
1504     part->seekfunc = mime_subparts_seek;
1505     part->freefunc = take_ownership? mime_subparts_free: mime_subparts_unbind;
1506     part->arg = subparts;
1507     part->datasize = -1;
1508     part->kind = MIMEKIND_MULTIPART;
1509   }
1510 
1511   return CURLE_OK;
1512 }
1513 
curl_mime_subparts(curl_mimepart * part,curl_mime * subparts)1514 CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
1515 {
1516   return Curl_mime_set_subparts(part, subparts, TRUE);
1517 }
1518 
1519 
1520 /* Readback from top mime. */
1521 /* Argument is the dummy top part. */
Curl_mime_read(char * buffer,size_t size,size_t nitems,void * instream)1522 size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream)
1523 {
1524   curl_mimepart *part = (curl_mimepart *) instream;
1525 
1526   (void) size;   /* Always 1. */
1527   return readback_part(part, buffer, nitems);
1528 }
1529 
1530 /* Rewind mime stream. */
Curl_mime_rewind(curl_mimepart * part)1531 CURLcode Curl_mime_rewind(curl_mimepart *part)
1532 {
1533   return mime_part_rewind(part) == CURL_SEEKFUNC_OK?
1534          CURLE_OK: CURLE_SEND_FAIL_REWIND;
1535 }
1536 
1537 /* Compute header list size. */
slist_size(struct curl_slist * s,size_t overhead,const char * skip)1538 static size_t slist_size(struct curl_slist *s,
1539                          size_t overhead, const char *skip)
1540 {
1541   size_t size = 0;
1542   size_t skiplen = skip? strlen(skip): 0;
1543 
1544   for(; s; s = s->next)
1545     if(!skip || !match_header(s, skip, skiplen))
1546       size += strlen(s->data) + overhead;
1547   return size;
1548 }
1549 
1550 /* Get/compute multipart size. */
multipart_size(curl_mime * mime)1551 static curl_off_t multipart_size(curl_mime *mime)
1552 {
1553   curl_off_t size;
1554   size_t boundarysize;
1555   curl_mimepart *part;
1556 
1557   if(!mime)
1558     return 0;           /* Not present -> empty. */
1559 
1560   boundarysize = 4 + strlen(mime->boundary) + 2;
1561   size = boundarysize;  /* Final boundary - CRLF after headers. */
1562 
1563   for(part = mime->firstpart; part; part = part->nextpart) {
1564     curl_off_t sz = Curl_mime_size(part);
1565 
1566     if(sz < 0)
1567       size = sz;
1568 
1569     if(size >= 0)
1570       size += boundarysize + sz;
1571   }
1572 
1573   return size;
1574 }
1575 
1576 /* Get/compute mime size. */
Curl_mime_size(curl_mimepart * part)1577 curl_off_t Curl_mime_size(curl_mimepart *part)
1578 {
1579   curl_off_t size;
1580 
1581   if(part->kind == MIMEKIND_MULTIPART)
1582     part->datasize = multipart_size(part->arg);
1583 
1584   size = part->datasize;
1585 
1586   if(part->encoder)
1587     size = part->encoder->sizefunc(part);
1588 
1589   if(size >= 0 && !(part->flags & MIME_BODY_ONLY)) {
1590     /* Compute total part size. */
1591     size += slist_size(part->curlheaders, 2, NULL);
1592     size += slist_size(part->userheaders, 2, "Content-Type");
1593     size += 2;    /* CRLF after headers. */
1594   }
1595   return size;
1596 }
1597 
1598 /* Add a header. */
1599 /* VARARGS2 */
Curl_mime_add_header(struct curl_slist ** slp,const char * fmt,...)1600 CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
1601 {
1602   struct curl_slist *hdr = NULL;
1603   char *s = NULL;
1604   va_list ap;
1605 
1606   va_start(ap, fmt);
1607   s = curl_mvaprintf(fmt, ap);
1608   va_end(ap);
1609 
1610   if(s) {
1611     hdr = Curl_slist_append_nodup(*slp, s);
1612     if(hdr)
1613       *slp = hdr;
1614     else
1615       free(s);
1616   }
1617 
1618   return hdr? CURLE_OK: CURLE_OUT_OF_MEMORY;
1619 }
1620 
1621 /* Add a content type header. */
add_content_type(struct curl_slist ** slp,const char * type,const char * boundary)1622 static CURLcode add_content_type(struct curl_slist **slp,
1623                                  const char *type, const char *boundary)
1624 {
1625   return Curl_mime_add_header(slp, "Content-Type: %s%s%s", type,
1626                               boundary? "; boundary=": "",
1627                               boundary? boundary: "");
1628 }
1629 
Curl_mime_contenttype(const char * filename)1630 const char *Curl_mime_contenttype(const char *filename)
1631 {
1632   /*
1633    * If no content type was specified, we scan through a few well-known
1634    * extensions and pick the first we match!
1635    */
1636   struct ContentType {
1637     const char *extension;
1638     const char *type;
1639   };
1640   static const struct ContentType ctts[] = {
1641     {".gif",  "image/gif"},
1642     {".jpg",  "image/jpeg"},
1643     {".jpeg", "image/jpeg"},
1644     {".png",  "image/png"},
1645     {".svg",  "image/svg+xml"},
1646     {".txt",  "text/plain"},
1647     {".htm",  "text/html"},
1648     {".html", "text/html"},
1649     {".pdf",  "application/pdf"},
1650     {".xml",  "application/xml"}
1651   };
1652 
1653   if(filename) {
1654     size_t len1 = strlen(filename);
1655     const char *nameend = filename + len1;
1656     unsigned int i;
1657 
1658     for(i = 0; i < sizeof(ctts) / sizeof(ctts[0]); i++) {
1659       size_t len2 = strlen(ctts[i].extension);
1660 
1661       if(len1 >= len2 && strcasecompare(nameend - len2, ctts[i].extension))
1662           return ctts[i].type;
1663     }
1664   }
1665   return NULL;
1666 }
1667 
Curl_mime_prepare_headers(curl_mimepart * part,const char * contenttype,const char * disposition,enum mimestrategy strategy)1668 CURLcode Curl_mime_prepare_headers(curl_mimepart *part,
1669                                    const char *contenttype,
1670                                    const char *disposition,
1671                                    enum mimestrategy strategy)
1672 {
1673   curl_mime *mime = NULL;
1674   const char *boundary = NULL;
1675   char *customct;
1676   const char *cte = NULL;
1677   CURLcode ret = CURLE_OK;
1678 
1679   /* Get rid of previously prepared headers. */
1680   curl_slist_free_all(part->curlheaders);
1681   part->curlheaders = NULL;
1682 
1683   /* Be sure we won't access old headers later. */
1684   if(part->state.state == MIMESTATE_CURLHEADERS)
1685     mimesetstate(&part->state, MIMESTATE_CURLHEADERS, NULL);
1686 
1687   /* Check if content type is specified. */
1688   customct = part->mimetype;
1689   if(!customct)
1690     customct = search_header(part->userheaders, "Content-Type");
1691   if(customct)
1692     contenttype = customct;
1693 
1694   /* If content type is not specified, try to determine it. */
1695   if(!contenttype) {
1696     switch(part->kind) {
1697     case MIMEKIND_MULTIPART:
1698       contenttype = MULTIPART_CONTENTTYPE_DEFAULT;
1699       break;
1700     case MIMEKIND_FILE:
1701       contenttype = Curl_mime_contenttype(part->filename);
1702       if(!contenttype)
1703         contenttype = Curl_mime_contenttype(part->data);
1704       if(!contenttype && part->filename)
1705         contenttype = FILE_CONTENTTYPE_DEFAULT;
1706       break;
1707     default:
1708       contenttype = Curl_mime_contenttype(part->filename);
1709       break;
1710     }
1711   }
1712 
1713   if(part->kind == MIMEKIND_MULTIPART) {
1714     mime = (curl_mime *) part->arg;
1715     if(mime)
1716       boundary = mime->boundary;
1717   }
1718   else if(contenttype && !customct &&
1719           strcasecompare(contenttype, "text/plain"))
1720     if(strategy == MIMESTRATEGY_MAIL || !part->filename)
1721       contenttype = NULL;
1722 
1723   /* Issue content-disposition header only if not already set by caller. */
1724   if(!search_header(part->userheaders, "Content-Disposition")) {
1725     if(!disposition)
1726       if(part->filename || part->name ||
1727         (contenttype && !strncasecompare(contenttype, "multipart/", 10)))
1728           disposition = DISPOSITION_DEFAULT;
1729     if(disposition && curl_strequal(disposition, "attachment") &&
1730      !part->name && !part->filename)
1731       disposition = NULL;
1732     if(disposition) {
1733       char *name = NULL;
1734       char *filename = NULL;
1735 
1736       if(part->name) {
1737         name = escape_string(part->name);
1738         if(!name)
1739           ret = CURLE_OUT_OF_MEMORY;
1740       }
1741       if(!ret && part->filename) {
1742         filename = escape_string(part->filename);
1743         if(!filename)
1744           ret = CURLE_OUT_OF_MEMORY;
1745       }
1746       if(!ret)
1747         ret = Curl_mime_add_header(&part->curlheaders,
1748                                    "Content-Disposition: %s%s%s%s%s%s%s",
1749                                    disposition,
1750                                    name? "; name=\"": "",
1751                                    name? name: "",
1752                                    name? "\"": "",
1753                                    filename? "; filename=\"": "",
1754                                    filename? filename: "",
1755                                    filename? "\"": "");
1756       Curl_safefree(name);
1757       Curl_safefree(filename);
1758       if(ret)
1759         return ret;
1760       }
1761     }
1762 
1763   /* Issue Content-Type header. */
1764   if(contenttype) {
1765     ret = add_content_type(&part->curlheaders, contenttype, boundary);
1766     if(ret)
1767       return ret;
1768   }
1769 
1770   /* Content-Transfer-Encoding header. */
1771   if(!search_header(part->userheaders, "Content-Transfer-Encoding")) {
1772     if(part->encoder)
1773       cte = part->encoder->name;
1774     else if(contenttype && strategy == MIMESTRATEGY_MAIL &&
1775      part->kind != MIMEKIND_MULTIPART)
1776       cte = "8bit";
1777     if(cte) {
1778       ret = Curl_mime_add_header(&part->curlheaders,
1779                                  "Content-Transfer-Encoding: %s", cte);
1780       if(ret)
1781         return ret;
1782     }
1783   }
1784 
1785   /* If we were reading curl-generated headers, restart with new ones (this
1786      should not occur). */
1787   if(part->state.state == MIMESTATE_CURLHEADERS)
1788     mimesetstate(&part->state, MIMESTATE_CURLHEADERS, part->curlheaders);
1789 
1790   /* Process subparts. */
1791   if(part->kind == MIMEKIND_MULTIPART && mime) {
1792     curl_mimepart *subpart;
1793 
1794     disposition = NULL;
1795     if(strcasecompare(contenttype, "multipart/form-data"))
1796       disposition = "form-data";
1797     for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) {
1798       ret = Curl_mime_prepare_headers(subpart, NULL, disposition, strategy);
1799       if(ret)
1800         return ret;
1801     }
1802   }
1803   return ret;
1804 }
1805 
1806 #else /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */
1807 
1808 /* Mime not compiled in: define stubs for externally-referenced functions. */
curl_mime_init(CURL * easy)1809 curl_mime *curl_mime_init(CURL *easy)
1810 {
1811   (void) easy;
1812   return NULL;
1813 }
1814 
curl_mime_free(curl_mime * mime)1815 void curl_mime_free(curl_mime *mime)
1816 {
1817   (void) mime;
1818 }
1819 
curl_mime_addpart(curl_mime * mime)1820 curl_mimepart *curl_mime_addpart(curl_mime *mime)
1821 {
1822   (void) mime;
1823   return NULL;
1824 }
1825 
curl_mime_name(curl_mimepart * part,const char * name)1826 CURLcode curl_mime_name(curl_mimepart *part, const char *name)
1827 {
1828   (void) part;
1829   (void) name;
1830   return CURLE_NOT_BUILT_IN;
1831 }
1832 
curl_mime_filename(curl_mimepart * part,const char * filename)1833 CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
1834 {
1835   (void) part;
1836   (void) filename;
1837   return CURLE_NOT_BUILT_IN;
1838 }
1839 
curl_mime_type(curl_mimepart * part,const char * mimetype)1840 CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
1841 {
1842   (void) part;
1843   (void) mimetype;
1844   return CURLE_NOT_BUILT_IN;
1845 }
1846 
curl_mime_encoder(curl_mimepart * part,const char * encoding)1847 CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
1848 {
1849   (void) part;
1850   (void) encoding;
1851   return CURLE_NOT_BUILT_IN;
1852 }
1853 
curl_mime_data(curl_mimepart * part,const char * data,size_t datasize)1854 CURLcode curl_mime_data(curl_mimepart *part,
1855                         const char *data, size_t datasize)
1856 {
1857   (void) part;
1858   (void) data;
1859   (void) datasize;
1860   return CURLE_NOT_BUILT_IN;
1861 }
1862 
curl_mime_filedata(curl_mimepart * part,const char * filename)1863 CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
1864 {
1865   (void) part;
1866   (void) filename;
1867   return CURLE_NOT_BUILT_IN;
1868 }
1869 
curl_mime_data_cb(curl_mimepart * part,curl_off_t datasize,curl_read_callback readfunc,curl_seek_callback seekfunc,curl_free_callback freefunc,void * arg)1870 CURLcode curl_mime_data_cb(curl_mimepart *part,
1871                            curl_off_t datasize,
1872                            curl_read_callback readfunc,
1873                            curl_seek_callback seekfunc,
1874                            curl_free_callback freefunc,
1875                            void *arg)
1876 {
1877   (void) part;
1878   (void) datasize;
1879   (void) readfunc;
1880   (void) seekfunc;
1881   (void) freefunc;
1882   (void) arg;
1883   return CURLE_NOT_BUILT_IN;
1884 }
1885 
curl_mime_subparts(curl_mimepart * part,curl_mime * subparts)1886 CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
1887 {
1888   (void) part;
1889   (void) subparts;
1890   return CURLE_NOT_BUILT_IN;
1891 }
1892 
curl_mime_headers(curl_mimepart * part,struct curl_slist * headers,int take_ownership)1893 CURLcode curl_mime_headers(curl_mimepart *part,
1894                            struct curl_slist *headers, int take_ownership)
1895 {
1896   (void) part;
1897   (void) headers;
1898   (void) take_ownership;
1899   return CURLE_NOT_BUILT_IN;
1900 }
1901 
Curl_mime_initpart(curl_mimepart * part,struct Curl_easy * easy)1902 void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy)
1903 {
1904   (void) part;
1905   (void) easy;
1906 }
1907 
Curl_mime_cleanpart(curl_mimepart * part)1908 void Curl_mime_cleanpart(curl_mimepart *part)
1909 {
1910   (void) part;
1911 }
1912 
Curl_mime_duppart(curl_mimepart * dst,const curl_mimepart * src)1913 CURLcode Curl_mime_duppart(curl_mimepart *dst, const curl_mimepart *src)
1914 {
1915   (void) dst;
1916   (void) src;
1917   return CURLE_OK;    /* Nothing to duplicate: always succeed. */
1918 }
1919 
Curl_mime_set_subparts(curl_mimepart * part,curl_mime * subparts,int take_ownership)1920 CURLcode Curl_mime_set_subparts(curl_mimepart *part,
1921                                 curl_mime *subparts, int take_ownership)
1922 {
1923   (void) part;
1924   (void) subparts;
1925   (void) take_ownership;
1926   return CURLE_NOT_BUILT_IN;
1927 }
1928 
Curl_mime_prepare_headers(curl_mimepart * part,const char * contenttype,const char * disposition,enum mimestrategy strategy)1929 CURLcode Curl_mime_prepare_headers(curl_mimepart *part,
1930                                    const char *contenttype,
1931                                    const char *disposition,
1932                                    enum mimestrategy strategy)
1933 {
1934   (void) part;
1935   (void) contenttype;
1936   (void) disposition;
1937   (void) strategy;
1938   return CURLE_NOT_BUILT_IN;
1939 }
1940 
Curl_mime_size(curl_mimepart * part)1941 curl_off_t Curl_mime_size(curl_mimepart *part)
1942 {
1943   (void) part;
1944   return (curl_off_t) -1;
1945 }
1946 
Curl_mime_read(char * buffer,size_t size,size_t nitems,void * instream)1947 size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream)
1948 {
1949   (void) buffer;
1950   (void) size;
1951   (void) nitems;
1952   (void) instream;
1953   return 0;
1954 }
1955 
Curl_mime_rewind(curl_mimepart * part)1956 CURLcode Curl_mime_rewind(curl_mimepart *part)
1957 {
1958   (void) part;
1959   return CURLE_NOT_BUILT_IN;
1960 }
1961 
1962 /* VARARGS2 */
Curl_mime_add_header(struct curl_slist ** slp,const char * fmt,...)1963 CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
1964 {
1965   (void) slp;
1966   (void) fmt;
1967   return CURLE_NOT_BUILT_IN;
1968 }
1969 
1970 #endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */
1971