winnet.c 51 KB

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