cf-socket.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187
  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->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->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.sa_addr, (curl_socklen_t)ctx->addr.addrlen,
  1010. ctx->ip.remote_ip, &ctx->ip.remote_port)) {
  1011. char buffer[STRERROR_LEN];
  1012. ctx->error = errno;
  1013. /* malformed address or bug in inet_ntop, try next address */
  1014. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  1015. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1016. return CURLE_FAILED_INIT;
  1017. }
  1018. return CURLE_OK;
  1019. }
  1020. static CURLcode cf_socket_open(struct Curl_cfilter *cf,
  1021. struct Curl_easy *data)
  1022. {
  1023. struct cf_socket_ctx *ctx = cf->ctx;
  1024. int error = 0;
  1025. bool isconnected = FALSE;
  1026. CURLcode result = CURLE_COULDNT_CONNECT;
  1027. bool is_tcp;
  1028. (void)data;
  1029. DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD);
  1030. ctx->started_at = Curl_now();
  1031. #ifdef SOCK_NONBLOCK
  1032. /* Do not tuck SOCK_NONBLOCK into socktype when opensocket callback is set
  1033. * because we would not know how socketype is about to be used in the
  1034. * callback, SOCK_NONBLOCK might get factored out before calling socket().
  1035. */
  1036. if(!data->set.fopensocket)
  1037. ctx->addr.socktype |= SOCK_NONBLOCK;
  1038. #endif
  1039. result = socket_open(data, &ctx->addr, &ctx->sock);
  1040. #ifdef SOCK_NONBLOCK
  1041. /* Restore the socktype after the socket is created. */
  1042. if(!data->set.fopensocket)
  1043. ctx->addr.socktype &= ~SOCK_NONBLOCK;
  1044. #endif
  1045. if(result)
  1046. goto out;
  1047. result = set_remote_ip(cf, data);
  1048. if(result)
  1049. goto out;
  1050. #ifdef USE_IPV6
  1051. if(ctx->addr.family == AF_INET6) {
  1052. set_ipv6_v6only(ctx->sock, 0);
  1053. infof(data, " Trying [%s]:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
  1054. }
  1055. else
  1056. #endif
  1057. infof(data, " Trying %s:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
  1058. #ifdef USE_IPV6
  1059. is_tcp = (ctx->addr.family == AF_INET
  1060. || ctx->addr.family == AF_INET6) &&
  1061. ctx->addr.socktype == SOCK_STREAM;
  1062. #else
  1063. is_tcp = (ctx->addr.family == AF_INET) &&
  1064. ctx->addr.socktype == SOCK_STREAM;
  1065. #endif
  1066. if(is_tcp && data->set.tcp_nodelay)
  1067. tcpnodelay(data, ctx->sock);
  1068. nosigpipe(data, ctx->sock);
  1069. Curl_sndbuf_init(ctx->sock);
  1070. if(is_tcp && data->set.tcp_keepalive)
  1071. tcpkeepalive(data, ctx->sock);
  1072. if(data->set.fsockopt) {
  1073. /* activate callback for setting socket options */
  1074. Curl_set_in_callback(data, true);
  1075. error = data->set.fsockopt(data->set.sockopt_client,
  1076. ctx->sock,
  1077. CURLSOCKTYPE_IPCXN);
  1078. Curl_set_in_callback(data, false);
  1079. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  1080. isconnected = TRUE;
  1081. else if(error) {
  1082. result = CURLE_ABORTED_BY_CALLBACK;
  1083. goto out;
  1084. }
  1085. }
  1086. #ifndef CURL_DISABLE_BINDLOCAL
  1087. /* possibly bind the local end to an IP, interface or port */
  1088. if(ctx->addr.family == AF_INET
  1089. #ifdef USE_IPV6
  1090. || ctx->addr.family == AF_INET6
  1091. #endif
  1092. ) {
  1093. result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family,
  1094. Curl_ipv6_scope(&ctx->addr.sa_addr));
  1095. if(result) {
  1096. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  1097. /* The address family is not supported on this interface.
  1098. We can continue trying addresses */
  1099. result = CURLE_COULDNT_CONNECT;
  1100. }
  1101. goto out;
  1102. }
  1103. }
  1104. #endif
  1105. #ifndef SOCK_NONBLOCK
  1106. /* Set socket non-blocking, must be a non-blocking socket for
  1107. * a non-blocking connect. */
  1108. error = curlx_nonblock(ctx->sock, TRUE);
  1109. if(error < 0) {
  1110. result = CURLE_UNSUPPORTED_PROTOCOL;
  1111. ctx->error = SOCKERRNO;
  1112. goto out;
  1113. }
  1114. #else
  1115. if(data->set.fopensocket) {
  1116. /* Set socket non-blocking, must be a non-blocking socket for
  1117. * a non-blocking connect. */
  1118. error = curlx_nonblock(ctx->sock, TRUE);
  1119. if(error < 0) {
  1120. result = CURLE_UNSUPPORTED_PROTOCOL;
  1121. ctx->error = SOCKERRNO;
  1122. goto out;
  1123. }
  1124. }
  1125. #endif
  1126. ctx->sock_connected = (ctx->addr.socktype != SOCK_DGRAM);
  1127. out:
  1128. if(result) {
  1129. if(ctx->sock != CURL_SOCKET_BAD) {
  1130. socket_close(data, cf->conn, TRUE, ctx->sock);
  1131. ctx->sock = CURL_SOCKET_BAD;
  1132. }
  1133. }
  1134. else if(isconnected) {
  1135. set_local_ip(cf, data);
  1136. ctx->connected_at = Curl_now();
  1137. cf->connected = TRUE;
  1138. }
  1139. CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" FMT_SOCKET_T,
  1140. result, ctx->sock);
  1141. return result;
  1142. }
  1143. static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data,
  1144. bool is_tcp_fastopen)
  1145. {
  1146. struct cf_socket_ctx *ctx = cf->ctx;
  1147. #ifdef TCP_FASTOPEN_CONNECT
  1148. int optval = 1;
  1149. #endif
  1150. int rc = -1;
  1151. (void)data;
  1152. if(is_tcp_fastopen) {
  1153. #if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */
  1154. # if defined(HAVE_BUILTIN_AVAILABLE)
  1155. /* while connectx function is available since macOS 10.11 / iOS 9,
  1156. it did not have the interface declared correctly until
  1157. Xcode 9 / macOS SDK 10.13 */
  1158. if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
  1159. sa_endpoints_t endpoints;
  1160. endpoints.sae_srcif = 0;
  1161. endpoints.sae_srcaddr = NULL;
  1162. endpoints.sae_srcaddrlen = 0;
  1163. endpoints.sae_dstaddr = &ctx->addr.sa_addr;
  1164. endpoints.sae_dstaddrlen = ctx->addr.addrlen;
  1165. rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY,
  1166. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  1167. NULL, 0, NULL, NULL);
  1168. }
  1169. else {
  1170. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1171. }
  1172. # else
  1173. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1174. # endif /* HAVE_BUILTIN_AVAILABLE */
  1175. #elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
  1176. if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
  1177. (void *)&optval, sizeof(optval)) < 0)
  1178. infof(data, "Failed to enable TCP Fast Open on fd %" FMT_SOCKET_T,
  1179. ctx->sock);
  1180. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1181. #elif defined(MSG_FASTOPEN) /* old Linux */
  1182. if(cf->conn->given->flags & PROTOPT_SSL)
  1183. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1184. else
  1185. rc = 0; /* Do nothing */
  1186. #endif
  1187. }
  1188. else {
  1189. rc = connect(ctx->sock, &ctx->addr.sa_addr,
  1190. (curl_socklen_t)ctx->addr.addrlen);
  1191. }
  1192. return rc;
  1193. }
  1194. static CURLcode cf_tcp_connect(struct Curl_cfilter *cf,
  1195. struct Curl_easy *data,
  1196. bool blocking, bool *done)
  1197. {
  1198. struct cf_socket_ctx *ctx = cf->ctx;
  1199. CURLcode result = CURLE_COULDNT_CONNECT;
  1200. int rc = 0;
  1201. (void)data;
  1202. if(cf->connected) {
  1203. *done = TRUE;
  1204. return CURLE_OK;
  1205. }
  1206. /* TODO: need to support blocking connect? */
  1207. if(blocking)
  1208. return CURLE_UNSUPPORTED_PROTOCOL;
  1209. *done = FALSE; /* a very negative world view is best */
  1210. if(ctx->sock == CURL_SOCKET_BAD) {
  1211. int error;
  1212. result = cf_socket_open(cf, data);
  1213. if(result)
  1214. goto out;
  1215. if(cf->connected) {
  1216. *done = TRUE;
  1217. return CURLE_OK;
  1218. }
  1219. /* Connect TCP socket */
  1220. rc = do_connect(cf, data, cf->conn->bits.tcp_fastopen);
  1221. error = SOCKERRNO;
  1222. set_local_ip(cf, data);
  1223. CURL_TRC_CF(data, cf, "local address %s port %d...",
  1224. ctx->ip.local_ip, ctx->ip.local_port);
  1225. if(-1 == rc) {
  1226. result = socket_connect_result(data, ctx->ip.remote_ip, error);
  1227. goto out;
  1228. }
  1229. }
  1230. #ifdef mpeix
  1231. /* Call this function once now, and ignore the results. We do this to
  1232. "clear" the error state on the socket so that we can later read it
  1233. reliably. This is reported necessary on the MPE/iX operating
  1234. system. */
  1235. (void)verifyconnect(ctx->sock, NULL);
  1236. #endif
  1237. /* check socket for connect */
  1238. rc = SOCKET_WRITABLE(ctx->sock, 0);
  1239. if(rc == 0) { /* no connection yet */
  1240. CURL_TRC_CF(data, cf, "not connected yet");
  1241. return CURLE_OK;
  1242. }
  1243. else if(rc == CURL_CSELECT_OUT || cf->conn->bits.tcp_fastopen) {
  1244. if(verifyconnect(ctx->sock, &ctx->error)) {
  1245. /* we are connected with TCP, awesome! */
  1246. ctx->connected_at = Curl_now();
  1247. set_local_ip(cf, data);
  1248. *done = TRUE;
  1249. cf->connected = TRUE;
  1250. CURL_TRC_CF(data, cf, "connected");
  1251. return CURLE_OK;
  1252. }
  1253. }
  1254. else if(rc & CURL_CSELECT_ERR) {
  1255. (void)verifyconnect(ctx->sock, &ctx->error);
  1256. result = CURLE_COULDNT_CONNECT;
  1257. }
  1258. out:
  1259. if(result) {
  1260. if(ctx->error) {
  1261. set_local_ip(cf, data);
  1262. data->state.os_errno = ctx->error;
  1263. SET_SOCKERRNO(ctx->error);
  1264. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1265. {
  1266. char buffer[STRERROR_LEN];
  1267. infof(data, "connect to %s port %u from %s port %d failed: %s",
  1268. ctx->ip.remote_ip, ctx->ip.remote_port,
  1269. ctx->ip.local_ip, ctx->ip.local_port,
  1270. Curl_strerror(ctx->error, buffer, sizeof(buffer)));
  1271. }
  1272. #endif
  1273. }
  1274. if(ctx->sock != CURL_SOCKET_BAD) {
  1275. socket_close(data, cf->conn, TRUE, ctx->sock);
  1276. ctx->sock = CURL_SOCKET_BAD;
  1277. }
  1278. *done = FALSE;
  1279. }
  1280. return result;
  1281. }
  1282. static void cf_socket_get_host(struct Curl_cfilter *cf,
  1283. struct Curl_easy *data,
  1284. const char **phost,
  1285. const char **pdisplay_host,
  1286. int *pport)
  1287. {
  1288. struct cf_socket_ctx *ctx = cf->ctx;
  1289. (void)data;
  1290. *phost = cf->conn->host.name;
  1291. *pdisplay_host = cf->conn->host.dispname;
  1292. *pport = ctx->ip.remote_port;
  1293. }
  1294. static void cf_socket_adjust_pollset(struct Curl_cfilter *cf,
  1295. struct Curl_easy *data,
  1296. struct easy_pollset *ps)
  1297. {
  1298. struct cf_socket_ctx *ctx = cf->ctx;
  1299. if(ctx->sock != CURL_SOCKET_BAD) {
  1300. /* A listening socket filter needs to be connected before the accept
  1301. * for some weird FTP interaction. This should be rewritten, so that
  1302. * FTP no longer does the socket checks and accept calls and delegates
  1303. * all that to the filter. TODO. */
  1304. if(ctx->listening) {
  1305. Curl_pollset_set_in_only(data, ps, ctx->sock);
  1306. CURL_TRC_CF(data, cf, "adjust_pollset, listening, POLLIN fd=%"
  1307. FMT_SOCKET_T, ctx->sock);
  1308. }
  1309. else if(!cf->connected) {
  1310. Curl_pollset_set_out_only(data, ps, ctx->sock);
  1311. CURL_TRC_CF(data, cf, "adjust_pollset, !connected, POLLOUT fd=%"
  1312. FMT_SOCKET_T, ctx->sock);
  1313. }
  1314. else if(!ctx->active) {
  1315. Curl_pollset_add_in(data, ps, ctx->sock);
  1316. CURL_TRC_CF(data, cf, "adjust_pollset, !active, POLLIN fd=%"
  1317. FMT_SOCKET_T, ctx->sock);
  1318. }
  1319. }
  1320. }
  1321. static bool cf_socket_data_pending(struct Curl_cfilter *cf,
  1322. const struct Curl_easy *data)
  1323. {
  1324. struct cf_socket_ctx *ctx = cf->ctx;
  1325. int readable;
  1326. (void)data;
  1327. readable = SOCKET_READABLE(ctx->sock, 0);
  1328. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1329. }
  1330. #ifdef USE_WINSOCK
  1331. #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
  1332. #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
  1333. #endif
  1334. static void win_update_sndbuf_size(struct cf_socket_ctx *ctx)
  1335. {
  1336. ULONG ideal;
  1337. DWORD ideallen;
  1338. struct curltime n = Curl_now();
  1339. if(Curl_timediff(n, ctx->last_sndbuf_query_at) > 1000) {
  1340. if(!WSAIoctl(ctx->sock, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
  1341. &ideal, sizeof(ideal), &ideallen, 0, 0) &&
  1342. ideal != ctx->sndbuf_size &&
  1343. !setsockopt(ctx->sock, SOL_SOCKET, SO_SNDBUF,
  1344. (const char *)&ideal, sizeof(ideal))) {
  1345. ctx->sndbuf_size = ideal;
  1346. }
  1347. ctx->last_sndbuf_query_at = n;
  1348. }
  1349. }
  1350. #endif /* USE_WINSOCK */
  1351. static ssize_t cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1352. const void *buf, size_t len, bool eos,
  1353. CURLcode *err)
  1354. {
  1355. struct cf_socket_ctx *ctx = cf->ctx;
  1356. curl_socket_t fdsave;
  1357. ssize_t nwritten;
  1358. size_t orig_len = len;
  1359. (void)eos; /* unused */
  1360. *err = CURLE_OK;
  1361. fdsave = cf->conn->sock[cf->sockindex];
  1362. cf->conn->sock[cf->sockindex] = ctx->sock;
  1363. #ifdef DEBUGBUILD
  1364. /* simulate network blocking/partial writes */
  1365. if(ctx->wblock_percent > 0) {
  1366. unsigned char c = 0;
  1367. Curl_rand_bytes(data, FALSE, &c, 1);
  1368. if(c >= ((100-ctx->wblock_percent)*256/100)) {
  1369. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len);
  1370. *err = CURLE_AGAIN;
  1371. nwritten = -1;
  1372. cf->conn->sock[cf->sockindex] = fdsave;
  1373. return nwritten;
  1374. }
  1375. }
  1376. if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) {
  1377. len = len * ctx->wpartial_percent / 100;
  1378. if(!len)
  1379. len = 1;
  1380. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes",
  1381. orig_len, len);
  1382. }
  1383. #endif
  1384. #if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
  1385. if(cf->conn->bits.tcp_fastopen) {
  1386. nwritten = sendto(ctx->sock, buf, len, MSG_FASTOPEN,
  1387. &cf->conn->remote_addr->sa_addr,
  1388. cf->conn->remote_addr->addrlen);
  1389. cf->conn->bits.tcp_fastopen = FALSE;
  1390. }
  1391. else
  1392. #endif
  1393. nwritten = swrite(ctx->sock, buf, len);
  1394. if(-1 == nwritten) {
  1395. int sockerr = SOCKERRNO;
  1396. if(
  1397. #ifdef WSAEWOULDBLOCK
  1398. /* This is how Windows does it */
  1399. (WSAEWOULDBLOCK == sockerr)
  1400. #else
  1401. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  1402. due to its inability to send off data without blocking. We therefore
  1403. treat both error codes the same here */
  1404. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr) ||
  1405. (EINPROGRESS == sockerr)
  1406. #endif
  1407. ) {
  1408. /* this is just a case of EWOULDBLOCK */
  1409. *err = CURLE_AGAIN;
  1410. }
  1411. else {
  1412. char buffer[STRERROR_LEN];
  1413. failf(data, "Send failure: %s",
  1414. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  1415. data->state.os_errno = sockerr;
  1416. *err = CURLE_SEND_ERROR;
  1417. }
  1418. }
  1419. #if defined(USE_WINSOCK)
  1420. if(!*err)
  1421. win_update_sndbuf_size(ctx);
  1422. #endif
  1423. CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, err=%d",
  1424. orig_len, (int)nwritten, *err);
  1425. cf->conn->sock[cf->sockindex] = fdsave;
  1426. return nwritten;
  1427. }
  1428. static ssize_t cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1429. char *buf, size_t len, CURLcode *err)
  1430. {
  1431. struct cf_socket_ctx *ctx = cf->ctx;
  1432. ssize_t nread;
  1433. *err = CURLE_OK;
  1434. #ifdef DEBUGBUILD
  1435. /* simulate network blocking/partial reads */
  1436. if(cf->cft != &Curl_cft_udp && ctx->rblock_percent > 0) {
  1437. unsigned char c = 0;
  1438. Curl_rand(data, &c, 1);
  1439. if(c >= ((100-ctx->rblock_percent)*256/100)) {
  1440. CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE EWOULDBLOCK", len);
  1441. *err = CURLE_AGAIN;
  1442. return -1;
  1443. }
  1444. }
  1445. if(cf->cft != &Curl_cft_udp && ctx->recv_max && ctx->recv_max < len) {
  1446. size_t orig_len = len;
  1447. len = ctx->recv_max;
  1448. CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE max read of %zu bytes",
  1449. orig_len, len);
  1450. }
  1451. #endif
  1452. *err = CURLE_OK;
  1453. nread = sread(ctx->sock, buf, len);
  1454. if(-1 == nread) {
  1455. int sockerr = SOCKERRNO;
  1456. if(
  1457. #ifdef WSAEWOULDBLOCK
  1458. /* This is how Windows does it */
  1459. (WSAEWOULDBLOCK == sockerr)
  1460. #else
  1461. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  1462. due to its inability to send off data without blocking. We therefore
  1463. treat both error codes the same here */
  1464. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr)
  1465. #endif
  1466. ) {
  1467. /* this is just a case of EWOULDBLOCK */
  1468. *err = CURLE_AGAIN;
  1469. }
  1470. else {
  1471. char buffer[STRERROR_LEN];
  1472. failf(data, "Recv failure: %s",
  1473. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  1474. data->state.os_errno = sockerr;
  1475. *err = CURLE_RECV_ERROR;
  1476. }
  1477. }
  1478. CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, err=%d", len, (int)nread,
  1479. *err);
  1480. if(nread > 0 && !ctx->got_first_byte) {
  1481. ctx->first_byte_at = Curl_now();
  1482. ctx->got_first_byte = TRUE;
  1483. }
  1484. return nread;
  1485. }
  1486. static void cf_socket_update_data(struct Curl_cfilter *cf,
  1487. struct Curl_easy *data)
  1488. {
  1489. /* Update the IP info held in the transfer, if we have that. */
  1490. if(cf->connected && (cf->sockindex == FIRSTSOCKET)) {
  1491. struct cf_socket_ctx *ctx = cf->ctx;
  1492. data->info.primary = ctx->ip;
  1493. /* not sure if this is redundant... */
  1494. data->info.conn_remote_port = cf->conn->remote_port;
  1495. }
  1496. }
  1497. static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data)
  1498. {
  1499. struct cf_socket_ctx *ctx = cf->ctx;
  1500. /* use this socket from now on */
  1501. cf->conn->sock[cf->sockindex] = ctx->sock;
  1502. set_local_ip(cf, data);
  1503. if(cf->sockindex == FIRSTSOCKET) {
  1504. cf->conn->primary = ctx->ip;
  1505. cf->conn->remote_addr = &ctx->addr;
  1506. #ifdef USE_IPV6
  1507. cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6)? TRUE : FALSE;
  1508. #endif
  1509. }
  1510. else {
  1511. cf->conn->secondary = ctx->ip;
  1512. }
  1513. ctx->active = TRUE;
  1514. }
  1515. static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf,
  1516. struct Curl_easy *data,
  1517. int event, int arg1, void *arg2)
  1518. {
  1519. struct cf_socket_ctx *ctx = cf->ctx;
  1520. (void)arg1;
  1521. (void)arg2;
  1522. switch(event) {
  1523. case CF_CTRL_CONN_INFO_UPDATE:
  1524. cf_socket_active(cf, data);
  1525. cf_socket_update_data(cf, data);
  1526. break;
  1527. case CF_CTRL_DATA_SETUP:
  1528. cf_socket_update_data(cf, data);
  1529. break;
  1530. case CF_CTRL_FORGET_SOCKET:
  1531. ctx->sock = CURL_SOCKET_BAD;
  1532. break;
  1533. }
  1534. return CURLE_OK;
  1535. }
  1536. static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf,
  1537. struct Curl_easy *data,
  1538. bool *input_pending)
  1539. {
  1540. struct cf_socket_ctx *ctx = cf->ctx;
  1541. struct pollfd pfd[1];
  1542. int r;
  1543. *input_pending = FALSE;
  1544. (void)data;
  1545. if(!ctx || ctx->sock == CURL_SOCKET_BAD)
  1546. return FALSE;
  1547. /* Check with 0 timeout if there are any events pending on the socket */
  1548. pfd[0].fd = ctx->sock;
  1549. pfd[0].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
  1550. pfd[0].revents = 0;
  1551. r = Curl_poll(pfd, 1, 0);
  1552. if(r < 0) {
  1553. CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead");
  1554. return FALSE;
  1555. }
  1556. else if(r == 0) {
  1557. CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive");
  1558. return TRUE;
  1559. }
  1560. else if(pfd[0].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) {
  1561. CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead");
  1562. return FALSE;
  1563. }
  1564. CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive");
  1565. *input_pending = TRUE;
  1566. return TRUE;
  1567. }
  1568. static CURLcode cf_socket_query(struct Curl_cfilter *cf,
  1569. struct Curl_easy *data,
  1570. int query, int *pres1, void *pres2)
  1571. {
  1572. struct cf_socket_ctx *ctx = cf->ctx;
  1573. switch(query) {
  1574. case CF_QUERY_SOCKET:
  1575. DEBUGASSERT(pres2);
  1576. *((curl_socket_t *)pres2) = ctx->sock;
  1577. return CURLE_OK;
  1578. case CF_QUERY_CONNECT_REPLY_MS:
  1579. if(ctx->got_first_byte) {
  1580. timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at);
  1581. *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX;
  1582. }
  1583. else
  1584. *pres1 = -1;
  1585. return CURLE_OK;
  1586. case CF_QUERY_TIMER_CONNECT: {
  1587. struct curltime *when = pres2;
  1588. switch(ctx->transport) {
  1589. case TRNSPRT_UDP:
  1590. case TRNSPRT_QUIC:
  1591. /* Since UDP connected sockets work different from TCP, we use the
  1592. * time of the first byte from the peer as the "connect" time. */
  1593. if(ctx->got_first_byte) {
  1594. *when = ctx->first_byte_at;
  1595. break;
  1596. }
  1597. FALLTHROUGH();
  1598. default:
  1599. *when = ctx->connected_at;
  1600. break;
  1601. }
  1602. return CURLE_OK;
  1603. }
  1604. case CF_QUERY_IP_INFO:
  1605. #ifdef USE_IPV6
  1606. *pres1 = (ctx->addr.family == AF_INET6)? TRUE : FALSE;
  1607. #else
  1608. *pres1 = FALSE;
  1609. #endif
  1610. *(struct ip_quadruple *)pres2 = ctx->ip;
  1611. return CURLE_OK;
  1612. default:
  1613. break;
  1614. }
  1615. return cf->next?
  1616. cf->next->cft->query(cf->next, data, query, pres1, pres2) :
  1617. CURLE_UNKNOWN_OPTION;
  1618. }
  1619. struct Curl_cftype Curl_cft_tcp = {
  1620. "TCP",
  1621. CF_TYPE_IP_CONNECT,
  1622. CURL_LOG_LVL_NONE,
  1623. cf_socket_destroy,
  1624. cf_tcp_connect,
  1625. cf_socket_close,
  1626. cf_socket_shutdown,
  1627. cf_socket_get_host,
  1628. cf_socket_adjust_pollset,
  1629. cf_socket_data_pending,
  1630. cf_socket_send,
  1631. cf_socket_recv,
  1632. cf_socket_cntrl,
  1633. cf_socket_conn_is_alive,
  1634. Curl_cf_def_conn_keep_alive,
  1635. cf_socket_query,
  1636. };
  1637. CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf,
  1638. struct Curl_easy *data,
  1639. struct connectdata *conn,
  1640. const struct Curl_addrinfo *ai,
  1641. int transport)
  1642. {
  1643. struct cf_socket_ctx *ctx = NULL;
  1644. struct Curl_cfilter *cf = NULL;
  1645. CURLcode result;
  1646. (void)data;
  1647. (void)conn;
  1648. DEBUGASSERT(transport == TRNSPRT_TCP);
  1649. ctx = calloc(1, sizeof(*ctx));
  1650. if(!ctx) {
  1651. result = CURLE_OUT_OF_MEMORY;
  1652. goto out;
  1653. }
  1654. cf_socket_ctx_init(ctx, ai, transport);
  1655. result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx);
  1656. out:
  1657. *pcf = (!result)? cf : NULL;
  1658. if(result) {
  1659. Curl_safefree(cf);
  1660. Curl_safefree(ctx);
  1661. }
  1662. return result;
  1663. }
  1664. static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf,
  1665. struct Curl_easy *data)
  1666. {
  1667. struct cf_socket_ctx *ctx = cf->ctx;
  1668. int rc;
  1669. int one = 1;
  1670. (void)one;
  1671. /* QUIC needs a connected socket, nonblocking */
  1672. DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD);
  1673. rc = connect(ctx->sock, &ctx->addr.sa_addr,
  1674. (curl_socklen_t)ctx->addr.addrlen);
  1675. if(-1 == rc) {
  1676. return socket_connect_result(data, ctx->ip.remote_ip, SOCKERRNO);
  1677. }
  1678. ctx->sock_connected = TRUE;
  1679. set_local_ip(cf, data);
  1680. CURL_TRC_CF(data, cf, "%s socket %" FMT_SOCKET_T
  1681. " connected: [%s:%d] -> [%s:%d]",
  1682. (ctx->transport == TRNSPRT_QUIC)? "QUIC" : "UDP",
  1683. ctx->sock, ctx->ip.local_ip, ctx->ip.local_port,
  1684. ctx->ip.remote_ip, ctx->ip.remote_port);
  1685. /* Currently, cf->ctx->sock is always non-blocking because the only
  1686. * caller to cf_udp_setup_quic() is cf_udp_connect() that passes the
  1687. * non-blocking socket created by cf_socket_open() to it. Thus, we
  1688. * do not need to call curlx_nonblock() in cf_udp_setup_quic() anymore.
  1689. */
  1690. switch(ctx->addr.family) {
  1691. #if defined(__linux__) && defined(IP_MTU_DISCOVER)
  1692. case AF_INET: {
  1693. int val = IP_PMTUDISC_DO;
  1694. (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val,
  1695. sizeof(val));
  1696. break;
  1697. }
  1698. #endif
  1699. #if defined(__linux__) && defined(IPV6_MTU_DISCOVER)
  1700. case AF_INET6: {
  1701. int val = IPV6_PMTUDISC_DO;
  1702. (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
  1703. sizeof(val));
  1704. break;
  1705. }
  1706. #endif
  1707. }
  1708. #if defined(__linux__) && defined(UDP_GRO) && \
  1709. (defined(HAVE_SENDMMSG) || defined(HAVE_SENDMSG)) && \
  1710. ((defined(USE_NGTCP2) && defined(USE_NGHTTP3)) || defined(USE_QUICHE))
  1711. (void)setsockopt(ctx->sock, IPPROTO_UDP, UDP_GRO, &one,
  1712. (socklen_t)sizeof(one));
  1713. #endif
  1714. return CURLE_OK;
  1715. }
  1716. static CURLcode cf_udp_connect(struct Curl_cfilter *cf,
  1717. struct Curl_easy *data,
  1718. bool blocking, bool *done)
  1719. {
  1720. struct cf_socket_ctx *ctx = cf->ctx;
  1721. CURLcode result = CURLE_COULDNT_CONNECT;
  1722. (void)blocking;
  1723. if(cf->connected) {
  1724. *done = TRUE;
  1725. return CURLE_OK;
  1726. }
  1727. *done = FALSE;
  1728. if(ctx->sock == CURL_SOCKET_BAD) {
  1729. result = cf_socket_open(cf, data);
  1730. if(result) {
  1731. CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d", result);
  1732. goto out;
  1733. }
  1734. if(ctx->transport == TRNSPRT_QUIC) {
  1735. result = cf_udp_setup_quic(cf, data);
  1736. if(result)
  1737. goto out;
  1738. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1739. FMT_SOCKET_T " (%s:%d)",
  1740. ctx->sock, ctx->ip.local_ip, ctx->ip.local_port);
  1741. }
  1742. else {
  1743. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1744. FMT_SOCKET_T " (unconnected)", ctx->sock);
  1745. }
  1746. *done = TRUE;
  1747. cf->connected = TRUE;
  1748. }
  1749. out:
  1750. return result;
  1751. }
  1752. struct Curl_cftype Curl_cft_udp = {
  1753. "UDP",
  1754. CF_TYPE_IP_CONNECT,
  1755. CURL_LOG_LVL_NONE,
  1756. cf_socket_destroy,
  1757. cf_udp_connect,
  1758. cf_socket_close,
  1759. cf_socket_shutdown,
  1760. cf_socket_get_host,
  1761. cf_socket_adjust_pollset,
  1762. cf_socket_data_pending,
  1763. cf_socket_send,
  1764. cf_socket_recv,
  1765. cf_socket_cntrl,
  1766. cf_socket_conn_is_alive,
  1767. Curl_cf_def_conn_keep_alive,
  1768. cf_socket_query,
  1769. };
  1770. CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf,
  1771. struct Curl_easy *data,
  1772. struct connectdata *conn,
  1773. const struct Curl_addrinfo *ai,
  1774. int transport)
  1775. {
  1776. struct cf_socket_ctx *ctx = NULL;
  1777. struct Curl_cfilter *cf = NULL;
  1778. CURLcode result;
  1779. (void)data;
  1780. (void)conn;
  1781. DEBUGASSERT(transport == TRNSPRT_UDP || transport == TRNSPRT_QUIC);
  1782. ctx = calloc(1, sizeof(*ctx));
  1783. if(!ctx) {
  1784. result = CURLE_OUT_OF_MEMORY;
  1785. goto out;
  1786. }
  1787. cf_socket_ctx_init(ctx, ai, transport);
  1788. result = Curl_cf_create(&cf, &Curl_cft_udp, ctx);
  1789. out:
  1790. *pcf = (!result)? cf : NULL;
  1791. if(result) {
  1792. Curl_safefree(cf);
  1793. Curl_safefree(ctx);
  1794. }
  1795. return result;
  1796. }
  1797. /* this is the TCP filter which can also handle this case */
  1798. struct Curl_cftype Curl_cft_unix = {
  1799. "UNIX",
  1800. CF_TYPE_IP_CONNECT,
  1801. CURL_LOG_LVL_NONE,
  1802. cf_socket_destroy,
  1803. cf_tcp_connect,
  1804. cf_socket_close,
  1805. cf_socket_shutdown,
  1806. cf_socket_get_host,
  1807. cf_socket_adjust_pollset,
  1808. cf_socket_data_pending,
  1809. cf_socket_send,
  1810. cf_socket_recv,
  1811. cf_socket_cntrl,
  1812. cf_socket_conn_is_alive,
  1813. Curl_cf_def_conn_keep_alive,
  1814. cf_socket_query,
  1815. };
  1816. CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf,
  1817. struct Curl_easy *data,
  1818. struct connectdata *conn,
  1819. const struct Curl_addrinfo *ai,
  1820. int transport)
  1821. {
  1822. struct cf_socket_ctx *ctx = NULL;
  1823. struct Curl_cfilter *cf = NULL;
  1824. CURLcode result;
  1825. (void)data;
  1826. (void)conn;
  1827. DEBUGASSERT(transport == TRNSPRT_UNIX);
  1828. ctx = calloc(1, sizeof(*ctx));
  1829. if(!ctx) {
  1830. result = CURLE_OUT_OF_MEMORY;
  1831. goto out;
  1832. }
  1833. cf_socket_ctx_init(ctx, ai, transport);
  1834. result = Curl_cf_create(&cf, &Curl_cft_unix, ctx);
  1835. out:
  1836. *pcf = (!result)? cf : NULL;
  1837. if(result) {
  1838. Curl_safefree(cf);
  1839. Curl_safefree(ctx);
  1840. }
  1841. return result;
  1842. }
  1843. static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
  1844. struct Curl_easy *data,
  1845. bool blocking, bool *done)
  1846. {
  1847. /* we start accepted, if we ever close, we cannot go on */
  1848. (void)data;
  1849. (void)blocking;
  1850. if(cf->connected) {
  1851. *done = TRUE;
  1852. return CURLE_OK;
  1853. }
  1854. return CURLE_FAILED_INIT;
  1855. }
  1856. struct Curl_cftype Curl_cft_tcp_accept = {
  1857. "TCP-ACCEPT",
  1858. CF_TYPE_IP_CONNECT,
  1859. CURL_LOG_LVL_NONE,
  1860. cf_socket_destroy,
  1861. cf_tcp_accept_connect,
  1862. cf_socket_close,
  1863. cf_socket_shutdown,
  1864. cf_socket_get_host, /* TODO: not accurate */
  1865. cf_socket_adjust_pollset,
  1866. cf_socket_data_pending,
  1867. cf_socket_send,
  1868. cf_socket_recv,
  1869. cf_socket_cntrl,
  1870. cf_socket_conn_is_alive,
  1871. Curl_cf_def_conn_keep_alive,
  1872. cf_socket_query,
  1873. };
  1874. CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data,
  1875. struct connectdata *conn,
  1876. int sockindex, curl_socket_t *s)
  1877. {
  1878. CURLcode result;
  1879. struct Curl_cfilter *cf = NULL;
  1880. struct cf_socket_ctx *ctx = NULL;
  1881. /* replace any existing */
  1882. Curl_conn_cf_discard_all(data, conn, sockindex);
  1883. DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD);
  1884. ctx = calloc(1, sizeof(*ctx));
  1885. if(!ctx) {
  1886. result = CURLE_OUT_OF_MEMORY;
  1887. goto out;
  1888. }
  1889. ctx->transport = conn->transport;
  1890. ctx->sock = *s;
  1891. ctx->listening = TRUE;
  1892. ctx->accepted = FALSE;
  1893. result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx);
  1894. if(result)
  1895. goto out;
  1896. Curl_conn_cf_add(data, conn, sockindex, cf);
  1897. conn->sock[sockindex] = ctx->sock;
  1898. set_local_ip(cf, data);
  1899. ctx->active = TRUE;
  1900. ctx->connected_at = Curl_now();
  1901. cf->connected = TRUE;
  1902. CURL_TRC_CF(data, cf, "Curl_conn_tcp_listen_set(%" FMT_SOCKET_T ")",
  1903. ctx->sock);
  1904. out:
  1905. if(result) {
  1906. Curl_safefree(cf);
  1907. Curl_safefree(ctx);
  1908. }
  1909. return result;
  1910. }
  1911. static void set_accepted_remote_ip(struct Curl_cfilter *cf,
  1912. struct Curl_easy *data)
  1913. {
  1914. struct cf_socket_ctx *ctx = cf->ctx;
  1915. #ifdef HAVE_GETPEERNAME
  1916. char buffer[STRERROR_LEN];
  1917. struct Curl_sockaddr_storage ssrem;
  1918. curl_socklen_t plen;
  1919. ctx->ip.remote_ip[0] = 0;
  1920. ctx->ip.remote_port = 0;
  1921. plen = sizeof(ssrem);
  1922. memset(&ssrem, 0, plen);
  1923. if(getpeername(ctx->sock, (struct sockaddr*) &ssrem, &plen)) {
  1924. int error = SOCKERRNO;
  1925. failf(data, "getpeername() failed with errno %d: %s",
  1926. error, Curl_strerror(error, buffer, sizeof(buffer)));
  1927. return;
  1928. }
  1929. if(!Curl_addr2string((struct sockaddr*)&ssrem, plen,
  1930. ctx->ip.remote_ip, &ctx->ip.remote_port)) {
  1931. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  1932. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1933. return;
  1934. }
  1935. #else
  1936. ctx->ip.remote_ip[0] = 0;
  1937. ctx->ip.remote_port = 0;
  1938. (void)data;
  1939. #endif
  1940. }
  1941. CURLcode Curl_conn_tcp_accepted_set(struct Curl_easy *data,
  1942. struct connectdata *conn,
  1943. int sockindex, curl_socket_t *s)
  1944. {
  1945. struct Curl_cfilter *cf = NULL;
  1946. struct cf_socket_ctx *ctx = NULL;
  1947. cf = conn->cfilter[sockindex];
  1948. if(!cf || cf->cft != &Curl_cft_tcp_accept)
  1949. return CURLE_FAILED_INIT;
  1950. ctx = cf->ctx;
  1951. DEBUGASSERT(ctx->listening);
  1952. /* discard the listen socket */
  1953. socket_close(data, conn, TRUE, ctx->sock);
  1954. ctx->listening = FALSE;
  1955. ctx->sock = *s;
  1956. conn->sock[sockindex] = ctx->sock;
  1957. set_accepted_remote_ip(cf, data);
  1958. set_local_ip(cf, data);
  1959. ctx->active = TRUE;
  1960. ctx->accepted = TRUE;
  1961. ctx->connected_at = Curl_now();
  1962. cf->connected = TRUE;
  1963. CURL_TRC_CF(data, cf, "accepted_set(sock=%" FMT_SOCKET_T
  1964. ", remote=%s port=%d)",
  1965. ctx->sock, ctx->ip.remote_ip, ctx->ip.remote_port);
  1966. return CURLE_OK;
  1967. }
  1968. /**
  1969. * Return TRUE iff `cf` is a socket filter.
  1970. */
  1971. static bool cf_is_socket(struct Curl_cfilter *cf)
  1972. {
  1973. return cf && (cf->cft == &Curl_cft_tcp ||
  1974. cf->cft == &Curl_cft_udp ||
  1975. cf->cft == &Curl_cft_unix ||
  1976. cf->cft == &Curl_cft_tcp_accept);
  1977. }
  1978. CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf,
  1979. struct Curl_easy *data,
  1980. curl_socket_t *psock,
  1981. const struct Curl_sockaddr_ex **paddr,
  1982. struct ip_quadruple *pip)
  1983. {
  1984. (void)data;
  1985. if(cf_is_socket(cf) && cf->ctx) {
  1986. struct cf_socket_ctx *ctx = cf->ctx;
  1987. if(psock)
  1988. *psock = ctx->sock;
  1989. if(paddr)
  1990. *paddr = &ctx->addr;
  1991. if(pip)
  1992. *pip = ctx->ip;
  1993. return CURLE_OK;
  1994. }
  1995. return CURLE_FAILED_INIT;
  1996. }