easy.c 35 KB

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