easy.c 31 KB

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