winnet.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  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. // WINSCP
  776. /*.plug =*/ sk_net_plug,
  777. /*.close =*/ sk_net_close,
  778. /*.write =*/ sk_net_write,
  779. /*.write_oob =*/ sk_net_write_oob,
  780. /*.write_eof =*/ sk_net_write_eof,
  781. /*.set_frozen =*/ sk_net_set_frozen,
  782. /*.socket_error =*/ sk_net_socket_error,
  783. /*.peer_info =*/ sk_net_peer_info,
  784. };
  785. static Socket *sk_net_accept(accept_ctx_t ctx, Plug *plug)
  786. {
  787. DWORD err;
  788. const char *errstr;
  789. NetSocket *ret;
  790. /*
  791. * Create NetSocket structure.
  792. */
  793. ret = snew(NetSocket);
  794. ret->sock.vt = &NetSocket_sockvt;
  795. ret->error = NULL;
  796. ret->plug = plug;
  797. bufchain_init(&ret->output_data);
  798. ret->writable = true; /* to start with */
  799. ret->sending_oob = 0;
  800. ret->outgoingeof = EOF_NO;
  801. ret->frozen = true;
  802. ret->frozen_readable = false;
  803. ret->localhost_only = false; /* unused, but best init anyway */
  804. ret->pending_error = 0;
  805. ret->parent = ret->child = NULL;
  806. ret->addr = NULL;
  807. ret->s = (SOCKET)ctx.p;
  808. if (ret->s == INVALID_SOCKET) {
  809. err = p_WSAGetLastError();
  810. ret->error = winsock_error_string(err);
  811. return &ret->sock;
  812. }
  813. ret->oobinline = false;
  814. /* Set up a select mechanism. This could be an AsyncSelect on a
  815. * window, or an EventSelect on an event object. */
  816. #ifdef MPEXT
  817. errstr = do_select(plug, ret->s, true);
  818. #else
  819. #endif
  820. if (errstr) {
  821. ret->error = errstr;
  822. return &ret->sock;
  823. }
  824. add234(sktree, ret);
  825. return &ret->sock;
  826. }
  827. static DWORD try_connect(NetSocket *sock,
  828. #ifdef MPEXT
  829. int timeout,
  830. int sndbuf,
  831. const char *srcaddr
  832. #endif
  833. )
  834. {
  835. SOCKET s;
  836. #ifndef NO_IPV6
  837. SOCKADDR_IN6 a6;
  838. #endif
  839. SOCKADDR_IN a;
  840. DWORD err;
  841. const char *errstr;
  842. short localport;
  843. int family;
  844. #ifdef MPEXT
  845. struct timeval rcvtimeo;
  846. #endif
  847. if (sock->s != INVALID_SOCKET) {
  848. #ifdef MPEXT
  849. do_select(sock->plug, sock->s, false);
  850. #else
  851. do_select(sock->s, false);
  852. #endif
  853. p_closesocket(sock->s);
  854. }
  855. {
  856. SockAddr thisaddr = sk_extractaddr_tmp(
  857. sock->addr, &sock->step);
  858. plug_log(sock->plug, PLUGLOG_CONNECT_TRYING,
  859. &thisaddr, sock->port, NULL, 0);
  860. }
  861. /*
  862. * Open socket.
  863. */
  864. family = SOCKADDR_FAMILY(sock->addr, sock->step);
  865. /*
  866. * Remove the socket from the tree before we overwrite its
  867. * internal socket id, because that forms part of the tree's
  868. * sorting criterion. We'll add it back before exiting this
  869. * function, whether we changed anything or not.
  870. */
  871. del234(sktree, sock);
  872. s = p_socket(family, SOCK_STREAM, 0);
  873. sock->s = s;
  874. if (s == INVALID_SOCKET) {
  875. err = p_WSAGetLastError();
  876. sock->error = winsock_error_string(err);
  877. goto ret;
  878. }
  879. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  880. if (sock->oobinline) {
  881. BOOL b = true;
  882. p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
  883. }
  884. if (sock->nodelay) {
  885. BOOL b = true;
  886. p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
  887. }
  888. if (sock->keepalive) {
  889. BOOL b = true;
  890. p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
  891. }
  892. if (sndbuf > 0)
  893. {
  894. int rcvbuf = 4 * 1024 * 1024;
  895. p_setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf, sizeof(sndbuf));
  896. // For now we increase receive buffer, whenever send buffer is set.
  897. // The size is not configurable. The constant taken from FZ.
  898. p_setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*) &rcvbuf, sizeof(rcvbuf));
  899. }
  900. /*
  901. * Bind to local address.
  902. */
  903. if (sock->privport)
  904. localport = 1023; /* count from 1023 downwards */
  905. else
  906. localport = 0; /* just use port 0 (ie winsock picks) */
  907. /* Loop round trying to bind */
  908. while (1) {
  909. int sockcode;
  910. #ifndef NO_IPV6
  911. if (family == AF_INET6) {
  912. memset(&a6, 0, sizeof(a6));
  913. a6.sin6_family = AF_INET6;
  914. /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
  915. a6.sin6_port = p_htons(localport);
  916. } else
  917. #endif
  918. {
  919. a.sin_family = AF_INET;
  920. if (srcaddr && srcaddr[0]) {
  921. a.sin_addr.s_addr = p_inet_addr(srcaddr);
  922. } else {
  923. a.sin_addr.s_addr = p_htonl(INADDR_ANY);
  924. }
  925. a.sin_port = p_htons(localport);
  926. }
  927. #ifndef NO_IPV6
  928. sockcode = p_bind(s, (family == AF_INET6 ?
  929. (struct sockaddr *) &a6 :
  930. (struct sockaddr *) &a),
  931. (family == AF_INET6 ? sizeof(a6) : sizeof(a)));
  932. #else
  933. sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
  934. #endif
  935. if (sockcode != SOCKET_ERROR) {
  936. err = 0;
  937. break; /* done */
  938. } else {
  939. err = p_WSAGetLastError();
  940. if (err != WSAEADDRINUSE) /* failed, for a bad reason */
  941. break;
  942. }
  943. if (localport == 0)
  944. break; /* we're only looping once */
  945. localport--;
  946. if (localport == 0)
  947. break; /* we might have got to the end */
  948. }
  949. if (err) {
  950. sock->error = winsock_error_string(err);
  951. goto ret;
  952. }
  953. /*
  954. * Connect to remote address.
  955. */
  956. #ifndef NO_IPV6
  957. if (sock->step.ai) {
  958. if (family == AF_INET6) {
  959. a6.sin6_family = AF_INET6;
  960. a6.sin6_port = p_htons((short) sock->port);
  961. a6.sin6_addr =
  962. ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr;
  963. a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo;
  964. a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id;
  965. } else {
  966. a.sin_family = AF_INET;
  967. a.sin_addr =
  968. ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr;
  969. a.sin_port = p_htons((short) sock->port);
  970. }
  971. } else
  972. #endif
  973. {
  974. assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses);
  975. a.sin_family = AF_INET;
  976. a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]);
  977. a.sin_port = p_htons((short) sock->port);
  978. }
  979. #ifndef MPEXT
  980. /* Set up a select mechanism. This could be an AsyncSelect on a
  981. * window, or an EventSelect on an event object. */
  982. errstr = do_select(s, true);
  983. if (errstr) {
  984. sock->error = errstr;
  985. err = 1;
  986. goto ret;
  987. }
  988. #endif
  989. #ifdef MPEXT
  990. if (timeout > 0)
  991. {
  992. if (p_getsockopt (s, SOL_SOCKET, SO_RCVTIMEO, (char *)&rcvtimeo, &rcvtimeo) < 0)
  993. {
  994. rcvtimeo.tv_sec = -1;
  995. }
  996. else
  997. {
  998. struct timeval timeoutval;
  999. timeoutval.tv_sec = timeout / 1000;
  1000. timeoutval.tv_usec = (timeout % 1000) * 1000;
  1001. p_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *) &timeoutval, sizeof(timeoutval));
  1002. }
  1003. }
  1004. #endif
  1005. if ((
  1006. #ifndef NO_IPV6
  1007. p_connect(s,
  1008. ((family == AF_INET6) ? (struct sockaddr *) &a6 :
  1009. (struct sockaddr *) &a),
  1010. (family == AF_INET6) ? sizeof(a6) : sizeof(a))
  1011. #else
  1012. p_connect(s, (struct sockaddr *) &a, sizeof(a))
  1013. #endif
  1014. ) == SOCKET_ERROR) {
  1015. err = p_WSAGetLastError();
  1016. /*
  1017. * We expect a potential EWOULDBLOCK here, because the
  1018. * chances are the front end has done a select for
  1019. * FD_CONNECT, so that connect() will complete
  1020. * asynchronously.
  1021. */
  1022. if ( err != WSAEWOULDBLOCK ) {
  1023. #ifdef MPEXT
  1024. // unselect on error
  1025. do_select(sock->plug, s, 0);
  1026. #endif
  1027. sock->error = winsock_error_string(err);
  1028. goto ret;
  1029. }
  1030. } else {
  1031. /*
  1032. * If we _don't_ get EWOULDBLOCK, the connect has completed
  1033. * and we should set the socket as writable.
  1034. */
  1035. sock->writable = true;
  1036. { // WINSCP
  1037. SockAddr thisaddr = sk_extractaddr_tmp(sock->addr, &sock->step);
  1038. plug_log(sock->plug, PLUGLOG_CONNECT_SUCCESS,
  1039. &thisaddr, sock->port, NULL, 0);
  1040. } // WINSCP
  1041. }
  1042. #ifdef MPEXT
  1043. if ((timeout > 0) && (rcvtimeo.tv_sec >= 0))
  1044. {
  1045. p_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *) &rcvtimeo, sizeof(rcvtimeo));
  1046. }
  1047. // MP: Calling EventSelect only after connect makes sure we receive FD_CLOSE.
  1048. /* Set up a select mechanism. This could be an AsyncSelect on a
  1049. * window, or an EventSelect on an event object. */
  1050. errstr = do_select(sock->plug, s, 1);
  1051. if (errstr) {
  1052. sock->error = errstr;
  1053. err = 1;
  1054. goto ret;
  1055. }
  1056. #endif
  1057. err = 0;
  1058. ret:
  1059. /*
  1060. * No matter what happened, put the socket back in the tree.
  1061. */
  1062. add234(sktree, sock);
  1063. if (err) {
  1064. SockAddr thisaddr = sk_extractaddr_tmp(
  1065. sock->addr, &sock->step);
  1066. plug_log(sock->plug, PLUGLOG_CONNECT_FAILED,
  1067. &thisaddr, sock->port, sock->error, err);
  1068. }
  1069. return err;
  1070. }
  1071. Socket *sk_new(SockAddr *addr, int port, bool privport, bool oobinline,
  1072. bool nodelay, bool keepalive, Plug *plug,
  1073. #ifdef MPEXT
  1074. int timeout,
  1075. int sndbuf,
  1076. const char *srcaddr
  1077. #endif
  1078. )
  1079. {
  1080. NetSocket *ret;
  1081. DWORD err;
  1082. /*
  1083. * Create NetSocket structure.
  1084. */
  1085. ret = snew(NetSocket);
  1086. ret->sock.vt = &NetSocket_sockvt;
  1087. ret->error = NULL;
  1088. ret->plug = plug;
  1089. bufchain_init(&ret->output_data);
  1090. ret->connected = false; /* to start with */
  1091. ret->writable = false; /* to start with */
  1092. ret->sending_oob = 0;
  1093. ret->outgoingeof = EOF_NO;
  1094. ret->frozen = false;
  1095. ret->frozen_readable = false;
  1096. ret->localhost_only = false; /* unused, but best init anyway */
  1097. ret->pending_error = 0;
  1098. ret->parent = ret->child = NULL;
  1099. ret->oobinline = oobinline;
  1100. ret->nodelay = nodelay;
  1101. ret->keepalive = keepalive;
  1102. ret->privport = privport;
  1103. ret->port = port;
  1104. ret->addr = addr;
  1105. START_STEP(ret->addr, ret->step);
  1106. ret->s = INVALID_SOCKET;
  1107. err = 0;
  1108. do {
  1109. #ifdef MPEXT
  1110. ret->error = NULL;
  1111. #endif
  1112. err = try_connect(ret
  1113. #ifdef MPEXT
  1114. , timeout, sndbuf, srcaddr
  1115. #endif
  1116. );
  1117. } while (err && sk_nextaddr(ret->addr, &ret->step));
  1118. return &ret->sock;
  1119. }
  1120. Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug,
  1121. bool local_host_only, int orig_address_family)
  1122. {
  1123. SOCKET s;
  1124. #ifndef NO_IPV6
  1125. SOCKADDR_IN6 a6;
  1126. #endif
  1127. SOCKADDR_IN a;
  1128. DWORD err;
  1129. const char *errstr;
  1130. NetSocket *ret;
  1131. int retcode;
  1132. int address_family;
  1133. /*
  1134. * Create NetSocket structure.
  1135. */
  1136. ret = snew(NetSocket);
  1137. ret->sock.vt = &NetSocket_sockvt;
  1138. ret->error = NULL;
  1139. ret->plug = plug;
  1140. bufchain_init(&ret->output_data);
  1141. ret->writable = false; /* to start with */
  1142. ret->sending_oob = 0;
  1143. ret->outgoingeof = EOF_NO;
  1144. ret->frozen = false;
  1145. ret->frozen_readable = false;
  1146. ret->localhost_only = local_host_only;
  1147. ret->pending_error = 0;
  1148. ret->parent = ret->child = NULL;
  1149. ret->addr = NULL;
  1150. /*
  1151. * Translate address_family from platform-independent constants
  1152. * into local reality.
  1153. */
  1154. address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
  1155. #ifndef NO_IPV6
  1156. orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  1157. #endif
  1158. AF_UNSPEC);
  1159. /*
  1160. * Our default, if passed the `don't care' value
  1161. * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
  1162. * we will also set up a second socket listening on IPv6, but
  1163. * the v4 one is primary since that ought to work even on
  1164. * non-v6-supporting systems.
  1165. */
  1166. if (address_family == AF_UNSPEC) address_family = AF_INET;
  1167. /*
  1168. * Open socket.
  1169. */
  1170. s = p_socket(address_family, SOCK_STREAM, 0);
  1171. ret->s = s;
  1172. if (s == INVALID_SOCKET) {
  1173. err = p_WSAGetLastError();
  1174. ret->error = winsock_error_string(err);
  1175. return &ret->sock;
  1176. }
  1177. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  1178. ret->oobinline = false;
  1179. {
  1180. BOOL on = true;
  1181. p_setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  1182. (const char *)&on, sizeof(on));
  1183. }
  1184. #ifndef NO_IPV6
  1185. if (address_family == AF_INET6) {
  1186. memset(&a6, 0, sizeof(a6));
  1187. a6.sin6_family = AF_INET6;
  1188. if (local_host_only)
  1189. a6.sin6_addr = in6addr_loopback;
  1190. else
  1191. a6.sin6_addr = in6addr_any;
  1192. if (srcaddr != NULL && p_getaddrinfo) {
  1193. struct addrinfo hints;
  1194. struct addrinfo *ai;
  1195. int err;
  1196. memset(&hints, 0, sizeof(hints));
  1197. hints.ai_family = AF_INET6;
  1198. hints.ai_flags = 0;
  1199. {
  1200. /* strip [] on IPv6 address literals */
  1201. char *trimmed_addr = host_strduptrim(srcaddr);
  1202. err = p_getaddrinfo(trimmed_addr, NULL, &hints, &ai);
  1203. sfree(trimmed_addr);
  1204. }
  1205. if (err == 0 && ai->ai_family == AF_INET6) {
  1206. a6.sin6_addr =
  1207. ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
  1208. }
  1209. }
  1210. a6.sin6_port = p_htons(port);
  1211. } else
  1212. #endif
  1213. {
  1214. bool got_addr = false;
  1215. a.sin_family = AF_INET;
  1216. /*
  1217. * Bind to source address. First try an explicitly
  1218. * specified one...
  1219. */
  1220. if (srcaddr) {
  1221. a.sin_addr.s_addr = p_inet_addr(srcaddr);
  1222. if (a.sin_addr.s_addr != INADDR_NONE) {
  1223. /* Override localhost_only with specified listen addr. */
  1224. ret->localhost_only = ipv4_is_loopback(a.sin_addr);
  1225. got_addr = true;
  1226. }
  1227. }
  1228. /*
  1229. * ... and failing that, go with one of the standard ones.
  1230. */
  1231. if (!got_addr) {
  1232. if (local_host_only)
  1233. a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
  1234. else
  1235. a.sin_addr.s_addr = p_htonl(INADDR_ANY);
  1236. }
  1237. a.sin_port = p_htons((short)port);
  1238. }
  1239. #ifndef NO_IPV6
  1240. retcode = p_bind(s, (address_family == AF_INET6 ?
  1241. (struct sockaddr *) &a6 :
  1242. (struct sockaddr *) &a),
  1243. (address_family ==
  1244. AF_INET6 ? sizeof(a6) : sizeof(a)));
  1245. #else
  1246. retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
  1247. #endif
  1248. if (retcode != SOCKET_ERROR) {
  1249. err = 0;
  1250. } else {
  1251. err = p_WSAGetLastError();
  1252. }
  1253. if (err) {
  1254. p_closesocket(s);
  1255. ret->error = winsock_error_string(err);
  1256. return &ret->sock;
  1257. }
  1258. if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
  1259. p_closesocket(s);
  1260. ret->error = winsock_error_string(p_WSAGetLastError());
  1261. return &ret->sock;
  1262. }
  1263. /* Set up a select mechanism. This could be an AsyncSelect on a
  1264. * window, or an EventSelect on an event object. */
  1265. #ifdef MPEXT
  1266. errstr = do_select(plug, s, true);
  1267. #else
  1268. errstr = do_select(s, true);
  1269. #endif
  1270. if (errstr) {
  1271. p_closesocket(s);
  1272. ret->error = errstr;
  1273. return &ret->sock;
  1274. }
  1275. add234(sktree, ret);
  1276. #ifndef NO_IPV6
  1277. /*
  1278. * If we were given ADDRTYPE_UNSPEC, we must also create an
  1279. * IPv6 listening socket and link it to this one.
  1280. */
  1281. if (address_family == AF_INET && orig_address_family == ADDRTYPE_UNSPEC) {
  1282. Socket *other = sk_newlistener(srcaddr, port, plug,
  1283. local_host_only, ADDRTYPE_IPV6);
  1284. if (other) {
  1285. NetSocket *ns = container_of(other, NetSocket, sock);
  1286. if (!ns->error) {
  1287. ns->parent = ret;
  1288. ret->child = ns;
  1289. } else {
  1290. sfree(ns);
  1291. }
  1292. }
  1293. }
  1294. #endif
  1295. return &ret->sock;
  1296. }
  1297. static void sk_net_close(Socket *sock)
  1298. {
  1299. NetSocket *s = container_of(sock, NetSocket, sock);
  1300. if (s->child)
  1301. sk_net_close(&s->child->sock);
  1302. bufchain_clear(&s->output_data);
  1303. del234(sktree, s);
  1304. #ifdef MPEXT
  1305. do_select(s->plug, s->s, false);
  1306. #else
  1307. do_select(s->s, false);
  1308. #endif
  1309. p_closesocket(s->s);
  1310. if (s->addr)
  1311. sk_addr_free(s->addr);
  1312. delete_callbacks_for_context(get_callback_set(s->plug), s);
  1313. sfree(s);
  1314. }
  1315. /*
  1316. * Deal with socket errors detected in try_send().
  1317. */
  1318. static void socket_error_callback(void *vs)
  1319. {
  1320. NetSocket *s = (NetSocket *)vs;
  1321. /*
  1322. * Just in case other socket work has caused this socket to vanish
  1323. * or become somehow non-erroneous before this callback arrived...
  1324. */
  1325. if (!find234(sktree, s, NULL) || !s->pending_error)
  1326. return;
  1327. /*
  1328. * An error has occurred on this socket. Pass it to the plug.
  1329. */
  1330. plug_closing(s->plug, winsock_error_string(s->pending_error),
  1331. s->pending_error, 0);
  1332. }
  1333. /*
  1334. * The function which tries to send on a socket once it's deemed
  1335. * writable.
  1336. */
  1337. void try_send(NetSocket *s)
  1338. {
  1339. while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
  1340. int nsent;
  1341. DWORD err;
  1342. const void *data;
  1343. size_t len;
  1344. int urgentflag;
  1345. if (s->sending_oob) {
  1346. urgentflag = MSG_OOB;
  1347. len = s->sending_oob;
  1348. data = &s->oobdata;
  1349. } else {
  1350. urgentflag = 0;
  1351. { // WINSCP
  1352. ptrlen bufdata = bufchain_prefix(&s->output_data);
  1353. data = bufdata.ptr;
  1354. len = bufdata.len;
  1355. } // WINSCP
  1356. }
  1357. len = min(len, INT_MAX); /* WinSock send() takes an int */
  1358. nsent = p_send(s->s, data, len, urgentflag);
  1359. noise_ultralight(NOISE_SOURCE_IOLEN, nsent);
  1360. if (nsent <= 0) {
  1361. err = (nsent < 0 ? p_WSAGetLastError() : 0);
  1362. if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
  1363. /*
  1364. * Perfectly normal: we've sent all we can for the moment.
  1365. *
  1366. * (Some WinSock send() implementations can return
  1367. * <0 but leave no sensible error indication -
  1368. * WSAGetLastError() is called but returns zero or
  1369. * a small number - so we check that case and treat
  1370. * it just like WSAEWOULDBLOCK.)
  1371. */
  1372. s->writable = false;
  1373. return;
  1374. } else {
  1375. /*
  1376. * If send() returns a socket error, we unfortunately
  1377. * can't just call plug_closing(), because it's quite
  1378. * likely that we're currently _in_ a call from the
  1379. * code we'd be calling back to, so we'd have to make
  1380. * half the SSH code reentrant. Instead we flag a
  1381. * pending error on the socket, to be dealt with (by
  1382. * calling plug_closing()) at some suitable future
  1383. * moment.
  1384. */
  1385. s->pending_error = err;
  1386. queue_toplevel_callback(get_callback_set(s->plug), socket_error_callback, s);
  1387. return;
  1388. }
  1389. } else {
  1390. if (s->sending_oob) {
  1391. if (nsent < len) {
  1392. memmove(s->oobdata, s->oobdata+nsent, len-nsent);
  1393. s->sending_oob = len - nsent;
  1394. } else {
  1395. s->sending_oob = 0;
  1396. }
  1397. } else {
  1398. bufchain_consume(&s->output_data, nsent);
  1399. }
  1400. }
  1401. }
  1402. /*
  1403. * If we reach here, we've finished sending everything we might
  1404. * have needed to send. Send EOF, if we need to.
  1405. */
  1406. if (s->outgoingeof == EOF_PENDING) {
  1407. p_shutdown(s->s, SD_SEND);
  1408. s->outgoingeof = EOF_SENT;
  1409. }
  1410. }
  1411. static size_t sk_net_write(Socket *sock, const void *buf, size_t len)
  1412. {
  1413. NetSocket *s = container_of(sock, NetSocket, sock);
  1414. assert(s->outgoingeof == EOF_NO);
  1415. /*
  1416. * Add the data to the buffer list on the socket.
  1417. */
  1418. bufchain_add(&s->output_data, buf, len);
  1419. /*
  1420. * Now try sending from the start of the buffer list.
  1421. */
  1422. if (s->writable)
  1423. try_send(s);
  1424. return bufchain_size(&s->output_data);
  1425. }
  1426. static size_t sk_net_write_oob(Socket *sock, const void *buf, size_t len)
  1427. {
  1428. NetSocket *s = container_of(sock, NetSocket, sock);
  1429. assert(s->outgoingeof == EOF_NO);
  1430. /*
  1431. * Replace the buffer list on the socket with the data.
  1432. */
  1433. bufchain_clear(&s->output_data);
  1434. assert(len <= sizeof(s->oobdata));
  1435. memcpy(s->oobdata, buf, len);
  1436. s->sending_oob = len;
  1437. /*
  1438. * Now try sending from the start of the buffer list.
  1439. */
  1440. if (s->writable)
  1441. try_send(s);
  1442. return s->sending_oob;
  1443. }
  1444. static void sk_net_write_eof(Socket *sock)
  1445. {
  1446. NetSocket *s = container_of(sock, NetSocket, sock);
  1447. assert(s->outgoingeof == EOF_NO);
  1448. /*
  1449. * Mark the socket as pending outgoing EOF.
  1450. */
  1451. s->outgoingeof = EOF_PENDING;
  1452. /*
  1453. * Now try sending from the start of the buffer list.
  1454. */
  1455. if (s->writable)
  1456. try_send(s);
  1457. }
  1458. void select_result(WPARAM wParam, LPARAM lParam)
  1459. {
  1460. int ret;
  1461. DWORD err;
  1462. char buf[20480]; /* nice big buffer for plenty of speed */
  1463. NetSocket *s;
  1464. bool atmark;
  1465. /* wParam is the socket itself */
  1466. if (wParam == 0)
  1467. return; /* boggle */
  1468. s = find234(sktree, (void *) wParam, cmpforsearch);
  1469. if (!s)
  1470. return; /* boggle */
  1471. if ((err = WSAGETSELECTERROR(lParam)) != 0) {
  1472. /*
  1473. * An error has occurred on this socket. Pass it to the
  1474. * plug.
  1475. */
  1476. if (s->addr) {
  1477. SockAddr thisaddr = sk_extractaddr_tmp(
  1478. s->addr, &s->step);
  1479. plug_log(s->plug, PLUGLOG_CONNECT_FAILED, &thisaddr, s->port,
  1480. winsock_error_string(err), err);
  1481. while (err && s->addr && sk_nextaddr(s->addr, &s->step)) {
  1482. err = try_connect(s
  1483. #ifdef MPEXT
  1484. , 0, 0, NULL
  1485. #endif
  1486. );
  1487. }
  1488. }
  1489. if (err != 0)
  1490. {
  1491. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1492. }
  1493. return;
  1494. }
  1495. noise_ultralight(NOISE_SOURCE_IOID, wParam);
  1496. switch (WSAGETSELECTEVENT(lParam)) {
  1497. case FD_CONNECT:
  1498. s->connected = true;
  1499. s->writable = true;
  1500. /*
  1501. * Once a socket is connected, we can stop falling back
  1502. * through the candidate addresses to connect to. But first,
  1503. * let the plug know we were successful.
  1504. */
  1505. if (s->addr) {
  1506. SockAddr thisaddr = sk_extractaddr_tmp(
  1507. s->addr, &s->step);
  1508. plug_log(s->plug, PLUGLOG_CONNECT_SUCCESS,
  1509. &thisaddr, s->port, NULL, 0);
  1510. sk_addr_free(s->addr);
  1511. s->addr = NULL;
  1512. }
  1513. break;
  1514. case FD_READ:
  1515. /* In the case the socket is still frozen, we don't even bother */
  1516. if (s->frozen) {
  1517. s->frozen_readable = true;
  1518. break;
  1519. }
  1520. /*
  1521. * We have received data on the socket. For an oobinline
  1522. * socket, this might be data _before_ an urgent pointer,
  1523. * in which case we send it to the back end with type==1
  1524. * (data prior to urgent).
  1525. */
  1526. if (s->oobinline) {
  1527. u_long atmark_from_ioctl = 1;
  1528. p_ioctlsocket(s->s, SIOCATMARK, &atmark_from_ioctl);
  1529. /*
  1530. * Avoid checking the return value from ioctlsocket(),
  1531. * on the grounds that some WinSock wrappers don't
  1532. * support it. If it does nothing, we get atmark==1,
  1533. * which is equivalent to `no OOB pending', so the
  1534. * effect will be to non-OOB-ify any OOB data.
  1535. */
  1536. atmark = atmark_from_ioctl;
  1537. } else
  1538. atmark = true;
  1539. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1540. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1541. if (ret < 0) {
  1542. err = p_WSAGetLastError();
  1543. if (err == WSAEWOULDBLOCK) {
  1544. break;
  1545. }
  1546. }
  1547. if (ret < 0) {
  1548. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1549. } else if (0 == ret) {
  1550. plug_closing(s->plug, NULL, 0, 0);
  1551. } else {
  1552. plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
  1553. }
  1554. break;
  1555. case FD_OOB:
  1556. /*
  1557. * This will only happen on a non-oobinline socket. It
  1558. * indicates that we can immediately perform an OOB read
  1559. * and get back OOB data, which we will send to the back
  1560. * end with type==2 (urgent data).
  1561. */
  1562. ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
  1563. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1564. if (ret <= 0) {
  1565. int err = p_WSAGetLastError();
  1566. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1567. } else {
  1568. plug_receive(s->plug, 2, buf, ret);
  1569. }
  1570. break;
  1571. case FD_WRITE: {
  1572. int bufsize_before, bufsize_after;
  1573. s->writable = true;
  1574. bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
  1575. try_send(s);
  1576. bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
  1577. if (bufsize_after < bufsize_before)
  1578. plug_sent(s->plug, bufsize_after);
  1579. break;
  1580. }
  1581. case FD_CLOSE:
  1582. /* Signal a close on the socket. First read any outstanding data. */
  1583. do {
  1584. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1585. if (ret < 0) {
  1586. err = p_WSAGetLastError();
  1587. if (err == WSAEWOULDBLOCK)
  1588. break;
  1589. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1590. } else {
  1591. if (ret)
  1592. plug_receive(s->plug, 0, buf, ret);
  1593. else
  1594. {
  1595. plug_closing(s->plug, NULL, 0, 0);
  1596. }
  1597. }
  1598. } while (ret > 0);
  1599. return;
  1600. case FD_ACCEPT: {
  1601. #ifdef NO_IPV6
  1602. struct sockaddr_in isa;
  1603. #else
  1604. struct sockaddr_storage isa;
  1605. #endif
  1606. int addrlen = sizeof(isa);
  1607. SOCKET t; /* socket of connection */
  1608. accept_ctx_t actx;
  1609. memset(&isa, 0, sizeof(isa));
  1610. err = 0;
  1611. t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
  1612. if (t == INVALID_SOCKET)
  1613. {
  1614. err = p_WSAGetLastError();
  1615. if (err == WSATRY_AGAIN)
  1616. break;
  1617. }
  1618. actx.p = (void *)t;
  1619. #ifndef NO_IPV6
  1620. if (isa.ss_family == AF_INET &&
  1621. s->localhost_only &&
  1622. !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
  1623. #else
  1624. if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
  1625. #endif
  1626. {
  1627. p_closesocket(t); /* dodgy WinSock let nonlocal through */
  1628. } else if (plug_accepting(s->plug, sk_net_accept, actx)) {
  1629. p_closesocket(t); /* denied or error */
  1630. }
  1631. break;
  1632. }
  1633. }
  1634. }
  1635. /*
  1636. * Special error values are returned from sk_namelookup and sk_new
  1637. * if there's a problem. These functions extract an error message,
  1638. * or return NULL if there's no problem.
  1639. */
  1640. const char *sk_addr_error(SockAddr *addr)
  1641. {
  1642. return addr->error;
  1643. }
  1644. static const char *sk_net_socket_error(Socket *sock)
  1645. {
  1646. NetSocket *s = container_of(sock, NetSocket, sock);
  1647. return s->error;
  1648. }
  1649. static SocketPeerInfo *sk_net_peer_info(Socket *sock)
  1650. {
  1651. NetSocket *s = container_of(sock, NetSocket, sock);
  1652. #ifdef NO_IPV6
  1653. struct sockaddr_in addr;
  1654. #else
  1655. struct sockaddr_storage addr;
  1656. char buf[INET6_ADDRSTRLEN];
  1657. #endif
  1658. int addrlen = sizeof(addr);
  1659. SocketPeerInfo *pi;
  1660. if (p_getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
  1661. return NULL;
  1662. pi = snew(SocketPeerInfo);
  1663. pi->addressfamily = ADDRTYPE_UNSPEC;
  1664. pi->addr_text = NULL;
  1665. pi->port = -1;
  1666. pi->log_text = NULL;
  1667. if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
  1668. pi->addressfamily = ADDRTYPE_IPV4;
  1669. memcpy(pi->addr_bin.ipv4, &((struct sockaddr_in *)&addr)->sin_addr, 4);
  1670. pi->port = p_ntohs(((struct sockaddr_in *)&addr)->sin_port);
  1671. pi->addr_text = dupstr(
  1672. p_inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr));
  1673. pi->log_text = dupprintf("%s:%d", pi->addr_text, pi->port);
  1674. #ifndef NO_IPV6
  1675. } else if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
  1676. pi->addressfamily = ADDRTYPE_IPV6;
  1677. memcpy(pi->addr_bin.ipv6,
  1678. &((struct sockaddr_in6 *)&addr)->sin6_addr, 16);
  1679. pi->port = p_ntohs(((struct sockaddr_in6 *)&addr)->sin6_port);
  1680. pi->addr_text = dupstr(
  1681. p_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
  1682. buf, sizeof(buf)));
  1683. pi->log_text = dupprintf("[%s]:%d", pi->addr_text, pi->port);
  1684. #endif
  1685. } else {
  1686. sfree(pi);
  1687. return NULL;
  1688. }
  1689. return pi;
  1690. }
  1691. static void sk_net_set_frozen(Socket *sock, bool is_frozen)
  1692. {
  1693. NetSocket *s = container_of(sock, NetSocket, sock);
  1694. if (s->frozen == is_frozen)
  1695. return;
  1696. s->frozen = is_frozen;
  1697. if (!is_frozen) {
  1698. #ifdef MPEXT
  1699. do_select(s->plug, s->s, true);
  1700. #else
  1701. do_select(s->s, true);
  1702. #endif
  1703. if (s->frozen_readable) {
  1704. char c;
  1705. p_recv(s->s, &c, 1, MSG_PEEK);
  1706. }
  1707. }
  1708. s->frozen_readable = false;
  1709. }
  1710. void socket_reselect_all(void)
  1711. {
  1712. NetSocket *s;
  1713. int i;
  1714. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  1715. if (!s->frozen)
  1716. #ifdef MPEXT
  1717. do_select(s->plug, s->s, true);
  1718. #else
  1719. do_select(s->s, true);
  1720. #endif
  1721. }
  1722. }
  1723. /*
  1724. * For Plink: enumerate all sockets currently active.
  1725. */
  1726. SOCKET first_socket(int *state)
  1727. {
  1728. NetSocket *s;
  1729. *state = 0;
  1730. s = index234(sktree, (*state)++);
  1731. return s ? s->s : INVALID_SOCKET;
  1732. }
  1733. SOCKET next_socket(int *state)
  1734. {
  1735. NetSocket *s = index234(sktree, (*state)++);
  1736. return s ? s->s : INVALID_SOCKET;
  1737. }
  1738. bool socket_writable(SOCKET skt)
  1739. {
  1740. NetSocket *s = find234(sktree, (void *)skt, cmpforsearch);
  1741. if (s)
  1742. return bufchain_size(&s->output_data) > 0;
  1743. else
  1744. return false;
  1745. }
  1746. int net_service_lookup(char *service)
  1747. {
  1748. struct servent *se;
  1749. se = p_getservbyname(service, NULL);
  1750. if (se != NULL)
  1751. return p_ntohs(se->s_port);
  1752. else
  1753. return 0;
  1754. }
  1755. char *get_hostname(void)
  1756. {
  1757. char hostbuf[256]; /* MSDN docs for gethostname() promise this is enough */
  1758. if (p_gethostname(hostbuf, sizeof(hostbuf)) < 0)
  1759. return NULL;
  1760. return dupstr(hostbuf);
  1761. }
  1762. SockAddr *platform_get_x11_unix_address(const char *display, int displaynum)
  1763. {
  1764. SockAddr *ret = snew(SockAddr);
  1765. memset(ret, 0, sizeof(SockAddr));
  1766. ret->error = "unix sockets not supported on this platform";
  1767. ret->refcount = 1;
  1768. return ret;
  1769. }