connect.c 38 KB

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