cf-socket.c 65 KB

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