easy.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2022, 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. * See comment in curl_memory.h for the explanation of this sanity check.
  27. */
  28. #ifdef CURLX_NO_MEMORY_CALLBACKS
  29. #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined"
  30. #endif
  31. #ifdef HAVE_NETINET_IN_H
  32. #include <netinet/in.h>
  33. #endif
  34. #ifdef HAVE_NETDB_H
  35. #include <netdb.h>
  36. #endif
  37. #ifdef HAVE_ARPA_INET_H
  38. #include <arpa/inet.h>
  39. #endif
  40. #ifdef HAVE_NET_IF_H
  41. #include <net/if.h>
  42. #endif
  43. #ifdef HAVE_SYS_IOCTL_H
  44. #include <sys/ioctl.h>
  45. #endif
  46. #ifdef HAVE_SYS_PARAM_H
  47. #include <sys/param.h>
  48. #endif
  49. #include "urldata.h"
  50. #include <curl/curl.h>
  51. #include "transfer.h"
  52. #include "vtls/vtls.h"
  53. #include "url.h"
  54. #include "getinfo.h"
  55. #include "hostip.h"
  56. #include "share.h"
  57. #include "strdup.h"
  58. #include "progress.h"
  59. #include "easyif.h"
  60. #include "multiif.h"
  61. #include "select.h"
  62. #include "sendf.h" /* for failf function prototype */
  63. #include "connect.h" /* for Curl_getconnectinfo */
  64. #include "slist.h"
  65. #include "mime.h"
  66. #include "amigaos.h"
  67. #include "warnless.h"
  68. #include "multiif.h"
  69. #include "sigpipe.h"
  70. #include "vssh/ssh.h"
  71. #include "setopt.h"
  72. #include "http_digest.h"
  73. #include "system_win32.h"
  74. #include "http2.h"
  75. #include "dynbuf.h"
  76. #include "altsvc.h"
  77. #include "hsts.h"
  78. /* The last 3 #include files should be in this order */
  79. #include "curl_printf.h"
  80. #include "curl_memory.h"
  81. #include "memdebug.h"
  82. #include "easy_lock.h"
  83. /* true globals -- for curl_global_init() and curl_global_cleanup() */
  84. static unsigned int initialized;
  85. static long init_flags;
  86. #ifdef GLOBAL_INIT_IS_THREADSAFE
  87. static curl_simple_lock s_lock = CURL_SIMPLE_LOCK_INIT;
  88. #define global_init_lock() curl_simple_lock_lock(&s_lock)
  89. #define global_init_unlock() curl_simple_lock_unlock(&s_lock)
  90. #else
  91. #define global_init_lock()
  92. #define global_init_unlock()
  93. #endif
  94. /*
  95. * strdup (and other memory functions) is redefined in complicated
  96. * ways, but at this point it must be defined as the system-supplied strdup
  97. * so the callback pointer is initialized correctly.
  98. */
  99. #if defined(_WIN32_WCE)
  100. #define system_strdup _strdup
  101. #elif !defined(HAVE_STRDUP)
  102. #define system_strdup curlx_strdup
  103. #else
  104. #define system_strdup strdup
  105. #endif
  106. #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
  107. # pragma warning(disable:4232) /* MSVC extension, dllimport identity */
  108. #endif
  109. /*
  110. * If a memory-using function (like curl_getenv) is used before
  111. * curl_global_init() is called, we need to have these pointers set already.
  112. */
  113. curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
  114. curl_free_callback Curl_cfree = (curl_free_callback)free;
  115. curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
  116. curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
  117. curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
  118. #if defined(WIN32) && defined(UNICODE)
  119. curl_wcsdup_callback Curl_cwcsdup = Curl_wcsdup;
  120. #endif
  121. #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
  122. # pragma warning(default:4232) /* MSVC extension, dllimport identity */
  123. #endif
  124. #ifdef DEBUGBUILD
  125. static char *leakpointer;
  126. #endif
  127. /**
  128. * curl_global_init() globally initializes curl given a bitwise set of the
  129. * different features of what to initialize.
  130. */
  131. static CURLcode global_init(long flags, bool memoryfuncs)
  132. {
  133. if(initialized++)
  134. return CURLE_OK;
  135. if(memoryfuncs) {
  136. /* Setup the default memory functions here (again) */
  137. Curl_cmalloc = (curl_malloc_callback)malloc;
  138. Curl_cfree = (curl_free_callback)free;
  139. Curl_crealloc = (curl_realloc_callback)realloc;
  140. Curl_cstrdup = (curl_strdup_callback)system_strdup;
  141. Curl_ccalloc = (curl_calloc_callback)calloc;
  142. #if defined(WIN32) && defined(UNICODE)
  143. Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
  144. #endif
  145. }
  146. if(!Curl_ssl_init()) {
  147. DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
  148. goto fail;
  149. }
  150. #ifdef WIN32
  151. if(Curl_win32_init(flags)) {
  152. DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
  153. goto fail;
  154. }
  155. #endif
  156. #ifdef __AMIGA__
  157. if(Curl_amiga_init()) {
  158. DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
  159. goto fail;
  160. }
  161. #endif
  162. if(Curl_resolver_global_init()) {
  163. DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
  164. goto fail;
  165. }
  166. #if defined(USE_SSH)
  167. if(Curl_ssh_init()) {
  168. goto fail;
  169. }
  170. #endif
  171. #ifdef USE_WOLFSSH
  172. if(WS_SUCCESS != wolfSSH_Init()) {
  173. DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n"));
  174. return CURLE_FAILED_INIT;
  175. }
  176. #endif
  177. init_flags = flags;
  178. #ifdef DEBUGBUILD
  179. if(getenv("CURL_GLOBAL_INIT"))
  180. /* alloc data that will leak if *cleanup() is not called! */
  181. leakpointer = malloc(1);
  182. #endif
  183. return CURLE_OK;
  184. fail:
  185. initialized--; /* undo the increase */
  186. return CURLE_FAILED_INIT;
  187. }
  188. /**
  189. * curl_global_init() globally initializes curl given a bitwise set of the
  190. * different features of what to initialize.
  191. */
  192. CURLcode curl_global_init(long flags)
  193. {
  194. CURLcode result;
  195. global_init_lock();
  196. result = global_init(flags, TRUE);
  197. global_init_unlock();
  198. return result;
  199. }
  200. /*
  201. * curl_global_init_mem() globally initializes curl and also registers the
  202. * user provided callback routines.
  203. */
  204. CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
  205. curl_free_callback f, curl_realloc_callback r,
  206. curl_strdup_callback s, curl_calloc_callback c)
  207. {
  208. CURLcode result;
  209. /* Invalid input, return immediately */
  210. if(!m || !f || !r || !s || !c)
  211. return CURLE_FAILED_INIT;
  212. global_init_lock();
  213. if(initialized) {
  214. /* Already initialized, don't do it again, but bump the variable anyway to
  215. work like curl_global_init() and require the same amount of cleanup
  216. calls. */
  217. initialized++;
  218. global_init_unlock();
  219. return CURLE_OK;
  220. }
  221. /* set memory functions before global_init() in case it wants memory
  222. functions */
  223. Curl_cmalloc = m;
  224. Curl_cfree = f;
  225. Curl_cstrdup = s;
  226. Curl_crealloc = r;
  227. Curl_ccalloc = c;
  228. /* Call the actual init function, but without setting */
  229. result = global_init(flags, FALSE);
  230. global_init_unlock();
  231. return result;
  232. }
  233. /**
  234. * curl_global_cleanup() globally cleanups curl, uses the value of
  235. * "init_flags" to determine what needs to be cleaned up and what doesn't.
  236. */
  237. void curl_global_cleanup(void)
  238. {
  239. global_init_lock();
  240. if(!initialized) {
  241. global_init_unlock();
  242. return;
  243. }
  244. if(--initialized) {
  245. global_init_unlock();
  246. return;
  247. }
  248. Curl_ssl_cleanup();
  249. Curl_resolver_global_cleanup();
  250. #ifdef WIN32
  251. Curl_win32_cleanup(init_flags);
  252. #endif
  253. Curl_amiga_cleanup();
  254. Curl_ssh_cleanup();
  255. #ifdef USE_WOLFSSH
  256. (void)wolfSSH_Cleanup();
  257. #endif
  258. #ifdef DEBUGBUILD
  259. free(leakpointer);
  260. #endif
  261. init_flags = 0;
  262. global_init_unlock();
  263. }
  264. /*
  265. * curl_global_sslset() globally initializes the SSL backend to use.
  266. */
  267. CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
  268. const curl_ssl_backend ***avail)
  269. {
  270. CURLsslset rc;
  271. global_init_lock();
  272. rc = Curl_init_sslset_nolock(id, name, avail);
  273. global_init_unlock();
  274. return rc;
  275. }
  276. /*
  277. * curl_easy_init() is the external interface to alloc, setup and init an
  278. * easy handle that is returned. If anything goes wrong, NULL is returned.
  279. */
  280. struct Curl_easy *curl_easy_init(void)
  281. {
  282. CURLcode result;
  283. struct Curl_easy *data;
  284. /* Make sure we inited the global SSL stuff */
  285. global_init_lock();
  286. if(!initialized) {
  287. result = global_init(CURL_GLOBAL_DEFAULT, TRUE);
  288. if(result) {
  289. /* something in the global init failed, return nothing */
  290. DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
  291. global_init_unlock();
  292. return NULL;
  293. }
  294. }
  295. global_init_unlock();
  296. /* We use curl_open() with undefined URL so far */
  297. result = Curl_open(&data);
  298. if(result) {
  299. DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
  300. return NULL;
  301. }
  302. return data;
  303. }
  304. #ifdef CURLDEBUG
  305. struct socketmonitor {
  306. struct socketmonitor *next; /* the next node in the list or NULL */
  307. struct pollfd socket; /* socket info of what to monitor */
  308. };
  309. struct events {
  310. long ms; /* timeout, run the timeout function when reached */
  311. bool msbump; /* set TRUE when timeout is set by callback */
  312. int num_sockets; /* number of nodes in the monitor list */
  313. struct socketmonitor *list; /* list of sockets to monitor */
  314. int running_handles; /* store the returned number */
  315. };
  316. /* events_timer
  317. *
  318. * Callback that gets called with a new value when the timeout should be
  319. * updated.
  320. */
  321. static int events_timer(struct Curl_multi *multi, /* multi handle */
  322. long timeout_ms, /* see above */
  323. void *userp) /* private callback pointer */
  324. {
  325. struct events *ev = userp;
  326. (void)multi;
  327. if(timeout_ms == -1)
  328. /* timeout removed */
  329. timeout_ms = 0;
  330. else if(timeout_ms == 0)
  331. /* timeout is already reached! */
  332. timeout_ms = 1; /* trigger asap */
  333. ev->ms = timeout_ms;
  334. ev->msbump = TRUE;
  335. return 0;
  336. }
  337. /* poll2cselect
  338. *
  339. * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
  340. */
  341. static int poll2cselect(int pollmask)
  342. {
  343. int omask = 0;
  344. if(pollmask & POLLIN)
  345. omask |= CURL_CSELECT_IN;
  346. if(pollmask & POLLOUT)
  347. omask |= CURL_CSELECT_OUT;
  348. if(pollmask & POLLERR)
  349. omask |= CURL_CSELECT_ERR;
  350. return omask;
  351. }
  352. /* socketcb2poll
  353. *
  354. * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
  355. */
  356. static short socketcb2poll(int pollmask)
  357. {
  358. short omask = 0;
  359. if(pollmask & CURL_POLL_IN)
  360. omask |= POLLIN;
  361. if(pollmask & CURL_POLL_OUT)
  362. omask |= POLLOUT;
  363. return omask;
  364. }
  365. /* events_socket
  366. *
  367. * Callback that gets called with information about socket activity to
  368. * monitor.
  369. */
  370. static int events_socket(struct Curl_easy *easy, /* easy handle */
  371. curl_socket_t s, /* socket */
  372. int what, /* see above */
  373. void *userp, /* private callback
  374. pointer */
  375. void *socketp) /* private socket
  376. pointer */
  377. {
  378. struct events *ev = userp;
  379. struct socketmonitor *m;
  380. struct socketmonitor *prev = NULL;
  381. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  382. (void) easy;
  383. #endif
  384. (void)socketp;
  385. m = ev->list;
  386. while(m) {
  387. if(m->socket.fd == s) {
  388. if(what == CURL_POLL_REMOVE) {
  389. struct socketmonitor *nxt = m->next;
  390. /* remove this node from the list of monitored sockets */
  391. if(prev)
  392. prev->next = nxt;
  393. else
  394. ev->list = nxt;
  395. free(m);
  396. m = nxt;
  397. infof(easy, "socket cb: socket %d REMOVED", s);
  398. }
  399. else {
  400. /* The socket 's' is already being monitored, update the activity
  401. mask. Convert from libcurl bitmask to the poll one. */
  402. m->socket.events = socketcb2poll(what);
  403. infof(easy, "socket cb: socket %d UPDATED as %s%s", s,
  404. (what&CURL_POLL_IN)?"IN":"",
  405. (what&CURL_POLL_OUT)?"OUT":"");
  406. }
  407. break;
  408. }
  409. prev = m;
  410. m = m->next; /* move to next node */
  411. }
  412. if(!m) {
  413. if(what == CURL_POLL_REMOVE) {
  414. /* this happens a bit too often, libcurl fix perhaps? */
  415. /* fprintf(stderr,
  416. "%s: socket %d asked to be REMOVED but not present!\n",
  417. __func__, s); */
  418. }
  419. else {
  420. m = malloc(sizeof(struct socketmonitor));
  421. if(m) {
  422. m->next = ev->list;
  423. m->socket.fd = s;
  424. m->socket.events = socketcb2poll(what);
  425. m->socket.revents = 0;
  426. ev->list = m;
  427. infof(easy, "socket cb: socket %d ADDED as %s%s", s,
  428. (what&CURL_POLL_IN)?"IN":"",
  429. (what&CURL_POLL_OUT)?"OUT":"");
  430. }
  431. else
  432. return CURLE_OUT_OF_MEMORY;
  433. }
  434. }
  435. return 0;
  436. }
  437. /*
  438. * events_setup()
  439. *
  440. * Do the multi handle setups that only event-based transfers need.
  441. */
  442. static void events_setup(struct Curl_multi *multi, struct events *ev)
  443. {
  444. /* timer callback */
  445. curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
  446. curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
  447. /* socket callback */
  448. curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
  449. curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
  450. }
  451. /* wait_or_timeout()
  452. *
  453. * waits for activity on any of the given sockets, or the timeout to trigger.
  454. */
  455. static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
  456. {
  457. bool done = FALSE;
  458. CURLMcode mcode = CURLM_OK;
  459. CURLcode result = CURLE_OK;
  460. while(!done) {
  461. CURLMsg *msg;
  462. struct socketmonitor *m;
  463. struct pollfd *f;
  464. struct pollfd fds[4];
  465. int numfds = 0;
  466. int pollrc;
  467. int i;
  468. struct curltime before;
  469. struct curltime after;
  470. /* populate the fds[] array */
  471. for(m = ev->list, f = &fds[0]; m; m = m->next) {
  472. f->fd = m->socket.fd;
  473. f->events = m->socket.events;
  474. f->revents = 0;
  475. /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
  476. f++;
  477. numfds++;
  478. }
  479. /* get the time stamp to use to figure out how long poll takes */
  480. before = Curl_now();
  481. /* wait for activity or timeout */
  482. pollrc = Curl_poll(fds, numfds, ev->ms);
  483. if(pollrc < 0)
  484. return CURLE_UNRECOVERABLE_POLL;
  485. after = Curl_now();
  486. ev->msbump = FALSE; /* reset here */
  487. if(!pollrc) {
  488. /* timeout! */
  489. ev->ms = 0;
  490. /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */
  491. mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
  492. &ev->running_handles);
  493. }
  494. else {
  495. /* here pollrc is > 0 */
  496. /* loop over the monitored sockets to see which ones had activity */
  497. for(i = 0; i< numfds; i++) {
  498. if(fds[i].revents) {
  499. /* socket activity, tell libcurl */
  500. int act = poll2cselect(fds[i].revents); /* convert */
  501. infof(multi->easyp, "call curl_multi_socket_action(socket %d)",
  502. fds[i].fd);
  503. mcode = curl_multi_socket_action(multi, fds[i].fd, act,
  504. &ev->running_handles);
  505. }
  506. }
  507. if(!ev->msbump) {
  508. /* If nothing updated the timeout, we decrease it by the spent time.
  509. * If it was updated, it has the new timeout time stored already.
  510. */
  511. timediff_t timediff = Curl_timediff(after, before);
  512. if(timediff > 0) {
  513. if(timediff > ev->ms)
  514. ev->ms = 0;
  515. else
  516. ev->ms -= (long)timediff;
  517. }
  518. }
  519. }
  520. if(mcode)
  521. return CURLE_URL_MALFORMAT;
  522. /* we don't really care about the "msgs_in_queue" value returned in the
  523. second argument */
  524. msg = curl_multi_info_read(multi, &pollrc);
  525. if(msg) {
  526. result = msg->data.result;
  527. done = TRUE;
  528. }
  529. }
  530. return result;
  531. }
  532. /* easy_events()
  533. *
  534. * Runs a transfer in a blocking manner using the events-based API
  535. */
  536. static CURLcode easy_events(struct Curl_multi *multi)
  537. {
  538. /* this struct is made static to allow it to be used after this function
  539. returns and curl_multi_remove_handle() is called */
  540. static struct events evs = {2, FALSE, 0, NULL, 0};
  541. /* if running event-based, do some further multi inits */
  542. events_setup(multi, &evs);
  543. return wait_or_timeout(multi, &evs);
  544. }
  545. #else /* CURLDEBUG */
  546. /* when not built with debug, this function doesn't exist */
  547. #define easy_events(x) CURLE_NOT_BUILT_IN
  548. #endif
  549. static CURLcode easy_transfer(struct Curl_multi *multi)
  550. {
  551. bool done = FALSE;
  552. CURLMcode mcode = CURLM_OK;
  553. CURLcode result = CURLE_OK;
  554. while(!done && !mcode) {
  555. int still_running = 0;
  556. mcode = curl_multi_poll(multi, NULL, 0, 1000, NULL);
  557. if(!mcode)
  558. mcode = curl_multi_perform(multi, &still_running);
  559. /* only read 'still_running' if curl_multi_perform() return OK */
  560. if(!mcode && !still_running) {
  561. int rc;
  562. CURLMsg *msg = curl_multi_info_read(multi, &rc);
  563. if(msg) {
  564. result = msg->data.result;
  565. done = TRUE;
  566. }
  567. }
  568. }
  569. /* Make sure to return some kind of error if there was a multi problem */
  570. if(mcode) {
  571. result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY :
  572. /* The other multi errors should never happen, so return
  573. something suitably generic */
  574. CURLE_BAD_FUNCTION_ARGUMENT;
  575. }
  576. return result;
  577. }
  578. /*
  579. * easy_perform() is the external interface that performs a blocking
  580. * transfer as previously setup.
  581. *
  582. * CONCEPT: This function creates a multi handle, adds the easy handle to it,
  583. * runs curl_multi_perform() until the transfer is done, then detaches the
  584. * easy handle, destroys the multi handle and returns the easy handle's return
  585. * code.
  586. *
  587. * REALITY: it can't just create and destroy the multi handle that easily. It
  588. * needs to keep it around since if this easy handle is used again by this
  589. * function, the same multi handle must be re-used so that the same pools and
  590. * caches can be used.
  591. *
  592. * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
  593. * instead of curl_multi_perform() and use curl_multi_socket_action().
  594. */
  595. static CURLcode easy_perform(struct Curl_easy *data, bool events)
  596. {
  597. struct Curl_multi *multi;
  598. CURLMcode mcode;
  599. CURLcode result = CURLE_OK;
  600. SIGPIPE_VARIABLE(pipe_st);
  601. if(!data)
  602. return CURLE_BAD_FUNCTION_ARGUMENT;
  603. if(data->set.errorbuffer)
  604. /* clear this as early as possible */
  605. data->set.errorbuffer[0] = 0;
  606. if(data->multi) {
  607. failf(data, "easy handle already used in multi handle");
  608. return CURLE_FAILED_INIT;
  609. }
  610. if(data->multi_easy)
  611. multi = data->multi_easy;
  612. else {
  613. /* this multi handle will only ever have a single easy handled attached
  614. to it, so make it use minimal hashes */
  615. multi = Curl_multi_handle(1, 3, 7);
  616. if(!multi)
  617. return CURLE_OUT_OF_MEMORY;
  618. data->multi_easy = multi;
  619. }
  620. if(multi->in_callback)
  621. return CURLE_RECURSIVE_API_CALL;
  622. /* Copy the MAXCONNECTS option to the multi handle */
  623. curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
  624. mcode = curl_multi_add_handle(multi, data);
  625. if(mcode) {
  626. curl_multi_cleanup(multi);
  627. data->multi_easy = NULL;
  628. if(mcode == CURLM_OUT_OF_MEMORY)
  629. return CURLE_OUT_OF_MEMORY;
  630. return CURLE_FAILED_INIT;
  631. }
  632. sigpipe_ignore(data, &pipe_st);
  633. /* run the transfer */
  634. result = events ? easy_events(multi) : easy_transfer(multi);
  635. /* ignoring the return code isn't nice, but atm we can't really handle
  636. a failure here, room for future improvement! */
  637. (void)curl_multi_remove_handle(multi, data);
  638. sigpipe_restore(&pipe_st);
  639. /* The multi handle is kept alive, owned by the easy handle */
  640. return result;
  641. }
  642. /*
  643. * curl_easy_perform() is the external interface that performs a blocking
  644. * transfer as previously setup.
  645. */
  646. CURLcode curl_easy_perform(struct Curl_easy *data)
  647. {
  648. return easy_perform(data, FALSE);
  649. }
  650. #ifdef CURLDEBUG
  651. /*
  652. * curl_easy_perform_ev() is the external interface that performs a blocking
  653. * transfer using the event-based API internally.
  654. */
  655. CURLcode curl_easy_perform_ev(struct Curl_easy *data)
  656. {
  657. return easy_perform(data, TRUE);
  658. }
  659. #endif
  660. /*
  661. * curl_easy_cleanup() is the external interface to cleaning/freeing the given
  662. * easy handle.
  663. */
  664. void curl_easy_cleanup(struct Curl_easy *data)
  665. {
  666. SIGPIPE_VARIABLE(pipe_st);
  667. if(!data)
  668. return;
  669. sigpipe_ignore(data, &pipe_st);
  670. Curl_close(&data);
  671. sigpipe_restore(&pipe_st);
  672. }
  673. /*
  674. * curl_easy_getinfo() is an external interface that allows an app to retrieve
  675. * information from a performed transfer and similar.
  676. */
  677. #undef curl_easy_getinfo
  678. CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...)
  679. {
  680. va_list arg;
  681. void *paramp;
  682. CURLcode result;
  683. va_start(arg, info);
  684. paramp = va_arg(arg, void *);
  685. result = Curl_getinfo(data, info, paramp);
  686. va_end(arg);
  687. return result;
  688. }
  689. static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src)
  690. {
  691. CURLcode result = CURLE_OK;
  692. enum dupstring i;
  693. enum dupblob j;
  694. /* Copy src->set into dst->set first, then deal with the strings
  695. afterwards */
  696. dst->set = src->set;
  697. Curl_mime_initpart(&dst->set.mimepost, dst);
  698. /* clear all string pointers first */
  699. memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
  700. /* duplicate all strings */
  701. for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
  702. result = Curl_setstropt(&dst->set.str[i], src->set.str[i]);
  703. if(result)
  704. return result;
  705. }
  706. /* clear all blob pointers first */
  707. memset(dst->set.blobs, 0, BLOB_LAST * sizeof(struct curl_blob *));
  708. /* duplicate all blobs */
  709. for(j = (enum dupblob)0; j < BLOB_LAST; j++) {
  710. result = Curl_setblobopt(&dst->set.blobs[j], src->set.blobs[j]);
  711. if(result)
  712. return result;
  713. }
  714. /* duplicate memory areas pointed to */
  715. i = STRING_COPYPOSTFIELDS;
  716. if(src->set.postfieldsize && src->set.str[i]) {
  717. /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */
  718. dst->set.str[i] = Curl_memdup(src->set.str[i],
  719. curlx_sotouz(src->set.postfieldsize));
  720. if(!dst->set.str[i])
  721. return CURLE_OUT_OF_MEMORY;
  722. /* point to the new copy */
  723. dst->set.postfields = dst->set.str[i];
  724. }
  725. /* Duplicate mime data. */
  726. result = Curl_mime_duppart(&dst->set.mimepost, &src->set.mimepost);
  727. if(src->set.resolve)
  728. dst->state.resolve = dst->set.resolve;
  729. return result;
  730. }
  731. /*
  732. * curl_easy_duphandle() is an external interface to allow duplication of a
  733. * given input easy handle. The returned handle will be a new working handle
  734. * with all options set exactly as the input source handle.
  735. */
  736. struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data)
  737. {
  738. struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy));
  739. if(!outcurl)
  740. goto fail;
  741. /*
  742. * We setup a few buffers we need. We should probably make them
  743. * get setup on-demand in the code, as that would probably decrease
  744. * the likeliness of us forgetting to init a buffer here in the future.
  745. */
  746. outcurl->set.buffer_size = data->set.buffer_size;
  747. /* copy all userdefined values */
  748. if(dupset(outcurl, data))
  749. goto fail;
  750. Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER);
  751. /* the connection cache is setup on demand */
  752. outcurl->state.conn_cache = NULL;
  753. outcurl->state.lastconnect_id = -1;
  754. outcurl->progress.flags = data->progress.flags;
  755. outcurl->progress.callback = data->progress.callback;
  756. #ifndef CURL_DISABLE_COOKIES
  757. if(data->cookies) {
  758. /* If cookies are enabled in the parent handle, we enable them
  759. in the clone as well! */
  760. outcurl->cookies = Curl_cookie_init(data,
  761. data->cookies->filename,
  762. outcurl->cookies,
  763. data->set.cookiesession);
  764. if(!outcurl->cookies)
  765. goto fail;
  766. }
  767. /* duplicate all values in 'change' */
  768. if(data->state.cookielist) {
  769. outcurl->state.cookielist =
  770. Curl_slist_duplicate(data->state.cookielist);
  771. if(!outcurl->state.cookielist)
  772. goto fail;
  773. }
  774. #endif
  775. if(data->state.url) {
  776. outcurl->state.url = strdup(data->state.url);
  777. if(!outcurl->state.url)
  778. goto fail;
  779. outcurl->state.url_alloc = TRUE;
  780. }
  781. if(data->state.referer) {
  782. outcurl->state.referer = strdup(data->state.referer);
  783. if(!outcurl->state.referer)
  784. goto fail;
  785. outcurl->state.referer_alloc = TRUE;
  786. }
  787. /* Reinitialize an SSL engine for the new handle
  788. * note: the engine name has already been copied by dupset */
  789. if(outcurl->set.str[STRING_SSL_ENGINE]) {
  790. if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE]))
  791. goto fail;
  792. }
  793. #ifdef USE_ALTSVC
  794. if(data->asi) {
  795. outcurl->asi = Curl_altsvc_init();
  796. if(!outcurl->asi)
  797. goto fail;
  798. if(outcurl->set.str[STRING_ALTSVC])
  799. (void)Curl_altsvc_load(outcurl->asi, outcurl->set.str[STRING_ALTSVC]);
  800. }
  801. #endif
  802. #ifndef CURL_DISABLE_HSTS
  803. if(data->hsts) {
  804. outcurl->hsts = Curl_hsts_init();
  805. if(!outcurl->hsts)
  806. goto fail;
  807. if(outcurl->set.str[STRING_HSTS])
  808. (void)Curl_hsts_loadfile(outcurl,
  809. outcurl->hsts, outcurl->set.str[STRING_HSTS]);
  810. (void)Curl_hsts_loadcb(outcurl, outcurl->hsts);
  811. }
  812. #endif
  813. /* Clone the resolver handle, if present, for the new handle */
  814. if(Curl_resolver_duphandle(outcurl,
  815. &outcurl->state.async.resolver,
  816. data->state.async.resolver))
  817. goto fail;
  818. #ifdef USE_ARES
  819. {
  820. CURLcode rc;
  821. rc = Curl_set_dns_servers(outcurl, data->set.str[STRING_DNS_SERVERS]);
  822. if(rc && rc != CURLE_NOT_BUILT_IN)
  823. goto fail;
  824. rc = Curl_set_dns_interface(outcurl, data->set.str[STRING_DNS_INTERFACE]);
  825. if(rc && rc != CURLE_NOT_BUILT_IN)
  826. goto fail;
  827. rc = Curl_set_dns_local_ip4(outcurl, data->set.str[STRING_DNS_LOCAL_IP4]);
  828. if(rc && rc != CURLE_NOT_BUILT_IN)
  829. goto fail;
  830. rc = Curl_set_dns_local_ip6(outcurl, data->set.str[STRING_DNS_LOCAL_IP6]);
  831. if(rc && rc != CURLE_NOT_BUILT_IN)
  832. goto fail;
  833. }
  834. #endif /* USE_ARES */
  835. Curl_initinfo(outcurl);
  836. outcurl->magic = CURLEASY_MAGIC_NUMBER;
  837. /* we reach this point and thus we are OK */
  838. return outcurl;
  839. fail:
  840. if(outcurl) {
  841. #ifndef CURL_DISABLE_COOKIES
  842. curl_slist_free_all(outcurl->state.cookielist);
  843. outcurl->state.cookielist = NULL;
  844. #endif
  845. Curl_safefree(outcurl->state.buffer);
  846. Curl_dyn_free(&outcurl->state.headerb);
  847. Curl_safefree(outcurl->state.url);
  848. Curl_safefree(outcurl->state.referer);
  849. Curl_altsvc_cleanup(&outcurl->asi);
  850. Curl_hsts_cleanup(&outcurl->hsts);
  851. Curl_freeset(outcurl);
  852. free(outcurl);
  853. }
  854. return NULL;
  855. }
  856. /*
  857. * curl_easy_reset() is an external interface that allows an app to re-
  858. * initialize a session handle to the default values.
  859. */
  860. void curl_easy_reset(struct Curl_easy *data)
  861. {
  862. Curl_free_request_state(data);
  863. /* zero out UserDefined data: */
  864. Curl_freeset(data);
  865. memset(&data->set, 0, sizeof(struct UserDefined));
  866. (void)Curl_init_userdefined(data);
  867. /* zero out Progress data: */
  868. memset(&data->progress, 0, sizeof(struct Progress));
  869. /* zero out PureInfo data: */
  870. Curl_initinfo(data);
  871. data->progress.flags |= PGRS_HIDE;
  872. data->state.current_speed = -1; /* init to negative == impossible */
  873. data->state.retrycount = 0; /* reset the retry counter */
  874. /* zero out authentication data: */
  875. memset(&data->state.authhost, 0, sizeof(struct auth));
  876. memset(&data->state.authproxy, 0, sizeof(struct auth));
  877. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
  878. Curl_http_auth_cleanup_digest(data);
  879. #endif
  880. }
  881. /*
  882. * curl_easy_pause() allows an application to pause or unpause a specific
  883. * transfer and direction. This function sets the full new state for the
  884. * current connection this easy handle operates on.
  885. *
  886. * NOTE: if you have the receiving paused and you call this function to remove
  887. * the pausing, you may get your write callback called at this point.
  888. *
  889. * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
  890. *
  891. * NOTE: This is one of few API functions that are allowed to be called from
  892. * within a callback.
  893. */
  894. CURLcode curl_easy_pause(struct Curl_easy *data, int action)
  895. {
  896. struct SingleRequest *k;
  897. CURLcode result = CURLE_OK;
  898. int oldstate;
  899. int newstate;
  900. if(!GOOD_EASY_HANDLE(data) || !data->conn)
  901. /* crazy input, don't continue */
  902. return CURLE_BAD_FUNCTION_ARGUMENT;
  903. k = &data->req;
  904. oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
  905. /* first switch off both pause bits then set the new pause bits */
  906. newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) |
  907. ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
  908. ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
  909. if((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) == oldstate) {
  910. /* Not changing any pause state, return */
  911. DEBUGF(infof(data, "pause: no change, early return"));
  912. return CURLE_OK;
  913. }
  914. /* Unpause parts in active mime tree. */
  915. if((k->keepon & ~newstate & KEEP_SEND_PAUSE) &&
  916. (data->mstate == MSTATE_PERFORMING ||
  917. data->mstate == MSTATE_RATELIMITING) &&
  918. data->state.fread_func == (curl_read_callback) Curl_mime_read) {
  919. Curl_mime_unpause(data->state.in);
  920. }
  921. /* put it back in the keepon */
  922. k->keepon = newstate;
  923. if(!(newstate & KEEP_RECV_PAUSE)) {
  924. Curl_http2_stream_pause(data, FALSE);
  925. if(data->state.tempcount) {
  926. /* there are buffers for sending that can be delivered as the receive
  927. pausing is lifted! */
  928. unsigned int i;
  929. unsigned int count = data->state.tempcount;
  930. struct tempbuf writebuf[3]; /* there can only be three */
  931. /* copy the structs to allow for immediate re-pausing */
  932. for(i = 0; i < data->state.tempcount; i++) {
  933. writebuf[i] = data->state.tempwrite[i];
  934. Curl_dyn_init(&data->state.tempwrite[i].b, DYN_PAUSE_BUFFER);
  935. }
  936. data->state.tempcount = 0;
  937. for(i = 0; i < count; i++) {
  938. /* even if one function returns error, this loops through and frees
  939. all buffers */
  940. if(!result)
  941. result = Curl_client_write(data, writebuf[i].type,
  942. Curl_dyn_ptr(&writebuf[i].b),
  943. Curl_dyn_len(&writebuf[i].b));
  944. Curl_dyn_free(&writebuf[i].b);
  945. }
  946. if(result)
  947. return result;
  948. }
  949. }
  950. #ifdef USE_HYPER
  951. if(!(newstate & KEEP_SEND_PAUSE)) {
  952. /* need to wake the send body waker */
  953. if(data->hyp.send_body_waker) {
  954. hyper_waker_wake(data->hyp.send_body_waker);
  955. data->hyp.send_body_waker = NULL;
  956. }
  957. }
  958. #endif
  959. /* if there's no error and we're not pausing both directions, we want
  960. to have this handle checked soon */
  961. if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
  962. (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) {
  963. Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */
  964. /* reset the too-slow time keeper */
  965. data->state.keeps_speed.tv_sec = 0;
  966. if(!data->state.tempcount)
  967. /* if not pausing again, force a recv/send check of this connection as
  968. the data might've been read off the socket already */
  969. data->conn->cselect_bits = CURL_CSELECT_IN | CURL_CSELECT_OUT;
  970. if(data->multi) {
  971. if(Curl_update_timer(data->multi))
  972. return CURLE_ABORTED_BY_CALLBACK;
  973. }
  974. }
  975. if(!data->state.done)
  976. /* This transfer may have been moved in or out of the bundle, update the
  977. corresponding socket callback, if used */
  978. result = Curl_updatesocket(data);
  979. return result;
  980. }
  981. static CURLcode easy_connection(struct Curl_easy *data, curl_socket_t *sfd,
  982. struct connectdata **connp)
  983. {
  984. if(!data)
  985. return CURLE_BAD_FUNCTION_ARGUMENT;
  986. /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
  987. if(!data->set.connect_only) {
  988. failf(data, "CONNECT_ONLY is required");
  989. return CURLE_UNSUPPORTED_PROTOCOL;
  990. }
  991. *sfd = Curl_getconnectinfo(data, connp);
  992. if(*sfd == CURL_SOCKET_BAD) {
  993. failf(data, "Failed to get recent socket");
  994. return CURLE_UNSUPPORTED_PROTOCOL;
  995. }
  996. return CURLE_OK;
  997. }
  998. /*
  999. * Receives data from the connected socket. Use after successful
  1000. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  1001. * Returns CURLE_OK on success, error code on error.
  1002. */
  1003. CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen,
  1004. size_t *n)
  1005. {
  1006. curl_socket_t sfd;
  1007. CURLcode result;
  1008. ssize_t n1;
  1009. struct connectdata *c;
  1010. if(Curl_is_in_callback(data))
  1011. return CURLE_RECURSIVE_API_CALL;
  1012. result = easy_connection(data, &sfd, &c);
  1013. if(result)
  1014. return result;
  1015. if(!data->conn)
  1016. /* on first invoke, the transfer has been detached from the connection and
  1017. needs to be reattached */
  1018. Curl_attach_connection(data, c);
  1019. *n = 0;
  1020. result = Curl_read(data, sfd, buffer, buflen, &n1);
  1021. if(result)
  1022. return result;
  1023. *n = (size_t)n1;
  1024. return CURLE_OK;
  1025. }
  1026. /*
  1027. * Sends data over the connected socket.
  1028. *
  1029. * This is the private internal version of curl_easy_send()
  1030. */
  1031. CURLcode Curl_senddata(struct Curl_easy *data, const void *buffer,
  1032. size_t buflen, size_t *n)
  1033. {
  1034. curl_socket_t sfd;
  1035. CURLcode result;
  1036. ssize_t n1;
  1037. struct connectdata *c = NULL;
  1038. SIGPIPE_VARIABLE(pipe_st);
  1039. result = easy_connection(data, &sfd, &c);
  1040. if(result)
  1041. return result;
  1042. if(!data->conn)
  1043. /* on first invoke, the transfer has been detached from the connection and
  1044. needs to be reattached */
  1045. Curl_attach_connection(data, c);
  1046. *n = 0;
  1047. sigpipe_ignore(data, &pipe_st);
  1048. result = Curl_write(data, sfd, buffer, buflen, &n1);
  1049. sigpipe_restore(&pipe_st);
  1050. if(n1 == -1)
  1051. return CURLE_SEND_ERROR;
  1052. /* detect EAGAIN */
  1053. if(!result && !n1)
  1054. return CURLE_AGAIN;
  1055. *n = (size_t)n1;
  1056. return result;
  1057. }
  1058. /*
  1059. * Sends data over the connected socket. Use after successful
  1060. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  1061. */
  1062. CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer,
  1063. size_t buflen, size_t *n)
  1064. {
  1065. if(Curl_is_in_callback(data))
  1066. return CURLE_RECURSIVE_API_CALL;
  1067. return Curl_senddata(data, buffer, buflen, n);
  1068. }
  1069. /*
  1070. * Wrapper to call functions in Curl_conncache_foreach()
  1071. *
  1072. * Returns always 0.
  1073. */
  1074. static int conn_upkeep(struct Curl_easy *data,
  1075. struct connectdata *conn,
  1076. void *param)
  1077. {
  1078. /* Param is unused. */
  1079. (void)param;
  1080. if(conn->handler->connection_check) {
  1081. /* briefly attach the connection to this transfer for the purpose of
  1082. checking it */
  1083. Curl_attach_connection(data, conn);
  1084. /* Do a protocol-specific keepalive check on the connection. */
  1085. conn->handler->connection_check(data, conn, CONNCHECK_KEEPALIVE);
  1086. /* detach the connection again */
  1087. Curl_detach_connection(data);
  1088. }
  1089. return 0; /* continue iteration */
  1090. }
  1091. static CURLcode upkeep(struct conncache *conn_cache, void *data)
  1092. {
  1093. /* Loop over every connection and make connection alive. */
  1094. Curl_conncache_foreach(data,
  1095. conn_cache,
  1096. data,
  1097. conn_upkeep);
  1098. return CURLE_OK;
  1099. }
  1100. /*
  1101. * Performs connection upkeep for the given session handle.
  1102. */
  1103. CURLcode curl_easy_upkeep(struct Curl_easy *data)
  1104. {
  1105. /* Verify that we got an easy handle we can work with. */
  1106. if(!GOOD_EASY_HANDLE(data))
  1107. return CURLE_BAD_FUNCTION_ARGUMENT;
  1108. if(data->multi_easy) {
  1109. /* Use the common function to keep connections alive. */
  1110. return upkeep(&data->multi_easy->conn_cache, data);
  1111. }
  1112. else {
  1113. /* No connections, so just return success */
  1114. return CURLE_OK;
  1115. }
  1116. }