winnet.c 59 KB

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