Coverage Report

Created: 2026-12-01 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/mime.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) 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.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
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
struct Curl_easy;
27
28
#include "mime.h"
29
#include "urldata.h"
30
#include "sendf.h"
31
#include "curl_trc.h"
32
#include "transfer.h"
33
#include "curlx/strdup.h"
34
#include "curlx/basename.h"
35
#include "curlx/strcopy.h"
36
#include "curlx/win32-fopen.h"
37
#include "curlx/base64.h"
38
39
#if !defined(CURL_DISABLE_MIME) && (!defined(CURL_DISABLE_HTTP) ||      \
40
                                    !defined(CURL_DISABLE_SMTP) ||      \
41
                                    !defined(CURL_DISABLE_IMAP))
42
43
#include "rand.h"
44
#include "slist.h"
45
#include "curlx/dynbuf.h"
46
47
0
#define MAX_MIME_LEVELS 40 /* avoid deep nesting */
48
49
0
#define READ_ERROR   ((size_t)-1)
50
0
#define STOP_FILLING ((size_t)-2)
51
52
static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems,
53
                                 void *instream, bool *hasread);
54
static curl_off_t mime_size(curl_mimepart *part);
55
56
/* Quoted-printable character class table.
57
 *
58
 * We cannot rely on ctype functions since quoted-printable input data
59
 * is assumed to be ASCII-compatible, even on non-ASCII platforms. */
60
0
#define QP_OK           1       /* Can be represented by itself. */
61
0
#define QP_SP           2       /* Space or tab. */
62
0
#define QP_CR           3       /* Carriage return. */
63
0
#define QP_LF           4       /* Line-feed. */
64
static const unsigned char qp_class[] = {
65
  0,     0,     0,     0,     0,     0,     0,     0,            /* 00 - 07 */
66
  0,     QP_SP, QP_LF, 0,     0,     QP_CR, 0,     0,            /* 08 - 0F */
67
  0,     0,     0,     0,     0,     0,     0,     0,            /* 10 - 17 */
68
  0,     0,     0,     0,     0,     0,     0,     0,            /* 18 - 1F */
69
  QP_SP, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 20 - 27 */
70
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 28 - 2F */
71
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 30 - 37 */
72
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0    , QP_OK, QP_OK,        /* 38 - 3F */
73
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 40 - 47 */
74
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 48 - 4F */
75
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 50 - 57 */
76
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 58 - 5F */
77
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 60 - 67 */
78
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 68 - 6F */
79
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK,        /* 70 - 77 */
80
  QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0,            /* 78 - 7F */
81
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* 80 - 8F */
82
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* 90 - 9F */
83
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* A0 - AF */
84
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* B0 - BF */
85
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* C0 - CF */
86
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* D0 - DF */
87
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                /* E0 - EF */
88
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0                 /* F0 - FF */
89
};
90
91
/* Binary --> hexadecimal ASCII table. */
92
static const char aschex[] =
93
  "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46";
94
95
#ifndef __VMS
96
0
#define filesize(name, stat_data) stat_data.st_size
97
0
#define fopen_read                curlx_fopen
98
99
#else
100
101
#include <fabdef.h>
102
/*
103
 * get_vms_file_size does what it takes to get the real size of the file
104
 *
105
 * For fixed files, find out the size of the EOF block and adjust.
106
 *
107
 * For all others, have to read the entire file in, discarding the contents.
108
 * Most posted text files will be small, and binary files like zlib archives
109
 * and CD/DVD images should be either a STREAM_LF format or a fixed format.
110
 *
111
 */
112
curl_off_t VmsRealFileSize(const char *name, const curlx_struct_stat *stat_buf)
113
{
114
  char buffer[8192];
115
  curl_off_t count;
116
  int ret_stat;
117
  FILE *file;
118
119
  file = curlx_fopen(name, FOPEN_READTEXT); /* VMS */
120
  if(!file)
121
    return 0;
122
123
  count = 0;
124
  ret_stat = 1;
125
  while(ret_stat > 0) {
126
    ret_stat = fread(buffer, 1, sizeof(buffer), file);
127
    if(ret_stat)
128
      count += ret_stat;
129
  }
130
  curlx_fclose(file);
131
132
  return count;
133
}
134
135
/*
136
 *
137
 *  VmsSpecialSize checks to see if the stat st_size can be trusted and
138
 *  if not to call a routine to get the correct size.
139
 *
140
 */
141
static curl_off_t VmsSpecialSize(const char *name,
142
                                 const curlx_struct_stat *stat_buf)
143
{
144
  switch(stat_buf->st_fab_rfm) {
145
  case FAB$C_VAR:
146
  case FAB$C_VFC:
147
    return VmsRealFileSize(name, stat_buf);
148
    break;
149
  default:
150
    return stat_buf->st_size;
151
  }
152
}
153
154
#define filesize(name, stat_data) VmsSpecialSize(name, &stat_data)
155
156
/*
157
 * vmsfopenread
158
 *
159
 * For upload to work as expected on VMS, different optional
160
 * parameters must be added to the fopen command based on
161
 * record format of the file.
162
 *
163
 */
164
static FILE *vmsfopenread(const char *file, const char *mode)
165
{
166
  curlx_struct_stat statbuf;
167
  int res = curlx_stat(file, &statbuf);
168
169
  if(res != -1) {
170
    switch(statbuf.st_fab_rfm) {
171
    case FAB$C_VAR:
172
    case FAB$C_VFC:
173
    case FAB$C_STMCR:
174
      return curlx_fopen(file, FOPEN_READTEXT); /* VMS */
175
      break;
176
    default:
177
      return curlx_fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm");
178
    }
179
  }
180
  return NULL;
181
}
182
183
#define fopen_read vmsfopenread
184
#endif /* !__VMS */
185
186
/* Set readback state. */
187
static void mimesetstate(struct mime_state *state,
188
                         enum mimestate tok, void *ptr)
189
0
{
190
0
  state->state = tok;
191
0
  state->ptr = ptr;
192
0
  state->offset = 0;
193
0
}
194
195
/* Escape header string into allocated memory. */
196
static char *escape_string(struct Curl_easy *data,
197
                           const char *src, enum mimestrategy strategy)
198
0
{
199
0
  CURLcode result;
200
0
  struct dynbuf db;
201
0
  const char * const *table;
202
0
  const char * const *p;
203
  /* replace first character by rest of string. */
204
0
  static const char * const mimetable[] = {
205
0
    "\\\\\\",
206
0
    "\"\\\"",
207
0
    NULL
208
0
  };
209
  /* WHATWG HTML living standard 4.10.21.8 2 specifies:
210
     For field names and filenames for file fields, the result of the
211
     encoding in the previous bullet point must be escaped by replacing
212
     any 0x0A (LF) bytes with the byte sequence `%0A`, 0x0D (CR) with `%0D`
213
     and 0x22 (") with `%22`.
214
     The user agent must not perform any other escapes. */
215
0
  static const char * const formtable[] = {
216
0
    "\"%22",
217
0
    "\r%0D",
218
0
    "\n%0A",
219
0
    NULL
220
0
  };
221
222
0
  table = formtable;
223
  /* data can be NULL when this function is called indirectly from
224
     curl_formget(). */
225
0
  if(strategy == MIMESTRATEGY_MAIL || (data && data->set.mime_formescape))
226
0
    table = mimetable;
227
228
0
  curlx_dyn_init(&db, CURL_MAX_INPUT_LENGTH);
229
230
0
  for(result = curlx_dyn_addn(&db, STRCONST("")); !result && *src; src++) {
231
0
    for(p = table; *p && **p != *src; p++)
232
0
      ;
233
234
0
    if(*p)
235
0
      result = curlx_dyn_add(&db, *p + 1);
236
0
    else
237
0
      result = curlx_dyn_addn(&db, src, 1);
238
0
  }
239
240
0
  return curlx_dyn_ptr(&db);
241
0
}
242
243
/* Check if header matches. */
244
static char *match_header(struct curl_slist *hdr, const char *lbl, size_t len)
245
0
{
246
0
  char *value = NULL;
247
248
0
  if(curl_strnequal(hdr->data, lbl, len) && hdr->data[len] == ':')
249
0
    for(value = hdr->data + len + 1; *value == ' '; value++)
250
0
      ;
251
0
  return value;
252
0
}
253
254
/* Get a header from an slist. */
255
static char *search_header(struct curl_slist *hdrlist,
256
                           const char *hdr, size_t len)
257
0
{
258
0
  char *value = NULL;
259
260
0
  for(; !value && hdrlist; hdrlist = hdrlist->next)
261
0
    value = match_header(hdrlist, hdr, len);
262
263
0
  return value;
264
0
}
265
266
static char *strippath(const char *fullfile)
267
0
{
268
0
  char *filename;
269
0
  char *base;
270
0
  filename = curlx_strdup(fullfile); /* duplicate since basename() may ruin
271
                                        the buffer it works on */
272
0
  if(!filename)
273
0
    return NULL;
274
0
  base = curlx_strdup(curlx_basename(filename));
275
276
0
  curlx_free(filename); /* free temporary buffer */
277
278
0
  return base; /* returns an allocated string or NULL ! */
279
0
}
280
281
/* Initialize data encoder state. */
282
static void cleanup_encoder_state(struct mime_encoder_state *p)
283
0
{
284
0
  p->pos = 0;
285
0
  p->bufbeg = 0;
286
0
  p->bufend = 0;
287
0
}
288
289
/* Dummy encoder. This is used for 8-bit and binary content encodings. */
290
static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
291
                               struct curl_mimepart *part)
292
0
{
293
0
  struct mime_encoder_state *st = &part->encstate;
294
0
  size_t insize = st->bufend - st->bufbeg;
295
296
0
  (void)ateof;
297
298
0
  if(!size)
299
0
    return STOP_FILLING;
300
301
0
  if(size > insize)
302
0
    size = insize;
303
304
0
  if(size)
305
0
    memcpy(buffer, st->buf + st->bufbeg, size);
306
307
0
  st->bufbeg += size;
308
0
  return size;
309
0
}
310
311
static curl_off_t encoder_nop_size(curl_mimepart *part)
312
0
{
313
0
  return part->datasize;
314
0
}
315
316
/* 7-bit encoder: the encoder is a data validity check. */
317
static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
318
                                curl_mimepart *part)
319
0
{
320
0
  struct mime_encoder_state *st = &part->encstate;
321
0
  size_t cursize = st->bufend - st->bufbeg;
322
323
0
  (void)ateof;
324
325
0
  if(!size)
326
0
    return STOP_FILLING;
327
328
0
  if(size > cursize)
329
0
    size = cursize;
330
331
0
  for(cursize = 0; cursize < size; cursize++) {
332
0
    *buffer = st->buf[st->bufbeg];
333
0
    if(*buffer++ & 0x80)
334
0
      return cursize ? cursize : READ_ERROR;
335
0
    st->bufbeg++;
336
0
  }
337
338
0
  return cursize;
339
0
}
340
341
/* Base64 content encoder. */
342
static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
343
                                  curl_mimepart *part)
344
0
{
345
0
  struct mime_encoder_state *st = &part->encstate;
346
0
  size_t cursize = 0;
347
0
  int i;
348
0
  char *ptr = buffer;
349
350
0
  while(st->bufbeg < st->bufend) {
351
    /* Line full ? */
352
0
    if(st->pos > MAX_ENCODED_LINE_LENGTH - 4) {
353
      /* Yes, we need 2 characters for CRLF. */
354
0
      if(size < 2) {
355
0
        if(!cursize)
356
0
          return STOP_FILLING;
357
0
        break;
358
0
      }
359
0
      *ptr++ = '\r';
360
0
      *ptr++ = '\n';
361
0
      st->pos = 0;
362
0
      cursize += 2;
363
0
      size -= 2;
364
0
    }
365
366
    /* Be sure there is enough space and input data for a base64 group. */
367
0
    if(size < 4) {
368
0
      if(!cursize)
369
0
        return STOP_FILLING;
370
0
      break;
371
0
    }
372
0
    if(st->bufend - st->bufbeg < 3)
373
0
      break;
374
375
    /* Encode three bytes as four characters. */
376
0
    i = st->buf[st->bufbeg++] & 0xFF;
377
0
    i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
378
0
    i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
379
0
    *ptr++ = curlx_base64encdec[(i >> 18) & 0x3F];
380
0
    *ptr++ = curlx_base64encdec[(i >> 12) & 0x3F];
381
0
    *ptr++ = curlx_base64encdec[(i >> 6) & 0x3F];
382
0
    *ptr++ = curlx_base64encdec[i & 0x3F];
383
0
    cursize += 4;
384
0
    st->pos += 4;
385
0
    size -= 4;
386
0
  }
387
388
  /* If at eof, we have to flush the buffered data. */
389
0
  if(ateof) {
390
0
    if(size < 4) {
391
0
      if(!cursize)
392
0
        return STOP_FILLING;
393
0
    }
394
0
    else {
395
      /* Buffered data size can only be 0, 1 or 2. */
396
0
      ptr[2] = ptr[3] = '=';
397
0
      i = 0;
398
399
      /* If there is buffered data */
400
0
      if(st->bufend != st->bufbeg) {
401
402
0
        if(st->bufend - st->bufbeg == 2)
403
0
          i = (st->buf[st->bufbeg + 1] & 0xFF) << 8;
404
405
0
        i |= (st->buf[st->bufbeg] & 0xFF) << 16;
406
0
        ptr[0] = curlx_base64encdec[(i >> 18) & 0x3F];
407
0
        ptr[1] = curlx_base64encdec[(i >> 12) & 0x3F];
408
0
        if(++st->bufbeg != st->bufend) {
409
0
          ptr[2] = curlx_base64encdec[(i >> 6) & 0x3F];
410
0
          st->bufbeg++;
411
0
        }
412
0
        cursize += 4;
413
0
        st->pos += 4;
414
0
      }
415
0
    }
416
0
  }
417
418
0
  return cursize;
419
0
}
420
421
/* The maximum input size that does not cause an overflow. */
422
#define BASE64_MAX_INPUT_SIZE                                           \
423
0
  (((CURL_OFF_T_MAX / (MAX_ENCODED_LINE_LENGTH + 2)) *                  \
424
0
    MAX_ENCODED_LINE_LENGTH / 4) * 3 - 3)
425
426
static curl_off_t encoder_base64_size(curl_mimepart *part)
427
0
{
428
0
  curl_off_t size = part->datasize;
429
430
0
  if(size <= 0)
431
0
    return size;    /* Unknown size or no data. */
432
433
  /* Prevent integer overflows */
434
0
  if(size > BASE64_MAX_INPUT_SIZE)
435
0
    return -1;
436
437
  /* Compute base64 character count. */
438
0
  size = 4 * (1 + ((size - 1) / 3));
439
440
  /* Effective character count must include CRLFs. */
441
0
  return size + (2 * ((size - 1) / MAX_ENCODED_LINE_LENGTH));
442
0
}
443
444
/* Quoted-printable lookahead.
445
 *
446
 * Check if a CRLF or end of data is in input buffer at current position + n.
447
 * Return -1 if more data needed, 1 if CRLF or end of data, else 0.
448
 */
449
static int qp_lookahead_eol(struct mime_encoder_state *st, int ateof, size_t n)
450
0
{
451
0
  n += st->bufbeg;
452
0
  if(n >= st->bufend && ateof)
453
0
    return 1;
454
0
  if(n + 2 > st->bufend)
455
0
    return ateof ? 0 : -1;
456
0
  if(qp_class[st->buf[n] & 0xFF] == QP_CR &&
457
0
     qp_class[st->buf[n + 1] & 0xFF] == QP_LF)
458
0
    return 1;
459
0
  return 0;
460
0
}
461
462
/* Quoted-printable encoder. */
463
static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
464
                              curl_mimepart *part)
465
0
{
466
0
  struct mime_encoder_state *st = &part->encstate;
467
0
  char *ptr = buffer;
468
0
  size_t cursize = 0;
469
0
  int softlinebreak;
470
0
  char buf[4];
471
472
  /* On all platforms, input is supposed to be ASCII compatible: for this
473
     reason, we use hexadecimal ASCII codes in this function rather than
474
     character constants that can be interpreted as non-ASCII on some
475
     platforms. Preserve ASCII encoding on output too. */
476
0
  while(st->bufbeg < st->bufend) {
477
0
    size_t len = 1;
478
0
    size_t consumed = 1;
479
0
    int i = (unsigned char)st->buf[st->bufbeg];
480
0
    buf[0] = (char)i;
481
0
    buf[1] = aschex[(i >> 4) & 0xF];
482
0
    buf[2] = aschex[i & 0xF];
483
484
0
    switch(qp_class[st->buf[st->bufbeg] & 0xFF]) {
485
0
    case QP_OK:          /* Not a special character. */
486
0
      break;
487
0
    case QP_SP:          /* Space or tab. */
488
      /* Spacing must be escaped if followed by CRLF. */
489
0
      switch(qp_lookahead_eol(st, ateof, 1)) {
490
0
      case -1:          /* More input data needed. */
491
0
        return cursize;
492
0
      case 0:           /* No encoding needed. */
493
0
        break;
494
0
      default:          /* CRLF after space or tab. */
495
0
        buf[0] = '\x3D';    /* '=' */
496
0
        len = 3;
497
0
        break;
498
0
      }
499
0
      break;
500
0
    case QP_CR:         /* Carriage return. */
501
      /* If followed by a line-feed, output the CRLF pair.
502
         Else escape it. */
503
0
      switch(qp_lookahead_eol(st, ateof, 0)) {
504
0
      case -1:          /* Need more data. */
505
0
        return cursize;
506
0
      case 1:           /* CRLF found. */
507
0
        buf[len++] = '\x0A';    /* Append '\n'. */
508
0
        consumed = 2;
509
0
        break;
510
0
      default:          /* Not followed by LF: escape. */
511
0
        buf[0] = '\x3D';    /* '=' */
512
0
        len = 3;
513
0
        break;
514
0
      }
515
0
      break;
516
0
    default:            /* Character must be escaped. */
517
0
      buf[0] = '\x3D';    /* '=' */
518
0
      len = 3;
519
0
      break;
520
0
    }
521
522
    /* Be sure the encoded character fits within maximum line length. */
523
0
    if(buf[len - 1] != '\x0A') {    /* '\n' */
524
0
      softlinebreak = st->pos + len > MAX_ENCODED_LINE_LENGTH;
525
0
      if(!softlinebreak && st->pos + len == MAX_ENCODED_LINE_LENGTH) {
526
        /* We may use the current line only if end of data or followed by
527
           a CRLF. */
528
0
        switch(qp_lookahead_eol(st, ateof, consumed)) {
529
0
        case -1:        /* Need more data. */
530
0
          return cursize;
531
0
        case 0:         /* Not followed by a CRLF. */
532
0
          softlinebreak = 1;
533
0
          break;
534
0
        }
535
0
      }
536
0
      if(softlinebreak) {
537
0
        curlx_strcopy(buf, sizeof(buf), STRCONST("\x3D\x0D\x0A")); /* =\r\n */
538
0
        len = 3;
539
0
        consumed = 0;
540
0
      }
541
0
    }
542
543
    /* If the output buffer would overflow, do not store. */
544
0
    if(len > size) {
545
0
      if(!cursize)
546
0
        return STOP_FILLING;
547
0
      break;
548
0
    }
549
550
    /* Append to output buffer. */
551
0
    memcpy(ptr, buf, len);
552
0
    cursize += len;
553
0
    ptr += len;
554
0
    size -= len;
555
0
    st->pos += len;
556
0
    if(buf[len - 1] == '\x0A')    /* '\n' */
557
0
      st->pos = 0;
558
0
    st->bufbeg += consumed;
559
0
  }
560
561
0
  return cursize;
562
0
}
563
564
static curl_off_t encoder_qp_size(curl_mimepart *part)
565
0
{
566
  /* Determining the size can only be done by reading the data: unless the
567
     data size is 0, we return it as unknown (-1). */
568
0
  return part->datasize ? -1 : 0;
569
0
}
570
571
/* In-memory data callbacks. */
572
/* Argument is a pointer to the mime part. */
573
static size_t mime_mem_read(char *buffer, size_t size, size_t nitems,
574
                            void *instream)
575
0
{
576
0
  curl_mimepart *part = (curl_mimepart *)instream;
577
0
  size_t sz = curlx_sotouz(part->datasize - part->state.offset);
578
0
  (void)size;  /* Always 1 */
579
580
0
  if(!nitems)
581
0
    return STOP_FILLING;
582
583
0
  if(sz > nitems)
584
0
    sz = nitems;
585
586
0
  if(sz)
587
0
    memcpy(buffer, part->data + curlx_sotouz(part->state.offset), sz);
588
589
0
  return sz;
590
0
}
591
592
static int mime_mem_seek(void *instream, curl_off_t offset, int whence)
593
0
{
594
0
  curl_mimepart *part = (curl_mimepart *)instream;
595
596
0
  switch(whence) {
597
0
  case SEEK_CUR:
598
0
    offset += part->state.offset;
599
0
    break;
600
0
  case SEEK_END:
601
0
    offset += part->datasize;
602
0
    break;
603
0
  }
604
605
0
  if(offset < 0 || offset > part->datasize)
606
0
    return CURL_SEEKFUNC_FAIL;
607
608
0
  part->state.offset = offset;
609
0
  return CURL_SEEKFUNC_OK;
610
0
}
611
612
static void mime_mem_free(void *ptr)
613
0
{
614
0
  curlx_safefree(((curl_mimepart *)ptr)->data);
615
0
}
616
617
/* Named file callbacks. */
618
/* Argument is a pointer to the mime part. */
619
static bool mime_open_file(curl_mimepart *part)
620
0
{
621
  /* Open a MIMEKIND_FILE part. */
622
623
0
  if(part->fp)
624
0
    return FALSE;
625
0
  part->fp = fopen_read(part->data, "rb");
626
0
  return part->fp ? FALSE : TRUE;
627
0
}
628
629
static size_t mime_file_read(char *buffer, size_t size, size_t nitems,
630
                             void *instream)
631
0
{
632
0
  curl_mimepart *part = (curl_mimepart *)instream;
633
0
  size_t nread;
634
635
0
  if(!nitems)
636
0
    return STOP_FILLING;
637
638
0
  if(mime_open_file(part))
639
0
    return READ_ERROR;
640
641
0
  clearerr(part->fp);
642
0
  nread = fread(buffer, size, nitems, part->fp);
643
0
  return ferror(part->fp) ? READ_ERROR : nread;
644
0
}
645
646
static int mime_file_seek(void *instream, curl_off_t offset, int whence)
647
0
{
648
0
  curl_mimepart *part = (curl_mimepart *)instream;
649
650
0
  if(whence == SEEK_SET && !offset && !part->fp)
651
0
    return CURL_SEEKFUNC_OK;   /* Not open: implicitly already at BOF. */
652
653
0
  if(mime_open_file(part))
654
0
    return CURL_SEEKFUNC_FAIL;
655
656
0
  return curlx_fseek(part->fp, offset, whence) ?
657
0
    CURL_SEEKFUNC_CANTSEEK : CURL_SEEKFUNC_OK;
658
0
}
659
660
static void mime_file_free(void *ptr)
661
0
{
662
0
  curl_mimepart *part = (curl_mimepart *)ptr;
663
664
0
  if(part->fp) {
665
0
    curlx_fclose(part->fp);
666
0
    part->fp = NULL;
667
0
  }
668
0
  curlx_safefree(part->data);
669
0
}
670
671
/* Subparts callbacks. */
672
/* Argument is a pointer to the mime structure. */
673
674
/* Readback a byte string segment. */
675
static size_t readback_bytes(struct mime_state *state,
676
                             char *buffer, size_t bufsize,
677
                             const char *bytes, size_t numbytes,
678
                             const char *trail, size_t traillen)
679
0
{
680
0
  size_t sz;
681
0
  size_t offset = curlx_sotouz(state->offset);
682
683
0
  if(numbytes > offset) {
684
0
    sz = numbytes - offset;
685
0
    bytes += offset;
686
0
  }
687
0
  else {
688
0
    sz = offset - numbytes;
689
0
    if(sz >= traillen)
690
0
      return 0;
691
0
    bytes = trail + sz;
692
0
    sz = traillen - sz;
693
0
  }
694
695
0
  if(sz > bufsize)
696
0
    sz = bufsize;
697
698
0
  memcpy(buffer, bytes, sz);
699
0
  state->offset += sz;
700
0
  return sz;
701
0
}
702
703
/* Read a non-encoded part content. */
704
705
static size_t read_part_content(curl_mimepart *part, char *buffer,
706
                                size_t bufsize, bool *hasread)
707
0
{
708
0
  size_t sz = 0;
709
710
0
  switch(part->lastreadstatus) {
711
0
  case 0:
712
0
  case CURL_READFUNC_ABORT:
713
0
  case CURL_READFUNC_PAUSE:
714
0
  case READ_ERROR:
715
0
    return part->lastreadstatus;
716
0
  default:
717
0
    break;
718
0
  }
719
720
  /* If we can determine we are at end of part data, spare a read. */
721
0
  if(part->datasize != (curl_off_t)-1 &&
722
0
     part->state.offset >= part->datasize) {
723
    /* sz is already zero. */
724
0
  }
725
0
  else {
726
0
    if(part->datasize != (curl_off_t)-1)
727
0
      bufsize = curlx_sotouz_range(part->datasize - part->state.offset,
728
0
                                  0, bufsize);
729
0
    switch(part->kind) {
730
0
    case MIMEKIND_MULTIPART:
731
      /*
732
       * Cannot be processed as other kinds since read function requires
733
       * an additional parameter and is highly recursive.
734
       */
735
0
      sz = mime_subparts_read(buffer, 1, bufsize, part->arg, hasread);
736
0
      break;
737
0
    case MIMEKIND_FILE:
738
0
      if(part->fp && feof(part->fp))
739
0
        break;  /* At EOF. */
740
0
      FALLTHROUGH();
741
0
    default:
742
0
      if(part->readfunc) {
743
0
        if(!(part->flags & MIME_FAST_READ)) {
744
0
          if(*hasread)
745
0
            return STOP_FILLING;
746
0
          *hasread = TRUE;
747
0
        }
748
0
        sz = part->readfunc(buffer, 1, bufsize, part->arg);
749
0
      }
750
0
      break;
751
0
    }
752
0
  }
753
754
0
  switch(sz) {
755
0
  case STOP_FILLING:
756
0
    break;
757
0
  case 0:
758
0
  case CURL_READFUNC_ABORT:
759
0
  case CURL_READFUNC_PAUSE:
760
0
  case READ_ERROR:
761
0
    part->lastreadstatus = sz;
762
0
    break;
763
0
  default:
764
0
    part->state.offset += sz;
765
0
    part->lastreadstatus = sz;
766
0
    break;
767
0
  }
768
769
0
  return sz;
770
0
}
771
772
/* Read and encode part content. */
773
static size_t read_encoded_part_content(curl_mimepart *part, char *buffer,
774
                                        size_t bufsize, bool *hasread)
775
0
{
776
0
  struct mime_encoder_state *st = &part->encstate;
777
0
  size_t cursize = 0;
778
0
  size_t sz;
779
0
  bool ateof = FALSE;
780
781
0
  for(;;) {
782
0
    if(st->bufbeg < st->bufend || ateof) {
783
      /* Encode buffered data. */
784
0
      sz = part->encoder->encodefunc(buffer, bufsize, ateof, part);
785
0
      switch(sz) {
786
0
      case 0:
787
0
        if(ateof)
788
0
          return cursize;
789
0
        break;
790
0
      case READ_ERROR:
791
0
      case STOP_FILLING:
792
0
        return cursize ? cursize : sz;
793
0
      default:
794
0
        cursize += sz;
795
0
        buffer += sz;
796
0
        bufsize -= sz;
797
0
        continue;
798
0
      }
799
0
    }
800
801
    /* We need more data in input buffer. */
802
0
    if(st->bufbeg) {
803
0
      size_t len = st->bufend - st->bufbeg;
804
805
0
      if(len)
806
0
        memmove(st->buf, st->buf + st->bufbeg, len);
807
0
      st->bufbeg = 0;
808
0
      st->bufend = len;
809
0
    }
810
0
    if(st->bufend >= sizeof(st->buf))
811
0
      return cursize ? cursize : READ_ERROR;    /* Buffer full. */
812
0
    sz = read_part_content(part, st->buf + st->bufend,
813
0
                           sizeof(st->buf) - st->bufend, hasread);
814
0
    switch(sz) {
815
0
    case 0:
816
0
      ateof = TRUE;
817
0
      break;
818
0
    case CURL_READFUNC_ABORT:
819
0
    case CURL_READFUNC_PAUSE:
820
0
    case READ_ERROR:
821
0
    case STOP_FILLING:
822
0
      return cursize ? cursize : sz;
823
0
    default:
824
0
      st->bufend += sz;
825
0
      break;
826
0
    }
827
0
  }
828
829
  /* NOTREACHED */
830
0
}
831
832
/* Readback a mime part. */
833
static size_t readback_part(curl_mimepart *part,
834
                            char *buffer, size_t bufsize, bool *hasread)
835
0
{
836
0
  size_t cursize = 0;
837
838
  /* Readback from part. */
839
0
  while(bufsize) {
840
0
    size_t sz = 0;
841
0
    struct curl_slist *hdr = (struct curl_slist *)part->state.ptr;
842
0
    switch(part->state.state) {
843
0
    case MIMESTATE_BEGIN:
844
0
      mimesetstate(&part->state,
845
0
                   (part->flags & MIME_BODY_ONLY) ?
846
0
                   MIMESTATE_BODY : MIMESTATE_CURLHEADERS,
847
0
                   part->curlheaders);
848
0
      break;
849
0
    case MIMESTATE_USERHEADERS:
850
0
      if(!hdr) {
851
0
        mimesetstate(&part->state, MIMESTATE_EOH, NULL);
852
0
        break;
853
0
      }
854
0
      if(match_header(hdr, "Content-Type", 12)) {
855
0
        mimesetstate(&part->state, MIMESTATE_USERHEADERS, hdr->next);
856
0
        break;
857
0
      }
858
0
      FALLTHROUGH();
859
0
    case MIMESTATE_CURLHEADERS:
860
0
      if(!hdr)
861
0
        mimesetstate(&part->state, MIMESTATE_USERHEADERS, part->userheaders);
862
0
      else {
863
0
        sz = readback_bytes(&part->state, buffer, bufsize,
864
0
                            hdr->data, strlen(hdr->data), STRCONST("\r\n"));
865
0
        if(!sz)
866
0
          mimesetstate(&part->state, part->state.state, hdr->next);
867
0
      }
868
0
      break;
869
0
    case MIMESTATE_EOH:
870
0
      sz = readback_bytes(&part->state, buffer, bufsize, STRCONST("\r\n"),
871
0
                          STRCONST(""));
872
0
      if(!sz)
873
0
        mimesetstate(&part->state, MIMESTATE_BODY, NULL);
874
0
      break;
875
0
    case MIMESTATE_BODY:
876
0
      cleanup_encoder_state(&part->encstate);
877
0
      mimesetstate(&part->state, MIMESTATE_CONTENT, NULL);
878
0
      break;
879
0
    case MIMESTATE_CONTENT:
880
0
      if(part->encoder)
881
0
        sz = read_encoded_part_content(part, buffer, bufsize, hasread);
882
0
      else
883
0
        sz = read_part_content(part, buffer, bufsize, hasread);
884
0
      switch(sz) {
885
0
      case 0:
886
0
        mimesetstate(&part->state, MIMESTATE_END, NULL);
887
        /* Try sparing open file descriptors. */
888
0
        if(part->kind == MIMEKIND_FILE && part->fp) {
889
0
          curlx_fclose(part->fp);
890
0
          part->fp = NULL;
891
0
        }
892
0
        FALLTHROUGH();
893
0
      case CURL_READFUNC_ABORT:
894
0
      case CURL_READFUNC_PAUSE:
895
0
      case READ_ERROR:
896
0
      case STOP_FILLING:
897
0
        return cursize ? cursize : sz;
898
0
      }
899
0
      break;
900
0
    case MIMESTATE_END:
901
0
      return cursize;
902
0
    default:
903
0
      break;    /* Other values not in part state. */
904
0
    }
905
906
    /* Bump buffer and counters according to read size. */
907
0
    cursize += sz;
908
0
    buffer += sz;
909
0
    bufsize -= sz;
910
0
  }
911
912
0
  return cursize;
913
0
}
914
915
/* Readback from mime. Warning: not a read callback function. */
916
static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems,
917
                                 void *instream, bool *hasread)
918
0
{
919
0
  curl_mime *mime = (curl_mime *)instream;
920
0
  size_t cursize = 0;
921
0
  (void)size;  /* Always 1 */
922
923
0
  while(nitems) {
924
0
    size_t sz = 0;
925
0
    curl_mimepart *part = mime->state.ptr;
926
0
    switch(mime->state.state) {
927
0
    case MIMESTATE_BEGIN:
928
0
    case MIMESTATE_BODY:
929
0
      mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, mime->firstpart);
930
      /* The first boundary always follows the header termination empty line,
931
         so is always preceded by a CRLF. We can then spare 2 characters
932
         by skipping the leading CRLF in boundary. */
933
0
      mime->state.offset += 2;
934
0
      break;
935
0
    case MIMESTATE_BOUNDARY1:
936
0
      sz = readback_bytes(&mime->state, buffer, nitems, STRCONST("\r\n--"),
937
0
                          STRCONST(""));
938
0
      if(!sz)
939
0
        mimesetstate(&mime->state, MIMESTATE_BOUNDARY2, part);
940
0
      break;
941
0
    case MIMESTATE_BOUNDARY2:
942
0
      if(part)
943
0
        sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary,
944
0
                            MIME_BOUNDARY_LEN, STRCONST("\r\n"));
945
0
      else
946
0
        sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary,
947
0
                            MIME_BOUNDARY_LEN, STRCONST("--\r\n"));
948
0
      if(!sz) {
949
0
        mimesetstate(&mime->state, MIMESTATE_CONTENT, part);
950
0
      }
951
0
      break;
952
0
    case MIMESTATE_CONTENT:
953
0
      if(!part) {
954
0
        mimesetstate(&mime->state, MIMESTATE_END, NULL);
955
0
        break;
956
0
      }
957
0
      sz = readback_part(part, buffer, nitems, hasread);
958
0
      switch(sz) {
959
0
      case CURL_READFUNC_ABORT:
960
0
      case CURL_READFUNC_PAUSE:
961
0
      case READ_ERROR:
962
0
      case STOP_FILLING:
963
0
        return cursize ? cursize : sz;
964
0
      case 0:
965
0
        mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, part->nextpart);
966
0
        break;
967
0
      }
968
0
      break;
969
0
    case MIMESTATE_END:
970
0
      return cursize;
971
0
    default:
972
0
      break;    /* other values not used in mime state. */
973
0
    }
974
975
    /* Bump buffer and counters according to read size. */
976
0
    cursize += sz;
977
0
    buffer += sz;
978
0
    nitems -= sz;
979
0
  }
980
981
0
  return cursize;
982
0
}
983
984
static int mime_part_rewind(curl_mimepart *part)
985
0
{
986
0
  int res = CURL_SEEKFUNC_OK;
987
0
  enum mimestate targetstate = MIMESTATE_BEGIN;
988
989
0
  if(part->flags & MIME_BODY_ONLY)
990
0
    targetstate = MIMESTATE_BODY;
991
0
  cleanup_encoder_state(&part->encstate);
992
0
  if(part->state.state > targetstate) {
993
0
    res = CURL_SEEKFUNC_CANTSEEK;
994
0
    if(part->seekfunc) {
995
0
      res = part->seekfunc(part->arg, (curl_off_t)0, SEEK_SET);
996
0
      switch(res) {
997
0
      case CURL_SEEKFUNC_OK:
998
0
      case CURL_SEEKFUNC_FAIL:
999
0
      case CURL_SEEKFUNC_CANTSEEK:
1000
0
        break;
1001
0
      case -1:    /* For fseek() error. */
1002
0
        res = CURL_SEEKFUNC_CANTSEEK;
1003
0
        break;
1004
0
      default:
1005
0
        res = CURL_SEEKFUNC_FAIL;
1006
0
        break;
1007
0
      }
1008
0
    }
1009
0
  }
1010
1011
0
  if(res == CURL_SEEKFUNC_OK)
1012
0
    mimesetstate(&part->state, targetstate, NULL);
1013
1014
0
  part->lastreadstatus = 1; /* Successful read status. */
1015
0
  return res;
1016
0
}
1017
1018
static int mime_subparts_seek(void *instream, curl_off_t offset, int whence)
1019
0
{
1020
0
  curl_mime *mime = (curl_mime *)instream;
1021
0
  curl_mimepart *part;
1022
0
  int rc = CURL_SEEKFUNC_OK;
1023
1024
0
  if(whence != SEEK_SET || offset)
1025
0
    return CURL_SEEKFUNC_CANTSEEK;    /* Only support full rewind. */
1026
1027
0
  if(mime->state.state == MIMESTATE_BEGIN)
1028
0
    return CURL_SEEKFUNC_OK;           /* Already rewound. */
1029
1030
0
  for(part = mime->firstpart; part; part = part->nextpart) {
1031
0
    int res = mime_part_rewind(part);
1032
0
    if(res != CURL_SEEKFUNC_OK)
1033
0
      rc = res;
1034
0
  }
1035
1036
0
  if(rc == CURL_SEEKFUNC_OK)
1037
0
    mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
1038
1039
0
  return rc;
1040
0
}
1041
1042
/* Release part content. */
1043
static void cleanup_part_content(curl_mimepart *part)
1044
0
{
1045
0
  if(part->freefunc)
1046
0
    part->freefunc(part->arg);
1047
1048
0
  part->readfunc = NULL;
1049
0
  part->seekfunc = NULL;
1050
0
  part->freefunc = NULL;
1051
0
  part->arg = (void *)part;           /* Defaults to part itself. */
1052
0
  part->data = NULL;
1053
0
  part->fp = NULL;
1054
0
  part->datasize = (curl_off_t)0;     /* No size yet. */
1055
0
  cleanup_encoder_state(&part->encstate);
1056
0
  part->kind = MIMEKIND_NONE;
1057
0
  part->flags &= ~(unsigned int)MIME_FAST_READ;
1058
0
  part->lastreadstatus = 1; /* Successful read status. */
1059
0
  part->state.state = MIMESTATE_BEGIN;
1060
0
}
1061
1062
static void mime_subparts_free(void *ptr)
1063
0
{
1064
0
  curl_mime *mime = (curl_mime *)ptr;
1065
1066
0
  if(mime && mime->parent) {
1067
0
    mime->parent->freefunc = NULL;  /* Be sure we will not be called again. */
1068
0
    cleanup_part_content(mime->parent);  /* Avoid dangling pointer in part. */
1069
0
  }
1070
0
  curl_mime_free(mime);
1071
0
}
1072
1073
/* Do not free subparts: unbind them. This is used for the top level only. */
1074
static void mime_subparts_unbind(void *ptr)
1075
0
{
1076
0
  curl_mime *mime = (curl_mime *)ptr;
1077
1078
0
  if(mime && mime->parent) {
1079
0
    mime->parent->freefunc = NULL;  /* Be sure we will not be called again. */
1080
0
    cleanup_part_content(mime->parent);  /* Avoid dangling pointer in part. */
1081
0
    mime->parent = NULL;
1082
0
  }
1083
0
}
1084
1085
void Curl_mime_cleanpart(curl_mimepart *part)
1086
0
{
1087
0
  if(part) {
1088
0
    cleanup_part_content(part);
1089
0
    curl_slist_free_all(part->curlheaders);
1090
0
    if(part->flags & MIME_USERHEADERS_OWNER)
1091
0
      curl_slist_free_all(part->userheaders);
1092
0
    curlx_safefree(part->mimetype);
1093
0
    curlx_safefree(part->name);
1094
0
    curlx_safefree(part->filename);
1095
0
    Curl_mime_initpart(part);
1096
0
  }
1097
0
}
1098
1099
/* Non-recursively delete a mime handle and its parts. */
1100
void curl_mime_free(curl_mime *mime)
1101
0
{
1102
0
  curl_mimepart *part;
1103
1104
0
  if(!mime)
1105
0
    return;
1106
1107
0
  mime_subparts_unbind(mime);  /* Be sure it is not referenced anymore. */
1108
1109
0
  while(mime) {
1110
0
    part = mime->firstpart;
1111
0
    if(part) {
1112
0
      mime->firstpart = part->nextpart;
1113
0
      if(part->kind == MIMEKIND_MULTIPART && part->arg &&
1114
0
         part->freefunc == mime_subparts_free) {
1115
0
        curl_mime *subparts = (curl_mime *)part->arg;
1116
0
        part->freefunc = NULL;
1117
0
        cleanup_part_content(part);
1118
0
        subparts->parent = mime->parent;
1119
0
        mime->parent = (curl_mimepart *)subparts;
1120
0
      }
1121
0
      Curl_mime_cleanpart(part);
1122
0
      curlx_free(part);
1123
0
    }
1124
0
    else {
1125
0
      curl_mime *parent = (curl_mime *)mime->parent;
1126
0
      curlx_free(mime);
1127
0
      mime = parent;
1128
0
    }
1129
0
  }
1130
0
}
1131
1132
static bool mime_is_too_deep(const curl_mimepart *part, size_t call_depth)
1133
0
{
1134
0
  DEBUGASSERT(part);
1135
1136
0
  if(++call_depth > MAX_MIME_LEVELS)
1137
0
    return TRUE;
1138
1139
0
  if(part->kind == MIMEKIND_MULTIPART && part->arg) {
1140
0
    const curl_mime *mime = (const curl_mime *)part->arg;
1141
0
    const curl_mimepart *s;
1142
1143
0
    for(s = mime->firstpart; s; s = s->nextpart) {
1144
0
      if(mime_is_too_deep(s, call_depth))
1145
0
        return TRUE;
1146
0
    }
1147
0
  }
1148
1149
0
  return FALSE;
1150
0
}
1151
1152
static CURLcode mime_duppart(struct Curl_easy *data,
1153
                             curl_mimepart *dst, const curl_mimepart *src,
1154
                             size_t call_depth)
1155
0
{
1156
0
  curl_mime *mime;
1157
0
  curl_mimepart *d;
1158
0
  const curl_mimepart *s;
1159
0
  CURLcode result = CURLE_OK;
1160
1161
0
  DEBUGASSERT(dst);
1162
0
  DEBUGASSERT(src);
1163
1164
0
  if(++call_depth > MAX_MIME_LEVELS)
1165
0
    return CURLE_TOO_LARGE;
1166
1167
  /* Duplicate content. */
1168
0
  switch(src->kind) {
1169
0
  case MIMEKIND_NONE:
1170
0
    break;
1171
0
  case MIMEKIND_DATA:
1172
0
    result = curl_mime_data(dst, src->data, (size_t)src->datasize);
1173
0
    break;
1174
0
  case MIMEKIND_FILE:
1175
0
    result = curl_mime_filedata(dst, src->data);
1176
    /* Do not abort duplication if file is not readable. */
1177
0
    if(result == CURLE_READ_ERROR)
1178
0
      result = CURLE_OK;
1179
0
    break;
1180
0
  case MIMEKIND_CALLBACK:
1181
0
    result = curl_mime_data_cb(dst, src->datasize, src->readfunc,
1182
0
                               src->seekfunc, src->freefunc, src->arg);
1183
0
    break;
1184
0
  case MIMEKIND_MULTIPART:
1185
    /* No one knows about the cloned subparts, thus always attach ownership
1186
       to the part. */
1187
0
    mime = curl_mime_init(data);
1188
0
    result = mime ? curl_mime_subparts(dst, mime) : CURLE_OUT_OF_MEMORY;
1189
1190
    /* Duplicate subparts. */
1191
0
    for(s = ((curl_mime *)src->arg)->firstpart; !result && s;
1192
0
        s = s->nextpart) {
1193
0
      d = curl_mime_addpart(mime);
1194
0
      result = d ? mime_duppart(data, d, s, call_depth) : CURLE_OUT_OF_MEMORY;
1195
0
    }
1196
0
    break;
1197
0
  default:  /* Invalid kind: should not occur. */
1198
0
    DEBUGF(infof(data, "invalid MIMEKIND* attempt"));
1199
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;  /* Internal error? */
1200
0
    break;
1201
0
  }
1202
1203
  /* Duplicate headers. */
1204
0
  if(!result && src->userheaders) {
1205
0
    struct curl_slist *hdrs = Curl_slist_duplicate(src->userheaders);
1206
1207
0
    if(!hdrs)
1208
0
      result = CURLE_OUT_OF_MEMORY;
1209
0
    else {
1210
      /* No one but this procedure knows about the new header list,
1211
         so always take ownership. */
1212
0
      result = curl_mime_headers(dst, hdrs, TRUE);
1213
0
      if(result)
1214
0
        curl_slist_free_all(hdrs);
1215
0
    }
1216
0
  }
1217
1218
0
  if(!result) {
1219
    /* Duplicate other fields. */
1220
0
    dst->encoder = src->encoder;
1221
0
    result = curl_mime_type(dst, src->mimetype);
1222
0
  }
1223
0
  if(!result)
1224
0
    result = curl_mime_name(dst, src->name);
1225
0
  if(!result)
1226
0
    result = curl_mime_filename(dst, src->filename);
1227
1228
  /* If an error occurred, rollback. */
1229
0
  if(result)
1230
0
    Curl_mime_cleanpart(dst);
1231
1232
0
  return result;
1233
0
}
1234
1235
CURLcode Curl_mime_duppart(struct Curl_easy *data,
1236
                           curl_mimepart *dst, const curl_mimepart *src)
1237
0
{
1238
0
  if(!dst || !src)
1239
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1240
1241
0
  if(mime_is_too_deep(src, 0))
1242
0
    return CURLE_TOO_LARGE;
1243
1244
0
  return mime_duppart(data, dst, src, 0);
1245
0
}
1246
1247
/*
1248
 * Mime build functions.
1249
 */
1250
1251
/* Create a mime handle. */
1252
curl_mime *curl_mime_init(void *easy)
1253
0
{
1254
0
  curl_mime *mime = curlx_malloc(sizeof(*mime));
1255
1256
0
  if(mime) {
1257
0
    mime->parent = NULL;
1258
0
    mime->firstpart = NULL;
1259
0
    mime->lastpart = NULL;
1260
1261
0
    memset(mime->boundary, '-', MIME_BOUNDARY_DASHES);
1262
0
    if(Curl_rand_alnum(easy,
1263
0
                       (unsigned char *)&mime->boundary[MIME_BOUNDARY_DASHES],
1264
0
                       MIME_RAND_BOUNDARY_CHARS + 1)) {
1265
      /* failed to get random separator, bail out */
1266
0
      curlx_free(mime);
1267
0
      return NULL;
1268
0
    }
1269
0
    mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
1270
0
  }
1271
1272
0
  return mime;
1273
0
}
1274
1275
/* Initialize a mime part. */
1276
void Curl_mime_initpart(curl_mimepart *part)
1277
0
{
1278
0
  memset(part, 0, sizeof(*part));
1279
0
  part->lastreadstatus = 1; /* Successful read status. */
1280
0
  mimesetstate(&part->state, MIMESTATE_BEGIN, NULL);
1281
0
}
1282
1283
/* Create a mime part and append it to a mime handle's part list. */
1284
curl_mimepart *curl_mime_addpart(curl_mime *mime)
1285
0
{
1286
0
  curl_mimepart *part;
1287
1288
0
  if(!mime)
1289
0
    return NULL;
1290
1291
0
  part = curlx_malloc(sizeof(*part));
1292
1293
0
  if(part) {
1294
0
    Curl_mime_initpart(part);
1295
0
    part->parent = mime;
1296
1297
0
    if(mime->lastpart)
1298
0
      mime->lastpart->nextpart = part;
1299
0
    else
1300
0
      mime->firstpart = part;
1301
1302
0
    mime->lastpart = part;
1303
0
  }
1304
1305
0
  return part;
1306
0
}
1307
1308
/* Set mime part name. */
1309
CURLcode curl_mime_name(curl_mimepart *part, const char *name)
1310
0
{
1311
0
  if(!part)
1312
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1313
1314
0
  curlx_safefree(part->name);
1315
1316
0
  if(name) {
1317
0
    part->name = curlx_strdup(name);
1318
0
    if(!part->name)
1319
0
      return CURLE_OUT_OF_MEMORY;
1320
0
  }
1321
1322
0
  return CURLE_OK;
1323
0
}
1324
1325
/* Set mime part remote filename. */
1326
CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
1327
0
{
1328
0
  if(!part)
1329
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1330
1331
0
  curlx_safefree(part->filename);
1332
1333
0
  if(filename) {
1334
0
    part->filename = curlx_strdup(filename);
1335
0
    if(!part->filename)
1336
0
      return CURLE_OUT_OF_MEMORY;
1337
0
  }
1338
1339
0
  return CURLE_OK;
1340
0
}
1341
1342
/* Set mime part content from memory data. */
1343
CURLcode curl_mime_data(curl_mimepart *part, const char *data, size_t datasize)
1344
0
{
1345
0
  if(!part)
1346
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1347
1348
0
  cleanup_part_content(part);
1349
1350
0
  if(data) {
1351
0
    if(datasize == CURL_ZERO_TERMINATED)
1352
0
      datasize = strlen(data);
1353
1354
0
    part->data = curlx_memdup0(data, datasize);
1355
0
    if(!part->data)
1356
0
      return CURLE_OUT_OF_MEMORY;
1357
1358
0
    part->datasize = datasize;
1359
0
    part->readfunc = mime_mem_read;
1360
0
    part->seekfunc = mime_mem_seek;
1361
0
    part->freefunc = mime_mem_free;
1362
0
    part->flags |= MIME_FAST_READ;
1363
0
    part->kind = MIMEKIND_DATA;
1364
0
  }
1365
1366
0
  return CURLE_OK;
1367
0
}
1368
1369
/* Set mime part content from named local file. */
1370
CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
1371
0
{
1372
0
  CURLcode result = CURLE_OK;
1373
1374
0
  if(!part)
1375
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1376
1377
0
  cleanup_part_content(part);
1378
1379
0
  if(filename) {
1380
0
    char *base;
1381
0
    curlx_struct_stat sbuf;
1382
1383
0
    if(curlx_stat(filename, &sbuf))
1384
0
      result = CURLE_READ_ERROR;
1385
0
    else {
1386
0
      part->data = curlx_strdup(filename);
1387
0
      if(!part->data)
1388
0
        result = CURLE_OUT_OF_MEMORY;
1389
0
      else {
1390
0
        part->datasize = -1;
1391
0
        if(S_ISREG(sbuf.st_mode)) {
1392
0
          part->datasize = filesize(filename, sbuf);
1393
0
          part->seekfunc = mime_file_seek;
1394
0
        }
1395
1396
0
        part->readfunc = mime_file_read;
1397
0
        part->freefunc = mime_file_free;
1398
0
        part->kind = MIMEKIND_FILE;
1399
1400
        /* As a side effect, set the filename to the current file's base name.
1401
           It is possible to withdraw this by explicitly calling
1402
           curl_mime_filename() with a NULL filename argument after the current
1403
           call. */
1404
0
        base = strippath(filename);
1405
0
        if(!base)
1406
0
          result = CURLE_OUT_OF_MEMORY;
1407
0
        else {
1408
0
          result = curl_mime_filename(part, base);
1409
0
          curlx_free(base);
1410
0
        }
1411
0
      }
1412
0
    }
1413
0
  }
1414
0
  return result;
1415
0
}
1416
1417
/* Set mime part type. */
1418
CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
1419
0
{
1420
0
  if(!part)
1421
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1422
1423
0
  curlx_safefree(part->mimetype);
1424
1425
0
  if(mimetype) {
1426
0
    part->mimetype = curlx_strdup(mimetype);
1427
0
    if(!part->mimetype)
1428
0
      return CURLE_OUT_OF_MEMORY;
1429
0
  }
1430
1431
0
  return CURLE_OK;
1432
0
}
1433
1434
static const struct mime_encoder encoders[] = {
1435
  { "binary", encoder_nop_read, encoder_nop_size },
1436
  { "8bit", encoder_nop_read, encoder_nop_size },
1437
  { "7bit", encoder_7bit_read, encoder_nop_size },
1438
  { "base64", encoder_base64_read, encoder_base64_size },
1439
  { "quoted-printable", encoder_qp_read, encoder_qp_size },
1440
  { ZERO_NULL, ZERO_NULL, ZERO_NULL }
1441
};
1442
1443
/* Set mime data transfer encoder. */
1444
CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
1445
0
{
1446
0
  CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
1447
0
  const struct mime_encoder *mep;
1448
1449
0
  if(!part)
1450
0
    return result;
1451
1452
0
  part->encoder = NULL;
1453
1454
0
  if(!encoding)
1455
0
    return CURLE_OK;    /* Removing current encoder. */
1456
1457
0
  for(mep = encoders; mep->name; mep++)
1458
0
    if(curl_strequal(encoding, mep->name)) {
1459
0
      part->encoder = mep;
1460
0
      result = CURLE_OK;
1461
0
    }
1462
1463
0
  return result;
1464
0
}
1465
1466
/* Set mime part headers. */
1467
CURLcode curl_mime_headers(curl_mimepart *part,
1468
                           struct curl_slist *headers, int take_ownership)
1469
0
{
1470
0
  if(!part)
1471
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1472
1473
0
  if(part->flags & MIME_USERHEADERS_OWNER) {
1474
0
    if(part->userheaders != headers)  /* Allow setting twice the same list. */
1475
0
      curl_slist_free_all(part->userheaders);
1476
0
    part->flags &= ~(unsigned int)MIME_USERHEADERS_OWNER;
1477
0
  }
1478
0
  part->userheaders = headers;
1479
0
  if(headers && take_ownership)
1480
0
    part->flags |= MIME_USERHEADERS_OWNER;
1481
0
  return CURLE_OK;
1482
0
}
1483
1484
/* Set mime part content from callback. */
1485
CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize,
1486
                           curl_read_callback readfunc,
1487
                           curl_seek_callback seekfunc,
1488
                           curl_free_callback freefunc, void *arg)
1489
0
{
1490
0
  if(!part)
1491
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1492
1493
0
  cleanup_part_content(part);
1494
1495
0
  if(readfunc) {
1496
0
    part->readfunc = readfunc;
1497
0
    part->seekfunc = seekfunc;
1498
0
    part->freefunc = freefunc;
1499
0
    part->arg = arg;
1500
0
    part->datasize = datasize;
1501
0
    part->kind = MIMEKIND_CALLBACK;
1502
0
  }
1503
1504
0
  return CURLE_OK;
1505
0
}
1506
1507
/* Set mime part content from subparts. */
1508
CURLcode Curl_mime_set_subparts(curl_mimepart *part,
1509
                                curl_mime *subparts, int take_ownership)
1510
0
{
1511
0
  curl_mime *root;
1512
1513
0
  if(!part)
1514
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1515
1516
  /* Accept setting twice the same subparts. */
1517
0
  if(part->kind == MIMEKIND_MULTIPART && part->arg == subparts)
1518
0
    return CURLE_OK;
1519
1520
0
  if(!subparts)
1521
0
    cleanup_part_content(part);
1522
0
  else {
1523
    /* Should not have been attached already. */
1524
0
    if(subparts->parent)
1525
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
1526
1527
    /* Should not be the part's root. */
1528
0
    root = part->parent;
1529
0
    if(root) {
1530
0
      while(root->parent && root->parent->parent)
1531
0
        root = root->parent->parent;
1532
0
      if(subparts == root) {
1533
        /* cannot add as a subpart of itself. */
1534
0
        return CURLE_BAD_FUNCTION_ARGUMENT;
1535
0
      }
1536
0
    }
1537
1538
    /* If subparts have already been used as a top-level MIMEPOST,
1539
       they might not be positioned at start. Rewind them now, as
1540
       a future check while rewinding the parent may cause this
1541
       content to be skipped. */
1542
0
    if(mime_subparts_seek(subparts, (curl_off_t)0, SEEK_SET) !=
1543
0
       CURL_SEEKFUNC_OK)
1544
0
      return CURLE_SEND_FAIL_REWIND;
1545
1546
0
    cleanup_part_content(part);
1547
1548
0
    subparts->parent = part;
1549
    /* Subparts are processed internally: no read callback. */
1550
0
    part->seekfunc = mime_subparts_seek;
1551
0
    part->freefunc = take_ownership ? mime_subparts_free :
1552
0
      mime_subparts_unbind;
1553
0
    part->arg = subparts;
1554
0
    part->datasize = -1;
1555
0
    part->kind = MIMEKIND_MULTIPART;
1556
0
  }
1557
1558
0
  return CURLE_OK;
1559
0
}
1560
1561
CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
1562
0
{
1563
0
  return Curl_mime_set_subparts(part, subparts, TRUE);
1564
0
}
1565
1566
/* Readback from top mime. */
1567
/* Argument is the dummy top part. */
1568
size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream)
1569
0
{
1570
0
  curl_mimepart *part = (curl_mimepart *)instream;
1571
0
  size_t ret;
1572
0
  bool hasread;
1573
1574
0
  (void)size;  /* Always 1 */
1575
1576
  /* If `nitems` is <= 4, some encoders will return STOP_FILLING without
1577
   * adding any data and this loops infinitely. */
1578
0
  do {
1579
0
    hasread = FALSE;
1580
0
    ret = readback_part(part, buffer, nitems, &hasread);
1581
    /*
1582
     * If this is not possible to get some data without calling more than
1583
     * one read callback (probably because a content encoder is not able to
1584
     * deliver a new bunch for the few data accumulated so far), force another
1585
     * read until we get enough data or a special exit code.
1586
     */
1587
0
  } while(ret == STOP_FILLING);
1588
1589
0
  return ret;
1590
0
}
1591
1592
/* Rewind mime stream. */
1593
static CURLcode mime_rewind(curl_mimepart *part)
1594
0
{
1595
0
  return mime_part_rewind(part) == CURL_SEEKFUNC_OK ?
1596
0
         CURLE_OK : CURLE_SEND_FAIL_REWIND;
1597
0
}
1598
1599
/* Compute header list size. */
1600
static size_t slist_size(struct curl_slist *s,
1601
                         size_t overhead, const char *skip, size_t skiplen)
1602
0
{
1603
0
  size_t size = 0;
1604
1605
0
  for(; s; s = s->next)
1606
0
    if(!skip || !match_header(s, skip, skiplen))
1607
0
      size += strlen(s->data) + overhead;
1608
0
  return size;
1609
0
}
1610
1611
/* Get/compute multipart size. */
1612
static curl_off_t multipart_size(curl_mime *mime)
1613
0
{
1614
0
  curl_off_t size;
1615
0
  curl_off_t boundarysize;
1616
0
  curl_mimepart *part;
1617
1618
0
  if(!mime)
1619
0
    return 0;           /* Not present -> empty. */
1620
1621
0
  boundarysize = 4 + MIME_BOUNDARY_LEN + 2;
1622
0
  size = boundarysize;  /* Final boundary - CRLF after headers. */
1623
1624
0
  for(part = mime->firstpart; part; part = part->nextpart) {
1625
0
    curl_off_t sz = mime_size(part);
1626
1627
0
    if(sz < 0)
1628
0
      size = sz;
1629
1630
0
    if(size >= 0)
1631
0
      size += boundarysize + sz;
1632
0
  }
1633
1634
0
  return size;
1635
0
}
1636
1637
/* Get/compute mime size. */
1638
static curl_off_t mime_size(curl_mimepart *part)
1639
0
{
1640
0
  curl_off_t size;
1641
1642
0
  if(part->kind == MIMEKIND_MULTIPART)
1643
0
    part->datasize = multipart_size(part->arg);
1644
1645
0
  size = part->datasize;
1646
1647
0
  if(part->encoder)
1648
0
    size = part->encoder->sizefunc(part);
1649
1650
0
  if(size >= 0 && !(part->flags & MIME_BODY_ONLY)) {
1651
    /* Compute total part size. */
1652
0
    size += slist_size(part->curlheaders, 2, NULL, 0);
1653
0
    size += slist_size(part->userheaders, 2, STRCONST("Content-Type"));
1654
0
    size += 2;    /* CRLF after headers. */
1655
0
  }
1656
0
  return size;
1657
0
}
1658
1659
/* Add a header. */
1660
/* VARARGS2 */
1661
CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
1662
0
{
1663
0
  struct curl_slist *hdr = NULL;
1664
0
  char *s = NULL;
1665
0
  va_list ap;
1666
1667
0
  va_start(ap, fmt);
1668
0
  s = curl_mvaprintf(fmt, ap);
1669
0
  va_end(ap);
1670
1671
0
  if(s) {
1672
0
    hdr = Curl_slist_append_nodup(*slp, s);
1673
0
    if(hdr)
1674
0
      *slp = hdr;
1675
0
    else
1676
0
      curlx_free(s);
1677
0
  }
1678
1679
0
  return hdr ? CURLE_OK : CURLE_OUT_OF_MEMORY;
1680
0
}
1681
1682
/* Add a content type header. */
1683
static CURLcode add_content_type(struct curl_slist **slp,
1684
                                 const char *type, const char *boundary)
1685
0
{
1686
0
  return Curl_mime_add_header(slp, "Content-Type: %s%s%s", type,
1687
0
                              boundary ? "; boundary=" : "",
1688
0
                              boundary ? boundary : "");
1689
0
}
1690
1691
const char *Curl_mime_contenttype(const char *filename)
1692
0
{
1693
  /*
1694
   * If no content type was specified, we scan through a few well-known
1695
   * extensions and pick the first we match!
1696
   */
1697
0
  struct ContentType {
1698
0
    const char *extension;
1699
0
    const char *type;
1700
0
  };
1701
0
  static const struct ContentType ctts[] = {
1702
0
    { ".gif",  "image/gif" },
1703
0
    { ".jpg",  "image/jpeg" },
1704
0
    { ".jpeg", "image/jpeg" },
1705
0
    { ".png",  "image/png" },
1706
0
    { ".svg",  "image/svg+xml" },
1707
0
    { ".txt",  "text/plain" },
1708
0
    { ".htm",  "text/html" },
1709
0
    { ".html", "text/html" },
1710
0
    { ".pdf",  "application/pdf" },
1711
0
    { ".xml",  "application/xml" }
1712
0
  };
1713
1714
0
  if(filename) {
1715
0
    size_t len1 = strlen(filename);
1716
0
    const char *nameend = filename + len1;
1717
0
    unsigned int i;
1718
1719
0
    for(i = 0; i < CURL_ARRAYSIZE(ctts); i++) {
1720
0
      size_t len2 = strlen(ctts[i].extension);
1721
1722
0
      if(len1 >= len2 && curl_strequal(nameend - len2, ctts[i].extension))
1723
0
        return ctts[i].type;
1724
0
    }
1725
0
  }
1726
0
  return NULL;
1727
0
}
1728
1729
static bool content_type_match(const char *contenttype,
1730
                               const char *target, size_t len)
1731
0
{
1732
0
  if(contenttype && curl_strnequal(contenttype, target, len))
1733
0
    switch(contenttype[len]) {
1734
0
    case '\0':
1735
0
    case '\t':
1736
0
    case '\r':
1737
0
    case '\n':
1738
0
    case ' ':
1739
0
    case ';':
1740
0
      return TRUE;
1741
0
    }
1742
0
  return FALSE;
1743
0
}
1744
1745
static CURLcode add_content_disposition(struct Curl_easy *data,
1746
                                        curl_mimepart *part,
1747
                                        const char *disposition,
1748
                                        const char *contenttype,
1749
                                        enum mimestrategy strategy)
1750
0
{
1751
0
  if(!disposition &&
1752
0
     (part->filename || part->name ||
1753
0
      (contenttype && !curl_strnequal(contenttype, "multipart/", 10))))
1754
0
    disposition = DISPOSITION_DEFAULT;
1755
1756
0
  if(disposition && curl_strequal(disposition, "attachment") &&
1757
0
     !part->name && !part->filename)
1758
0
    disposition = NULL;
1759
1760
0
  if(disposition) {
1761
0
    CURLcode result = CURLE_OK;
1762
0
    char *name = NULL;
1763
0
    char *filename = NULL;
1764
    /* The mail (and legacy mime_formescape) strategy quotes the name and
1765
       filename with a backslash and has no in-band way to represent a CR or
1766
       LF, so one embedded in the value would split the generated header. The
1767
       form strategy percent-encodes CR/LF (see escape_string) and is safe. */
1768
0
    bool backslash = (strategy == MIMESTRATEGY_MAIL) ||
1769
0
                     (data && data->set.mime_formescape);
1770
0
    if(backslash &&
1771
0
       ((part->name && part->name[strcspn(part->name, "\r\n")]) ||
1772
0
        (part->filename && part->filename[strcspn(part->filename, "\r\n")])))
1773
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
1774
1775
0
    if(part->name) {
1776
0
      name = escape_string(data, part->name, strategy);
1777
0
      if(!name)
1778
0
        return CURLE_OUT_OF_MEMORY;
1779
0
    }
1780
0
    if(part->filename) {
1781
0
      filename = escape_string(data, part->filename, strategy);
1782
0
      if(!filename)
1783
0
        result = CURLE_OUT_OF_MEMORY;
1784
0
    }
1785
0
    if(!result)
1786
0
      result = Curl_mime_add_header(&part->curlheaders,
1787
0
                                    "Content-Disposition: %s%s%s%s%s%s%s",
1788
0
                                    disposition,
1789
0
                                    name ? "; name=\"" : "",
1790
0
                                    name ? name : "",
1791
0
                                    name ? "\"" : "",
1792
0
                                    filename ? "; filename=\"" : "",
1793
0
                                    filename ? filename : "",
1794
0
                                    filename ? "\"" : "");
1795
0
    curlx_safefree(name);
1796
0
    curlx_safefree(filename);
1797
0
    if(result)
1798
0
      return result;
1799
0
  }
1800
0
  return CURLE_OK;
1801
0
}
1802
1803
static CURLcode mime_prepare_headers(struct Curl_easy *data,
1804
                                     curl_mimepart *part,
1805
                                     const char *contenttype,
1806
                                     const char *disposition,
1807
                                     enum mimestrategy strategy,
1808
                                     size_t call_depth)
1809
0
{
1810
0
  curl_mime *mime = NULL;
1811
0
  const char *boundary = NULL;
1812
0
  char *customct;
1813
0
  const char *cte = NULL;
1814
0
  CURLcode result = CURLE_OK;
1815
1816
0
  if(++call_depth > MAX_MIME_LEVELS)
1817
0
    return CURLE_TOO_LARGE;
1818
1819
  /* Get rid of previously prepared headers. */
1820
0
  curl_slist_free_all(part->curlheaders);
1821
0
  part->curlheaders = NULL;
1822
1823
  /* Be sure we will not access old headers later. */
1824
0
  if(part->state.state == MIMESTATE_CURLHEADERS)
1825
0
    mimesetstate(&part->state, MIMESTATE_CURLHEADERS, NULL);
1826
1827
  /* Check if content type is specified. */
1828
0
  customct = part->mimetype;
1829
0
  if(!customct)
1830
0
    customct = search_header(part->userheaders, STRCONST("Content-Type"));
1831
0
  if(customct)
1832
0
    contenttype = customct;
1833
1834
  /* If content type is not specified, try to determine it. */
1835
0
  if(!contenttype) {
1836
0
    switch(part->kind) {
1837
0
    case MIMEKIND_MULTIPART:
1838
0
      contenttype = MULTIPART_CONTENTTYPE_DEFAULT;
1839
0
      break;
1840
0
    case MIMEKIND_FILE:
1841
0
      contenttype = Curl_mime_contenttype(part->filename);
1842
0
      if(!contenttype)
1843
0
        contenttype = Curl_mime_contenttype(part->data);
1844
0
      if(!contenttype && part->filename)
1845
0
        contenttype = FILE_CONTENTTYPE_DEFAULT;
1846
0
      break;
1847
0
    default:
1848
0
      contenttype = Curl_mime_contenttype(part->filename);
1849
0
      break;
1850
0
    }
1851
0
  }
1852
1853
0
  if(part->kind == MIMEKIND_MULTIPART) {
1854
0
    mime = (curl_mime *)part->arg;
1855
0
    if(mime)
1856
0
      boundary = mime->boundary;
1857
0
  }
1858
0
  else if(contenttype && !customct &&
1859
0
          content_type_match(contenttype, STRCONST("text/plain")) &&
1860
0
          (strategy == MIMESTRATEGY_MAIL || !part->filename))
1861
0
    contenttype = NULL;
1862
1863
  /* Issue content-disposition header only if not already set by caller. */
1864
0
  if(!search_header(part->userheaders, STRCONST("Content-Disposition"))) {
1865
0
    result = add_content_disposition(data, part, disposition,
1866
0
                                     contenttype, strategy);
1867
0
    if(result)
1868
0
      return result;
1869
0
  }
1870
1871
  /* Issue Content-Type header. */
1872
0
  if(contenttype) {
1873
0
    result = add_content_type(&part->curlheaders, contenttype, boundary);
1874
0
    if(result)
1875
0
      return result;
1876
0
  }
1877
1878
  /* Content-Transfer-Encoding header. */
1879
0
  if(!search_header(part->userheaders,
1880
0
                    STRCONST("Content-Transfer-Encoding"))) {
1881
0
    if(part->encoder)
1882
0
      cte = part->encoder->name;
1883
0
    else if(contenttype && strategy == MIMESTRATEGY_MAIL &&
1884
0
            part->kind != MIMEKIND_MULTIPART)
1885
0
      cte = "8bit";
1886
0
    if(cte) {
1887
0
      result = Curl_mime_add_header(&part->curlheaders,
1888
0
                                    "Content-Transfer-Encoding: %s", cte);
1889
0
      if(result)
1890
0
        return result;
1891
0
    }
1892
0
  }
1893
1894
  /* If we were reading curl-generated headers, restart with new ones (this
1895
     should not occur). */
1896
0
  if(part->state.state == MIMESTATE_CURLHEADERS)
1897
0
    mimesetstate(&part->state, MIMESTATE_CURLHEADERS, part->curlheaders);
1898
1899
  /* Process subparts. */
1900
0
  if(part->kind == MIMEKIND_MULTIPART && mime) {
1901
0
    curl_mimepart *subpart;
1902
1903
0
    disposition = NULL;
1904
0
    if(content_type_match(contenttype, STRCONST("multipart/form-data")))
1905
0
      disposition = "form-data";
1906
0
    for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) {
1907
0
      result = mime_prepare_headers(data, subpart, NULL,
1908
0
                                    disposition, strategy, call_depth);
1909
0
      if(result)
1910
0
        return result;
1911
0
    }
1912
0
  }
1913
0
  return result;
1914
0
}
1915
1916
CURLcode Curl_mime_prepare_headers(struct Curl_easy *data,
1917
                                   curl_mimepart *part,
1918
                                   const char *contenttype,
1919
                                   const char *disposition,
1920
                                   enum mimestrategy strategy)
1921
0
{
1922
0
  return mime_prepare_headers(data, part, contenttype, disposition,
1923
0
                              strategy, 0);
1924
0
}
1925
1926
/* Recursively reset paused status in the given part. */
1927
static void mime_unpause(curl_mimepart *part)
1928
0
{
1929
0
  if(part) {
1930
0
    if(part->lastreadstatus == CURL_READFUNC_PAUSE)
1931
0
      part->lastreadstatus = 1; /* Successful read status. */
1932
0
    if(part->kind == MIMEKIND_MULTIPART) {
1933
0
      curl_mime *mime = (curl_mime *)part->arg;
1934
1935
0
      if(mime) {
1936
0
        curl_mimepart *subpart;
1937
1938
0
        for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart)
1939
0
          mime_unpause(subpart);
1940
0
      }
1941
0
    }
1942
0
  }
1943
0
}
1944
1945
struct cr_mime_ctx {
1946
  struct Curl_creader super;
1947
  curl_mimepart *part;
1948
  curl_off_t total_len;
1949
  curl_off_t read_len;
1950
  CURLcode error_result;
1951
  struct bufq tmpbuf;
1952
  BIT(seen_eos);
1953
  BIT(errored);
1954
};
1955
1956
static CURLcode cr_mime_init(struct Curl_easy *data,
1957
                             struct Curl_creader *reader)
1958
0
{
1959
0
  struct cr_mime_ctx *ctx = reader->ctx;
1960
0
  (void)data;
1961
0
  ctx->total_len = -1;
1962
0
  ctx->read_len = 0;
1963
0
  Curl_bufq_init2(&ctx->tmpbuf, 1024, 1, BUFQ_OPT_NO_SPARES);
1964
0
  return CURLE_OK;
1965
0
}
1966
1967
static void cr_mime_close(struct Curl_easy *data,
1968
                          struct Curl_creader *reader)
1969
0
{
1970
0
  struct cr_mime_ctx *ctx = reader->ctx;
1971
0
  (void)data;
1972
0
  Curl_bufq_free(&ctx->tmpbuf);
1973
0
}
1974
1975
/* Real client reader to installed client callbacks. */
1976
static CURLcode cr_mime_read(struct Curl_easy *data,
1977
                             struct Curl_creader *reader,
1978
                             char *buf, size_t blen,
1979
                             size_t *pnread, bool *peos)
1980
0
{
1981
0
  struct cr_mime_ctx *ctx = reader->ctx;
1982
0
  CURLcode result = CURLE_OK;
1983
0
  size_t nread;
1984
0
  char tmp[256];
1985
1986
  /* Once we have errored, we will return the same error forever */
1987
0
  if(ctx->errored) {
1988
0
    CURL_TRC_READ(data, "cr_mime_read(len=%zu) is errored -> %d, eos=0",
1989
0
                  blen, (int)ctx->error_result);
1990
0
    *pnread = 0;
1991
0
    *peos = FALSE;
1992
0
    return ctx->error_result;
1993
0
  }
1994
0
  if(ctx->seen_eos) {
1995
0
    CURL_TRC_READ(data, "cr_mime_read(len=%zu) seen eos -> 0, eos=1", blen);
1996
0
    *pnread = 0;
1997
0
    *peos = TRUE;
1998
0
    return CURLE_OK;
1999
0
  }
2000
  /* respect length limitations */
2001
0
  if(ctx->total_len >= 0) {
2002
0
    curl_off_t remain = ctx->total_len - ctx->read_len;
2003
0
    if(remain <= 0)
2004
0
      blen = 0;
2005
0
    else if(remain < (curl_off_t)blen)
2006
0
      blen = (size_t)remain;
2007
0
  }
2008
2009
0
  if(!Curl_bufq_is_empty(&ctx->tmpbuf)) {
2010
0
    result = Curl_bufq_read(&ctx->tmpbuf, (unsigned char *)buf, blen, &nread);
2011
0
    if(result) {
2012
0
      ctx->errored = TRUE;
2013
0
      ctx->error_result = result;
2014
0
      return result;
2015
0
    }
2016
0
  }
2017
0
  else if(blen <= 4) {
2018
    /* Curl_mime_read() may go into an infinite loop when reading
2019
     * via a base64 encoder, as it stalls when the read buffer is too small
2020
     * to contain a complete 3-byte encoding. Read into a larger buffer
2021
     * and use that until empty. */
2022
0
    CURL_TRC_READ(data, "cr_mime_read(len=%zu), small read, using tmp", blen);
2023
0
    nread = Curl_mime_read(tmp, 1, sizeof(tmp), ctx->part);
2024
0
    if(nread <= sizeof(tmp)) {
2025
0
      size_t n;
2026
0
      result = Curl_bufq_write(&ctx->tmpbuf, (unsigned char *)tmp, nread, &n);
2027
0
      if(result) {
2028
0
        ctx->errored = TRUE;
2029
0
        ctx->error_result = result;
2030
0
        return result;
2031
0
      }
2032
      /* stored it, read again */
2033
0
      result = Curl_bufq_cread(&ctx->tmpbuf, buf, blen, &nread);
2034
0
      if(result) {
2035
0
        ctx->errored = TRUE;
2036
0
        ctx->error_result = result;
2037
0
        return result;
2038
0
      }
2039
0
    }
2040
0
  }
2041
0
  else
2042
0
    nread = Curl_mime_read(buf, 1, blen, ctx->part);
2043
2044
0
  CURL_TRC_READ(data, "cr_mime_read(len=%zu), mime_read() -> %zu",
2045
0
                blen, nread);
2046
2047
0
  switch(nread) {
2048
0
  case 0:
2049
0
    if((ctx->total_len >= 0) && (ctx->read_len < ctx->total_len)) {
2050
0
      failf(data, "client mime read EOF fail, "
2051
0
            "only %" FMT_OFF_T "/%" FMT_OFF_T
2052
0
            " of needed bytes read", ctx->read_len, ctx->total_len);
2053
0
      return CURLE_READ_ERROR;
2054
0
    }
2055
0
    *pnread = 0;
2056
0
    *peos = TRUE;
2057
0
    ctx->seen_eos = TRUE;
2058
0
    break;
2059
2060
0
  case CURL_READFUNC_ABORT:
2061
0
    failf(data, "operation aborted by callback");
2062
0
    *pnread = 0;
2063
0
    *peos = FALSE;
2064
0
    ctx->errored = TRUE;
2065
0
    ctx->error_result = CURLE_ABORTED_BY_CALLBACK;
2066
0
    result = CURLE_ABORTED_BY_CALLBACK;
2067
0
    break;
2068
2069
0
  case CURL_READFUNC_PAUSE:
2070
    /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
2071
0
    CURL_TRC_READ(data, "cr_mime_read(len=%zu), paused by callback", blen);
2072
0
    *pnread = 0;
2073
0
    *peos = FALSE;
2074
0
    result = Curl_xfer_pause_send(data, TRUE);
2075
0
    break; /* nothing was read */
2076
2077
0
  case STOP_FILLING:
2078
0
  case READ_ERROR:
2079
0
    failf(data, "read error getting mime data");
2080
0
    *pnread = 0;
2081
0
    *peos = FALSE;
2082
0
    ctx->errored = TRUE;
2083
0
    ctx->error_result = CURLE_READ_ERROR;
2084
0
    result = CURLE_READ_ERROR;
2085
0
    break;
2086
2087
0
  default:
2088
0
    if(nread > blen) {
2089
      /* the read function returned a too large value */
2090
0
      failf(data, "read function returned funny value");
2091
0
      *pnread = 0;
2092
0
      *peos = FALSE;
2093
0
      ctx->errored = TRUE;
2094
0
      ctx->error_result = CURLE_READ_ERROR;
2095
0
      return CURLE_READ_ERROR;
2096
0
    }
2097
0
    ctx->read_len += nread;
2098
0
    if(ctx->total_len >= 0)
2099
0
      ctx->seen_eos = (ctx->read_len >= ctx->total_len);
2100
0
    *pnread = nread;
2101
0
    *peos = (bool)ctx->seen_eos;
2102
0
    break;
2103
0
  }
2104
2105
0
  CURL_TRC_READ(data, "cr_mime_read(len=%zu, total=%" FMT_OFF_T
2106
0
                ", read=%" FMT_OFF_T ") -> %d, %zu, %d", blen,
2107
0
                ctx->total_len, ctx->read_len, (int)result, *pnread, *peos);
2108
0
  return result;
2109
0
}
2110
2111
static bool cr_mime_needs_rewind(struct Curl_easy *data,
2112
                                 struct Curl_creader *reader)
2113
0
{
2114
0
  struct cr_mime_ctx *ctx = reader->ctx;
2115
0
  (void)data;
2116
0
  return ctx->read_len > 0;
2117
0
}
2118
2119
static curl_off_t cr_mime_total_length(struct Curl_easy *data,
2120
                                       struct Curl_creader *reader)
2121
0
{
2122
0
  struct cr_mime_ctx *ctx = reader->ctx;
2123
0
  (void)data;
2124
0
  return ctx->total_len;
2125
0
}
2126
2127
static CURLcode cr_mime_resume_from(struct Curl_easy *data,
2128
                                    struct Curl_creader *reader,
2129
                                    curl_off_t offset)
2130
0
{
2131
0
  struct cr_mime_ctx *ctx = reader->ctx;
2132
2133
0
  if(offset > 0) {
2134
0
    curl_off_t passed = 0;
2135
2136
0
    do {
2137
0
      char scratch[4 * 1024];
2138
0
      size_t readthisamountnow =
2139
0
        (offset - passed > (curl_off_t)sizeof(scratch)) ?
2140
0
        sizeof(scratch) :
2141
0
        curlx_sotouz(offset - passed);
2142
0
      size_t nread;
2143
2144
0
      nread = Curl_mime_read(scratch, 1, readthisamountnow, ctx->part);
2145
0
      passed += (curl_off_t)nread;
2146
0
      if((nread == 0) || (nread > readthisamountnow)) {
2147
        /* this checks for greater-than only to make sure that the
2148
           CURL_READFUNC_ABORT return code still aborts */
2149
0
        failf(data, "Could only read %" FMT_OFF_T
2150
0
              " bytes from the mime post", passed);
2151
0
        return CURLE_READ_ERROR;
2152
0
      }
2153
0
    } while(passed < offset);
2154
2155
    /* now, decrease the size of the read */
2156
0
    if(ctx->total_len > 0) {
2157
0
      ctx->total_len -= offset;
2158
2159
0
      if(ctx->total_len <= 0) {
2160
0
        failf(data, "Mime post already completely uploaded");
2161
0
        return CURLE_PARTIAL_FILE;
2162
0
      }
2163
0
    }
2164
    /* we have passed, proceed as normal */
2165
0
  }
2166
0
  return CURLE_OK;
2167
0
}
2168
2169
static CURLcode cr_mime_cntrl(struct Curl_easy *data,
2170
                              struct Curl_creader *reader,
2171
                              Curl_creader_cntrl opcode)
2172
0
{
2173
0
  struct cr_mime_ctx *ctx = reader->ctx;
2174
0
  switch(opcode) {
2175
0
  case CURL_CRCNTRL_REWIND: {
2176
0
    CURLcode result = mime_rewind(ctx->part);
2177
0
    if(result)
2178
0
      failf(data, "Cannot rewind mime/post data");
2179
0
    return result;
2180
0
  }
2181
0
  case CURL_CRCNTRL_UNPAUSE:
2182
0
    mime_unpause(ctx->part);
2183
0
    break;
2184
0
  case CURL_CRCNTRL_CLEAR_EOS:
2185
0
    ctx->seen_eos = FALSE;
2186
0
    break;
2187
0
  default:
2188
0
    break;
2189
0
  }
2190
0
  return CURLE_OK;
2191
0
}
2192
2193
static bool cr_mime_is_paused(struct Curl_easy *data,
2194
                              struct Curl_creader *reader)
2195
0
{
2196
0
  struct cr_mime_ctx *ctx = reader->ctx;
2197
0
  (void)data;
2198
0
  return ctx->part && ctx->part->lastreadstatus == CURL_READFUNC_PAUSE;
2199
0
}
2200
2201
static const struct Curl_crtype cr_mime = {
2202
  "cr-mime",
2203
  cr_mime_init,
2204
  cr_mime_read,
2205
  cr_mime_close,
2206
  cr_mime_needs_rewind,
2207
  cr_mime_total_length,
2208
  cr_mime_resume_from,
2209
  cr_mime_cntrl,
2210
  cr_mime_is_paused,
2211
  Curl_creader_def_done,
2212
  sizeof(struct cr_mime_ctx)
2213
};
2214
2215
CURLcode Curl_creader_set_mime(struct Curl_easy *data, curl_mimepart *part)
2216
0
{
2217
0
  struct Curl_creader *r;
2218
0
  struct cr_mime_ctx *ctx;
2219
0
  CURLcode result;
2220
2221
0
  result = Curl_creader_create(&r, data, &cr_mime, CURL_CR_CLIENT);
2222
0
  if(result)
2223
0
    return result;
2224
0
  ctx = r->ctx;
2225
0
  ctx->part = part;
2226
  /* Make sure we will read the entire mime structure. */
2227
0
  result = mime_rewind(ctx->part);
2228
0
  if(result) {
2229
0
    Curl_creader_free(data, r);
2230
0
    return result;
2231
0
  }
2232
0
  ctx->total_len = mime_size(ctx->part);
2233
2234
0
  return Curl_creader_set(data, r);
2235
0
}
2236
2237
#else /* !CURL_DISABLE_MIME && (!CURL_DISABLE_HTTP ||
2238
                                !CURL_DISABLE_SMTP ||
2239
                                !CURL_DISABLE_IMAP) */
2240
2241
/* Mime not compiled in: define stubs for externally-referenced functions. */
2242
curl_mime *curl_mime_init(CURL *easy)
2243
{
2244
  (void)easy;
2245
  return NULL;
2246
}
2247
2248
void curl_mime_free(curl_mime *mime)
2249
{
2250
  (void)mime;
2251
}
2252
2253
curl_mimepart *curl_mime_addpart(curl_mime *mime)
2254
{
2255
  (void)mime;
2256
  return NULL;
2257
}
2258
2259
CURLcode curl_mime_name(curl_mimepart *part, const char *name)
2260
{
2261
  (void)part;
2262
  (void)name;
2263
  return CURLE_NOT_BUILT_IN;
2264
}
2265
2266
CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
2267
{
2268
  (void)part;
2269
  (void)filename;
2270
  return CURLE_NOT_BUILT_IN;
2271
}
2272
2273
CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
2274
{
2275
  (void)part;
2276
  (void)mimetype;
2277
  return CURLE_NOT_BUILT_IN;
2278
}
2279
2280
CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
2281
{
2282
  (void)part;
2283
  (void)encoding;
2284
  return CURLE_NOT_BUILT_IN;
2285
}
2286
2287
CURLcode curl_mime_data(curl_mimepart *part, const char *data, size_t datasize)
2288
{
2289
  (void)part;
2290
  (void)data;
2291
  (void)datasize;
2292
  return CURLE_NOT_BUILT_IN;
2293
}
2294
2295
CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
2296
{
2297
  (void)part;
2298
  (void)filename;
2299
  return CURLE_NOT_BUILT_IN;
2300
}
2301
2302
CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize,
2303
                           curl_read_callback readfunc,
2304
                           curl_seek_callback seekfunc,
2305
                           curl_free_callback freefunc,
2306
                           void *arg)
2307
{
2308
  (void)part;
2309
  (void)datasize;
2310
  (void)readfunc;
2311
  (void)seekfunc;
2312
  (void)freefunc;
2313
  (void)arg;
2314
  return CURLE_NOT_BUILT_IN;
2315
}
2316
2317
CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
2318
{
2319
  (void)part;
2320
  (void)subparts;
2321
  return CURLE_NOT_BUILT_IN;
2322
}
2323
2324
CURLcode curl_mime_headers(curl_mimepart *part,
2325
                           struct curl_slist *headers, int take_ownership)
2326
{
2327
  (void)part;
2328
  (void)headers;
2329
  (void)take_ownership;
2330
  return CURLE_NOT_BUILT_IN;
2331
}
2332
2333
CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
2334
{
2335
  (void)slp;
2336
  (void)fmt;
2337
  return CURLE_NOT_BUILT_IN;
2338
}
2339
2340
#endif /* if disabled */