2
0

easy.c 32 KB

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