connect.c 38 KB

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