PageRenderTime 421ms CodeModel.GetById 33ms RepoModel.GetById 3ms app.codeStats 1ms

/src/TortoisePlink/Windows/WINNET.C

https://gitlab.com/info29/tortoisegit
C | 1877 lines | 1445 code | 181 blank | 251 comment | 271 complexity | 456de8ec8af82affc185d79ebd966a69 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, MPL-2.0-no-copyleft-exception

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

Large files files are truncated, but you can click here to view the full file