PageRenderTime 57ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/windows/winnet.c

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