network.c 61 KB

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