easy.c 29 KB

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