cf-socket.c 58 KB

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