mime.c 62 KB

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