PageRenderTime 885ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/windows/winnet.c

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