connect.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. #ifdef HAVE_NETINET_IN_H
  24. #include <netinet/in.h> /* <netinet/tcp.h> may need it */
  25. #endif
  26. #ifdef HAVE_SYS_UN_H
  27. #include <sys/un.h> /* for sockaddr_un */
  28. #endif
  29. #ifdef HAVE_NETINET_TCP_H
  30. #include <netinet/tcp.h> /* for TCP_NODELAY */
  31. #endif
  32. #ifdef HAVE_SYS_IOCTL_H
  33. #include <sys/ioctl.h>
  34. #endif
  35. #ifdef HAVE_NETDB_H
  36. #include <netdb.h>
  37. #endif
  38. #ifdef HAVE_FCNTL_H
  39. #include <fcntl.h>
  40. #endif
  41. #ifdef HAVE_ARPA_INET_H
  42. #include <arpa/inet.h>
  43. #endif
  44. #if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
  45. #include <sys/filio.h>
  46. #endif
  47. #ifdef NETWARE
  48. #undef in_addr_t
  49. #define in_addr_t unsigned long
  50. #endif
  51. #ifdef __VMS
  52. #include <in.h>
  53. #include <inet.h>
  54. #endif
  55. #include "curl_printf.h"
  56. #include "urldata.h"
  57. #include "sendf.h"
  58. #include "if2ip.h"
  59. #include "strerror.h"
  60. #include "connect.h"
  61. #include "select.h"
  62. #include "url.h" /* for Curl_safefree() */
  63. #include "multiif.h"
  64. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  65. #include "inet_ntop.h"
  66. #include "inet_pton.h"
  67. #include "vtls/vtls.h" /* for Curl_ssl_check_cxn() */
  68. #include "progress.h"
  69. #include "warnless.h"
  70. #include "conncache.h"
  71. #include "multihandle.h"
  72. /* The last #include files should be: */
  73. #include "curl_memory.h"
  74. #include "memdebug.h"
  75. #ifdef __SYMBIAN32__
  76. /* This isn't actually supported under Symbian OS */
  77. #undef SO_NOSIGPIPE
  78. #endif
  79. static bool verifyconnect(curl_socket_t sockfd, int *error);
  80. #if defined(__DragonFly__) || defined(HAVE_WINSOCK_H)
  81. /* DragonFlyBSD and Windows use millisecond units */
  82. #define KEEPALIVE_FACTOR(x) (x *= 1000)
  83. #else
  84. #define KEEPALIVE_FACTOR(x)
  85. #endif
  86. #if defined(HAVE_WINSOCK2_H) && !defined(SIO_KEEPALIVE_VALS)
  87. #define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
  88. struct tcp_keepalive {
  89. u_long onoff;
  90. u_long keepalivetime;
  91. u_long keepaliveinterval;
  92. };
  93. #endif
  94. static void
  95. tcpkeepalive(struct SessionHandle *data,
  96. curl_socket_t sockfd)
  97. {
  98. int optval = data->set.tcp_keepalive?1:0;
  99. /* only set IDLE and INTVL if setting KEEPALIVE is successful */
  100. if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
  101. (void *)&optval, sizeof(optval)) < 0) {
  102. infof(data, "Failed to set SO_KEEPALIVE on fd %d\n", sockfd);
  103. }
  104. else {
  105. #if defined(SIO_KEEPALIVE_VALS)
  106. struct tcp_keepalive vals;
  107. DWORD dummy;
  108. vals.onoff = 1;
  109. optval = curlx_sltosi(data->set.tcp_keepidle);
  110. KEEPALIVE_FACTOR(optval);
  111. vals.keepalivetime = optval;
  112. optval = curlx_sltosi(data->set.tcp_keepintvl);
  113. KEEPALIVE_FACTOR(optval);
  114. vals.keepaliveinterval = optval;
  115. if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
  116. NULL, 0, &dummy, NULL, NULL) != 0) {
  117. infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd %d: %d\n",
  118. (int)sockfd, WSAGetLastError());
  119. }
  120. #else
  121. #ifdef TCP_KEEPIDLE
  122. optval = curlx_sltosi(data->set.tcp_keepidle);
  123. KEEPALIVE_FACTOR(optval);
  124. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
  125. (void *)&optval, sizeof(optval)) < 0) {
  126. infof(data, "Failed to set TCP_KEEPIDLE on fd %d\n", sockfd);
  127. }
  128. #endif
  129. #ifdef TCP_KEEPINTVL
  130. optval = curlx_sltosi(data->set.tcp_keepintvl);
  131. KEEPALIVE_FACTOR(optval);
  132. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
  133. (void *)&optval, sizeof(optval)) < 0) {
  134. infof(data, "Failed to set TCP_KEEPINTVL on fd %d\n", sockfd);
  135. }
  136. #endif
  137. #ifdef TCP_KEEPALIVE
  138. /* Mac OS X style */
  139. optval = curlx_sltosi(data->set.tcp_keepidle);
  140. KEEPALIVE_FACTOR(optval);
  141. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
  142. (void *)&optval, sizeof(optval)) < 0) {
  143. infof(data, "Failed to set TCP_KEEPALIVE on fd %d\n", sockfd);
  144. }
  145. #endif
  146. #endif
  147. }
  148. }
  149. static CURLcode
  150. singleipconnect(struct connectdata *conn,
  151. const Curl_addrinfo *ai, /* start connecting to this */
  152. curl_socket_t *sock);
  153. /*
  154. * Curl_timeleft() returns the amount of milliseconds left allowed for the
  155. * transfer/connection. If the value is negative, the timeout time has already
  156. * elapsed.
  157. *
  158. * The start time is stored in progress.t_startsingle - as set with
  159. * Curl_pgrsTime(..., TIMER_STARTSINGLE);
  160. *
  161. * If 'nowp' is non-NULL, it points to the current time.
  162. * 'duringconnect' is FALSE if not during a connect, as then of course the
  163. * connect timeout is not taken into account!
  164. *
  165. * @unittest: 1303
  166. */
  167. long Curl_timeleft(struct SessionHandle *data,
  168. struct timeval *nowp,
  169. bool duringconnect)
  170. {
  171. int timeout_set = 0;
  172. long timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0;
  173. struct timeval now;
  174. /* if a timeout is set, use the most restrictive one */
  175. if(data->set.timeout > 0)
  176. timeout_set |= 1;
  177. if(duringconnect && (data->set.connecttimeout > 0))
  178. timeout_set |= 2;
  179. switch (timeout_set) {
  180. case 1:
  181. timeout_ms = data->set.timeout;
  182. break;
  183. case 2:
  184. timeout_ms = data->set.connecttimeout;
  185. break;
  186. case 3:
  187. if(data->set.timeout < data->set.connecttimeout)
  188. timeout_ms = data->set.timeout;
  189. else
  190. timeout_ms = data->set.connecttimeout;
  191. break;
  192. default:
  193. /* use the default */
  194. if(!duringconnect)
  195. /* if we're not during connect, there's no default timeout so if we're
  196. at zero we better just return zero and not make it a negative number
  197. by the math below */
  198. return 0;
  199. break;
  200. }
  201. if(!nowp) {
  202. now = Curl_tvnow();
  203. nowp = &now;
  204. }
  205. /* subtract elapsed time */
  206. if(duringconnect)
  207. /* since this most recent connect started */
  208. timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startsingle);
  209. else
  210. /* since the entire operation started */
  211. timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startop);
  212. if(!timeout_ms)
  213. /* avoid returning 0 as that means no timeout! */
  214. return -1;
  215. return timeout_ms;
  216. }
  217. static CURLcode bindlocal(struct connectdata *conn,
  218. curl_socket_t sockfd, int af, unsigned int scope)
  219. {
  220. struct SessionHandle *data = conn->data;
  221. struct Curl_sockaddr_storage sa;
  222. struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
  223. curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
  224. struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
  225. #ifdef ENABLE_IPV6
  226. struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
  227. #endif
  228. struct Curl_dns_entry *h=NULL;
  229. unsigned short port = data->set.localport; /* use this port number, 0 for
  230. "random" */
  231. /* how many port numbers to try to bind to, increasing one at a time */
  232. int portnum = data->set.localportrange;
  233. const char *dev = data->set.str[STRING_DEVICE];
  234. int error;
  235. /*************************************************************
  236. * Select device to bind socket to
  237. *************************************************************/
  238. if(!dev && !port)
  239. /* no local kind of binding was requested */
  240. return CURLE_OK;
  241. memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
  242. if(dev && (strlen(dev)<255) ) {
  243. char myhost[256] = "";
  244. int done = 0; /* -1 for error, 1 for address found */
  245. bool is_interface = FALSE;
  246. bool is_host = FALSE;
  247. static const char *if_prefix = "if!";
  248. static const char *host_prefix = "host!";
  249. if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
  250. dev += strlen(if_prefix);
  251. is_interface = TRUE;
  252. }
  253. else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
  254. dev += strlen(host_prefix);
  255. is_host = TRUE;
  256. }
  257. /* interface */
  258. if(!is_host) {
  259. switch(Curl_if2ip(af, scope, conn->scope_id, dev,
  260. myhost, sizeof(myhost))) {
  261. case IF2IP_NOT_FOUND:
  262. if(is_interface) {
  263. /* Do not fall back to treating it as a host name */
  264. failf(data, "Couldn't bind to interface '%s'", dev);
  265. return CURLE_INTERFACE_FAILED;
  266. }
  267. break;
  268. case IF2IP_AF_NOT_SUPPORTED:
  269. /* Signal the caller to try another address family if available */
  270. return CURLE_UNSUPPORTED_PROTOCOL;
  271. case IF2IP_FOUND:
  272. is_interface = TRUE;
  273. /*
  274. * We now have the numerical IP address in the 'myhost' buffer
  275. */
  276. infof(data, "Local Interface %s is ip %s using address family %i\n",
  277. dev, myhost, af);
  278. done = 1;
  279. #ifdef SO_BINDTODEVICE
  280. /* I am not sure any other OSs than Linux that provide this feature,
  281. * and at the least I cannot test. --Ben
  282. *
  283. * This feature allows one to tightly bind the local socket to a
  284. * particular interface. This will force even requests to other
  285. * local interfaces to go out the external interface.
  286. *
  287. *
  288. * Only bind to the interface when specified as interface, not just
  289. * as a hostname or ip address.
  290. */
  291. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  292. dev, (curl_socklen_t)strlen(dev)+1) != 0) {
  293. error = SOCKERRNO;
  294. infof(data, "SO_BINDTODEVICE %s failed with errno %d: %s;"
  295. " will do regular bind\n",
  296. dev, error, Curl_strerror(conn, error));
  297. /* This is typically "errno 1, error: Operation not permitted" if
  298. you're not running as root or another suitable privileged
  299. user */
  300. }
  301. #endif
  302. break;
  303. }
  304. }
  305. if(!is_interface) {
  306. /*
  307. * This was not an interface, resolve the name as a host name
  308. * or IP number
  309. *
  310. * Temporarily force name resolution to use only the address type
  311. * of the connection. The resolve functions should really be changed
  312. * to take a type parameter instead.
  313. */
  314. long ipver = conn->ip_version;
  315. int rc;
  316. if(af == AF_INET)
  317. conn->ip_version = CURL_IPRESOLVE_V4;
  318. #ifdef ENABLE_IPV6
  319. else if(af == AF_INET6)
  320. conn->ip_version = CURL_IPRESOLVE_V6;
  321. #endif
  322. rc = Curl_resolv(conn, dev, 0, &h);
  323. if(rc == CURLRESOLV_PENDING)
  324. (void)Curl_resolver_wait_resolv(conn, &h);
  325. conn->ip_version = ipver;
  326. if(h) {
  327. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  328. Curl_printable_address(h->addr, myhost, sizeof(myhost));
  329. infof(data, "Name '%s' family %i resolved to '%s' family %i\n",
  330. dev, af, myhost, h->addr->ai_family);
  331. Curl_resolv_unlock(data, h);
  332. done = 1;
  333. }
  334. else {
  335. /*
  336. * provided dev was no interface (or interfaces are not supported
  337. * e.g. solaris) no ip address and no domain we fail here
  338. */
  339. done = -1;
  340. }
  341. }
  342. if(done > 0) {
  343. #ifdef ENABLE_IPV6
  344. /* IPv6 address */
  345. if(af == AF_INET6) {
  346. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  347. char *scope_ptr = strchr(myhost, '%');
  348. if(scope_ptr)
  349. *(scope_ptr++) = 0;
  350. #endif
  351. if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
  352. si6->sin6_family = AF_INET6;
  353. si6->sin6_port = htons(port);
  354. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  355. if(scope_ptr)
  356. /* The "myhost" string either comes from Curl_if2ip or from
  357. Curl_printable_address. The latter returns only numeric scope
  358. IDs and the former returns none at all. So the scope ID, if
  359. present, is known to be numeric */
  360. si6->sin6_scope_id = atoi(scope_ptr);
  361. #endif
  362. }
  363. sizeof_sa = sizeof(struct sockaddr_in6);
  364. }
  365. else
  366. #endif
  367. /* IPv4 address */
  368. if((af == AF_INET) &&
  369. (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
  370. si4->sin_family = AF_INET;
  371. si4->sin_port = htons(port);
  372. sizeof_sa = sizeof(struct sockaddr_in);
  373. }
  374. }
  375. if(done < 1) {
  376. failf(data, "Couldn't bind to '%s'", dev);
  377. return CURLE_INTERFACE_FAILED;
  378. }
  379. }
  380. else {
  381. /* no device was given, prepare sa to match af's needs */
  382. #ifdef ENABLE_IPV6
  383. if(af == AF_INET6) {
  384. si6->sin6_family = AF_INET6;
  385. si6->sin6_port = htons(port);
  386. sizeof_sa = sizeof(struct sockaddr_in6);
  387. }
  388. else
  389. #endif
  390. if(af == AF_INET) {
  391. si4->sin_family = AF_INET;
  392. si4->sin_port = htons(port);
  393. sizeof_sa = sizeof(struct sockaddr_in);
  394. }
  395. }
  396. for(;;) {
  397. if(bind(sockfd, sock, sizeof_sa) >= 0) {
  398. /* we succeeded to bind */
  399. struct Curl_sockaddr_storage add;
  400. curl_socklen_t size = sizeof(add);
  401. memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
  402. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  403. data->state.os_errno = error = SOCKERRNO;
  404. failf(data, "getsockname() failed with errno %d: %s",
  405. error, Curl_strerror(conn, error));
  406. return CURLE_INTERFACE_FAILED;
  407. }
  408. infof(data, "Local port: %hu\n", port);
  409. conn->bits.bound = TRUE;
  410. return CURLE_OK;
  411. }
  412. if(--portnum > 0) {
  413. infof(data, "Bind to local port %hu failed, trying next\n", port);
  414. port++; /* try next port */
  415. /* We re-use/clobber the port variable here below */
  416. if(sock->sa_family == AF_INET)
  417. si4->sin_port = ntohs(port);
  418. #ifdef ENABLE_IPV6
  419. else
  420. si6->sin6_port = ntohs(port);
  421. #endif
  422. }
  423. else
  424. break;
  425. }
  426. data->state.os_errno = error = SOCKERRNO;
  427. failf(data, "bind failed with errno %d: %s",
  428. error, Curl_strerror(conn, error));
  429. return CURLE_INTERFACE_FAILED;
  430. }
  431. /*
  432. * verifyconnect() returns TRUE if the connect really has happened.
  433. */
  434. static bool verifyconnect(curl_socket_t sockfd, int *error)
  435. {
  436. bool rc = TRUE;
  437. #ifdef SO_ERROR
  438. int err = 0;
  439. curl_socklen_t errSize = sizeof(err);
  440. #ifdef WIN32
  441. /*
  442. * In October 2003 we effectively nullified this function on Windows due to
  443. * problems with it using all CPU in multi-threaded cases.
  444. *
  445. * In May 2004, we bring it back to offer more info back on connect failures.
  446. * Gisle Vanem could reproduce the former problems with this function, but
  447. * could avoid them by adding this SleepEx() call below:
  448. *
  449. * "I don't have Rational Quantify, but the hint from his post was
  450. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  451. * just Sleep(0) would be enough?) would release whatever
  452. * mutex/critical-section the ntdll call is waiting on.
  453. *
  454. * Someone got to verify this on Win-NT 4.0, 2000."
  455. */
  456. #ifdef _WIN32_WCE
  457. Sleep(0);
  458. #else
  459. SleepEx(0, FALSE);
  460. #endif
  461. #endif
  462. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  463. err = SOCKERRNO;
  464. #ifdef _WIN32_WCE
  465. /* Old WinCE versions don't support SO_ERROR */
  466. if(WSAENOPROTOOPT == err) {
  467. SET_SOCKERRNO(0);
  468. err = 0;
  469. }
  470. #endif
  471. #ifdef __minix
  472. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  473. if(EBADIOCTL == err) {
  474. SET_SOCKERRNO(0);
  475. err = 0;
  476. }
  477. #endif
  478. if((0 == err) || (EISCONN == err))
  479. /* we are connected, awesome! */
  480. rc = TRUE;
  481. else
  482. /* This wasn't a successful connect */
  483. rc = FALSE;
  484. if(error)
  485. *error = err;
  486. #else
  487. (void)sockfd;
  488. if(error)
  489. *error = SOCKERRNO;
  490. #endif
  491. return rc;
  492. }
  493. /* Used within the multi interface. Try next IP address, return TRUE if no
  494. more address exists or error */
  495. static CURLcode trynextip(struct connectdata *conn,
  496. int sockindex,
  497. int tempindex)
  498. {
  499. const int other = tempindex ^ 1;
  500. CURLcode result = CURLE_COULDNT_CONNECT;
  501. /* First clean up after the failed socket.
  502. Don't close it yet to ensure that the next IP's socket gets a different
  503. file descriptor, which can prevent bugs when the curl_multi_socket_action
  504. interface is used with certain select() replacements such as kqueue. */
  505. curl_socket_t fd_to_close = conn->tempsock[tempindex];
  506. conn->tempsock[tempindex] = CURL_SOCKET_BAD;
  507. if(sockindex == FIRSTSOCKET) {
  508. Curl_addrinfo *ai = NULL;
  509. int family = AF_UNSPEC;
  510. if(conn->tempaddr[tempindex]) {
  511. /* find next address in the same protocol family */
  512. family = conn->tempaddr[tempindex]->ai_family;
  513. ai = conn->tempaddr[tempindex]->ai_next;
  514. }
  515. #ifdef ENABLE_IPV6
  516. else if(conn->tempaddr[0]) {
  517. /* happy eyeballs - try the other protocol family */
  518. int firstfamily = conn->tempaddr[0]->ai_family;
  519. family = (firstfamily == AF_INET) ? AF_INET6 : AF_INET;
  520. ai = conn->tempaddr[0]->ai_next;
  521. }
  522. #endif
  523. while(ai) {
  524. if(conn->tempaddr[other]) {
  525. /* we can safely skip addresses of the other protocol family */
  526. while(ai && ai->ai_family != family)
  527. ai = ai->ai_next;
  528. }
  529. if(ai) {
  530. result = singleipconnect(conn, ai, &conn->tempsock[tempindex]);
  531. if(result == CURLE_COULDNT_CONNECT) {
  532. ai = ai->ai_next;
  533. continue;
  534. }
  535. conn->tempaddr[tempindex] = ai;
  536. }
  537. break;
  538. }
  539. }
  540. if(fd_to_close != CURL_SOCKET_BAD)
  541. Curl_closesocket(conn, fd_to_close);
  542. return result;
  543. }
  544. /* Copies connection info into the session handle to make it available
  545. when the session handle is no longer associated with a connection. */
  546. void Curl_persistconninfo(struct connectdata *conn)
  547. {
  548. memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
  549. memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
  550. conn->data->info.conn_primary_port = conn->primary_port;
  551. conn->data->info.conn_local_port = conn->local_port;
  552. }
  553. /* retrieves ip address and port from a sockaddr structure */
  554. static bool getaddressinfo(struct sockaddr* sa, char* addr,
  555. long* port)
  556. {
  557. unsigned short us_port;
  558. struct sockaddr_in* si = NULL;
  559. #ifdef ENABLE_IPV6
  560. struct sockaddr_in6* si6 = NULL;
  561. #endif
  562. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  563. struct sockaddr_un* su = NULL;
  564. #endif
  565. switch (sa->sa_family) {
  566. case AF_INET:
  567. si = (struct sockaddr_in*) sa;
  568. if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
  569. addr, MAX_IPADR_LEN)) {
  570. us_port = ntohs(si->sin_port);
  571. *port = us_port;
  572. return TRUE;
  573. }
  574. break;
  575. #ifdef ENABLE_IPV6
  576. case AF_INET6:
  577. si6 = (struct sockaddr_in6*)sa;
  578. if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
  579. addr, MAX_IPADR_LEN)) {
  580. us_port = ntohs(si6->sin6_port);
  581. *port = us_port;
  582. return TRUE;
  583. }
  584. break;
  585. #endif
  586. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  587. case AF_UNIX:
  588. su = (struct sockaddr_un*)sa;
  589. snprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
  590. *port = 0;
  591. return TRUE;
  592. #endif
  593. default:
  594. break;
  595. }
  596. addr[0] = '\0';
  597. *port = 0;
  598. return FALSE;
  599. }
  600. /* retrieves the start/end point information of a socket of an established
  601. connection */
  602. void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
  603. {
  604. curl_socklen_t len;
  605. struct Curl_sockaddr_storage ssrem;
  606. struct Curl_sockaddr_storage ssloc;
  607. struct SessionHandle *data = conn->data;
  608. if(conn->socktype == SOCK_DGRAM)
  609. /* there's no connection! */
  610. return;
  611. if(!conn->bits.reuse) {
  612. int error;
  613. len = sizeof(struct Curl_sockaddr_storage);
  614. if(getpeername(sockfd, (struct sockaddr*) &ssrem, &len)) {
  615. error = SOCKERRNO;
  616. failf(data, "getpeername() failed with errno %d: %s",
  617. error, Curl_strerror(conn, error));
  618. return;
  619. }
  620. len = sizeof(struct Curl_sockaddr_storage);
  621. memset(&ssloc, 0, sizeof(ssloc));
  622. if(getsockname(sockfd, (struct sockaddr*) &ssloc, &len)) {
  623. error = SOCKERRNO;
  624. failf(data, "getsockname() failed with errno %d: %s",
  625. error, Curl_strerror(conn, error));
  626. return;
  627. }
  628. if(!getaddressinfo((struct sockaddr*)&ssrem,
  629. conn->primary_ip, &conn->primary_port)) {
  630. error = ERRNO;
  631. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  632. error, Curl_strerror(conn, error));
  633. return;
  634. }
  635. memcpy(conn->ip_addr_str, conn->primary_ip, MAX_IPADR_LEN);
  636. if(!getaddressinfo((struct sockaddr*)&ssloc,
  637. conn->local_ip, &conn->local_port)) {
  638. error = ERRNO;
  639. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  640. error, Curl_strerror(conn, error));
  641. return;
  642. }
  643. }
  644. /* persist connection info in session handle */
  645. Curl_persistconninfo(conn);
  646. }
  647. /*
  648. * Curl_is_connected() checks if the socket has connected.
  649. */
  650. CURLcode Curl_is_connected(struct connectdata *conn,
  651. int sockindex,
  652. bool *connected)
  653. {
  654. struct SessionHandle *data = conn->data;
  655. CURLcode result = CURLE_OK;
  656. long allow;
  657. int error = 0;
  658. struct timeval now;
  659. int rc;
  660. int i;
  661. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  662. *connected = FALSE; /* a very negative world view is best */
  663. if(conn->bits.tcpconnect[sockindex]) {
  664. /* we are connected already! */
  665. *connected = TRUE;
  666. return CURLE_OK;
  667. }
  668. now = Curl_tvnow();
  669. /* figure out how long time we have left to connect */
  670. allow = Curl_timeleft(data, &now, TRUE);
  671. if(allow < 0) {
  672. /* time-out, bail out, go home */
  673. failf(data, "Connection time-out");
  674. return CURLE_OPERATION_TIMEDOUT;
  675. }
  676. for(i=0; i<2; i++) {
  677. const int other = i ^ 1;
  678. if(conn->tempsock[i] == CURL_SOCKET_BAD)
  679. continue;
  680. #ifdef mpeix
  681. /* Call this function once now, and ignore the results. We do this to
  682. "clear" the error state on the socket so that we can later read it
  683. reliably. This is reported necessary on the MPE/iX operating system. */
  684. (void)verifyconnect(conn->tempsock[i], NULL);
  685. #endif
  686. /* check socket for connect */
  687. rc = Curl_socket_ready(CURL_SOCKET_BAD, conn->tempsock[i], 0);
  688. if(rc == 0) { /* no connection yet */
  689. if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
  690. infof(data, "After %ldms connect time, move on!\n",
  691. conn->timeoutms_per_addr);
  692. error = ETIMEDOUT;
  693. }
  694. /* should we try another protocol family? */
  695. if(i == 0 && conn->tempaddr[1] == NULL &&
  696. curlx_tvdiff(now, conn->connecttime) >= HAPPY_EYEBALLS_TIMEOUT) {
  697. trynextip(conn, sockindex, 1);
  698. }
  699. }
  700. else if(rc == CURL_CSELECT_OUT) {
  701. if(verifyconnect(conn->tempsock[i], &error)) {
  702. /* we are connected with TCP, awesome! */
  703. /* use this socket from now on */
  704. conn->sock[sockindex] = conn->tempsock[i];
  705. conn->ip_addr = conn->tempaddr[i];
  706. conn->tempsock[i] = CURL_SOCKET_BAD;
  707. /* close the other socket, if open */
  708. if(conn->tempsock[other] != CURL_SOCKET_BAD) {
  709. Curl_closesocket(conn, conn->tempsock[other]);
  710. conn->tempsock[other] = CURL_SOCKET_BAD;
  711. }
  712. /* see if we need to do any proxy magic first once we connected */
  713. result = Curl_connected_proxy(conn, sockindex);
  714. if(result)
  715. return result;
  716. conn->bits.tcpconnect[sockindex] = TRUE;
  717. *connected = TRUE;
  718. if(sockindex == FIRSTSOCKET)
  719. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  720. Curl_updateconninfo(conn, conn->sock[sockindex]);
  721. Curl_verboseconnect(conn);
  722. return CURLE_OK;
  723. }
  724. else
  725. infof(data, "Connection failed\n");
  726. }
  727. else if(rc & CURL_CSELECT_ERR)
  728. (void)verifyconnect(conn->tempsock[i], &error);
  729. /*
  730. * The connection failed here, we should attempt to connect to the "next
  731. * address" for the given host. But first remember the latest error.
  732. */
  733. if(error) {
  734. data->state.os_errno = error;
  735. SET_SOCKERRNO(error);
  736. if(conn->tempaddr[i]) {
  737. CURLcode status;
  738. char ipaddress[MAX_IPADR_LEN];
  739. Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN);
  740. infof(data, "connect to %s port %ld failed: %s\n",
  741. ipaddress, conn->port, Curl_strerror(conn, error));
  742. conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ?
  743. allow : allow / 2;
  744. status = trynextip(conn, sockindex, i);
  745. if(status != CURLE_COULDNT_CONNECT
  746. || conn->tempsock[other] == CURL_SOCKET_BAD)
  747. /* the last attempt failed and no other sockets remain open */
  748. result = status;
  749. }
  750. }
  751. }
  752. if(result) {
  753. /* no more addresses to try */
  754. /* if the first address family runs out of addresses to try before
  755. the happy eyeball timeout, go ahead and try the next family now */
  756. if(conn->tempaddr[1] == NULL) {
  757. result = trynextip(conn, sockindex, 1);
  758. if(!result)
  759. return result;
  760. }
  761. failf(data, "Failed to connect to %s port %ld: %s",
  762. conn->bits.proxy?conn->proxy.name:conn->host.name,
  763. conn->port, Curl_strerror(conn, error));
  764. }
  765. return result;
  766. }
  767. static void tcpnodelay(struct connectdata *conn,
  768. curl_socket_t sockfd)
  769. {
  770. #ifdef TCP_NODELAY
  771. struct SessionHandle *data= conn->data;
  772. curl_socklen_t onoff = (curl_socklen_t) data->set.tcp_nodelay;
  773. int level = IPPROTO_TCP;
  774. #if 0
  775. /* The use of getprotobyname() is disabled since it isn't thread-safe on
  776. numerous systems. On these getprotobyname_r() should be used instead, but
  777. that exists in at least one 4 arg version and one 5 arg version, and
  778. since the proto number rarely changes anyway we now just use the hard
  779. coded number. The "proper" fix would need a configure check for the
  780. correct function much in the same style the gethostbyname_r versions are
  781. detected. */
  782. struct protoent *pe = getprotobyname("tcp");
  783. if(pe)
  784. level = pe->p_proto;
  785. #endif
  786. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  787. sizeof(onoff)) < 0)
  788. infof(data, "Could not set TCP_NODELAY: %s\n",
  789. Curl_strerror(conn, SOCKERRNO));
  790. else
  791. infof(data, "TCP_NODELAY set\n");
  792. #else
  793. (void)conn;
  794. (void)sockfd;
  795. #endif
  796. }
  797. #ifdef SO_NOSIGPIPE
  798. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  799. sending data to a dead peer (instead of relying on the 4th argument to send
  800. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  801. systems? */
  802. static void nosigpipe(struct connectdata *conn,
  803. curl_socket_t sockfd)
  804. {
  805. struct SessionHandle *data= conn->data;
  806. int onoff = 1;
  807. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  808. sizeof(onoff)) < 0)
  809. infof(data, "Could not set SO_NOSIGPIPE: %s\n",
  810. Curl_strerror(conn, SOCKERRNO));
  811. }
  812. #else
  813. #define nosigpipe(x,y) Curl_nop_stmt
  814. #endif
  815. #ifdef USE_WINSOCK
  816. /* When you run a program that uses the Windows Sockets API, you may
  817. experience slow performance when you copy data to a TCP server.
  818. http://support.microsoft.com/kb/823764
  819. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  820. Buffer Size
  821. The problem described in this knowledge-base is applied only to pre-Vista
  822. Windows. Following function trying to detect OS version and skips
  823. SO_SNDBUF adjustment for Windows Vista and above.
  824. */
  825. #define DETECT_OS_NONE 0
  826. #define DETECT_OS_PREVISTA 1
  827. #define DETECT_OS_VISTA_OR_LATER 2
  828. void Curl_sndbufset(curl_socket_t sockfd)
  829. {
  830. int val = CURL_MAX_WRITE_SIZE + 32;
  831. int curval = 0;
  832. int curlen = sizeof(curval);
  833. DWORD majorVersion = 6;
  834. static int detectOsState = DETECT_OS_NONE;
  835. if(detectOsState == DETECT_OS_NONE) {
  836. #if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \
  837. (_WIN32_WINNT < _WIN32_WINNT_WIN2K)
  838. OSVERSIONINFO osver;
  839. memset(&osver, 0, sizeof(osver));
  840. osver.dwOSVersionInfoSize = sizeof(osver);
  841. detectOsState = DETECT_OS_PREVISTA;
  842. if(GetVersionEx(&osver)) {
  843. if(osver.dwMajorVersion >= majorVersion)
  844. detectOsState = DETECT_OS_VISTA_OR_LATER;
  845. }
  846. #else
  847. ULONGLONG cm;
  848. OSVERSIONINFOEX osver;
  849. memset(&osver, 0, sizeof(osver));
  850. osver.dwOSVersionInfoSize = sizeof(osver);
  851. osver.dwMajorVersion = majorVersion;
  852. cm = VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL);
  853. cm = VerSetConditionMask(cm, VER_MINORVERSION, VER_GREATER_EQUAL);
  854. cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
  855. cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL);
  856. if(VerifyVersionInfo(&osver, (VER_MAJORVERSION | VER_MINORVERSION |
  857. VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR),
  858. cm))
  859. detectOsState = DETECT_OS_VISTA_OR_LATER;
  860. else
  861. detectOsState = DETECT_OS_PREVISTA;
  862. #endif
  863. }
  864. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  865. return;
  866. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  867. if(curval > val)
  868. return;
  869. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  870. }
  871. #endif
  872. /*
  873. * singleipconnect()
  874. *
  875. * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
  876. * CURL_SOCKET_BAD. Other errors will however return proper errors.
  877. *
  878. * singleipconnect() connects to the given IP only, and it may return without
  879. * having connected.
  880. */
  881. static CURLcode singleipconnect(struct connectdata *conn,
  882. const Curl_addrinfo *ai,
  883. curl_socket_t *sockp)
  884. {
  885. struct Curl_sockaddr_ex addr;
  886. int rc;
  887. int error = 0;
  888. bool isconnected = FALSE;
  889. struct SessionHandle *data = conn->data;
  890. curl_socket_t sockfd;
  891. CURLcode result;
  892. char ipaddress[MAX_IPADR_LEN];
  893. long port;
  894. bool is_tcp;
  895. *sockp = CURL_SOCKET_BAD;
  896. result = Curl_socket(conn, ai, &addr, &sockfd);
  897. if(result)
  898. /* Failed to create the socket, but still return OK since we signal the
  899. lack of socket as well. This allows the parent function to keep looping
  900. over alternative addresses/socket families etc. */
  901. return CURLE_OK;
  902. /* store remote address and port used in this connection attempt */
  903. if(!getaddressinfo((struct sockaddr*)&addr.sa_addr,
  904. ipaddress, &port)) {
  905. /* malformed address or bug in inet_ntop, try next address */
  906. error = ERRNO;
  907. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  908. error, Curl_strerror(conn, error));
  909. Curl_closesocket(conn, sockfd);
  910. return CURLE_OK;
  911. }
  912. infof(data, " Trying %s...\n", ipaddress);
  913. #ifdef ENABLE_IPV6
  914. is_tcp = (addr.family == AF_INET || addr.family == AF_INET6) &&
  915. addr.socktype == SOCK_STREAM;
  916. #else
  917. is_tcp = (addr.family == AF_INET) && addr.socktype == SOCK_STREAM;
  918. #endif
  919. if(is_tcp && data->set.tcp_nodelay)
  920. tcpnodelay(conn, sockfd);
  921. nosigpipe(conn, sockfd);
  922. Curl_sndbufset(sockfd);
  923. if(is_tcp && data->set.tcp_keepalive)
  924. tcpkeepalive(data, sockfd);
  925. if(data->set.fsockopt) {
  926. /* activate callback for setting socket options */
  927. error = data->set.fsockopt(data->set.sockopt_client,
  928. sockfd,
  929. CURLSOCKTYPE_IPCXN);
  930. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  931. isconnected = TRUE;
  932. else if(error) {
  933. Curl_closesocket(conn, sockfd); /* close the socket and bail out */
  934. return CURLE_ABORTED_BY_CALLBACK;
  935. }
  936. }
  937. /* possibly bind the local end to an IP, interface or port */
  938. if(addr.family == AF_INET
  939. #ifdef ENABLE_IPV6
  940. || addr.family == AF_INET6
  941. #endif
  942. ) {
  943. result = bindlocal(conn, sockfd, addr.family,
  944. Curl_ipv6_scope((struct sockaddr*)&addr.sa_addr));
  945. if(result) {
  946. Curl_closesocket(conn, sockfd); /* close socket and bail out */
  947. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  948. /* The address family is not supported on this interface.
  949. We can continue trying addresses */
  950. return CURLE_COULDNT_CONNECT;
  951. }
  952. return result;
  953. }
  954. }
  955. /* set socket non-blocking */
  956. (void)curlx_nonblock(sockfd, TRUE);
  957. conn->connecttime = Curl_tvnow();
  958. if(conn->num_addr > 1)
  959. Curl_expire_latest(data, conn->timeoutms_per_addr);
  960. /* Connect TCP sockets, bind UDP */
  961. if(!isconnected && (conn->socktype == SOCK_STREAM)) {
  962. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  963. if(-1 == rc)
  964. error = SOCKERRNO;
  965. }
  966. else {
  967. *sockp = sockfd;
  968. return CURLE_OK;
  969. }
  970. #ifdef ENABLE_IPV6
  971. conn->bits.ipv6 = (addr.family == AF_INET6)?TRUE:FALSE;
  972. #endif
  973. if(-1 == rc) {
  974. switch(error) {
  975. case EINPROGRESS:
  976. case EWOULDBLOCK:
  977. #if defined(EAGAIN)
  978. #if (EAGAIN) != (EWOULDBLOCK)
  979. /* On some platforms EAGAIN and EWOULDBLOCK are the
  980. * same value, and on others they are different, hence
  981. * the odd #if
  982. */
  983. case EAGAIN:
  984. #endif
  985. #endif
  986. result = CURLE_OK;
  987. break;
  988. default:
  989. /* unknown error, fallthrough and try another address! */
  990. infof(data, "Immediate connect fail for %s: %s\n",
  991. ipaddress, Curl_strerror(conn, error));
  992. data->state.os_errno = error;
  993. /* connect failed */
  994. Curl_closesocket(conn, sockfd);
  995. result = CURLE_COULDNT_CONNECT;
  996. }
  997. }
  998. if(!result)
  999. *sockp = sockfd;
  1000. return result;
  1001. }
  1002. /*
  1003. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  1004. * There might be more than one IP address to try out. Fill in the passed
  1005. * pointer with the connected socket.
  1006. */
  1007. CURLcode Curl_connecthost(struct connectdata *conn, /* context */
  1008. const struct Curl_dns_entry *remotehost)
  1009. {
  1010. struct SessionHandle *data = conn->data;
  1011. struct timeval before = Curl_tvnow();
  1012. CURLcode result = CURLE_COULDNT_CONNECT;
  1013. long timeout_ms = Curl_timeleft(data, &before, TRUE);
  1014. if(timeout_ms < 0) {
  1015. /* a precaution, no need to continue if time already is up */
  1016. failf(data, "Connection time-out");
  1017. return CURLE_OPERATION_TIMEDOUT;
  1018. }
  1019. conn->num_addr = Curl_num_addresses(remotehost->addr);
  1020. conn->tempaddr[0] = remotehost->addr;
  1021. conn->tempaddr[1] = NULL;
  1022. conn->tempsock[0] = CURL_SOCKET_BAD;
  1023. conn->tempsock[1] = CURL_SOCKET_BAD;
  1024. Curl_expire(conn->data, HAPPY_EYEBALLS_TIMEOUT);
  1025. /* Max time for the next connection attempt */
  1026. conn->timeoutms_per_addr =
  1027. conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1028. /* start connecting to first IP */
  1029. while(conn->tempaddr[0]) {
  1030. result = singleipconnect(conn, conn->tempaddr[0], &(conn->tempsock[0]));
  1031. if(!result)
  1032. break;
  1033. conn->tempaddr[0] = conn->tempaddr[0]->ai_next;
  1034. }
  1035. if(conn->tempsock[0] == CURL_SOCKET_BAD) {
  1036. if(!result)
  1037. result = CURLE_COULDNT_CONNECT;
  1038. return result;
  1039. }
  1040. data->info.numconnects++; /* to track the number of connections made */
  1041. return CURLE_OK;
  1042. }
  1043. struct connfind {
  1044. struct connectdata *tofind;
  1045. bool found;
  1046. };
  1047. static int conn_is_conn(struct connectdata *conn, void *param)
  1048. {
  1049. struct connfind *f = (struct connfind *)param;
  1050. if(conn == f->tofind) {
  1051. f->found = TRUE;
  1052. return 1;
  1053. }
  1054. return 0;
  1055. }
  1056. /*
  1057. * Used to extract socket and connectdata struct for the most recent
  1058. * transfer on the given SessionHandle.
  1059. *
  1060. * The returned socket will be CURL_SOCKET_BAD in case of failure!
  1061. */
  1062. curl_socket_t Curl_getconnectinfo(struct SessionHandle *data,
  1063. struct connectdata **connp)
  1064. {
  1065. curl_socket_t sockfd;
  1066. DEBUGASSERT(data);
  1067. /* this works for an easy handle:
  1068. * - that has been used for curl_easy_perform()
  1069. * - that is associated with a multi handle, and whose connection
  1070. * was detached with CURLOPT_CONNECT_ONLY
  1071. */
  1072. if(data->state.lastconnect && (data->multi_easy || data->multi)) {
  1073. struct connectdata *c = data->state.lastconnect;
  1074. struct connfind find;
  1075. find.tofind = data->state.lastconnect;
  1076. find.found = FALSE;
  1077. Curl_conncache_foreach(data->multi_easy?
  1078. &data->multi_easy->conn_cache:
  1079. &data->multi->conn_cache, &find, conn_is_conn);
  1080. if(!find.found) {
  1081. data->state.lastconnect = NULL;
  1082. return CURL_SOCKET_BAD;
  1083. }
  1084. if(connp)
  1085. /* only store this if the caller cares for it */
  1086. *connp = c;
  1087. sockfd = c->sock[FIRSTSOCKET];
  1088. /* we have a socket connected, let's determine if the server shut down */
  1089. /* determine if ssl */
  1090. if(c->ssl[FIRSTSOCKET].use) {
  1091. /* use the SSL context */
  1092. if(!Curl_ssl_check_cxn(c))
  1093. return CURL_SOCKET_BAD; /* FIN received */
  1094. }
  1095. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  1096. #ifdef MSG_PEEK
  1097. else {
  1098. /* use the socket */
  1099. char buf;
  1100. if(recv((RECV_TYPE_ARG1)c->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1101. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  1102. return CURL_SOCKET_BAD; /* FIN received */
  1103. }
  1104. }
  1105. #endif
  1106. }
  1107. else
  1108. return CURL_SOCKET_BAD;
  1109. return sockfd;
  1110. }
  1111. /*
  1112. * Close a socket.
  1113. *
  1114. * 'conn' can be NULL, beware!
  1115. */
  1116. int Curl_closesocket(struct connectdata *conn,
  1117. curl_socket_t sock)
  1118. {
  1119. if(conn && conn->fclosesocket) {
  1120. if((sock == conn->sock[SECONDARYSOCKET]) &&
  1121. conn->sock_accepted[SECONDARYSOCKET])
  1122. /* if this socket matches the second socket, and that was created with
  1123. accept, then we MUST NOT call the callback but clear the accepted
  1124. status */
  1125. conn->sock_accepted[SECONDARYSOCKET] = FALSE;
  1126. else {
  1127. Curl_multi_closed(conn, sock);
  1128. return conn->fclosesocket(conn->closesocket_client, sock);
  1129. }
  1130. }
  1131. if(conn)
  1132. /* tell the multi-socket code about this */
  1133. Curl_multi_closed(conn, sock);
  1134. sclose(sock);
  1135. return 0;
  1136. }
  1137. /*
  1138. * Create a socket based on info from 'conn' and 'ai'.
  1139. *
  1140. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  1141. * 'sockfd' must be a pointer to a socket descriptor.
  1142. *
  1143. * If the open socket callback is set, used that!
  1144. *
  1145. */
  1146. CURLcode Curl_socket(struct connectdata *conn,
  1147. const Curl_addrinfo *ai,
  1148. struct Curl_sockaddr_ex *addr,
  1149. curl_socket_t *sockfd)
  1150. {
  1151. struct SessionHandle *data = conn->data;
  1152. struct Curl_sockaddr_ex dummy;
  1153. if(!addr)
  1154. /* if the caller doesn't want info back, use a local temp copy */
  1155. addr = &dummy;
  1156. /*
  1157. * The Curl_sockaddr_ex structure is basically libcurl's external API
  1158. * curl_sockaddr structure with enough space available to directly hold
  1159. * any protocol-specific address structures. The variable declared here
  1160. * will be used to pass / receive data to/from the fopensocket callback
  1161. * if this has been set, before that, it is initialized from parameters.
  1162. */
  1163. addr->family = ai->ai_family;
  1164. addr->socktype = conn->socktype;
  1165. addr->protocol = conn->socktype==SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
  1166. addr->addrlen = ai->ai_addrlen;
  1167. if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
  1168. addr->addrlen = sizeof(struct Curl_sockaddr_storage);
  1169. memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
  1170. if(data->set.fopensocket)
  1171. /*
  1172. * If the opensocket callback is set, all the destination address
  1173. * information is passed to the callback. Depending on this information the
  1174. * callback may opt to abort the connection, this is indicated returning
  1175. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  1176. * the callback returns a valid socket the destination address information
  1177. * might have been changed and this 'new' address will actually be used
  1178. * here to connect.
  1179. */
  1180. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  1181. CURLSOCKTYPE_IPCXN,
  1182. (struct curl_sockaddr *)addr);
  1183. else
  1184. /* opensocket callback not set, so simply create the socket now */
  1185. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  1186. if(*sockfd == CURL_SOCKET_BAD)
  1187. /* no socket, no connection */
  1188. return CURLE_COULDNT_CONNECT;
  1189. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  1190. if(conn->scope_id && (addr->family == AF_INET6)) {
  1191. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  1192. sa6->sin6_scope_id = conn->scope_id;
  1193. }
  1194. #endif
  1195. return CURLE_OK;
  1196. }
  1197. #ifdef CURLDEBUG
  1198. /*
  1199. * Curl_conncontrol() is used to set the conn->bits.close bit on or off. It
  1200. * MUST be called with the connclose() or connkeep() macros with a stated
  1201. * reason. The reason is only shown in debug builds but helps to figure out
  1202. * decision paths when connections are or aren't re-used as expected.
  1203. */
  1204. void Curl_conncontrol(struct connectdata *conn, bool closeit,
  1205. const char *reason)
  1206. {
  1207. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  1208. (void) reason;
  1209. #endif
  1210. if(closeit != conn->bits.close) {
  1211. infof(conn->data, "Marked for [%s]: %s\n", closeit?"closure":"keep alive",
  1212. reason);
  1213. conn->bits.close = closeit; /* the only place in the source code that
  1214. should assign this bit */
  1215. }
  1216. }
  1217. #endif