cf-socket.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifdef HAVE_NETINET_IN_H
  26. #include <netinet/in.h> /* <netinet/tcp.h> may need it */
  27. #endif
  28. #ifdef HAVE_SYS_UN_H
  29. #include <sys/un.h> /* for sockaddr_un */
  30. #endif
  31. #ifdef HAVE_LINUX_TCP_H
  32. #include <linux/tcp.h>
  33. #elif defined(HAVE_NETINET_TCP_H)
  34. #include <netinet/tcp.h>
  35. #endif
  36. #ifdef HAVE_SYS_IOCTL_H
  37. #include <sys/ioctl.h>
  38. #endif
  39. #ifdef HAVE_NETDB_H
  40. #include <netdb.h>
  41. #endif
  42. #ifdef HAVE_FCNTL_H
  43. #include <fcntl.h>
  44. #endif
  45. #ifdef HAVE_ARPA_INET_H
  46. #include <arpa/inet.h>
  47. #endif
  48. #ifdef __VMS
  49. #include <in.h>
  50. #include <inet.h>
  51. #endif
  52. #include "urldata.h"
  53. #include "bufq.h"
  54. #include "sendf.h"
  55. #include "if2ip.h"
  56. #include "strerror.h"
  57. #include "cfilters.h"
  58. #include "cf-socket.h"
  59. #include "connect.h"
  60. #include "select.h"
  61. #include "url.h" /* for Curl_safefree() */
  62. #include "multiif.h"
  63. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  64. #include "inet_ntop.h"
  65. #include "inet_pton.h"
  66. #include "progress.h"
  67. #include "warnless.h"
  68. #include "conncache.h"
  69. #include "multihandle.h"
  70. #include "rand.h"
  71. #include "share.h"
  72. #include "version_win32.h"
  73. /* The last 3 #include files should be in this order */
  74. #include "curl_printf.h"
  75. #include "curl_memory.h"
  76. #include "memdebug.h"
  77. #if defined(ENABLE_IPV6) && defined(IPV6_V6ONLY) && defined(WIN32)
  78. /* It makes support for IPv4-mapped IPv6 addresses.
  79. * Linux kernel, NetBSD, FreeBSD and Darwin: default is off;
  80. * Windows Vista and later: default is on;
  81. * DragonFly BSD: acts like off, and dummy setting;
  82. * OpenBSD and earlier Windows: unsupported.
  83. * Linux: controlled by /proc/sys/net/ipv6/bindv6only.
  84. */
  85. static void set_ipv6_v6only(curl_socket_t sockfd, int on)
  86. {
  87. (void)setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(on));
  88. }
  89. #else
  90. #define set_ipv6_v6only(x,y)
  91. #endif
  92. static void tcpnodelay(struct Curl_easy *data, curl_socket_t sockfd)
  93. {
  94. #if defined(TCP_NODELAY)
  95. curl_socklen_t onoff = (curl_socklen_t) 1;
  96. int level = IPPROTO_TCP;
  97. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  98. char buffer[STRERROR_LEN];
  99. #else
  100. (void) data;
  101. #endif
  102. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  103. sizeof(onoff)) < 0)
  104. infof(data, "Could not set TCP_NODELAY: %s",
  105. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  106. #else
  107. (void)data;
  108. (void)sockfd;
  109. #endif
  110. }
  111. #ifdef SO_NOSIGPIPE
  112. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  113. sending data to a dead peer (instead of relying on the 4th argument to send
  114. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  115. systems? */
  116. static void nosigpipe(struct Curl_easy *data,
  117. curl_socket_t sockfd)
  118. {
  119. int onoff = 1;
  120. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  121. sizeof(onoff)) < 0) {
  122. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  123. char buffer[STRERROR_LEN];
  124. infof(data, "Could not set SO_NOSIGPIPE: %s",
  125. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  126. #endif
  127. }
  128. }
  129. #else
  130. #define nosigpipe(x,y) Curl_nop_stmt
  131. #endif
  132. #if defined(__DragonFly__) || defined(HAVE_WINSOCK2_H)
  133. /* DragonFlyBSD and Windows use millisecond units */
  134. #define KEEPALIVE_FACTOR(x) (x *= 1000)
  135. #else
  136. #define KEEPALIVE_FACTOR(x)
  137. #endif
  138. #if defined(HAVE_WINSOCK2_H) && !defined(SIO_KEEPALIVE_VALS)
  139. #define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
  140. struct tcp_keepalive {
  141. u_long onoff;
  142. u_long keepalivetime;
  143. u_long keepaliveinterval;
  144. };
  145. #endif
  146. static void
  147. tcpkeepalive(struct Curl_easy *data,
  148. curl_socket_t sockfd)
  149. {
  150. int optval = data->set.tcp_keepalive?1:0;
  151. /* only set IDLE and INTVL if setting KEEPALIVE is successful */
  152. if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
  153. (void *)&optval, sizeof(optval)) < 0) {
  154. infof(data, "Failed to set SO_KEEPALIVE on fd %d", sockfd);
  155. }
  156. else {
  157. #if defined(SIO_KEEPALIVE_VALS)
  158. struct tcp_keepalive vals;
  159. DWORD dummy;
  160. vals.onoff = 1;
  161. optval = curlx_sltosi(data->set.tcp_keepidle);
  162. KEEPALIVE_FACTOR(optval);
  163. vals.keepalivetime = optval;
  164. optval = curlx_sltosi(data->set.tcp_keepintvl);
  165. KEEPALIVE_FACTOR(optval);
  166. vals.keepaliveinterval = optval;
  167. if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
  168. NULL, 0, &dummy, NULL, NULL) != 0) {
  169. infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd %d: %d",
  170. (int)sockfd, WSAGetLastError());
  171. }
  172. #else
  173. #ifdef TCP_KEEPIDLE
  174. optval = curlx_sltosi(data->set.tcp_keepidle);
  175. KEEPALIVE_FACTOR(optval);
  176. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
  177. (void *)&optval, sizeof(optval)) < 0) {
  178. infof(data, "Failed to set TCP_KEEPIDLE on fd %d", sockfd);
  179. }
  180. #elif defined(TCP_KEEPALIVE)
  181. /* Mac OS X style */
  182. optval = curlx_sltosi(data->set.tcp_keepidle);
  183. KEEPALIVE_FACTOR(optval);
  184. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
  185. (void *)&optval, sizeof(optval)) < 0) {
  186. infof(data, "Failed to set TCP_KEEPALIVE on fd %d", sockfd);
  187. }
  188. #endif
  189. #ifdef TCP_KEEPINTVL
  190. optval = curlx_sltosi(data->set.tcp_keepintvl);
  191. KEEPALIVE_FACTOR(optval);
  192. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
  193. (void *)&optval, sizeof(optval)) < 0) {
  194. infof(data, "Failed to set TCP_KEEPINTVL on fd %d", sockfd);
  195. }
  196. #endif
  197. #endif
  198. }
  199. }
  200. /**
  201. * Assign the address `ai` to the Curl_sockaddr_ex `dest` and
  202. * set the transport used.
  203. */
  204. void Curl_sock_assign_addr(struct Curl_sockaddr_ex *dest,
  205. const struct Curl_addrinfo *ai,
  206. int transport)
  207. {
  208. /*
  209. * The Curl_sockaddr_ex structure is basically libcurl's external API
  210. * curl_sockaddr structure with enough space available to directly hold
  211. * any protocol-specific address structures. The variable declared here
  212. * will be used to pass / receive data to/from the fopensocket callback
  213. * if this has been set, before that, it is initialized from parameters.
  214. */
  215. dest->family = ai->ai_family;
  216. switch(transport) {
  217. case TRNSPRT_TCP:
  218. dest->socktype = SOCK_STREAM;
  219. dest->protocol = IPPROTO_TCP;
  220. break;
  221. case TRNSPRT_UNIX:
  222. dest->socktype = SOCK_STREAM;
  223. dest->protocol = IPPROTO_IP;
  224. break;
  225. default: /* UDP and QUIC */
  226. dest->socktype = SOCK_DGRAM;
  227. dest->protocol = IPPROTO_UDP;
  228. break;
  229. }
  230. dest->addrlen = ai->ai_addrlen;
  231. if(dest->addrlen > sizeof(struct Curl_sockaddr_storage))
  232. dest->addrlen = sizeof(struct Curl_sockaddr_storage);
  233. memcpy(&dest->sa_addr, ai->ai_addr, dest->addrlen);
  234. }
  235. static CURLcode socket_open(struct Curl_easy *data,
  236. struct Curl_sockaddr_ex *addr,
  237. curl_socket_t *sockfd)
  238. {
  239. DEBUGASSERT(data);
  240. DEBUGASSERT(data->conn);
  241. if(data->set.fopensocket) {
  242. /*
  243. * If the opensocket callback is set, all the destination address
  244. * information is passed to the callback. Depending on this information the
  245. * callback may opt to abort the connection, this is indicated returning
  246. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  247. * the callback returns a valid socket the destination address information
  248. * might have been changed and this 'new' address will actually be used
  249. * here to connect.
  250. */
  251. Curl_set_in_callback(data, true);
  252. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  253. CURLSOCKTYPE_IPCXN,
  254. (struct curl_sockaddr *)addr);
  255. Curl_set_in_callback(data, false);
  256. }
  257. else {
  258. /* opensocket callback not set, so simply create the socket now */
  259. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  260. }
  261. if(*sockfd == CURL_SOCKET_BAD)
  262. /* no socket, no connection */
  263. return CURLE_COULDNT_CONNECT;
  264. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  265. if(data->conn->scope_id && (addr->family == AF_INET6)) {
  266. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  267. sa6->sin6_scope_id = data->conn->scope_id;
  268. }
  269. #endif
  270. return CURLE_OK;
  271. }
  272. /*
  273. * Create a socket based on info from 'conn' and 'ai'.
  274. *
  275. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  276. * 'sockfd' must be a pointer to a socket descriptor.
  277. *
  278. * If the open socket callback is set, used that!
  279. *
  280. */
  281. CURLcode Curl_socket_open(struct Curl_easy *data,
  282. const struct Curl_addrinfo *ai,
  283. struct Curl_sockaddr_ex *addr,
  284. int transport,
  285. curl_socket_t *sockfd)
  286. {
  287. struct Curl_sockaddr_ex dummy;
  288. if(!addr)
  289. /* if the caller doesn't want info back, use a local temp copy */
  290. addr = &dummy;
  291. Curl_sock_assign_addr(addr, ai, transport);
  292. return socket_open(data, addr, sockfd);
  293. }
  294. static int socket_close(struct Curl_easy *data, struct connectdata *conn,
  295. int use_callback, curl_socket_t sock)
  296. {
  297. if(use_callback && conn && conn->fclosesocket) {
  298. int rc;
  299. Curl_multi_closed(data, sock);
  300. Curl_set_in_callback(data, true);
  301. rc = conn->fclosesocket(conn->closesocket_client, sock);
  302. Curl_set_in_callback(data, false);
  303. return rc;
  304. }
  305. if(conn)
  306. /* tell the multi-socket code about this */
  307. Curl_multi_closed(data, sock);
  308. sclose(sock);
  309. return 0;
  310. }
  311. /*
  312. * Close a socket.
  313. *
  314. * 'conn' can be NULL, beware!
  315. */
  316. int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn,
  317. curl_socket_t sock)
  318. {
  319. return socket_close(data, conn, FALSE, sock);
  320. }
  321. #ifdef USE_WINSOCK
  322. /* When you run a program that uses the Windows Sockets API, you may
  323. experience slow performance when you copy data to a TCP server.
  324. https://support.microsoft.com/kb/823764
  325. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  326. Buffer Size
  327. The problem described in this knowledge-base is applied only to pre-Vista
  328. Windows. Following function trying to detect OS version and skips
  329. SO_SNDBUF adjustment for Windows Vista and above.
  330. */
  331. #define DETECT_OS_NONE 0
  332. #define DETECT_OS_PREVISTA 1
  333. #define DETECT_OS_VISTA_OR_LATER 2
  334. void Curl_sndbufset(curl_socket_t sockfd)
  335. {
  336. int val = CURL_MAX_WRITE_SIZE + 32;
  337. int curval = 0;
  338. int curlen = sizeof(curval);
  339. static int detectOsState = DETECT_OS_NONE;
  340. if(detectOsState == DETECT_OS_NONE) {
  341. if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT,
  342. VERSION_GREATER_THAN_EQUAL))
  343. detectOsState = DETECT_OS_VISTA_OR_LATER;
  344. else
  345. detectOsState = DETECT_OS_PREVISTA;
  346. }
  347. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  348. return;
  349. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  350. if(curval > val)
  351. return;
  352. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  353. }
  354. #endif
  355. #ifndef CURL_DISABLE_BINDLOCAL
  356. static CURLcode bindlocal(struct Curl_easy *data, struct connectdata *conn,
  357. curl_socket_t sockfd, int af, unsigned int scope)
  358. {
  359. struct Curl_sockaddr_storage sa;
  360. struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
  361. curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
  362. struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
  363. #ifdef ENABLE_IPV6
  364. struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
  365. #endif
  366. struct Curl_dns_entry *h = NULL;
  367. unsigned short port = data->set.localport; /* use this port number, 0 for
  368. "random" */
  369. /* how many port numbers to try to bind to, increasing one at a time */
  370. int portnum = data->set.localportrange;
  371. const char *dev = data->set.str[STRING_DEVICE];
  372. int error;
  373. #ifdef IP_BIND_ADDRESS_NO_PORT
  374. int on = 1;
  375. #endif
  376. #ifndef ENABLE_IPV6
  377. (void)scope;
  378. #endif
  379. /*************************************************************
  380. * Select device to bind socket to
  381. *************************************************************/
  382. if(!dev && !port)
  383. /* no local kind of binding was requested */
  384. return CURLE_OK;
  385. memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
  386. if(dev && (strlen(dev)<255) ) {
  387. char myhost[256] = "";
  388. int done = 0; /* -1 for error, 1 for address found */
  389. bool is_interface = FALSE;
  390. bool is_host = FALSE;
  391. static const char *if_prefix = "if!";
  392. static const char *host_prefix = "host!";
  393. if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
  394. dev += strlen(if_prefix);
  395. is_interface = TRUE;
  396. }
  397. else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
  398. dev += strlen(host_prefix);
  399. is_host = TRUE;
  400. }
  401. /* interface */
  402. if(!is_host) {
  403. #ifdef SO_BINDTODEVICE
  404. /*
  405. * This binds the local socket to a particular interface. This will
  406. * force even requests to other local interfaces to go out the external
  407. * interface. Only bind to the interface when specified as interface,
  408. * not just as a hostname or ip address.
  409. *
  410. * The interface might be a VRF, eg: vrf-blue, which means it cannot be
  411. * converted to an IP address and would fail Curl_if2ip. Simply try to
  412. * use it straight away.
  413. */
  414. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  415. dev, (curl_socklen_t)strlen(dev) + 1) == 0) {
  416. /* This is often "errno 1, error: Operation not permitted" if you're
  417. * not running as root or another suitable privileged user. If it
  418. * succeeds it means the parameter was a valid interface and not an IP
  419. * address. Return immediately.
  420. */
  421. infof(data, "socket successfully bound to interface '%s'", dev);
  422. return CURLE_OK;
  423. }
  424. #endif
  425. switch(Curl_if2ip(af,
  426. #ifdef ENABLE_IPV6
  427. scope, conn->scope_id,
  428. #endif
  429. dev, myhost, sizeof(myhost))) {
  430. case IF2IP_NOT_FOUND:
  431. if(is_interface) {
  432. /* Do not fall back to treating it as a host name */
  433. failf(data, "Couldn't bind to interface '%s'", dev);
  434. return CURLE_INTERFACE_FAILED;
  435. }
  436. break;
  437. case IF2IP_AF_NOT_SUPPORTED:
  438. /* Signal the caller to try another address family if available */
  439. return CURLE_UNSUPPORTED_PROTOCOL;
  440. case IF2IP_FOUND:
  441. is_interface = TRUE;
  442. /*
  443. * We now have the numerical IP address in the 'myhost' buffer
  444. */
  445. infof(data, "Local Interface %s is ip %s using address family %i",
  446. dev, myhost, af);
  447. done = 1;
  448. break;
  449. }
  450. }
  451. if(!is_interface) {
  452. /*
  453. * This was not an interface, resolve the name as a host name
  454. * or IP number
  455. *
  456. * Temporarily force name resolution to use only the address type
  457. * of the connection. The resolve functions should really be changed
  458. * to take a type parameter instead.
  459. */
  460. unsigned char ipver = conn->ip_version;
  461. int rc;
  462. if(af == AF_INET)
  463. conn->ip_version = CURL_IPRESOLVE_V4;
  464. #ifdef ENABLE_IPV6
  465. else if(af == AF_INET6)
  466. conn->ip_version = CURL_IPRESOLVE_V6;
  467. #endif
  468. rc = Curl_resolv(data, dev, 80, FALSE, &h);
  469. if(rc == CURLRESOLV_PENDING)
  470. (void)Curl_resolver_wait_resolv(data, &h);
  471. conn->ip_version = ipver;
  472. if(h) {
  473. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  474. Curl_printable_address(h->addr, myhost, sizeof(myhost));
  475. infof(data, "Name '%s' family %i resolved to '%s' family %i",
  476. dev, af, myhost, h->addr->ai_family);
  477. Curl_resolv_unlock(data, h);
  478. if(af != h->addr->ai_family) {
  479. /* bad IP version combo, signal the caller to try another address
  480. family if available */
  481. return CURLE_UNSUPPORTED_PROTOCOL;
  482. }
  483. done = 1;
  484. }
  485. else {
  486. /*
  487. * provided dev was no interface (or interfaces are not supported
  488. * e.g. solaris) no ip address and no domain we fail here
  489. */
  490. done = -1;
  491. }
  492. }
  493. if(done > 0) {
  494. #ifdef ENABLE_IPV6
  495. /* IPv6 address */
  496. if(af == AF_INET6) {
  497. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  498. char *scope_ptr = strchr(myhost, '%');
  499. if(scope_ptr)
  500. *(scope_ptr++) = '\0';
  501. #endif
  502. if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
  503. si6->sin6_family = AF_INET6;
  504. si6->sin6_port = htons(port);
  505. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  506. if(scope_ptr) {
  507. /* The "myhost" string either comes from Curl_if2ip or from
  508. Curl_printable_address. The latter returns only numeric scope
  509. IDs and the former returns none at all. So the scope ID, if
  510. present, is known to be numeric */
  511. unsigned long scope_id = strtoul(scope_ptr, NULL, 10);
  512. if(scope_id > UINT_MAX)
  513. return CURLE_UNSUPPORTED_PROTOCOL;
  514. si6->sin6_scope_id = (unsigned int)scope_id;
  515. }
  516. #endif
  517. }
  518. sizeof_sa = sizeof(struct sockaddr_in6);
  519. }
  520. else
  521. #endif
  522. /* IPv4 address */
  523. if((af == AF_INET) &&
  524. (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
  525. si4->sin_family = AF_INET;
  526. si4->sin_port = htons(port);
  527. sizeof_sa = sizeof(struct sockaddr_in);
  528. }
  529. }
  530. if(done < 1) {
  531. /* errorbuf is set false so failf will overwrite any message already in
  532. the error buffer, so the user receives this error message instead of a
  533. generic resolve error. */
  534. data->state.errorbuf = FALSE;
  535. failf(data, "Couldn't bind to '%s'", dev);
  536. return CURLE_INTERFACE_FAILED;
  537. }
  538. }
  539. else {
  540. /* no device was given, prepare sa to match af's needs */
  541. #ifdef ENABLE_IPV6
  542. if(af == AF_INET6) {
  543. si6->sin6_family = AF_INET6;
  544. si6->sin6_port = htons(port);
  545. sizeof_sa = sizeof(struct sockaddr_in6);
  546. }
  547. else
  548. #endif
  549. if(af == AF_INET) {
  550. si4->sin_family = AF_INET;
  551. si4->sin_port = htons(port);
  552. sizeof_sa = sizeof(struct sockaddr_in);
  553. }
  554. }
  555. #ifdef IP_BIND_ADDRESS_NO_PORT
  556. (void)setsockopt(sockfd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &on, sizeof(on));
  557. #endif
  558. for(;;) {
  559. if(bind(sockfd, sock, sizeof_sa) >= 0) {
  560. /* we succeeded to bind */
  561. struct Curl_sockaddr_storage add;
  562. curl_socklen_t size = sizeof(add);
  563. memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
  564. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  565. char buffer[STRERROR_LEN];
  566. data->state.os_errno = error = SOCKERRNO;
  567. failf(data, "getsockname() failed with errno %d: %s",
  568. error, Curl_strerror(error, buffer, sizeof(buffer)));
  569. return CURLE_INTERFACE_FAILED;
  570. }
  571. infof(data, "Local port: %hu", port);
  572. conn->bits.bound = TRUE;
  573. return CURLE_OK;
  574. }
  575. if(--portnum > 0) {
  576. port++; /* try next port */
  577. if(port == 0)
  578. break;
  579. infof(data, "Bind to local port %d failed, trying next", port - 1);
  580. /* We reuse/clobber the port variable here below */
  581. if(sock->sa_family == AF_INET)
  582. si4->sin_port = ntohs(port);
  583. #ifdef ENABLE_IPV6
  584. else
  585. si6->sin6_port = ntohs(port);
  586. #endif
  587. }
  588. else
  589. break;
  590. }
  591. {
  592. char buffer[STRERROR_LEN];
  593. data->state.os_errno = error = SOCKERRNO;
  594. failf(data, "bind failed with errno %d: %s",
  595. error, Curl_strerror(error, buffer, sizeof(buffer)));
  596. }
  597. return CURLE_INTERFACE_FAILED;
  598. }
  599. #endif
  600. /*
  601. * verifyconnect() returns TRUE if the connect really has happened.
  602. */
  603. static bool verifyconnect(curl_socket_t sockfd, int *error)
  604. {
  605. bool rc = TRUE;
  606. #ifdef SO_ERROR
  607. int err = 0;
  608. curl_socklen_t errSize = sizeof(err);
  609. #ifdef WIN32
  610. /*
  611. * In October 2003 we effectively nullified this function on Windows due to
  612. * problems with it using all CPU in multi-threaded cases.
  613. *
  614. * In May 2004, we bring it back to offer more info back on connect failures.
  615. * Gisle Vanem could reproduce the former problems with this function, but
  616. * could avoid them by adding this SleepEx() call below:
  617. *
  618. * "I don't have Rational Quantify, but the hint from his post was
  619. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  620. * just Sleep(0) would be enough?) would release whatever
  621. * mutex/critical-section the ntdll call is waiting on.
  622. *
  623. * Someone got to verify this on Win-NT 4.0, 2000."
  624. */
  625. #ifdef _WIN32_WCE
  626. Sleep(0);
  627. #else
  628. SleepEx(0, FALSE);
  629. #endif
  630. #endif
  631. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  632. err = SOCKERRNO;
  633. #ifdef _WIN32_WCE
  634. /* Old WinCE versions don't support SO_ERROR */
  635. if(WSAENOPROTOOPT == err) {
  636. SET_SOCKERRNO(0);
  637. err = 0;
  638. }
  639. #endif
  640. #if defined(EBADIOCTL) && defined(__minix)
  641. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  642. if(EBADIOCTL == err) {
  643. SET_SOCKERRNO(0);
  644. err = 0;
  645. }
  646. #endif
  647. if((0 == err) || (EISCONN == err))
  648. /* we are connected, awesome! */
  649. rc = TRUE;
  650. else
  651. /* This wasn't a successful connect */
  652. rc = FALSE;
  653. if(error)
  654. *error = err;
  655. #else
  656. (void)sockfd;
  657. if(error)
  658. *error = SOCKERRNO;
  659. #endif
  660. return rc;
  661. }
  662. /**
  663. * Determine the curl code for a socket connect() == -1 with errno.
  664. */
  665. static CURLcode socket_connect_result(struct Curl_easy *data,
  666. const char *ipaddress, int error)
  667. {
  668. switch(error) {
  669. case EINPROGRESS:
  670. case EWOULDBLOCK:
  671. #if defined(EAGAIN)
  672. #if (EAGAIN) != (EWOULDBLOCK)
  673. /* On some platforms EAGAIN and EWOULDBLOCK are the
  674. * same value, and on others they are different, hence
  675. * the odd #if
  676. */
  677. case EAGAIN:
  678. #endif
  679. #endif
  680. return CURLE_OK;
  681. default:
  682. /* unknown error, fallthrough and try another address! */
  683. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  684. (void)ipaddress;
  685. #else
  686. {
  687. char buffer[STRERROR_LEN];
  688. infof(data, "Immediate connect fail for %s: %s",
  689. ipaddress, Curl_strerror(error, buffer, sizeof(buffer)));
  690. }
  691. #endif
  692. data->state.os_errno = error;
  693. /* connect failed */
  694. return CURLE_COULDNT_CONNECT;
  695. }
  696. }
  697. /* We have a recv buffer to enhance reads with len < NW_SMALL_READS.
  698. * This happens often on TLS connections where the TLS implementation
  699. * tries to read the head of a TLS record, determine the length of the
  700. * full record and then make a subsequent read for that.
  701. * On large reads, we will not fill the buffer to avoid the double copy. */
  702. #define NW_RECV_CHUNK_SIZE (64 * 1024)
  703. #define NW_RECV_CHUNKS 1
  704. #define NW_SMALL_READS (1024)
  705. struct cf_socket_ctx {
  706. int transport;
  707. struct Curl_sockaddr_ex addr; /* address to connect to */
  708. curl_socket_t sock; /* current attempt socket */
  709. struct bufq recvbuf; /* used when `buffer_recv` is set */
  710. char r_ip[MAX_IPADR_LEN]; /* remote IP as string */
  711. int r_port; /* remote port number */
  712. char l_ip[MAX_IPADR_LEN]; /* local IP as string */
  713. int l_port; /* local port number */
  714. struct curltime started_at; /* when socket was created */
  715. struct curltime connected_at; /* when socket connected/got first byte */
  716. struct curltime first_byte_at; /* when first byte was recvd */
  717. int error; /* errno of last failure or 0 */
  718. #ifdef DEBUGBUILD
  719. int wblock_percent; /* percent of writes doing EAGAIN */
  720. int wpartial_percent; /* percent of bytes written in send */
  721. #endif
  722. BIT(got_first_byte); /* if first byte was received */
  723. BIT(accepted); /* socket was accepted, not connected */
  724. BIT(active);
  725. BIT(buffer_recv);
  726. };
  727. static void cf_socket_ctx_init(struct cf_socket_ctx *ctx,
  728. const struct Curl_addrinfo *ai,
  729. int transport)
  730. {
  731. memset(ctx, 0, sizeof(*ctx));
  732. ctx->sock = CURL_SOCKET_BAD;
  733. ctx->transport = transport;
  734. Curl_sock_assign_addr(&ctx->addr, ai, transport);
  735. Curl_bufq_init(&ctx->recvbuf, NW_RECV_CHUNK_SIZE, NW_RECV_CHUNKS);
  736. #ifdef DEBUGBUILD
  737. {
  738. char *p = getenv("CURL_DBG_SOCK_WBLOCK");
  739. if(p) {
  740. long l = strtol(p, NULL, 10);
  741. if(l >= 0 && l <= 100)
  742. ctx->wblock_percent = (int)l;
  743. }
  744. p = getenv("CURL_DBG_SOCK_WPARTIAL");
  745. if(p) {
  746. long l = strtol(p, NULL, 10);
  747. if(l >= 0 && l <= 100)
  748. ctx->wpartial_percent = (int)l;
  749. }
  750. }
  751. #endif
  752. }
  753. struct reader_ctx {
  754. struct Curl_cfilter *cf;
  755. struct Curl_easy *data;
  756. };
  757. static ssize_t nw_in_read(void *reader_ctx,
  758. unsigned char *buf, size_t len,
  759. CURLcode *err)
  760. {
  761. struct reader_ctx *rctx = reader_ctx;
  762. struct cf_socket_ctx *ctx = rctx->cf->ctx;
  763. ssize_t nread;
  764. *err = CURLE_OK;
  765. nread = sread(ctx->sock, buf, len);
  766. if(-1 == nread) {
  767. int sockerr = SOCKERRNO;
  768. if(
  769. #ifdef WSAEWOULDBLOCK
  770. /* This is how Windows does it */
  771. (WSAEWOULDBLOCK == sockerr)
  772. #else
  773. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  774. due to its inability to send off data without blocking. We therefore
  775. treat both error codes the same here */
  776. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr)
  777. #endif
  778. ) {
  779. /* this is just a case of EWOULDBLOCK */
  780. *err = CURLE_AGAIN;
  781. nread = -1;
  782. }
  783. else {
  784. char buffer[STRERROR_LEN];
  785. failf(rctx->data, "Recv failure: %s",
  786. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  787. rctx->data->state.os_errno = sockerr;
  788. *err = CURLE_RECV_ERROR;
  789. nread = -1;
  790. }
  791. }
  792. CURL_TRC_CF(rctx->data, rctx->cf, "nw_in_read(len=%zu) -> %d, err=%d",
  793. len, (int)nread, *err);
  794. return nread;
  795. }
  796. static void cf_socket_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  797. {
  798. struct cf_socket_ctx *ctx = cf->ctx;
  799. if(ctx && CURL_SOCKET_BAD != ctx->sock) {
  800. if(ctx->active) {
  801. /* We share our socket at cf->conn->sock[cf->sockindex] when active.
  802. * If it is no longer there, someone has stolen (and hopefully
  803. * closed it) and we just forget about it.
  804. */
  805. if(ctx->sock == cf->conn->sock[cf->sockindex]) {
  806. CURL_TRC_CF(data, cf, "cf_socket_close(%" CURL_FORMAT_SOCKET_T
  807. ", active)", ctx->sock);
  808. socket_close(data, cf->conn, !ctx->accepted, ctx->sock);
  809. cf->conn->sock[cf->sockindex] = CURL_SOCKET_BAD;
  810. }
  811. else {
  812. CURL_TRC_CF(data, cf, "cf_socket_close(%" CURL_FORMAT_SOCKET_T
  813. ") no longer at conn->sock[], discarding", ctx->sock);
  814. /* TODO: we do not want this to happen. Need to check which
  815. * code is messing with conn->sock[cf->sockindex] */
  816. }
  817. ctx->sock = CURL_SOCKET_BAD;
  818. if(cf->sockindex == FIRSTSOCKET)
  819. cf->conn->remote_addr = NULL;
  820. }
  821. else {
  822. /* this is our local socket, we did never publish it */
  823. CURL_TRC_CF(data, cf, "cf_socket_close(%" CURL_FORMAT_SOCKET_T
  824. ", not active)", ctx->sock);
  825. socket_close(data, cf->conn, !ctx->accepted, ctx->sock);
  826. ctx->sock = CURL_SOCKET_BAD;
  827. }
  828. Curl_bufq_reset(&ctx->recvbuf);
  829. ctx->active = FALSE;
  830. ctx->buffer_recv = FALSE;
  831. memset(&ctx->started_at, 0, sizeof(ctx->started_at));
  832. memset(&ctx->connected_at, 0, sizeof(ctx->connected_at));
  833. }
  834. cf->connected = FALSE;
  835. }
  836. static void cf_socket_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
  837. {
  838. struct cf_socket_ctx *ctx = cf->ctx;
  839. cf_socket_close(cf, data);
  840. CURL_TRC_CF(data, cf, "destroy");
  841. Curl_bufq_free(&ctx->recvbuf);
  842. free(ctx);
  843. cf->ctx = NULL;
  844. }
  845. static CURLcode set_local_ip(struct Curl_cfilter *cf,
  846. struct Curl_easy *data)
  847. {
  848. struct cf_socket_ctx *ctx = cf->ctx;
  849. #ifdef HAVE_GETSOCKNAME
  850. if(!(data->conn->handler->protocol & CURLPROTO_TFTP)) {
  851. /* TFTP does not connect, so it cannot get the IP like this */
  852. char buffer[STRERROR_LEN];
  853. struct Curl_sockaddr_storage ssloc;
  854. curl_socklen_t slen = sizeof(struct Curl_sockaddr_storage);
  855. memset(&ssloc, 0, sizeof(ssloc));
  856. if(getsockname(ctx->sock, (struct sockaddr*) &ssloc, &slen)) {
  857. int error = SOCKERRNO;
  858. failf(data, "getsockname() failed with errno %d: %s",
  859. error, Curl_strerror(error, buffer, sizeof(buffer)));
  860. return CURLE_FAILED_INIT;
  861. }
  862. if(!Curl_addr2string((struct sockaddr*)&ssloc, slen,
  863. ctx->l_ip, &ctx->l_port)) {
  864. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  865. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  866. return CURLE_FAILED_INIT;
  867. }
  868. }
  869. #else
  870. (void)data;
  871. ctx->l_ip[0] = 0;
  872. ctx->l_port = -1;
  873. #endif
  874. return CURLE_OK;
  875. }
  876. static CURLcode set_remote_ip(struct Curl_cfilter *cf,
  877. struct Curl_easy *data)
  878. {
  879. struct cf_socket_ctx *ctx = cf->ctx;
  880. /* store remote address and port used in this connection attempt */
  881. if(!Curl_addr2string(&ctx->addr.sa_addr, ctx->addr.addrlen,
  882. ctx->r_ip, &ctx->r_port)) {
  883. char buffer[STRERROR_LEN];
  884. ctx->error = errno;
  885. /* malformed address or bug in inet_ntop, try next address */
  886. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  887. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  888. return CURLE_FAILED_INIT;
  889. }
  890. return CURLE_OK;
  891. }
  892. static CURLcode cf_socket_open(struct Curl_cfilter *cf,
  893. struct Curl_easy *data)
  894. {
  895. struct cf_socket_ctx *ctx = cf->ctx;
  896. int error = 0;
  897. bool isconnected = FALSE;
  898. CURLcode result = CURLE_COULDNT_CONNECT;
  899. bool is_tcp;
  900. (void)data;
  901. DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD);
  902. ctx->started_at = Curl_now();
  903. result = socket_open(data, &ctx->addr, &ctx->sock);
  904. if(result)
  905. goto out;
  906. result = set_remote_ip(cf, data);
  907. if(result)
  908. goto out;
  909. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  910. {
  911. const char *ipmsg;
  912. #ifdef ENABLE_IPV6
  913. if(ctx->addr.family == AF_INET6) {
  914. set_ipv6_v6only(ctx->sock, 0);
  915. ipmsg = " Trying [%s]:%d...";
  916. }
  917. else
  918. #endif
  919. ipmsg = " Trying %s:%d...";
  920. infof(data, ipmsg, ctx->r_ip, ctx->r_port);
  921. }
  922. #endif
  923. #ifdef ENABLE_IPV6
  924. is_tcp = (ctx->addr.family == AF_INET
  925. || ctx->addr.family == AF_INET6) &&
  926. ctx->addr.socktype == SOCK_STREAM;
  927. #else
  928. is_tcp = (ctx->addr.family == AF_INET) &&
  929. ctx->addr.socktype == SOCK_STREAM;
  930. #endif
  931. if(is_tcp && data->set.tcp_nodelay)
  932. tcpnodelay(data, ctx->sock);
  933. nosigpipe(data, ctx->sock);
  934. Curl_sndbufset(ctx->sock);
  935. if(is_tcp && data->set.tcp_keepalive)
  936. tcpkeepalive(data, ctx->sock);
  937. if(data->set.fsockopt) {
  938. /* activate callback for setting socket options */
  939. Curl_set_in_callback(data, true);
  940. error = data->set.fsockopt(data->set.sockopt_client,
  941. ctx->sock,
  942. CURLSOCKTYPE_IPCXN);
  943. Curl_set_in_callback(data, false);
  944. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  945. isconnected = TRUE;
  946. else if(error) {
  947. result = CURLE_ABORTED_BY_CALLBACK;
  948. goto out;
  949. }
  950. }
  951. #ifndef CURL_DISABLE_BINDLOCAL
  952. /* possibly bind the local end to an IP, interface or port */
  953. if(ctx->addr.family == AF_INET
  954. #ifdef ENABLE_IPV6
  955. || ctx->addr.family == AF_INET6
  956. #endif
  957. ) {
  958. result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family,
  959. Curl_ipv6_scope(&ctx->addr.sa_addr));
  960. if(result) {
  961. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  962. /* The address family is not supported on this interface.
  963. We can continue trying addresses */
  964. result = CURLE_COULDNT_CONNECT;
  965. }
  966. goto out;
  967. }
  968. }
  969. #endif
  970. /* set socket non-blocking */
  971. (void)curlx_nonblock(ctx->sock, TRUE);
  972. out:
  973. if(result) {
  974. if(ctx->sock != CURL_SOCKET_BAD) {
  975. socket_close(data, cf->conn, TRUE, ctx->sock);
  976. ctx->sock = CURL_SOCKET_BAD;
  977. }
  978. }
  979. else if(isconnected) {
  980. set_local_ip(cf, data);
  981. ctx->connected_at = Curl_now();
  982. cf->connected = TRUE;
  983. }
  984. CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" CURL_FORMAT_SOCKET_T,
  985. result, ctx->sock);
  986. return result;
  987. }
  988. static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data,
  989. bool is_tcp_fastopen)
  990. {
  991. struct cf_socket_ctx *ctx = cf->ctx;
  992. #ifdef TCP_FASTOPEN_CONNECT
  993. int optval = 1;
  994. #endif
  995. int rc = -1;
  996. (void)data;
  997. if(is_tcp_fastopen) {
  998. #if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */
  999. # if defined(HAVE_BUILTIN_AVAILABLE)
  1000. /* while connectx function is available since macOS 10.11 / iOS 9,
  1001. it did not have the interface declared correctly until
  1002. Xcode 9 / macOS SDK 10.13 */
  1003. if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
  1004. sa_endpoints_t endpoints;
  1005. endpoints.sae_srcif = 0;
  1006. endpoints.sae_srcaddr = NULL;
  1007. endpoints.sae_srcaddrlen = 0;
  1008. endpoints.sae_dstaddr = &ctx->addr.sa_addr;
  1009. endpoints.sae_dstaddrlen = ctx->addr.addrlen;
  1010. rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY,
  1011. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  1012. NULL, 0, NULL, NULL);
  1013. }
  1014. else {
  1015. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1016. }
  1017. # else
  1018. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1019. # endif /* HAVE_BUILTIN_AVAILABLE */
  1020. #elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
  1021. if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
  1022. (void *)&optval, sizeof(optval)) < 0)
  1023. infof(data, "Failed to enable TCP Fast Open on fd %"
  1024. CURL_FORMAT_SOCKET_T, ctx->sock);
  1025. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1026. #elif defined(MSG_FASTOPEN) /* old Linux */
  1027. if(cf->conn->given->flags & PROTOPT_SSL)
  1028. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1029. else
  1030. rc = 0; /* Do nothing */
  1031. #endif
  1032. }
  1033. else {
  1034. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1035. }
  1036. return rc;
  1037. }
  1038. static CURLcode cf_tcp_connect(struct Curl_cfilter *cf,
  1039. struct Curl_easy *data,
  1040. bool blocking, bool *done)
  1041. {
  1042. struct cf_socket_ctx *ctx = cf->ctx;
  1043. CURLcode result = CURLE_COULDNT_CONNECT;
  1044. int rc = 0;
  1045. (void)data;
  1046. if(cf->connected) {
  1047. *done = TRUE;
  1048. return CURLE_OK;
  1049. }
  1050. /* TODO: need to support blocking connect? */
  1051. if(blocking)
  1052. return CURLE_UNSUPPORTED_PROTOCOL;
  1053. *done = FALSE; /* a very negative world view is best */
  1054. if(ctx->sock == CURL_SOCKET_BAD) {
  1055. result = cf_socket_open(cf, data);
  1056. if(result)
  1057. goto out;
  1058. if(cf->connected) {
  1059. *done = TRUE;
  1060. return CURLE_OK;
  1061. }
  1062. /* Connect TCP socket */
  1063. rc = do_connect(cf, data, cf->conn->bits.tcp_fastopen);
  1064. if(-1 == rc) {
  1065. result = socket_connect_result(data, ctx->r_ip, SOCKERRNO);
  1066. goto out;
  1067. }
  1068. }
  1069. #ifdef mpeix
  1070. /* Call this function once now, and ignore the results. We do this to
  1071. "clear" the error state on the socket so that we can later read it
  1072. reliably. This is reported necessary on the MPE/iX operating
  1073. system. */
  1074. (void)verifyconnect(ctx->sock, NULL);
  1075. #endif
  1076. /* check socket for connect */
  1077. rc = SOCKET_WRITABLE(ctx->sock, 0);
  1078. if(rc == 0) { /* no connection yet */
  1079. CURL_TRC_CF(data, cf, "not connected yet");
  1080. return CURLE_OK;
  1081. }
  1082. else if(rc == CURL_CSELECT_OUT || cf->conn->bits.tcp_fastopen) {
  1083. if(verifyconnect(ctx->sock, &ctx->error)) {
  1084. /* we are connected with TCP, awesome! */
  1085. ctx->connected_at = Curl_now();
  1086. set_local_ip(cf, data);
  1087. *done = TRUE;
  1088. cf->connected = TRUE;
  1089. CURL_TRC_CF(data, cf, "connected");
  1090. return CURLE_OK;
  1091. }
  1092. }
  1093. else if(rc & CURL_CSELECT_ERR) {
  1094. (void)verifyconnect(ctx->sock, &ctx->error);
  1095. result = CURLE_COULDNT_CONNECT;
  1096. }
  1097. out:
  1098. if(result) {
  1099. if(ctx->error) {
  1100. data->state.os_errno = ctx->error;
  1101. SET_SOCKERRNO(ctx->error);
  1102. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1103. {
  1104. char buffer[STRERROR_LEN];
  1105. infof(data, "connect to %s port %u failed: %s",
  1106. ctx->r_ip, ctx->r_port,
  1107. Curl_strerror(ctx->error, buffer, sizeof(buffer)));
  1108. }
  1109. #endif
  1110. }
  1111. if(ctx->sock != CURL_SOCKET_BAD) {
  1112. socket_close(data, cf->conn, TRUE, ctx->sock);
  1113. ctx->sock = CURL_SOCKET_BAD;
  1114. }
  1115. *done = FALSE;
  1116. }
  1117. return result;
  1118. }
  1119. static void cf_socket_get_host(struct Curl_cfilter *cf,
  1120. struct Curl_easy *data,
  1121. const char **phost,
  1122. const char **pdisplay_host,
  1123. int *pport)
  1124. {
  1125. (void)data;
  1126. *phost = cf->conn->host.name;
  1127. *pdisplay_host = cf->conn->host.dispname;
  1128. *pport = cf->conn->port;
  1129. }
  1130. static int cf_socket_get_select_socks(struct Curl_cfilter *cf,
  1131. struct Curl_easy *data,
  1132. curl_socket_t *socks)
  1133. {
  1134. struct cf_socket_ctx *ctx = cf->ctx;
  1135. int rc = GETSOCK_BLANK;
  1136. (void)data;
  1137. if(!cf->connected && ctx->sock != CURL_SOCKET_BAD) {
  1138. socks[0] = ctx->sock;
  1139. rc |= GETSOCK_WRITESOCK(0);
  1140. }
  1141. return rc;
  1142. }
  1143. static bool cf_socket_data_pending(struct Curl_cfilter *cf,
  1144. const struct Curl_easy *data)
  1145. {
  1146. struct cf_socket_ctx *ctx = cf->ctx;
  1147. int readable;
  1148. (void)data;
  1149. if(!Curl_bufq_is_empty(&ctx->recvbuf))
  1150. return TRUE;
  1151. readable = SOCKET_READABLE(ctx->sock, 0);
  1152. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1153. }
  1154. static ssize_t cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1155. const void *buf, size_t len, CURLcode *err)
  1156. {
  1157. struct cf_socket_ctx *ctx = cf->ctx;
  1158. curl_socket_t fdsave;
  1159. ssize_t nwritten;
  1160. size_t orig_len = len;
  1161. *err = CURLE_OK;
  1162. fdsave = cf->conn->sock[cf->sockindex];
  1163. cf->conn->sock[cf->sockindex] = ctx->sock;
  1164. #ifdef DEBUGBUILD
  1165. /* simulate network blocking/partial writes */
  1166. if(ctx->wblock_percent > 0) {
  1167. unsigned char c;
  1168. Curl_rand(data, &c, 1);
  1169. if(c >= ((100-ctx->wblock_percent)*256/100)) {
  1170. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len);
  1171. *err = CURLE_AGAIN;
  1172. nwritten = -1;
  1173. cf->conn->sock[cf->sockindex] = fdsave;
  1174. return nwritten;
  1175. }
  1176. }
  1177. if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) {
  1178. len = len * ctx->wpartial_percent / 100;
  1179. if(!len)
  1180. len = 1;
  1181. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes",
  1182. orig_len, len);
  1183. }
  1184. #endif
  1185. #if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
  1186. if(cf->conn->bits.tcp_fastopen) {
  1187. nwritten = sendto(ctx->sock, buf, len, MSG_FASTOPEN,
  1188. &cf->conn->remote_addr->sa_addr,
  1189. cf->conn->remote_addr->addrlen);
  1190. cf->conn->bits.tcp_fastopen = FALSE;
  1191. }
  1192. else
  1193. #endif
  1194. nwritten = swrite(ctx->sock, buf, len);
  1195. if(-1 == nwritten) {
  1196. int sockerr = SOCKERRNO;
  1197. if(
  1198. #ifdef WSAEWOULDBLOCK
  1199. /* This is how Windows does it */
  1200. (WSAEWOULDBLOCK == sockerr)
  1201. #else
  1202. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  1203. due to its inability to send off data without blocking. We therefore
  1204. treat both error codes the same here */
  1205. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr) ||
  1206. (EINPROGRESS == sockerr)
  1207. #endif
  1208. ) {
  1209. /* this is just a case of EWOULDBLOCK */
  1210. *err = CURLE_AGAIN;
  1211. }
  1212. else {
  1213. char buffer[STRERROR_LEN];
  1214. failf(data, "Send failure: %s",
  1215. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  1216. data->state.os_errno = sockerr;
  1217. *err = CURLE_SEND_ERROR;
  1218. }
  1219. }
  1220. CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, err=%d",
  1221. orig_len, (int)nwritten, *err);
  1222. cf->conn->sock[cf->sockindex] = fdsave;
  1223. return nwritten;
  1224. }
  1225. static ssize_t cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1226. char *buf, size_t len, CURLcode *err)
  1227. {
  1228. struct cf_socket_ctx *ctx = cf->ctx;
  1229. curl_socket_t fdsave;
  1230. ssize_t nread;
  1231. *err = CURLE_OK;
  1232. fdsave = cf->conn->sock[cf->sockindex];
  1233. cf->conn->sock[cf->sockindex] = ctx->sock;
  1234. if(ctx->buffer_recv && !Curl_bufq_is_empty(&ctx->recvbuf)) {
  1235. CURL_TRC_CF(data, cf, "recv from buffer");
  1236. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1237. }
  1238. else {
  1239. struct reader_ctx rctx;
  1240. rctx.cf = cf;
  1241. rctx.data = data;
  1242. /* "small" reads may trigger filling our buffer, "large" reads
  1243. * are probably not worth the additional copy */
  1244. if(ctx->buffer_recv && len < NW_SMALL_READS) {
  1245. ssize_t nwritten;
  1246. nwritten = Curl_bufq_slurp(&ctx->recvbuf, nw_in_read, &rctx, err);
  1247. if(nwritten < 0 && !Curl_bufq_is_empty(&ctx->recvbuf)) {
  1248. /* we have a partial read with an error. need to deliver
  1249. * what we got, return the error later. */
  1250. CURL_TRC_CF(data, cf, "partial read: empty buffer first");
  1251. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1252. }
  1253. else if(nwritten < 0) {
  1254. nread = -1;
  1255. goto out;
  1256. }
  1257. else if(nwritten == 0) {
  1258. /* eof */
  1259. *err = CURLE_OK;
  1260. nread = 0;
  1261. }
  1262. else {
  1263. CURL_TRC_CF(data, cf, "buffered %zd additional bytes", nwritten);
  1264. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1265. }
  1266. }
  1267. else {
  1268. nread = nw_in_read(&rctx, (unsigned char *)buf, len, err);
  1269. }
  1270. }
  1271. out:
  1272. CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, err=%d", len, (int)nread,
  1273. *err);
  1274. if(nread > 0 && !ctx->got_first_byte) {
  1275. ctx->first_byte_at = Curl_now();
  1276. ctx->got_first_byte = TRUE;
  1277. }
  1278. cf->conn->sock[cf->sockindex] = fdsave;
  1279. return nread;
  1280. }
  1281. static void conn_set_primary_ip(struct Curl_cfilter *cf,
  1282. struct Curl_easy *data)
  1283. {
  1284. #ifdef HAVE_GETPEERNAME
  1285. struct cf_socket_ctx *ctx = cf->ctx;
  1286. if(!(data->conn->handler->protocol & CURLPROTO_TFTP)) {
  1287. /* TFTP does not connect the endpoint: getpeername() failed with errno
  1288. 107: Transport endpoint is not connected */
  1289. char buffer[STRERROR_LEN];
  1290. struct Curl_sockaddr_storage ssrem;
  1291. curl_socklen_t plen;
  1292. int port;
  1293. plen = sizeof(ssrem);
  1294. memset(&ssrem, 0, plen);
  1295. if(getpeername(ctx->sock, (struct sockaddr*) &ssrem, &plen)) {
  1296. int error = SOCKERRNO;
  1297. failf(data, "getpeername() failed with errno %d: %s",
  1298. error, Curl_strerror(error, buffer, sizeof(buffer)));
  1299. return;
  1300. }
  1301. if(!Curl_addr2string((struct sockaddr*)&ssrem, plen,
  1302. cf->conn->primary_ip, &port)) {
  1303. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  1304. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1305. return;
  1306. }
  1307. }
  1308. #else
  1309. cf->conn->primary_ip[0] = 0;
  1310. (void)data;
  1311. #endif
  1312. }
  1313. static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data)
  1314. {
  1315. struct cf_socket_ctx *ctx = cf->ctx;
  1316. /* use this socket from now on */
  1317. cf->conn->sock[cf->sockindex] = ctx->sock;
  1318. /* the first socket info gets set at conn and data */
  1319. if(cf->sockindex == FIRSTSOCKET) {
  1320. cf->conn->remote_addr = &ctx->addr;
  1321. #ifdef ENABLE_IPV6
  1322. cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6)? TRUE : FALSE;
  1323. #endif
  1324. conn_set_primary_ip(cf, data);
  1325. set_local_ip(cf, data);
  1326. Curl_persistconninfo(data, cf->conn, ctx->l_ip, ctx->l_port);
  1327. /* buffering is currently disabled by default because we have stalls
  1328. * in parallel transfers where not all buffered data is consumed and no
  1329. * socket events happen.
  1330. */
  1331. ctx->buffer_recv = FALSE;
  1332. }
  1333. ctx->active = TRUE;
  1334. }
  1335. static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf,
  1336. struct Curl_easy *data,
  1337. int event, int arg1, void *arg2)
  1338. {
  1339. struct cf_socket_ctx *ctx = cf->ctx;
  1340. (void)arg1;
  1341. (void)arg2;
  1342. switch(event) {
  1343. case CF_CTRL_CONN_INFO_UPDATE:
  1344. cf_socket_active(cf, data);
  1345. break;
  1346. case CF_CTRL_DATA_SETUP:
  1347. Curl_persistconninfo(data, cf->conn, ctx->l_ip, ctx->l_port);
  1348. break;
  1349. }
  1350. return CURLE_OK;
  1351. }
  1352. static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf,
  1353. struct Curl_easy *data,
  1354. bool *input_pending)
  1355. {
  1356. struct cf_socket_ctx *ctx = cf->ctx;
  1357. struct pollfd pfd[1];
  1358. int r;
  1359. *input_pending = FALSE;
  1360. (void)data;
  1361. if(!ctx || ctx->sock == CURL_SOCKET_BAD)
  1362. return FALSE;
  1363. /* Check with 0 timeout if there are any events pending on the socket */
  1364. pfd[0].fd = ctx->sock;
  1365. pfd[0].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
  1366. pfd[0].revents = 0;
  1367. r = Curl_poll(pfd, 1, 0);
  1368. if(r < 0) {
  1369. CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead");
  1370. return FALSE;
  1371. }
  1372. else if(r == 0) {
  1373. CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive");
  1374. return TRUE;
  1375. }
  1376. else if(pfd[0].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) {
  1377. CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead");
  1378. return FALSE;
  1379. }
  1380. CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive");
  1381. *input_pending = TRUE;
  1382. return TRUE;
  1383. }
  1384. static CURLcode cf_socket_query(struct Curl_cfilter *cf,
  1385. struct Curl_easy *data,
  1386. int query, int *pres1, void *pres2)
  1387. {
  1388. struct cf_socket_ctx *ctx = cf->ctx;
  1389. switch(query) {
  1390. case CF_QUERY_SOCKET:
  1391. DEBUGASSERT(pres2);
  1392. *((curl_socket_t *)pres2) = ctx->sock;
  1393. return CURLE_OK;
  1394. case CF_QUERY_CONNECT_REPLY_MS:
  1395. if(ctx->got_first_byte) {
  1396. timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at);
  1397. *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX;
  1398. }
  1399. else
  1400. *pres1 = -1;
  1401. return CURLE_OK;
  1402. case CF_QUERY_TIMER_CONNECT: {
  1403. struct curltime *when = pres2;
  1404. switch(ctx->transport) {
  1405. case TRNSPRT_UDP:
  1406. case TRNSPRT_QUIC:
  1407. /* Since UDP connected sockets work different from TCP, we use the
  1408. * time of the first byte from the peer as the "connect" time. */
  1409. if(ctx->got_first_byte) {
  1410. *when = ctx->first_byte_at;
  1411. break;
  1412. }
  1413. /* FALLTHROUGH */
  1414. default:
  1415. *when = ctx->connected_at;
  1416. break;
  1417. }
  1418. return CURLE_OK;
  1419. }
  1420. default:
  1421. break;
  1422. }
  1423. return cf->next?
  1424. cf->next->cft->query(cf->next, data, query, pres1, pres2) :
  1425. CURLE_UNKNOWN_OPTION;
  1426. }
  1427. struct Curl_cftype Curl_cft_tcp = {
  1428. "TCP",
  1429. CF_TYPE_IP_CONNECT,
  1430. CURL_LOG_LVL_NONE,
  1431. cf_socket_destroy,
  1432. cf_tcp_connect,
  1433. cf_socket_close,
  1434. cf_socket_get_host,
  1435. cf_socket_get_select_socks,
  1436. cf_socket_data_pending,
  1437. cf_socket_send,
  1438. cf_socket_recv,
  1439. cf_socket_cntrl,
  1440. cf_socket_conn_is_alive,
  1441. Curl_cf_def_conn_keep_alive,
  1442. cf_socket_query,
  1443. };
  1444. CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf,
  1445. struct Curl_easy *data,
  1446. struct connectdata *conn,
  1447. const struct Curl_addrinfo *ai,
  1448. int transport)
  1449. {
  1450. struct cf_socket_ctx *ctx = NULL;
  1451. struct Curl_cfilter *cf = NULL;
  1452. CURLcode result;
  1453. (void)data;
  1454. (void)conn;
  1455. DEBUGASSERT(transport == TRNSPRT_TCP);
  1456. ctx = calloc(sizeof(*ctx), 1);
  1457. if(!ctx) {
  1458. result = CURLE_OUT_OF_MEMORY;
  1459. goto out;
  1460. }
  1461. cf_socket_ctx_init(ctx, ai, transport);
  1462. result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx);
  1463. out:
  1464. *pcf = (!result)? cf : NULL;
  1465. if(result) {
  1466. Curl_safefree(cf);
  1467. Curl_safefree(ctx);
  1468. }
  1469. return result;
  1470. }
  1471. static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf,
  1472. struct Curl_easy *data)
  1473. {
  1474. struct cf_socket_ctx *ctx = cf->ctx;
  1475. int rc;
  1476. /* QUIC needs a connected socket, nonblocking */
  1477. DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD);
  1478. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1479. if(-1 == rc) {
  1480. return socket_connect_result(data, ctx->r_ip, SOCKERRNO);
  1481. }
  1482. set_local_ip(cf, data);
  1483. CURL_TRC_CF(data, cf, "%s socket %" CURL_FORMAT_SOCKET_T
  1484. " connected: [%s:%d] -> [%s:%d]",
  1485. (ctx->transport == TRNSPRT_QUIC)? "QUIC" : "UDP",
  1486. ctx->sock, ctx->l_ip, ctx->l_port, ctx->r_ip, ctx->r_port);
  1487. (void)curlx_nonblock(ctx->sock, TRUE);
  1488. switch(ctx->addr.family) {
  1489. #if defined(__linux__) && defined(IP_MTU_DISCOVER)
  1490. case AF_INET: {
  1491. int val = IP_PMTUDISC_DO;
  1492. (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val,
  1493. sizeof(val));
  1494. break;
  1495. }
  1496. #endif
  1497. #if defined(__linux__) && defined(IPV6_MTU_DISCOVER)
  1498. case AF_INET6: {
  1499. int val = IPV6_PMTUDISC_DO;
  1500. (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
  1501. sizeof(val));
  1502. break;
  1503. }
  1504. #endif
  1505. }
  1506. return CURLE_OK;
  1507. }
  1508. static CURLcode cf_udp_connect(struct Curl_cfilter *cf,
  1509. struct Curl_easy *data,
  1510. bool blocking, bool *done)
  1511. {
  1512. struct cf_socket_ctx *ctx = cf->ctx;
  1513. CURLcode result = CURLE_COULDNT_CONNECT;
  1514. (void)blocking;
  1515. if(cf->connected) {
  1516. *done = TRUE;
  1517. return CURLE_OK;
  1518. }
  1519. *done = FALSE;
  1520. if(ctx->sock == CURL_SOCKET_BAD) {
  1521. result = cf_socket_open(cf, data);
  1522. if(result) {
  1523. CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d", result);
  1524. goto out;
  1525. }
  1526. if(ctx->transport == TRNSPRT_QUIC) {
  1527. result = cf_udp_setup_quic(cf, data);
  1528. if(result)
  1529. goto out;
  1530. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1531. CURL_FORMAT_SOCKET_T " (%s:%d)",
  1532. ctx->sock, ctx->l_ip, ctx->l_port);
  1533. }
  1534. else {
  1535. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1536. CURL_FORMAT_SOCKET_T " (unconnected)", ctx->sock);
  1537. }
  1538. *done = TRUE;
  1539. cf->connected = TRUE;
  1540. }
  1541. out:
  1542. return result;
  1543. }
  1544. struct Curl_cftype Curl_cft_udp = {
  1545. "UDP",
  1546. CF_TYPE_IP_CONNECT,
  1547. CURL_LOG_LVL_NONE,
  1548. cf_socket_destroy,
  1549. cf_udp_connect,
  1550. cf_socket_close,
  1551. cf_socket_get_host,
  1552. cf_socket_get_select_socks,
  1553. cf_socket_data_pending,
  1554. cf_socket_send,
  1555. cf_socket_recv,
  1556. cf_socket_cntrl,
  1557. cf_socket_conn_is_alive,
  1558. Curl_cf_def_conn_keep_alive,
  1559. cf_socket_query,
  1560. };
  1561. CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf,
  1562. struct Curl_easy *data,
  1563. struct connectdata *conn,
  1564. const struct Curl_addrinfo *ai,
  1565. int transport)
  1566. {
  1567. struct cf_socket_ctx *ctx = NULL;
  1568. struct Curl_cfilter *cf = NULL;
  1569. CURLcode result;
  1570. (void)data;
  1571. (void)conn;
  1572. DEBUGASSERT(transport == TRNSPRT_UDP || transport == TRNSPRT_QUIC);
  1573. ctx = calloc(sizeof(*ctx), 1);
  1574. if(!ctx) {
  1575. result = CURLE_OUT_OF_MEMORY;
  1576. goto out;
  1577. }
  1578. cf_socket_ctx_init(ctx, ai, transport);
  1579. result = Curl_cf_create(&cf, &Curl_cft_udp, ctx);
  1580. out:
  1581. *pcf = (!result)? cf : NULL;
  1582. if(result) {
  1583. Curl_safefree(cf);
  1584. Curl_safefree(ctx);
  1585. }
  1586. return result;
  1587. }
  1588. /* this is the TCP filter which can also handle this case */
  1589. struct Curl_cftype Curl_cft_unix = {
  1590. "UNIX",
  1591. CF_TYPE_IP_CONNECT,
  1592. CURL_LOG_LVL_NONE,
  1593. cf_socket_destroy,
  1594. cf_tcp_connect,
  1595. cf_socket_close,
  1596. cf_socket_get_host,
  1597. cf_socket_get_select_socks,
  1598. cf_socket_data_pending,
  1599. cf_socket_send,
  1600. cf_socket_recv,
  1601. cf_socket_cntrl,
  1602. cf_socket_conn_is_alive,
  1603. Curl_cf_def_conn_keep_alive,
  1604. cf_socket_query,
  1605. };
  1606. CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf,
  1607. struct Curl_easy *data,
  1608. struct connectdata *conn,
  1609. const struct Curl_addrinfo *ai,
  1610. int transport)
  1611. {
  1612. struct cf_socket_ctx *ctx = NULL;
  1613. struct Curl_cfilter *cf = NULL;
  1614. CURLcode result;
  1615. (void)data;
  1616. (void)conn;
  1617. DEBUGASSERT(transport == TRNSPRT_UNIX);
  1618. ctx = calloc(sizeof(*ctx), 1);
  1619. if(!ctx) {
  1620. result = CURLE_OUT_OF_MEMORY;
  1621. goto out;
  1622. }
  1623. cf_socket_ctx_init(ctx, ai, transport);
  1624. result = Curl_cf_create(&cf, &Curl_cft_unix, ctx);
  1625. out:
  1626. *pcf = (!result)? cf : NULL;
  1627. if(result) {
  1628. Curl_safefree(cf);
  1629. Curl_safefree(ctx);
  1630. }
  1631. return result;
  1632. }
  1633. static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
  1634. struct Curl_easy *data,
  1635. bool blocking, bool *done)
  1636. {
  1637. /* we start accepted, if we ever close, we cannot go on */
  1638. (void)data;
  1639. (void)blocking;
  1640. if(cf->connected) {
  1641. *done = TRUE;
  1642. return CURLE_OK;
  1643. }
  1644. return CURLE_FAILED_INIT;
  1645. }
  1646. struct Curl_cftype Curl_cft_tcp_accept = {
  1647. "TCP-ACCEPT",
  1648. CF_TYPE_IP_CONNECT,
  1649. CURL_LOG_LVL_NONE,
  1650. cf_socket_destroy,
  1651. cf_tcp_accept_connect,
  1652. cf_socket_close,
  1653. cf_socket_get_host, /* TODO: not accurate */
  1654. cf_socket_get_select_socks,
  1655. cf_socket_data_pending,
  1656. cf_socket_send,
  1657. cf_socket_recv,
  1658. cf_socket_cntrl,
  1659. cf_socket_conn_is_alive,
  1660. Curl_cf_def_conn_keep_alive,
  1661. cf_socket_query,
  1662. };
  1663. CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data,
  1664. struct connectdata *conn,
  1665. int sockindex, curl_socket_t *s)
  1666. {
  1667. CURLcode result;
  1668. struct Curl_cfilter *cf = NULL;
  1669. struct cf_socket_ctx *ctx = NULL;
  1670. /* replace any existing */
  1671. Curl_conn_cf_discard_all(data, conn, sockindex);
  1672. DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD);
  1673. ctx = calloc(sizeof(*ctx), 1);
  1674. if(!ctx) {
  1675. result = CURLE_OUT_OF_MEMORY;
  1676. goto out;
  1677. }
  1678. ctx->transport = conn->transport;
  1679. ctx->sock = *s;
  1680. ctx->accepted = FALSE;
  1681. result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx);
  1682. if(result)
  1683. goto out;
  1684. Curl_conn_cf_add(data, conn, sockindex, cf);
  1685. conn->sock[sockindex] = ctx->sock;
  1686. set_local_ip(cf, data);
  1687. ctx->active = TRUE;
  1688. ctx->connected_at = Curl_now();
  1689. cf->connected = TRUE;
  1690. CURL_TRC_CF(data, cf, "Curl_conn_tcp_listen_set(%"
  1691. CURL_FORMAT_SOCKET_T ")", ctx->sock);
  1692. out:
  1693. if(result) {
  1694. Curl_safefree(cf);
  1695. Curl_safefree(ctx);
  1696. }
  1697. return result;
  1698. }
  1699. static void set_accepted_remote_ip(struct Curl_cfilter *cf,
  1700. struct Curl_easy *data)
  1701. {
  1702. struct cf_socket_ctx *ctx = cf->ctx;
  1703. #ifdef HAVE_GETPEERNAME
  1704. char buffer[STRERROR_LEN];
  1705. struct Curl_sockaddr_storage ssrem;
  1706. curl_socklen_t plen;
  1707. ctx->r_ip[0] = 0;
  1708. ctx->r_port = 0;
  1709. plen = sizeof(ssrem);
  1710. memset(&ssrem, 0, plen);
  1711. if(getpeername(ctx->sock, (struct sockaddr*) &ssrem, &plen)) {
  1712. int error = SOCKERRNO;
  1713. failf(data, "getpeername() failed with errno %d: %s",
  1714. error, Curl_strerror(error, buffer, sizeof(buffer)));
  1715. return;
  1716. }
  1717. if(!Curl_addr2string((struct sockaddr*)&ssrem, plen,
  1718. ctx->r_ip, &ctx->r_port)) {
  1719. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  1720. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1721. return;
  1722. }
  1723. #else
  1724. ctx->r_ip[0] = 0;
  1725. ctx->r_port = 0;
  1726. (void)data;
  1727. #endif
  1728. }
  1729. CURLcode Curl_conn_tcp_accepted_set(struct Curl_easy *data,
  1730. struct connectdata *conn,
  1731. int sockindex, curl_socket_t *s)
  1732. {
  1733. struct Curl_cfilter *cf = NULL;
  1734. struct cf_socket_ctx *ctx = NULL;
  1735. cf = conn->cfilter[sockindex];
  1736. if(!cf || cf->cft != &Curl_cft_tcp_accept)
  1737. return CURLE_FAILED_INIT;
  1738. ctx = cf->ctx;
  1739. /* discard the listen socket */
  1740. socket_close(data, conn, TRUE, ctx->sock);
  1741. ctx->sock = *s;
  1742. conn->sock[sockindex] = ctx->sock;
  1743. set_accepted_remote_ip(cf, data);
  1744. set_local_ip(cf, data);
  1745. ctx->active = TRUE;
  1746. ctx->accepted = TRUE;
  1747. ctx->connected_at = Curl_now();
  1748. cf->connected = TRUE;
  1749. CURL_TRC_CF(data, cf, "accepted_set(sock=%" CURL_FORMAT_SOCKET_T
  1750. ", remote=%s port=%d)",
  1751. ctx->sock, ctx->r_ip, ctx->r_port);
  1752. return CURLE_OK;
  1753. }
  1754. /**
  1755. * Return TRUE iff `cf` is a socket filter.
  1756. */
  1757. static bool cf_is_socket(struct Curl_cfilter *cf)
  1758. {
  1759. return cf && (cf->cft == &Curl_cft_tcp ||
  1760. cf->cft == &Curl_cft_udp ||
  1761. cf->cft == &Curl_cft_unix ||
  1762. cf->cft == &Curl_cft_tcp_accept);
  1763. }
  1764. CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf,
  1765. struct Curl_easy *data,
  1766. curl_socket_t *psock,
  1767. const struct Curl_sockaddr_ex **paddr,
  1768. const char **pr_ip_str, int *pr_port,
  1769. const char **pl_ip_str, int *pl_port)
  1770. {
  1771. if(cf_is_socket(cf) && cf->ctx) {
  1772. struct cf_socket_ctx *ctx = cf->ctx;
  1773. if(psock)
  1774. *psock = ctx->sock;
  1775. if(paddr)
  1776. *paddr = &ctx->addr;
  1777. if(pr_ip_str)
  1778. *pr_ip_str = ctx->r_ip;
  1779. if(pr_port)
  1780. *pr_port = ctx->r_port;
  1781. if(pl_port ||pl_ip_str) {
  1782. set_local_ip(cf, data);
  1783. if(pl_ip_str)
  1784. *pl_ip_str = ctx->l_ip;
  1785. if(pl_port)
  1786. *pl_port = ctx->l_port;
  1787. }
  1788. return CURLE_OK;
  1789. }
  1790. return CURLE_FAILED_INIT;
  1791. }