network.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  1. /*
  2. * Windows networking abstraction.
  3. *
  4. * For the IPv6 code in here I am indebted to Jeroen Massar and
  5. * unfix.org.
  6. */
  7. #include <winsock2.h> /* need to put this first, for winelib builds */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <assert.h>
  11. #define NEED_DECLARATION_OF_SELECT /* in order to initialise it */
  12. #include "putty.h"
  13. #include "network.h"
  14. #include "tree234.h"
  15. #include "ssh.h"
  16. #ifdef MPEXT
  17. // ws2tcpip.h does not compile without _MSC_VER defined
  18. #define _MSC_VER 1000
  19. #endif
  20. #include <ws2tcpip.h>
  21. #if HAVE_AFUNIX_H
  22. #include <afunix.h>
  23. #endif
  24. #ifndef NO_IPV6
  25. #ifdef __clang__
  26. #pragma clang diagnostic push
  27. #pragma clang diagnostic ignored "-Wmissing-braces"
  28. #endif
  29. const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
  30. const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
  31. #ifdef __clang__
  32. #pragma clang diagnostic pop
  33. #endif
  34. #endif
  35. #define ipv4_is_loopback(addr) \
  36. ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
  37. /*
  38. * Mutable state that goes with a SockAddr: stores information
  39. * about where in the list of candidate IP(v*) addresses we've
  40. * currently got to.
  41. */
  42. typedef struct SockAddrStep_tag SockAddrStep;
  43. struct SockAddrStep_tag {
  44. #ifndef NO_IPV6
  45. struct addrinfo *ai; /* steps along addr->ais */
  46. #endif
  47. int curraddr;
  48. };
  49. typedef struct NetSocket NetSocket;
  50. struct NetSocket {
  51. const char *error;
  52. SOCKET s;
  53. Plug *plug;
  54. bufchain output_data;
  55. bool connected;
  56. bool writable;
  57. bool frozen; /* this causes readability notifications to be ignored */
  58. bool frozen_readable; /* this means we missed at least one readability
  59. * notification while we were frozen */
  60. bool localhost_only; /* for listening sockets */
  61. char oobdata[1];
  62. size_t sending_oob;
  63. bool oobinline, nodelay, keepalive, privport;
  64. enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
  65. SockAddr *addr;
  66. SockAddrStep step;
  67. int port;
  68. int pending_error; /* in case send() returns error */
  69. /*
  70. * We sometimes need pairs of Socket structures to be linked:
  71. * if we are listening on the same IPv6 and v4 port, for
  72. * example. So here we define `parent' and `child' pointers to
  73. * track this link.
  74. */
  75. NetSocket *parent, *child;
  76. Socket sock;
  77. };
  78. /*
  79. * Top-level discriminator for SockAddr.
  80. *
  81. * UNRESOLVED means a host name not yet put through DNS; IP means a
  82. * resolved IP address (or list of them); UNIX indicates the AF_UNIX
  83. * network family (which Windows also has); NAMEDPIPE indicates that
  84. * this SockAddr is phony, holding a Windows named pipe pathname
  85. * instead of any address WinSock can understand.
  86. */
  87. typedef enum SuperFamily {
  88. UNRESOLVED,
  89. IP,
  90. #if HAVE_AFUNIX_H
  91. UNIX,
  92. #endif
  93. NAMEDPIPE
  94. } SuperFamily;
  95. struct SockAddr {
  96. int refcount;
  97. const char *error;
  98. SuperFamily superfamily;
  99. #ifndef NO_IPV6
  100. struct addrinfo *ais; /* Addresses IPv6 style. */
  101. #endif
  102. unsigned long *addresses; /* Addresses IPv4 style. */
  103. int naddresses;
  104. char hostname[512]; /* Store an unresolved host name. */
  105. };
  106. /*
  107. * Which address family this address belongs to. AF_INET for IPv4;
  108. * AF_INET6 for IPv6; AF_UNIX for Unix-domain sockets; AF_UNSPEC
  109. * indicates that name resolution has not been done and a simple host
  110. * name is held in this SockAddr structure.
  111. */
  112. static inline int sockaddr_family(SockAddr *addr, SockAddrStep step)
  113. {
  114. switch (addr->superfamily) {
  115. case IP:
  116. #ifndef NO_IPV6
  117. if (step.ai)
  118. return step.ai->ai_family;
  119. #endif
  120. return AF_INET;
  121. #if HAVE_AFUNIX_H
  122. case UNIX:
  123. return AF_UNIX;
  124. #endif
  125. default:
  126. return AF_UNSPEC;
  127. }
  128. }
  129. /*
  130. * Start a SockAddrStep structure to step through multiple
  131. * addresses.
  132. */
  133. #ifndef NO_IPV6
  134. #define START_STEP(addr, step) \
  135. ((step).ai = (addr)->ais, (step).curraddr = 0)
  136. #else
  137. #define START_STEP(addr, step) \
  138. ((step).curraddr = 0)
  139. #endif
  140. static tree234 *sktree;
  141. static int cmpfortree(void *av, void *bv)
  142. {
  143. NetSocket *a = (NetSocket *)av, *b = (NetSocket *)bv;
  144. uintptr_t as = (uintptr_t) a->s, bs = (uintptr_t) b->s;
  145. if (as < bs)
  146. return -1;
  147. if (as > bs)
  148. return +1;
  149. if (a < b)
  150. return -1;
  151. if (a > b)
  152. return +1;
  153. return 0;
  154. }
  155. static int cmpforsearch(void *av, void *bv)
  156. {
  157. NetSocket *b = (NetSocket *)bv;
  158. uintptr_t as = (uintptr_t) av, bs = (uintptr_t) b->s;
  159. if (as < bs)
  160. return -1;
  161. if (as > bs)
  162. return +1;
  163. return 0;
  164. }
  165. DECL_WINDOWS_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
  166. DECL_WINDOWS_FUNCTION(static, int, WSACleanup, (void));
  167. DECL_WINDOWS_FUNCTION(static, int, closesocket, (SOCKET));
  168. DECL_WINDOWS_FUNCTION(static, ULONG, ntohl, (ULONG));
  169. DECL_WINDOWS_FUNCTION(static, ULONG, htonl, (ULONG));
  170. DECL_WINDOWS_FUNCTION(static, USHORT, htons, (USHORT));
  171. DECL_WINDOWS_FUNCTION(static, USHORT, ntohs, (USHORT));
  172. DECL_WINDOWS_FUNCTION(static, int, gethostname, (char *, int));
  173. DECL_WINDOWS_FUNCTION(static, struct hostent FAR *, gethostbyname,
  174. (const char FAR *));
  175. DECL_WINDOWS_FUNCTION(static, struct servent FAR *, getservbyname,
  176. (const char FAR *, const char FAR *));
  177. DECL_WINDOWS_FUNCTION(static, ULONG, inet_addr, (const char FAR *));
  178. DECL_WINDOWS_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
  179. DECL_WINDOWS_FUNCTION(static, const char FAR *, inet_ntop,
  180. (int, void FAR *, char *, size_t));
  181. DECL_WINDOWS_FUNCTION(static, int, connect,
  182. (SOCKET, const struct sockaddr FAR *, int));
  183. DECL_WINDOWS_FUNCTION(static, int, bind,
  184. (SOCKET, const struct sockaddr FAR *, int));
  185. #ifdef MPEXT
  186. DECL_WINDOWS_FUNCTION(static, int, getsockopt,
  187. (SOCKET, int, int, char FAR *, int *));
  188. #endif
  189. DECL_WINDOWS_FUNCTION(static, int, setsockopt,
  190. (SOCKET, int, int, const char FAR *, int));
  191. DECL_WINDOWS_FUNCTION(static, SOCKET, socket, (int, int, int));
  192. DECL_WINDOWS_FUNCTION(static, int, listen, (SOCKET, int));
  193. DECL_WINDOWS_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
  194. DECL_WINDOWS_FUNCTION(static, int, shutdown, (SOCKET, int));
  195. DECL_WINDOWS_FUNCTION(static, int, ioctlsocket,
  196. (SOCKET, LONG, ULONG FAR *));
  197. DECL_WINDOWS_FUNCTION(static, SOCKET, accept,
  198. (SOCKET, struct sockaddr FAR *, int FAR *));
  199. DECL_WINDOWS_FUNCTION(static, int, getpeername,
  200. (SOCKET, struct sockaddr FAR *, int FAR *));
  201. DECL_WINDOWS_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
  202. DECL_WINDOWS_FUNCTION(static, int, WSAIoctl,
  203. (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
  204. LPDWORD, LPWSAOVERLAPPED,
  205. LPWSAOVERLAPPED_COMPLETION_ROUTINE));
  206. #ifndef NO_IPV6
  207. DECL_WINDOWS_FUNCTION(static, int, getaddrinfo,
  208. (const char *nodename, const char *servname,
  209. const struct addrinfo *hints, struct addrinfo **res));
  210. DECL_WINDOWS_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res));
  211. DECL_WINDOWS_FUNCTION(static, int, getnameinfo,
  212. (const struct sockaddr FAR *sa, socklen_t salen,
  213. char FAR *host, DWORD hostlen, char FAR *serv,
  214. DWORD servlen, int flags));
  215. DECL_WINDOWS_FUNCTION(static, int, WSAAddressToStringA,
  216. (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO,
  217. LPSTR, LPDWORD));
  218. #endif
  219. static HMODULE winsock_module = NULL;
  220. static WSADATA wsadata;
  221. #ifndef NO_IPV6
  222. static HMODULE winsock2_module = NULL;
  223. static HMODULE wship6_module = NULL;
  224. #endif
  225. static bool sk_startup(int hi, int lo)
  226. {
  227. WORD winsock_ver;
  228. winsock_ver = MAKEWORD(hi, lo);
  229. if (p_WSAStartup(winsock_ver, &wsadata)) {
  230. return false;
  231. }
  232. if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
  233. return false;
  234. }
  235. return true;
  236. }
  237. DEF_WINDOWS_FUNCTION(WSAAsyncSelect);
  238. DEF_WINDOWS_FUNCTION(WSAEventSelect);
  239. DEF_WINDOWS_FUNCTION(WSAGetLastError);
  240. DEF_WINDOWS_FUNCTION(WSAEnumNetworkEvents);
  241. DEF_WINDOWS_FUNCTION(select);
  242. void sk_init(void)
  243. {
  244. #ifndef NO_IPV6
  245. winsock2_module =
  246. #endif
  247. winsock_module = load_system32_dll("ws2_32.dll");
  248. if (!winsock_module) {
  249. winsock_module = load_system32_dll("wsock32.dll");
  250. }
  251. if (!winsock_module)
  252. {
  253. modalfatalbox("Unable to load any WinSock library");
  254. }
  255. #ifndef NO_IPV6
  256. /* Check if we have getaddrinfo in Winsock */
  257. if (GetProcAddress(winsock_module, "getaddrinfo") != NULL) {
  258. GET_WINDOWS_FUNCTION(winsock_module, getaddrinfo);
  259. GET_WINDOWS_FUNCTION(winsock_module, freeaddrinfo);
  260. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, getnameinfo);
  261. /* This function would fail its type-check if we did one,
  262. * because the VS header file provides an inline definition
  263. * which is __cdecl instead of WINAPI. */
  264. } else {
  265. /* Fall back to wship6.dll for Windows 2000 */
  266. wship6_module = load_system32_dll("wship6.dll");
  267. if (wship6_module) {
  268. GET_WINDOWS_FUNCTION(wship6_module, getaddrinfo);
  269. GET_WINDOWS_FUNCTION(wship6_module, freeaddrinfo);
  270. /* See comment above about type check */
  271. GET_WINDOWS_FUNCTION_NO_TYPECHECK(wship6_module, getnameinfo);
  272. } else {
  273. }
  274. }
  275. GET_WINDOWS_FUNCTION(winsock2_module, WSAAddressToStringA);
  276. #endif
  277. GET_WINDOWS_FUNCTION(winsock_module, WSAAsyncSelect);
  278. GET_WINDOWS_FUNCTION(winsock_module, WSAEventSelect);
  279. /* We don't type-check select because at least some MinGW versions
  280. * of the Windows API headers seem to disagree with the
  281. * documentation on whether the 'struct timeval *' pointer is
  282. * const or not. */
  283. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, select);
  284. GET_WINDOWS_FUNCTION(winsock_module, WSAGetLastError);
  285. GET_WINDOWS_FUNCTION(winsock_module, WSAEnumNetworkEvents);
  286. GET_WINDOWS_FUNCTION(winsock_module, WSAStartup);
  287. GET_WINDOWS_FUNCTION(winsock_module, WSACleanup);
  288. GET_WINDOWS_FUNCTION(winsock_module, closesocket);
  289. /* Winelib maps ntohl and friends to things like
  290. * __wine_ulong_swap, which fail these type checks hopelessly */
  291. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, ntohl);
  292. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, htonl);
  293. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, htons);
  294. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, ntohs);
  295. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, gethostname);
  296. GET_WINDOWS_FUNCTION(winsock_module, gethostbyname);
  297. GET_WINDOWS_FUNCTION(winsock_module, getservbyname);
  298. GET_WINDOWS_FUNCTION(winsock_module, inet_addr);
  299. GET_WINDOWS_FUNCTION(winsock_module, inet_ntoa);
  300. /* Older Visual Studio, and MinGW as of Ubuntu 16.04, don't know
  301. * about this function at all, so can't type-check it. Also there
  302. * seems to be some disagreement in the VS headers about whether
  303. * the second argument is void * or const void *, so I omit the
  304. * type check. */
  305. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, inet_ntop);
  306. GET_WINDOWS_FUNCTION(winsock_module, connect);
  307. GET_WINDOWS_FUNCTION(winsock_module, bind);
  308. #ifdef MPEXT
  309. GET_WINDOWS_FUNCTION(winsock_module, getsockopt);
  310. #endif
  311. GET_WINDOWS_FUNCTION(winsock_module, setsockopt);
  312. GET_WINDOWS_FUNCTION(winsock_module, socket);
  313. GET_WINDOWS_FUNCTION(winsock_module, listen);
  314. GET_WINDOWS_FUNCTION(winsock_module, send);
  315. GET_WINDOWS_FUNCTION(winsock_module, shutdown);
  316. GET_WINDOWS_FUNCTION(winsock_module, ioctlsocket);
  317. GET_WINDOWS_FUNCTION(winsock_module, accept);
  318. GET_WINDOWS_FUNCTION(winsock_module, getpeername);
  319. GET_WINDOWS_FUNCTION(winsock_module, recv);
  320. GET_WINDOWS_FUNCTION(winsock_module, WSAIoctl);
  321. /* Try to get the best WinSock version we can get */
  322. if (!sk_startup(2,2) &&
  323. !sk_startup(2,0) &&
  324. !sk_startup(1,1)) {
  325. modalfatalbox("Unable to initialise WinSock");
  326. }
  327. sktree = newtree234(cmpfortree);
  328. }
  329. void sk_cleanup(void)
  330. {
  331. NetSocket *s;
  332. int i;
  333. if (sktree) {
  334. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  335. p_closesocket(s->s);
  336. }
  337. freetree234(sktree);
  338. sktree = NULL;
  339. }
  340. if (p_WSACleanup)
  341. {
  342. p_WSACleanup();
  343. }
  344. if (winsock_module)
  345. FreeLibrary(winsock_module);
  346. #ifndef NO_IPV6
  347. if (wship6_module)
  348. FreeLibrary(wship6_module);
  349. #endif
  350. }
  351. const char *winsock_error_string(int error)
  352. {
  353. /*
  354. * Error codes we know about and have historically had reasonably
  355. * sensible error messages for.
  356. */
  357. switch (error) {
  358. case WSAEACCES:
  359. return "Network error: Permission denied";
  360. case WSAEADDRINUSE:
  361. return "Network error: Address already in use";
  362. case WSAEADDRNOTAVAIL:
  363. return "Network error: Cannot assign requested address";
  364. case WSAEAFNOSUPPORT:
  365. return
  366. "Network error: Address family not supported by protocol family";
  367. case WSAEALREADY:
  368. return "Network error: Operation already in progress";
  369. case WSAECONNABORTED:
  370. return "Network error: Software caused connection abort";
  371. case WSAECONNREFUSED:
  372. return "Network error: Connection refused";
  373. case WSAECONNRESET:
  374. return "Network error: Connection reset by peer";
  375. case WSAEDESTADDRREQ:
  376. return "Network error: Destination address required";
  377. case WSAEFAULT:
  378. return "Network error: Bad address";
  379. case WSAEHOSTDOWN:
  380. return "Network error: Host is down";
  381. case WSAEHOSTUNREACH:
  382. return "Network error: No route to host";
  383. case WSAEINPROGRESS:
  384. return "Network error: Operation now in progress";
  385. case WSAEINTR:
  386. return "Network error: Interrupted function call";
  387. case WSAEINVAL:
  388. return "Network error: Invalid argument";
  389. case WSAEISCONN:
  390. return "Network error: Socket is already connected";
  391. case WSAEMFILE:
  392. return "Network error: Too many open files";
  393. case WSAEMSGSIZE:
  394. return "Network error: Message too long";
  395. case WSAENETDOWN:
  396. return "Network error: Network is down";
  397. case WSAENETRESET:
  398. return "Network error: Network dropped connection on reset";
  399. case WSAENETUNREACH:
  400. return "Network error: Network is unreachable";
  401. case WSAENOBUFS:
  402. return "Network error: No buffer space available";
  403. case WSAENOPROTOOPT:
  404. return "Network error: Bad protocol option";
  405. case WSAENOTCONN:
  406. return "Network error: Socket is not connected";
  407. case WSAENOTSOCK:
  408. return "Network error: Socket operation on non-socket";
  409. case WSAEOPNOTSUPP:
  410. return "Network error: Operation not supported";
  411. case WSAEPFNOSUPPORT:
  412. return "Network error: Protocol family not supported";
  413. case WSAEPROCLIM:
  414. return "Network error: Too many processes";
  415. case WSAEPROTONOSUPPORT:
  416. return "Network error: Protocol not supported";
  417. case WSAEPROTOTYPE:
  418. return "Network error: Protocol wrong type for socket";
  419. case WSAESHUTDOWN:
  420. return "Network error: Cannot send after socket shutdown";
  421. case WSAESOCKTNOSUPPORT:
  422. return "Network error: Socket type not supported";
  423. case WSAETIMEDOUT:
  424. return "Network error: Connection timed out";
  425. case WSAEWOULDBLOCK:
  426. return "Network error: Resource temporarily unavailable";
  427. case WSAEDISCON:
  428. return "Network error: Graceful shutdown in progress";
  429. }
  430. /*
  431. * Handle any other error code by delegating to win_strerror.
  432. */
  433. return win_strerror(error);
  434. }
  435. static inline const char *namelookup_strerror(DWORD err)
  436. {
  437. /* PuTTY has traditionally translated a few of the likely error
  438. * messages into more concise strings than the standard Windows ones */
  439. return (err == WSAENETDOWN ? "Network is down" :
  440. err == WSAHOST_NOT_FOUND ? "Host does not exist" :
  441. err == WSATRY_AGAIN ? "Host not found" :
  442. win_strerror(err));
  443. }
  444. SockAddr *sk_namelookup(const char *host, char **canonicalname,
  445. int address_family)
  446. {
  447. *canonicalname = NULL;
  448. { // WINSCP
  449. SockAddr *addr = snew(SockAddr);
  450. memset(addr, 0, sizeof(SockAddr));
  451. addr->superfamily = UNRESOLVED;
  452. addr->refcount = 1;
  453. #ifndef NO_IPV6
  454. /*
  455. * Use getaddrinfo, as long as it's available. This should handle
  456. * both IPv4 and IPv6 address literals, and hostnames, in one
  457. * unified API.
  458. */
  459. if (p_getaddrinfo) {
  460. struct addrinfo hints;
  461. memset(&hints, 0, sizeof(hints));
  462. hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
  463. address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  464. AF_UNSPEC);
  465. hints.ai_flags = AI_CANONNAME;
  466. hints.ai_socktype = SOCK_STREAM;
  467. /* strip [] on IPv6 address literals */
  468. { // WINSCP
  469. char *trimmed_host = host_strduptrim(host);
  470. int err = p_getaddrinfo(trimmed_host, NULL, &hints, &addr->ais);
  471. sfree(trimmed_host);
  472. if (addr->ais) {
  473. addr->superfamily = IP;
  474. if (addr->ais->ai_canonname)
  475. *canonicalname = dupstr(addr->ais->ai_canonname);
  476. else
  477. *canonicalname = dupstr(host);
  478. } else {
  479. addr->error = namelookup_strerror(err);
  480. }
  481. return addr;
  482. } // WINSCP
  483. }
  484. #endif
  485. /*
  486. * Failing that (if IPv6 support was not compiled in, or if
  487. * getaddrinfo turned out to be unavailable at run time), try the
  488. * old-fashioned approach, which is to start by manually checking
  489. * for an IPv4 literal and then use gethostbyname.
  490. */
  491. { // WINSCP
  492. unsigned long a = p_inet_addr(host);
  493. if (a != (unsigned long) INADDR_NONE) {
  494. addr->addresses = snew(unsigned long);
  495. addr->naddresses = 1;
  496. addr->addresses[0] = p_ntohl(a);
  497. addr->superfamily = IP;
  498. *canonicalname = dupstr(host);
  499. return addr;
  500. }
  501. { // WINSCP
  502. struct hostent *h = p_gethostbyname(host);
  503. if (h) {
  504. addr->superfamily = IP;
  505. { // WINSCP
  506. size_t n;
  507. for (n = 0; h->h_addr_list[n]; n++);
  508. addr->addresses = snewn(n, unsigned long);
  509. addr->naddresses = n;
  510. for (n = 0; n < addr->naddresses; n++) {
  511. uint32_t a;
  512. memcpy(&a, h->h_addr_list[n], sizeof(a));
  513. addr->addresses[n] = p_ntohl(a);
  514. }
  515. *canonicalname = dupstr(h->h_name);
  516. } // WINSCP
  517. } else {
  518. DWORD err = p_WSAGetLastError();
  519. addr->error = namelookup_strerror(err);
  520. }
  521. return addr;
  522. } // WINSCP
  523. } // WINSCP
  524. } // WINSCP
  525. }
  526. static SockAddr *sk_special_addr(SuperFamily superfamily, const char *name)
  527. {
  528. SockAddr *ret = snew(SockAddr);
  529. ret->error = NULL;
  530. ret->superfamily = superfamily;
  531. #ifndef NO_IPV6
  532. ret->ais = NULL;
  533. #endif
  534. ret->addresses = NULL;
  535. ret->naddresses = 0;
  536. ret->refcount = 1;
  537. strncpy(ret->hostname, name, lenof(ret->hostname));
  538. ret->hostname[lenof(ret->hostname)-1] = '\0';
  539. return ret;
  540. }
  541. SockAddr *sk_nonamelookup(const char *host)
  542. {
  543. return sk_special_addr(UNRESOLVED, host);
  544. }
  545. SockAddr *sk_namedpipe_addr(const char *pipename)
  546. {
  547. return sk_special_addr(NAMEDPIPE, pipename);
  548. }
  549. #if HAVE_AFUNIX_H
  550. SockAddr *sk_unix_addr(const char *sockpath)
  551. {
  552. return sk_special_addr(UNIX, sockpath);
  553. }
  554. #endif
  555. static bool sk_nextaddr(SockAddr *addr, SockAddrStep *step)
  556. {
  557. #ifndef NO_IPV6
  558. if (step->ai) {
  559. if (step->ai->ai_next) {
  560. step->ai = step->ai->ai_next;
  561. return true;
  562. } else
  563. return false;
  564. }
  565. #endif
  566. if (step->curraddr+1 < addr->naddresses) {
  567. step->curraddr++;
  568. return true;
  569. } else {
  570. return false;
  571. }
  572. }
  573. void sk_getaddr(SockAddr *addr, char *buf, int buflen)
  574. {
  575. SockAddrStep step;
  576. START_STEP(addr, step);
  577. #ifndef NO_IPV6
  578. if (step.ai) {
  579. int err = 0;
  580. if (p_WSAAddressToStringA) {
  581. DWORD dwbuflen = buflen;
  582. err = p_WSAAddressToStringA(step.ai->ai_addr, step.ai->ai_addrlen,
  583. NULL, buf, &dwbuflen);
  584. } else
  585. err = -1;
  586. if (err) {
  587. strncpy(buf, addr->hostname, buflen);
  588. if (!buf[0])
  589. strncpy(buf, "<unknown>", buflen);
  590. buf[buflen-1] = '\0';
  591. }
  592. } else
  593. #endif
  594. if (sockaddr_family(addr, step) == AF_INET) {
  595. struct in_addr a;
  596. assert(addr->addresses && step.curraddr < addr->naddresses);
  597. a.s_addr = p_htonl(addr->addresses[step.curraddr]);
  598. strncpy(buf, p_inet_ntoa(a), buflen);
  599. buf[buflen-1] = '\0';
  600. } else {
  601. strncpy(buf, addr->hostname, buflen);
  602. buf[buflen-1] = '\0';
  603. }
  604. }
  605. /*
  606. * This constructs a SockAddr that points at one specific sub-address
  607. * of a parent SockAddr. The returned SockAddr does not own all its
  608. * own memory: it points into the old one's data structures, so it
  609. * MUST NOT be used after the old one is freed, and it MUST NOT be
  610. * passed to sk_addr_free. (The latter is why it's returned by value
  611. * rather than dynamically allocated - that should clue in anyone
  612. * writing a call to it that something is weird about it.)
  613. */
  614. static SockAddr sk_extractaddr_tmp(
  615. SockAddr *addr, const SockAddrStep *step)
  616. {
  617. SockAddr toret;
  618. toret = *addr; /* structure copy */
  619. toret.refcount = 1;
  620. #ifndef NO_IPV6
  621. toret.ais = step->ai;
  622. #endif
  623. if (sockaddr_family(addr, *step) == AF_INET
  624. #ifndef NO_IPV6
  625. && !toret.ais
  626. #endif
  627. )
  628. toret.addresses += step->curraddr;
  629. return toret;
  630. }
  631. bool sk_addr_needs_port(SockAddr *addr)
  632. {
  633. return addr->superfamily != NAMEDPIPE
  634. #if HAVE_AFUNIX_H
  635. && addr->superfamily != UNIX
  636. #endif
  637. ;
  638. }
  639. bool sk_hostname_is_local(const char *name)
  640. {
  641. return !strcmp(name, "localhost") ||
  642. !strcmp(name, "::1") ||
  643. !strncmp(name, "127.", 4);
  644. }
  645. static INTERFACE_INFO local_interfaces[16];
  646. static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
  647. static bool ipv4_is_local_addr(struct in_addr addr)
  648. {
  649. if (ipv4_is_loopback(addr))
  650. return true; /* loopback addresses are local */
  651. if (!n_local_interfaces) {
  652. SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
  653. DWORD retbytes;
  654. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  655. if (p_WSAIoctl &&
  656. p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
  657. local_interfaces, sizeof(local_interfaces),
  658. &retbytes, NULL, NULL) == 0)
  659. n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
  660. else
  661. n_local_interfaces = -1;
  662. }
  663. if (n_local_interfaces > 0) {
  664. int i;
  665. for (i = 0; i < n_local_interfaces; i++) {
  666. SOCKADDR_IN *address =
  667. (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
  668. if (address->sin_addr.s_addr == addr.s_addr)
  669. return true; /* this address is local */
  670. }
  671. }
  672. return false; /* this address is not local */
  673. }
  674. bool sk_address_is_local(SockAddr *addr)
  675. {
  676. SockAddrStep step;
  677. int family;
  678. START_STEP(addr, step);
  679. family = sockaddr_family(addr, step);
  680. #ifndef NO_IPV6
  681. if (family == AF_INET6) {
  682. return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr);
  683. } else
  684. #endif
  685. if (family == AF_INET) {
  686. #ifndef NO_IPV6
  687. if (step.ai) {
  688. return ipv4_is_local_addr(((struct sockaddr_in *)step.ai->ai_addr)
  689. ->sin_addr);
  690. } else
  691. #endif
  692. {
  693. struct in_addr a;
  694. assert(addr->addresses && step.curraddr < addr->naddresses);
  695. a.s_addr = p_htonl(addr->addresses[step.curraddr]);
  696. return ipv4_is_local_addr(a);
  697. }
  698. } else {
  699. assert(family == AF_UNSPEC);
  700. return false; /* we don't know; assume not */
  701. }
  702. }
  703. bool sk_address_is_special_local(SockAddr *addr)
  704. {
  705. return false; /* no Unix-domain socket analogue here */
  706. }
  707. int sk_addrtype(SockAddr *addr)
  708. {
  709. SockAddrStep step;
  710. int family;
  711. START_STEP(addr, step);
  712. family = sockaddr_family(addr, step);
  713. return (family == AF_INET ? ADDRTYPE_IPV4 :
  714. #ifndef NO_IPV6
  715. family == AF_INET6 ? ADDRTYPE_IPV6 :
  716. #endif
  717. ADDRTYPE_NAME);
  718. }
  719. void sk_addrcopy(SockAddr *addr, char *buf)
  720. {
  721. SockAddrStep step;
  722. int family;
  723. START_STEP(addr, step);
  724. family = sockaddr_family(addr, step);
  725. assert(family != AF_UNSPEC);
  726. #ifndef NO_IPV6
  727. if (step.ai) {
  728. if (family == AF_INET)
  729. memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
  730. sizeof(struct in_addr));
  731. else if (family == AF_INET6)
  732. memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
  733. sizeof(struct in6_addr));
  734. else
  735. unreachable("bad address family in sk_addrcopy");
  736. } else
  737. #endif
  738. if (family == AF_INET) {
  739. struct in_addr a;
  740. assert(addr->addresses && step.curraddr < addr->naddresses);
  741. a.s_addr = p_htonl(addr->addresses[step.curraddr]);
  742. memcpy(buf, (char*) &a.s_addr, 4);
  743. }
  744. }
  745. void sk_addr_free(SockAddr *addr)
  746. {
  747. if (--addr->refcount > 0)
  748. return;
  749. #ifndef NO_IPV6
  750. if (addr->ais && p_freeaddrinfo)
  751. p_freeaddrinfo(addr->ais);
  752. #endif
  753. if (addr->addresses)
  754. sfree(addr->addresses);
  755. sfree(addr);
  756. }
  757. SockAddr *sk_addr_dup(SockAddr *addr)
  758. {
  759. addr->refcount++;
  760. return addr;
  761. }
  762. static Plug *sk_net_plug(Socket *sock, Plug *p)
  763. {
  764. NetSocket *s = container_of(sock, NetSocket, sock);
  765. Plug *ret = s->plug;
  766. if (p)
  767. s->plug = p;
  768. return ret;
  769. }
  770. static void sk_net_close(Socket *s);
  771. static size_t sk_net_write(Socket *s, const void *data, size_t len);
  772. static size_t sk_net_write_oob(Socket *s, const void *data, size_t len);
  773. static void sk_net_write_eof(Socket *s);
  774. static void sk_net_set_frozen(Socket *s, bool is_frozen);
  775. static const char *sk_net_socket_error(Socket *s);
  776. static SocketPeerInfo *sk_net_peer_info(Socket *s);
  777. static const SocketVtable NetSocket_sockvt = {
  778. // WINSCP
  779. /*.plug =*/ sk_net_plug,
  780. /*.close =*/ sk_net_close,
  781. /*.write =*/ sk_net_write,
  782. /*.write_oob =*/ sk_net_write_oob,
  783. /*.write_eof =*/ sk_net_write_eof,
  784. /*.set_frozen =*/ sk_net_set_frozen,
  785. /*.socket_error =*/ sk_net_socket_error,
  786. /*.peer_info =*/ sk_net_peer_info,
  787. };
  788. static Socket *sk_net_accept(accept_ctx_t ctx, Plug *plug)
  789. {
  790. DWORD err;
  791. const char *errstr;
  792. NetSocket *ret;
  793. /*
  794. * Create NetSocket structure.
  795. */
  796. ret = snew(NetSocket);
  797. ret->sock.vt = &NetSocket_sockvt;
  798. ret->error = NULL;
  799. ret->plug = plug;
  800. bufchain_init(&ret->output_data);
  801. ret->writable = true; /* to start with */
  802. ret->sending_oob = 0;
  803. ret->outgoingeof = EOF_NO;
  804. ret->frozen = true;
  805. ret->frozen_readable = false;
  806. ret->localhost_only = false; /* unused, but best init anyway */
  807. ret->pending_error = 0;
  808. ret->parent = ret->child = NULL;
  809. ret->addr = NULL;
  810. ret->s = (SOCKET)ctx.p;
  811. if (ret->s == INVALID_SOCKET) {
  812. err = p_WSAGetLastError();
  813. ret->error = winsock_error_string(err);
  814. return &ret->sock;
  815. }
  816. ret->oobinline = false;
  817. /* Set up a select mechanism. This could be an AsyncSelect on a
  818. * window, or an EventSelect on an event object. */
  819. #ifdef MPEXT
  820. errstr = do_select(plug, ret->s, true);
  821. #else
  822. #endif
  823. if (errstr) {
  824. ret->error = errstr;
  825. return &ret->sock;
  826. }
  827. add234(sktree, ret);
  828. return &ret->sock;
  829. }
  830. static DWORD try_connect(NetSocket *sock,
  831. #ifdef MPEXT
  832. int timeout,
  833. int sndbuf,
  834. const char *srcaddr
  835. #endif
  836. )
  837. {
  838. SOCKET s;
  839. #ifndef NO_IPV6
  840. SOCKADDR_IN6 a6;
  841. #endif
  842. SOCKADDR_IN a;
  843. DWORD err;
  844. const char *errstr;
  845. short localport;
  846. int family;
  847. #ifdef MPEXT
  848. struct timeval rcvtimeo;
  849. #endif
  850. if (sock->s != INVALID_SOCKET) {
  851. #ifdef MPEXT
  852. do_select(sock->plug, sock->s, false);
  853. #else
  854. do_select(sock->s, false);
  855. #endif
  856. p_closesocket(sock->s);
  857. }
  858. {
  859. SockAddr thisaddr = sk_extractaddr_tmp(
  860. sock->addr, &sock->step);
  861. plug_log(sock->plug, PLUGLOG_CONNECT_TRYING,
  862. &thisaddr, sock->port, NULL, 0);
  863. }
  864. /*
  865. * Open socket.
  866. */
  867. family = sockaddr_family(sock->addr, sock->step);
  868. /*
  869. * Remove the socket from the tree before we overwrite its
  870. * internal socket id, because that forms part of the tree's
  871. * sorting criterion. We'll add it back before exiting this
  872. * function, whether we changed anything or not.
  873. */
  874. del234(sktree, sock);
  875. s = p_socket(family, SOCK_STREAM, 0);
  876. sock->s = s;
  877. if (s == INVALID_SOCKET) {
  878. err = p_WSAGetLastError();
  879. sock->error = winsock_error_string(err);
  880. goto ret;
  881. }
  882. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  883. if (sock->oobinline) {
  884. BOOL b = true;
  885. p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
  886. }
  887. if (sock->nodelay) {
  888. BOOL b = true;
  889. p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
  890. }
  891. if (sock->keepalive) {
  892. BOOL b = true;
  893. p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
  894. }
  895. if (sndbuf > 0)
  896. {
  897. int rcvbuf = 4 * 1024 * 1024;
  898. p_setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf, sizeof(sndbuf));
  899. // For now we increase receive buffer, whenever send buffer is set.
  900. // The size is not configurable. The constant taken from FZ.
  901. p_setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*) &rcvbuf, sizeof(rcvbuf));
  902. }
  903. /*
  904. * Bind to local address.
  905. */
  906. if (sock->privport)
  907. localport = 1023; /* count from 1023 downwards */
  908. else
  909. localport = 0; /* just use port 0 (ie winsock picks) */
  910. /* Loop round trying to bind */
  911. while (1) {
  912. int sockcode;
  913. #ifndef NO_IPV6
  914. if (family == AF_INET6) {
  915. memset(&a6, 0, sizeof(a6));
  916. a6.sin6_family = AF_INET6;
  917. /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
  918. a6.sin6_port = p_htons(localport);
  919. } else
  920. #endif
  921. {
  922. a.sin_family = AF_INET;
  923. if (srcaddr && srcaddr[0]) {
  924. a.sin_addr.s_addr = p_inet_addr(srcaddr);
  925. } else {
  926. a.sin_addr.s_addr = p_htonl(INADDR_ANY);
  927. }
  928. a.sin_port = p_htons(localport);
  929. }
  930. #ifndef NO_IPV6
  931. sockcode = p_bind(s, (family == AF_INET6 ?
  932. (struct sockaddr *) &a6 :
  933. (struct sockaddr *) &a),
  934. (family == AF_INET6 ? sizeof(a6) : sizeof(a)));
  935. #else
  936. sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
  937. #endif
  938. if (sockcode != SOCKET_ERROR) {
  939. err = 0;
  940. break; /* done */
  941. } else {
  942. err = p_WSAGetLastError();
  943. if (err != WSAEADDRINUSE) /* failed, for a bad reason */
  944. break;
  945. }
  946. if (localport == 0)
  947. break; /* we're only looping once */
  948. localport--;
  949. if (localport == 0)
  950. break; /* we might have got to the end */
  951. }
  952. if (err) {
  953. sock->error = winsock_error_string(err);
  954. goto ret;
  955. }
  956. /*
  957. * Connect to remote address.
  958. */
  959. #ifndef NO_IPV6
  960. if (sock->step.ai) {
  961. if (family == AF_INET6) {
  962. a6.sin6_family = AF_INET6;
  963. a6.sin6_port = p_htons((short) sock->port);
  964. a6.sin6_addr =
  965. ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr;
  966. a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo;
  967. a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id;
  968. } else {
  969. a.sin_family = AF_INET;
  970. a.sin_addr =
  971. ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr;
  972. a.sin_port = p_htons((short) sock->port);
  973. }
  974. } else
  975. #endif
  976. {
  977. assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses);
  978. a.sin_family = AF_INET;
  979. a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]);
  980. a.sin_port = p_htons((short) sock->port);
  981. }
  982. #ifndef MPEXT
  983. /* Set up a select mechanism. This could be an AsyncSelect on a
  984. * window, or an EventSelect on an event object. */
  985. errstr = do_select(s, true);
  986. if (errstr) {
  987. sock->error = errstr;
  988. err = 1;
  989. goto ret;
  990. }
  991. #endif
  992. #ifdef MPEXT
  993. if (timeout > 0)
  994. {
  995. if (p_getsockopt (s, SOL_SOCKET, SO_RCVTIMEO, (char *)&rcvtimeo, &rcvtimeo) < 0)
  996. {
  997. rcvtimeo.tv_sec = -1;
  998. }
  999. else
  1000. {
  1001. struct timeval timeoutval;
  1002. timeoutval.tv_sec = timeout / 1000;
  1003. timeoutval.tv_usec = (timeout % 1000) * 1000;
  1004. p_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *) &timeoutval, sizeof(timeoutval));
  1005. }
  1006. }
  1007. #endif
  1008. if ((
  1009. #ifndef NO_IPV6
  1010. p_connect(s,
  1011. ((family == AF_INET6) ? (struct sockaddr *) &a6 :
  1012. (struct sockaddr *) &a),
  1013. (family == AF_INET6) ? sizeof(a6) : sizeof(a))
  1014. #else
  1015. p_connect(s, (struct sockaddr *) &a, sizeof(a))
  1016. #endif
  1017. ) == SOCKET_ERROR) {
  1018. err = p_WSAGetLastError();
  1019. /*
  1020. * We expect a potential EWOULDBLOCK here, because the
  1021. * chances are the front end has done a select for
  1022. * FD_CONNECT, so that connect() will complete
  1023. * asynchronously.
  1024. */
  1025. if ( err != WSAEWOULDBLOCK ) {
  1026. #ifdef MPEXT
  1027. // unselect on error
  1028. do_select(sock->plug, s, 0);
  1029. #endif
  1030. sock->error = winsock_error_string(err);
  1031. goto ret;
  1032. }
  1033. } else {
  1034. /*
  1035. * If we _don't_ get EWOULDBLOCK, the connect has completed
  1036. * and we should set the socket as writable.
  1037. */
  1038. sock->writable = true;
  1039. { // WINSCP
  1040. SockAddr thisaddr = sk_extractaddr_tmp(sock->addr, &sock->step);
  1041. plug_log(sock->plug, PLUGLOG_CONNECT_SUCCESS,
  1042. &thisaddr, sock->port, NULL, 0);
  1043. } // WINSCP
  1044. }
  1045. #ifdef MPEXT
  1046. if ((timeout > 0) && (rcvtimeo.tv_sec >= 0))
  1047. {
  1048. p_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *) &rcvtimeo, sizeof(rcvtimeo));
  1049. }
  1050. // MP: Calling EventSelect only after connect makes sure we receive FD_CLOSE.
  1051. /* Set up a select mechanism. This could be an AsyncSelect on a
  1052. * window, or an EventSelect on an event object. */
  1053. errstr = do_select(sock->plug, s, 1);
  1054. if (errstr) {
  1055. sock->error = errstr;
  1056. err = 1;
  1057. goto ret;
  1058. }
  1059. #endif
  1060. err = 0;
  1061. ret:
  1062. /*
  1063. * No matter what happened, put the socket back in the tree.
  1064. */
  1065. add234(sktree, sock);
  1066. if (err) {
  1067. SockAddr thisaddr = sk_extractaddr_tmp(
  1068. sock->addr, &sock->step);
  1069. plug_log(sock->plug, PLUGLOG_CONNECT_FAILED,
  1070. &thisaddr, sock->port, sock->error, err);
  1071. }
  1072. return err;
  1073. }
  1074. Socket *sk_new(SockAddr *addr, int port, bool privport, bool oobinline,
  1075. bool nodelay, bool keepalive, Plug *plug,
  1076. #ifdef MPEXT
  1077. int timeout,
  1078. int sndbuf,
  1079. const char *srcaddr
  1080. #endif
  1081. )
  1082. {
  1083. NetSocket *ret;
  1084. DWORD err;
  1085. /*
  1086. * Create NetSocket structure.
  1087. */
  1088. ret = snew(NetSocket);
  1089. ret->sock.vt = &NetSocket_sockvt;
  1090. ret->error = NULL;
  1091. ret->plug = plug;
  1092. bufchain_init(&ret->output_data);
  1093. ret->connected = false; /* to start with */
  1094. ret->writable = false; /* to start with */
  1095. ret->sending_oob = 0;
  1096. ret->outgoingeof = EOF_NO;
  1097. ret->frozen = false;
  1098. ret->frozen_readable = false;
  1099. ret->localhost_only = false; /* unused, but best init anyway */
  1100. ret->pending_error = 0;
  1101. ret->parent = ret->child = NULL;
  1102. ret->oobinline = oobinline;
  1103. ret->nodelay = nodelay;
  1104. ret->keepalive = keepalive;
  1105. ret->privport = privport;
  1106. ret->port = port;
  1107. ret->addr = addr;
  1108. START_STEP(ret->addr, ret->step);
  1109. ret->s = INVALID_SOCKET;
  1110. err = 0;
  1111. do {
  1112. #ifdef MPEXT
  1113. ret->error = NULL;
  1114. #endif
  1115. err = try_connect(ret
  1116. #ifdef MPEXT
  1117. , timeout, sndbuf, srcaddr
  1118. #endif
  1119. );
  1120. } while (err && sk_nextaddr(ret->addr, &ret->step));
  1121. return &ret->sock;
  1122. }
  1123. static Socket *sk_newlistener_internal(
  1124. const char *srcaddr, int port, Plug *plug,
  1125. bool local_host_only, int orig_address_family)
  1126. {
  1127. SOCKET s;
  1128. SOCKADDR_IN a;
  1129. #ifndef NO_IPV6
  1130. SOCKADDR_IN6 a6;
  1131. #endif
  1132. #if HAVE_AFUNIX_H
  1133. SOCKADDR_UN au;
  1134. #endif
  1135. struct sockaddr *bindaddr;
  1136. unsigned bindsize;
  1137. DWORD err;
  1138. const char *errstr;
  1139. NetSocket *ret;
  1140. int retcode;
  1141. int address_family = orig_address_family;
  1142. /*
  1143. * Create NetSocket structure.
  1144. */
  1145. ret = snew(NetSocket);
  1146. ret->sock.vt = &NetSocket_sockvt;
  1147. ret->error = NULL;
  1148. ret->plug = plug;
  1149. bufchain_init(&ret->output_data);
  1150. ret->writable = false; /* to start with */
  1151. ret->sending_oob = 0;
  1152. ret->outgoingeof = EOF_NO;
  1153. ret->frozen = false;
  1154. ret->frozen_readable = false;
  1155. ret->localhost_only = local_host_only;
  1156. ret->pending_error = 0;
  1157. ret->parent = ret->child = NULL;
  1158. ret->addr = NULL;
  1159. /*
  1160. * Our default, if passed the `don't care' value
  1161. * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
  1162. * we will also set up a second socket listening on IPv6, but
  1163. * the v4 one is primary since that ought to work even on
  1164. * non-v6-supporting systems.
  1165. */
  1166. if (address_family == AF_UNSPEC) address_family = AF_INET;
  1167. /*
  1168. * Open socket.
  1169. */
  1170. s = p_socket(address_family, SOCK_STREAM, 0);
  1171. ret->s = s;
  1172. if (s == INVALID_SOCKET) {
  1173. err = p_WSAGetLastError();
  1174. ret->error = winsock_error_string(err);
  1175. return &ret->sock;
  1176. }
  1177. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  1178. ret->oobinline = false;
  1179. #if HAVE_AFUNIX_H
  1180. if (address_family != AF_UNIX)
  1181. #endif
  1182. {
  1183. BOOL on = true;
  1184. p_setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  1185. (const char *)&on, sizeof(on));
  1186. }
  1187. switch (address_family) {
  1188. #ifndef NO_IPV6
  1189. case AF_INET6: {
  1190. memset(&a6, 0, sizeof(a6));
  1191. a6.sin6_family = AF_INET6;
  1192. if (local_host_only)
  1193. a6.sin6_addr = in6addr_loopback;
  1194. else
  1195. a6.sin6_addr = in6addr_any;
  1196. if (srcaddr != NULL && p_getaddrinfo) {
  1197. struct addrinfo hints;
  1198. struct addrinfo *ai;
  1199. int err;
  1200. memset(&hints, 0, sizeof(hints));
  1201. hints.ai_family = AF_INET6;
  1202. hints.ai_flags = 0;
  1203. {
  1204. /* strip [] on IPv6 address literals */
  1205. char *trimmed_addr = host_strduptrim(srcaddr);
  1206. err = p_getaddrinfo(trimmed_addr, NULL, &hints, &ai);
  1207. sfree(trimmed_addr);
  1208. }
  1209. if (err == 0 && ai->ai_family == AF_INET6) {
  1210. a6.sin6_addr =
  1211. ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
  1212. }
  1213. }
  1214. a6.sin6_port = p_htons(port);
  1215. bindaddr = (struct sockaddr *)&a6;
  1216. bindsize = sizeof(a6);
  1217. break;
  1218. }
  1219. #endif
  1220. case AF_INET: {
  1221. bool got_addr = false;
  1222. a.sin_family = AF_INET;
  1223. /*
  1224. * Bind to source address. First try an explicitly
  1225. * specified one...
  1226. */
  1227. if (srcaddr) {
  1228. a.sin_addr.s_addr = p_inet_addr(srcaddr);
  1229. if (a.sin_addr.s_addr != INADDR_NONE) {
  1230. /* Override localhost_only with specified listen addr. */
  1231. ret->localhost_only = ipv4_is_loopback(a.sin_addr);
  1232. got_addr = true;
  1233. }
  1234. }
  1235. /*
  1236. * ... and failing that, go with one of the standard ones.
  1237. */
  1238. if (!got_addr) {
  1239. if (local_host_only)
  1240. a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
  1241. else
  1242. a.sin_addr.s_addr = p_htonl(INADDR_ANY);
  1243. }
  1244. a.sin_port = p_htons((short)port);
  1245. bindaddr = (struct sockaddr *)&a;
  1246. bindsize = sizeof(a);
  1247. break;
  1248. }
  1249. #if HAVE_AFUNIX_H
  1250. case AF_UNIX: {
  1251. au.sun_family = AF_UNIX;
  1252. strncpy(au.sun_path, srcaddr, sizeof(au.sun_path));
  1253. bindaddr = (struct sockaddr *)&au;
  1254. bindsize = sizeof(au);
  1255. break;
  1256. }
  1257. #endif
  1258. default:
  1259. unreachable("bad address family in sk_newlistener_internal");
  1260. }
  1261. retcode = p_bind(s, bindaddr, bindsize);
  1262. if (retcode != SOCKET_ERROR) {
  1263. err = 0;
  1264. } else {
  1265. err = p_WSAGetLastError();
  1266. }
  1267. if (err) {
  1268. p_closesocket(s);
  1269. ret->error = winsock_error_string(err);
  1270. return &ret->sock;
  1271. }
  1272. if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
  1273. p_closesocket(s);
  1274. ret->error = winsock_error_string(p_WSAGetLastError());
  1275. return &ret->sock;
  1276. }
  1277. /* Set up a select mechanism. This could be an AsyncSelect on a
  1278. * window, or an EventSelect on an event object. */
  1279. #ifdef MPEXT
  1280. errstr = do_select(plug, s, true);
  1281. #else
  1282. errstr = do_select(s, true);
  1283. #endif
  1284. if (errstr) {
  1285. p_closesocket(s);
  1286. ret->error = errstr;
  1287. return &ret->sock;
  1288. }
  1289. add234(sktree, ret);
  1290. #ifndef NO_IPV6
  1291. /*
  1292. * If we were given ADDRTYPE_UNSPEC, we must also create an
  1293. * IPv6 listening socket and link it to this one.
  1294. */
  1295. if (address_family == AF_INET && orig_address_family == AF_UNSPEC) {
  1296. Socket *other = sk_newlistener_internal(srcaddr, port, plug,
  1297. local_host_only, AF_INET6);
  1298. if (other) {
  1299. NetSocket *ns = container_of(other, NetSocket, sock);
  1300. if (!ns->error) {
  1301. ns->parent = ret;
  1302. ret->child = ns;
  1303. } else {
  1304. sfree(ns);
  1305. }
  1306. }
  1307. }
  1308. #endif
  1309. return &ret->sock;
  1310. }
  1311. Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug,
  1312. bool local_host_only, int orig_address_family)
  1313. {
  1314. /*
  1315. * Translate address_family from platform-independent constants
  1316. * into local reality.
  1317. */
  1318. int address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
  1319. #ifndef NO_IPV6
  1320. orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  1321. #endif
  1322. AF_UNSPEC);
  1323. return sk_newlistener_internal(srcaddr, port, plug, local_host_only,
  1324. address_family);
  1325. }
  1326. Socket *sk_newlistener_unix(const char *path, Plug *plug)
  1327. {
  1328. #if HAVE_AFUNIX_H
  1329. return sk_newlistener_internal(path, 0, plug, false, AF_UNIX);
  1330. #else
  1331. return new_error_socket_fmt(
  1332. plug, "AF_UNIX support not compiled into this program");
  1333. #endif
  1334. }
  1335. static void sk_net_close(Socket *sock)
  1336. {
  1337. NetSocket *s = container_of(sock, NetSocket, sock);
  1338. if (s->child)
  1339. sk_net_close(&s->child->sock);
  1340. bufchain_clear(&s->output_data);
  1341. del234(sktree, s);
  1342. #ifdef MPEXT
  1343. do_select(s->plug, s->s, false);
  1344. #else
  1345. do_select(s->s, false);
  1346. #endif
  1347. p_closesocket(s->s);
  1348. if (s->addr)
  1349. sk_addr_free(s->addr);
  1350. delete_callbacks_for_context(get_callback_set(s->plug), s);
  1351. sfree(s);
  1352. }
  1353. void plug_closing_system_error(Plug *plug, DWORD error)
  1354. {
  1355. PlugCloseType type = PLUGCLOSE_ERROR;
  1356. if (error == ERROR_BROKEN_PIPE)
  1357. type = PLUGCLOSE_BROKEN_PIPE;
  1358. plug_closing(plug, type, win_strerror(error));
  1359. }
  1360. void plug_closing_winsock_error(Plug *plug, DWORD error)
  1361. {
  1362. plug_closing(plug, PLUGCLOSE_ERROR, winsock_error_string(error));
  1363. }
  1364. /*
  1365. * Deal with socket errors detected in try_send().
  1366. */
  1367. static void socket_error_callback(void *vs)
  1368. {
  1369. NetSocket *s = (NetSocket *)vs;
  1370. /*
  1371. * Just in case other socket work has caused this socket to vanish
  1372. * or become somehow non-erroneous before this callback arrived...
  1373. */
  1374. if (!find234(sktree, s, NULL) || !s->pending_error)
  1375. return;
  1376. /*
  1377. * An error has occurred on this socket. Pass it to the plug.
  1378. */
  1379. plug_closing_winsock_error(s->plug, s->pending_error);
  1380. }
  1381. /*
  1382. * The function which tries to send on a socket once it's deemed
  1383. * writable.
  1384. */
  1385. static void try_send(NetSocket *s)
  1386. {
  1387. while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
  1388. int nsent;
  1389. DWORD err;
  1390. const void *data;
  1391. size_t len;
  1392. int urgentflag;
  1393. if (s->sending_oob) {
  1394. urgentflag = MSG_OOB;
  1395. len = s->sending_oob;
  1396. data = &s->oobdata;
  1397. } else {
  1398. urgentflag = 0;
  1399. { // WINSCP
  1400. ptrlen bufdata = bufchain_prefix(&s->output_data);
  1401. data = bufdata.ptr;
  1402. len = bufdata.len;
  1403. } // WINSCP
  1404. }
  1405. len = min(len, INT_MAX); /* WinSock send() takes an int */
  1406. nsent = p_send(s->s, data, len, urgentflag);
  1407. noise_ultralight(NOISE_SOURCE_IOLEN, nsent);
  1408. if (nsent <= 0) {
  1409. err = (nsent < 0 ? p_WSAGetLastError() : 0);
  1410. if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
  1411. /*
  1412. * Perfectly normal: we've sent all we can for the moment.
  1413. *
  1414. * (Some WinSock send() implementations can return
  1415. * <0 but leave no sensible error indication -
  1416. * WSAGetLastError() is called but returns zero or
  1417. * a small number - so we check that case and treat
  1418. * it just like WSAEWOULDBLOCK.)
  1419. */
  1420. s->writable = false;
  1421. return;
  1422. } else {
  1423. /*
  1424. * If send() returns a socket error, we unfortunately
  1425. * can't just call plug_closing(), because it's quite
  1426. * likely that we're currently _in_ a call from the
  1427. * code we'd be calling back to, so we'd have to make
  1428. * half the SSH code reentrant. Instead we flag a
  1429. * pending error on the socket, to be dealt with (by
  1430. * calling plug_closing()) at some suitable future
  1431. * moment.
  1432. */
  1433. s->pending_error = err;
  1434. queue_toplevel_callback(get_callback_set(s->plug), socket_error_callback, s);
  1435. return;
  1436. }
  1437. } else {
  1438. if (s->sending_oob) {
  1439. if (nsent < len) {
  1440. memmove(s->oobdata, s->oobdata+nsent, len-nsent);
  1441. s->sending_oob = len - nsent;
  1442. } else {
  1443. s->sending_oob = 0;
  1444. }
  1445. } else {
  1446. bufchain_consume(&s->output_data, nsent);
  1447. }
  1448. }
  1449. }
  1450. /*
  1451. * If we reach here, we've finished sending everything we might
  1452. * have needed to send. Send EOF, if we need to.
  1453. */
  1454. if (s->outgoingeof == EOF_PENDING) {
  1455. p_shutdown(s->s, SD_SEND);
  1456. s->outgoingeof = EOF_SENT;
  1457. }
  1458. }
  1459. static size_t sk_net_write(Socket *sock, const void *buf, size_t len)
  1460. {
  1461. NetSocket *s = container_of(sock, NetSocket, sock);
  1462. assert(s->outgoingeof == EOF_NO);
  1463. /*
  1464. * Add the data to the buffer list on the socket.
  1465. */
  1466. bufchain_add(&s->output_data, buf, len);
  1467. /*
  1468. * Now try sending from the start of the buffer list.
  1469. */
  1470. if (s->writable)
  1471. try_send(s);
  1472. return bufchain_size(&s->output_data);
  1473. }
  1474. static size_t sk_net_write_oob(Socket *sock, const void *buf, size_t len)
  1475. {
  1476. NetSocket *s = container_of(sock, NetSocket, sock);
  1477. assert(s->outgoingeof == EOF_NO);
  1478. /*
  1479. * Replace the buffer list on the socket with the data.
  1480. */
  1481. bufchain_clear(&s->output_data);
  1482. assert(len <= sizeof(s->oobdata));
  1483. memcpy(s->oobdata, buf, len);
  1484. s->sending_oob = len;
  1485. /*
  1486. * Now try sending from the start of the buffer list.
  1487. */
  1488. if (s->writable)
  1489. try_send(s);
  1490. return s->sending_oob;
  1491. }
  1492. static void sk_net_write_eof(Socket *sock)
  1493. {
  1494. NetSocket *s = container_of(sock, NetSocket, sock);
  1495. assert(s->outgoingeof == EOF_NO);
  1496. /*
  1497. * Mark the socket as pending outgoing EOF.
  1498. */
  1499. s->outgoingeof = EOF_PENDING;
  1500. /*
  1501. * Now try sending from the start of the buffer list.
  1502. */
  1503. if (s->writable)
  1504. try_send(s);
  1505. }
  1506. void select_result(WPARAM wParam, LPARAM lParam)
  1507. {
  1508. int ret;
  1509. DWORD err;
  1510. char buf[20480]; /* nice big buffer for plenty of speed */
  1511. NetSocket *s;
  1512. bool atmark;
  1513. /* wParam is the socket itself */
  1514. if (wParam == 0)
  1515. return; /* boggle */
  1516. s = find234(sktree, (void *) wParam, cmpforsearch);
  1517. if (!s)
  1518. return; /* boggle */
  1519. if ((err = WSAGETSELECTERROR(lParam)) != 0) {
  1520. /*
  1521. * An error has occurred on this socket. Pass it to the
  1522. * plug.
  1523. */
  1524. if (s->addr) {
  1525. SockAddr thisaddr = sk_extractaddr_tmp(
  1526. s->addr, &s->step);
  1527. plug_log(s->plug, PLUGLOG_CONNECT_FAILED, &thisaddr, s->port,
  1528. winsock_error_string(err), err);
  1529. while (err && s->addr && sk_nextaddr(s->addr, &s->step)) {
  1530. err = try_connect(s
  1531. #ifdef MPEXT
  1532. , 0, 0, NULL
  1533. #endif
  1534. );
  1535. }
  1536. }
  1537. if (err != 0)
  1538. {
  1539. plug_closing_winsock_error(s->plug, err);
  1540. }
  1541. return;
  1542. }
  1543. noise_ultralight(NOISE_SOURCE_IOID, wParam);
  1544. switch (WSAGETSELECTEVENT(lParam)) {
  1545. case FD_CONNECT:
  1546. s->connected = true;
  1547. s->writable = true;
  1548. /*
  1549. * Once a socket is connected, we can stop falling back
  1550. * through the candidate addresses to connect to. But first,
  1551. * let the plug know we were successful.
  1552. */
  1553. if (s->addr) {
  1554. SockAddr thisaddr = sk_extractaddr_tmp(
  1555. s->addr, &s->step);
  1556. plug_log(s->plug, PLUGLOG_CONNECT_SUCCESS,
  1557. &thisaddr, s->port, NULL, 0);
  1558. sk_addr_free(s->addr);
  1559. s->addr = NULL;
  1560. }
  1561. break;
  1562. case FD_READ:
  1563. /* In the case the socket is still frozen, we don't even bother */
  1564. if (s->frozen) {
  1565. s->frozen_readable = true;
  1566. break;
  1567. }
  1568. /*
  1569. * We have received data on the socket. For an oobinline
  1570. * socket, this might be data _before_ an urgent pointer,
  1571. * in which case we send it to the back end with type==1
  1572. * (data prior to urgent).
  1573. */
  1574. if (s->oobinline) {
  1575. u_long atmark_from_ioctl = 1;
  1576. p_ioctlsocket(s->s, SIOCATMARK, &atmark_from_ioctl);
  1577. /*
  1578. * Avoid checking the return value from ioctlsocket(),
  1579. * on the grounds that some WinSock wrappers don't
  1580. * support it. If it does nothing, we get atmark==1,
  1581. * which is equivalent to `no OOB pending', so the
  1582. * effect will be to non-OOB-ify any OOB data.
  1583. */
  1584. atmark = atmark_from_ioctl;
  1585. } else
  1586. atmark = true;
  1587. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1588. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1589. if (ret < 0) {
  1590. err = p_WSAGetLastError();
  1591. if (err == WSAEWOULDBLOCK) {
  1592. break;
  1593. }
  1594. }
  1595. if (ret < 0) {
  1596. plug_closing_winsock_error(s->plug, err);
  1597. } else if (0 == ret) {
  1598. plug_closing_normal(s->plug);
  1599. } else {
  1600. plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
  1601. }
  1602. break;
  1603. case FD_OOB:
  1604. /*
  1605. * This will only happen on a non-oobinline socket. It
  1606. * indicates that we can immediately perform an OOB read
  1607. * and get back OOB data, which we will send to the back
  1608. * end with type==2 (urgent data).
  1609. */
  1610. ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
  1611. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1612. if (ret <= 0) {
  1613. int err = p_WSAGetLastError();
  1614. plug_closing_winsock_error(s->plug, err);
  1615. } else {
  1616. plug_receive(s->plug, 2, buf, ret);
  1617. }
  1618. break;
  1619. case FD_WRITE: {
  1620. int bufsize_before, bufsize_after;
  1621. s->writable = true;
  1622. bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
  1623. try_send(s);
  1624. bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
  1625. if (bufsize_after < bufsize_before)
  1626. plug_sent(s->plug, bufsize_after);
  1627. break;
  1628. }
  1629. case FD_CLOSE:
  1630. /* Signal a close on the socket. First read any outstanding data. */
  1631. do {
  1632. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1633. if (ret < 0) {
  1634. err = p_WSAGetLastError();
  1635. if (err == WSAEWOULDBLOCK)
  1636. break;
  1637. plug_closing_winsock_error(s->plug, err);
  1638. } else {
  1639. if (ret)
  1640. plug_receive(s->plug, 0, buf, ret);
  1641. else
  1642. {
  1643. plug_closing_normal(s->plug);
  1644. }
  1645. }
  1646. } while (ret > 0);
  1647. return;
  1648. case FD_ACCEPT: {
  1649. #ifdef NO_IPV6
  1650. struct sockaddr_in isa;
  1651. #else
  1652. struct sockaddr_storage isa; // FIXME: also if Unix and no IPv6
  1653. #endif
  1654. int addrlen = sizeof(isa);
  1655. SOCKET t; /* socket of connection */
  1656. accept_ctx_t actx;
  1657. memset(&isa, 0, sizeof(isa));
  1658. err = 0;
  1659. t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
  1660. if (t == INVALID_SOCKET)
  1661. {
  1662. err = p_WSAGetLastError();
  1663. if (err == WSATRY_AGAIN)
  1664. break;
  1665. }
  1666. actx.p = (void *)t;
  1667. #ifndef NO_IPV6
  1668. if (isa.ss_family == AF_INET &&
  1669. s->localhost_only &&
  1670. !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
  1671. #else
  1672. if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
  1673. #endif
  1674. {
  1675. p_closesocket(t); /* dodgy WinSock let nonlocal through */
  1676. } else if (plug_accepting(s->plug, sk_net_accept, actx)) {
  1677. p_closesocket(t); /* denied or error */
  1678. }
  1679. break;
  1680. }
  1681. }
  1682. }
  1683. /*
  1684. * Special error values are returned from sk_namelookup and sk_new
  1685. * if there's a problem. These functions extract an error message,
  1686. * or return NULL if there's no problem.
  1687. */
  1688. const char *sk_addr_error(SockAddr *addr)
  1689. {
  1690. return addr->error;
  1691. }
  1692. static const char *sk_net_socket_error(Socket *sock)
  1693. {
  1694. NetSocket *s = container_of(sock, NetSocket, sock);
  1695. return s->error;
  1696. }
  1697. static SocketPeerInfo *sk_net_peer_info(Socket *sock)
  1698. {
  1699. NetSocket *s = container_of(sock, NetSocket, sock);
  1700. #ifdef NO_IPV6
  1701. struct sockaddr_in addr;
  1702. #else
  1703. struct sockaddr_storage addr; // FIXME: also if Unix and no IPv6
  1704. char buf[INET6_ADDRSTRLEN];
  1705. #endif
  1706. int addrlen = sizeof(addr);
  1707. SocketPeerInfo *pi;
  1708. if (p_getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
  1709. return NULL;
  1710. pi = snew(SocketPeerInfo);
  1711. pi->addressfamily = ADDRTYPE_UNSPEC;
  1712. pi->addr_text = NULL;
  1713. pi->port = -1;
  1714. pi->log_text = NULL;
  1715. if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
  1716. pi->addressfamily = ADDRTYPE_IPV4;
  1717. memcpy(pi->addr_bin.ipv4, &((struct sockaddr_in *)&addr)->sin_addr, 4);
  1718. pi->port = p_ntohs(((struct sockaddr_in *)&addr)->sin_port);
  1719. pi->addr_text = dupstr(
  1720. p_inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr));
  1721. pi->log_text = dupprintf("%s:%d", pi->addr_text, pi->port);
  1722. #ifndef NO_IPV6
  1723. } else if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
  1724. pi->addressfamily = ADDRTYPE_IPV6;
  1725. memcpy(pi->addr_bin.ipv6,
  1726. &((struct sockaddr_in6 *)&addr)->sin6_addr, 16);
  1727. pi->port = p_ntohs(((struct sockaddr_in6 *)&addr)->sin6_port);
  1728. pi->addr_text = dupstr(
  1729. p_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
  1730. buf, sizeof(buf)));
  1731. pi->log_text = dupprintf("[%s]:%d", pi->addr_text, pi->port);
  1732. #endif
  1733. } else {
  1734. sfree(pi);
  1735. return NULL;
  1736. }
  1737. return pi;
  1738. }
  1739. static void sk_net_set_frozen(Socket *sock, bool is_frozen)
  1740. {
  1741. NetSocket *s = container_of(sock, NetSocket, sock);
  1742. if (s->frozen == is_frozen)
  1743. return;
  1744. s->frozen = is_frozen;
  1745. if (!is_frozen) {
  1746. #ifdef MPEXT
  1747. do_select(s->plug, s->s, true);
  1748. #else
  1749. do_select(s->s, true);
  1750. #endif
  1751. if (s->frozen_readable) {
  1752. char c;
  1753. p_recv(s->s, &c, 1, MSG_PEEK);
  1754. }
  1755. }
  1756. s->frozen_readable = false;
  1757. }
  1758. void socket_reselect_all(void)
  1759. {
  1760. NetSocket *s;
  1761. int i;
  1762. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  1763. if (!s->frozen)
  1764. #ifdef MPEXT
  1765. do_select(s->plug, s->s, true);
  1766. #else
  1767. do_select(s->s, true);
  1768. #endif
  1769. }
  1770. }
  1771. /*
  1772. * For Plink: enumerate all sockets currently active.
  1773. */
  1774. SOCKET first_socket(int *state)
  1775. {
  1776. NetSocket *s;
  1777. *state = 0;
  1778. s = index234(sktree, (*state)++);
  1779. return s ? s->s : INVALID_SOCKET;
  1780. }
  1781. SOCKET next_socket(int *state)
  1782. {
  1783. NetSocket *s = index234(sktree, (*state)++);
  1784. return s ? s->s : INVALID_SOCKET;
  1785. }
  1786. bool socket_writable(SOCKET skt)
  1787. {
  1788. NetSocket *s = find234(sktree, (void *)skt, cmpforsearch);
  1789. if (s)
  1790. return bufchain_size(&s->output_data) > 0;
  1791. else
  1792. return false;
  1793. }
  1794. int net_service_lookup(const char *service)
  1795. {
  1796. struct servent *se;
  1797. se = p_getservbyname(service, NULL);
  1798. if (se != NULL)
  1799. return p_ntohs(se->s_port);
  1800. else
  1801. return 0;
  1802. }
  1803. char *get_hostname(void)
  1804. {
  1805. char hostbuf[256]; /* MSDN docs for gethostname() promise this is enough */
  1806. if (p_gethostname(hostbuf, sizeof(hostbuf)) < 0)
  1807. return NULL;
  1808. return dupstr(hostbuf);
  1809. }
  1810. SockAddr *platform_get_x11_unix_address(const char *display, int displaynum)
  1811. {
  1812. SockAddr *ret = snew(SockAddr);
  1813. memset(ret, 0, sizeof(SockAddr));
  1814. ret->error = "unix sockets for X11 not supported on this platform";
  1815. ret->refcount = 1;
  1816. return ret;
  1817. }