easy.c 35 KB

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