2
0

cf-socket.c 68 KB

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