winnet.c 54 KB

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