uxnet.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  1. /*
  2. * Unix networking abstraction.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <sys/types.h>
  11. #include <sys/socket.h>
  12. #include <sys/ioctl.h>
  13. #include <arpa/inet.h>
  14. #include <netinet/in.h>
  15. #include <netinet/tcp.h>
  16. #include <netdb.h>
  17. #include <sys/un.h>
  18. #include <pwd.h>
  19. #include <grp.h>
  20. #define DEFINE_PLUG_METHOD_MACROS
  21. #include "putty.h"
  22. #include "network.h"
  23. #include "tree234.h"
  24. /* Solaris needs <sys/sockio.h> for SIOCATMARK. */
  25. #ifndef SIOCATMARK
  26. #include <sys/sockio.h>
  27. #endif
  28. #ifndef X11_UNIX_PATH
  29. # define X11_UNIX_PATH "/tmp/.X11-unix/X"
  30. #endif
  31. /*
  32. * Access to sockaddr types without breaking C strict aliasing rules.
  33. */
  34. union sockaddr_union {
  35. struct sockaddr_storage storage;
  36. struct sockaddr sa;
  37. struct sockaddr_in sin;
  38. #ifndef NO_IPV6
  39. struct sockaddr_in6 sin6;
  40. #endif
  41. struct sockaddr_un su;
  42. };
  43. /*
  44. * We used to typedef struct Socket_tag *Socket.
  45. *
  46. * Since we have made the networking abstraction slightly more
  47. * abstract, Socket no longer means a tcp socket (it could mean
  48. * an ssl socket). So now we must use Actual_Socket when we know
  49. * we are talking about a tcp socket.
  50. */
  51. typedef struct Socket_tag *Actual_Socket;
  52. /*
  53. * Mutable state that goes with a SockAddr: stores information
  54. * about where in the list of candidate IP(v*) addresses we've
  55. * currently got to.
  56. */
  57. typedef struct SockAddrStep_tag SockAddrStep;
  58. struct SockAddrStep_tag {
  59. #ifndef NO_IPV6
  60. struct addrinfo *ai; /* steps along addr->ais */
  61. #endif
  62. int curraddr;
  63. };
  64. struct Socket_tag {
  65. struct socket_function_table *fn;
  66. /* the above variable absolutely *must* be the first in this structure */
  67. const char *error;
  68. int s;
  69. Plug plug;
  70. bufchain output_data;
  71. int connected; /* irrelevant for listening sockets */
  72. int writable;
  73. int frozen; /* this causes readability notifications to be ignored */
  74. int localhost_only; /* for listening sockets */
  75. char oobdata[1];
  76. int sending_oob;
  77. int oobpending; /* is there OOB data available to read? */
  78. int oobinline;
  79. enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
  80. int incomingeof;
  81. int pending_error; /* in case send() returns error */
  82. int listener;
  83. int nodelay, keepalive; /* for connect()-type sockets */
  84. int privport, port; /* and again */
  85. SockAddr addr;
  86. SockAddrStep step;
  87. /*
  88. * We sometimes need pairs of Socket structures to be linked:
  89. * if we are listening on the same IPv6 and v4 port, for
  90. * example. So here we define `parent' and `child' pointers to
  91. * track this link.
  92. */
  93. Actual_Socket parent, child;
  94. };
  95. struct SockAddr_tag {
  96. int refcount;
  97. const char *error;
  98. enum { UNRESOLVED, UNIX, IP } superfamily;
  99. #ifndef NO_IPV6
  100. struct addrinfo *ais; /* Addresses IPv6 style. */
  101. #else
  102. unsigned long *addresses; /* Addresses IPv4 style. */
  103. int naddresses;
  104. #endif
  105. char hostname[512]; /* Store an unresolved host name. */
  106. };
  107. /*
  108. * Which address family this address belongs to. AF_INET for IPv4;
  109. * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
  110. * not been done and a simple host name is held in this SockAddr
  111. * structure.
  112. */
  113. #ifndef NO_IPV6
  114. #define SOCKADDR_FAMILY(addr, step) \
  115. ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
  116. (addr)->superfamily == UNIX ? AF_UNIX : \
  117. (step).ai ? (step).ai->ai_family : AF_INET)
  118. #else
  119. /* Here we gratuitously reference 'step' to avoid gcc warnings about
  120. * 'set but not used' when compiling -DNO_IPV6 */
  121. #define SOCKADDR_FAMILY(addr, step) \
  122. ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
  123. (addr)->superfamily == UNIX ? AF_UNIX : \
  124. (step).curraddr ? AF_INET : AF_INET)
  125. #endif
  126. /*
  127. * Start a SockAddrStep structure to step through multiple
  128. * addresses.
  129. */
  130. #ifndef NO_IPV6
  131. #define START_STEP(addr, step) \
  132. ((step).ai = (addr)->ais, (step).curraddr = 0)
  133. #else
  134. #define START_STEP(addr, step) \
  135. ((step).curraddr = 0)
  136. #endif
  137. static tree234 *sktree;
  138. static void uxsel_tell(Actual_Socket s);
  139. static int cmpfortree(void *av, void *bv)
  140. {
  141. Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
  142. int as = a->s, bs = b->s;
  143. if (as < bs)
  144. return -1;
  145. if (as > bs)
  146. return +1;
  147. if (a < b)
  148. return -1;
  149. if (a > b)
  150. return +1;
  151. return 0;
  152. }
  153. static int cmpforsearch(void *av, void *bv)
  154. {
  155. Actual_Socket b = (Actual_Socket) bv;
  156. int as = *(int *)av, bs = b->s;
  157. if (as < bs)
  158. return -1;
  159. if (as > bs)
  160. return +1;
  161. return 0;
  162. }
  163. void sk_init(void)
  164. {
  165. sktree = newtree234(cmpfortree);
  166. }
  167. void sk_cleanup(void)
  168. {
  169. Actual_Socket s;
  170. int i;
  171. if (sktree) {
  172. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  173. close(s->s);
  174. }
  175. }
  176. }
  177. SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
  178. {
  179. SockAddr ret = snew(struct SockAddr_tag);
  180. #ifndef NO_IPV6
  181. struct addrinfo hints;
  182. int err;
  183. #else
  184. unsigned long a;
  185. struct hostent *h = NULL;
  186. int n;
  187. #endif
  188. char realhost[8192];
  189. /* Clear the structure and default to IPv4. */
  190. memset(ret, 0, sizeof(struct SockAddr_tag));
  191. ret->superfamily = UNRESOLVED;
  192. *realhost = '\0';
  193. ret->error = NULL;
  194. ret->refcount = 1;
  195. #ifndef NO_IPV6
  196. hints.ai_flags = AI_CANONNAME;
  197. hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
  198. address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  199. AF_UNSPEC);
  200. hints.ai_socktype = SOCK_STREAM;
  201. hints.ai_protocol = 0;
  202. hints.ai_addrlen = 0;
  203. hints.ai_addr = NULL;
  204. hints.ai_canonname = NULL;
  205. hints.ai_next = NULL;
  206. {
  207. char *trimmed_host = host_strduptrim(host); /* strip [] on literals */
  208. err = getaddrinfo(trimmed_host, NULL, &hints, &ret->ais);
  209. sfree(trimmed_host);
  210. }
  211. if (err != 0) {
  212. ret->error = gai_strerror(err);
  213. return ret;
  214. }
  215. ret->superfamily = IP;
  216. *realhost = '\0';
  217. if (ret->ais->ai_canonname != NULL)
  218. strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
  219. else
  220. strncat(realhost, host, sizeof(realhost) - 1);
  221. #else
  222. if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
  223. /*
  224. * Otherwise use the IPv4-only gethostbyname... (NOTE:
  225. * we don't use gethostbyname as a fallback!)
  226. */
  227. if (ret->superfamily == UNRESOLVED) {
  228. /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
  229. if ( (h = gethostbyname(host)) )
  230. ret->superfamily = IP;
  231. }
  232. if (ret->superfamily == UNRESOLVED) {
  233. ret->error = (h_errno == HOST_NOT_FOUND ||
  234. h_errno == NO_DATA ||
  235. h_errno == NO_ADDRESS ? "Host does not exist" :
  236. h_errno == TRY_AGAIN ?
  237. "Temporary name service failure" :
  238. "gethostbyname: unknown error");
  239. return ret;
  240. }
  241. /* This way we are always sure the h->h_name is valid :) */
  242. strncpy(realhost, h->h_name, sizeof(realhost));
  243. for (n = 0; h->h_addr_list[n]; n++);
  244. ret->addresses = snewn(n, unsigned long);
  245. ret->naddresses = n;
  246. for (n = 0; n < ret->naddresses; n++) {
  247. memcpy(&a, h->h_addr_list[n], sizeof(a));
  248. ret->addresses[n] = ntohl(a);
  249. }
  250. } else {
  251. /*
  252. * This must be a numeric IPv4 address because it caused a
  253. * success return from inet_addr.
  254. */
  255. ret->superfamily = IP;
  256. strncpy(realhost, host, sizeof(realhost));
  257. ret->addresses = snew(unsigned long);
  258. ret->naddresses = 1;
  259. ret->addresses[0] = ntohl(a);
  260. }
  261. #endif
  262. realhost[lenof(realhost)-1] = '\0';
  263. *canonicalname = snewn(1+strlen(realhost), char);
  264. strcpy(*canonicalname, realhost);
  265. return ret;
  266. }
  267. SockAddr sk_nonamelookup(const char *host)
  268. {
  269. SockAddr ret = snew(struct SockAddr_tag);
  270. ret->error = NULL;
  271. ret->superfamily = UNRESOLVED;
  272. strncpy(ret->hostname, host, lenof(ret->hostname));
  273. ret->hostname[lenof(ret->hostname)-1] = '\0';
  274. #ifndef NO_IPV6
  275. ret->ais = NULL;
  276. #else
  277. ret->addresses = NULL;
  278. #endif
  279. ret->refcount = 1;
  280. return ret;
  281. }
  282. static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
  283. {
  284. #ifndef NO_IPV6
  285. if (step->ai && step->ai->ai_next) {
  286. step->ai = step->ai->ai_next;
  287. return TRUE;
  288. } else
  289. return FALSE;
  290. #else
  291. if (step->curraddr+1 < addr->naddresses) {
  292. step->curraddr++;
  293. return TRUE;
  294. } else {
  295. return FALSE;
  296. }
  297. #endif
  298. }
  299. void sk_getaddr(SockAddr addr, char *buf, int buflen)
  300. {
  301. if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
  302. strncpy(buf, addr->hostname, buflen);
  303. buf[buflen-1] = '\0';
  304. } else {
  305. #ifndef NO_IPV6
  306. if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
  307. NULL, 0, NI_NUMERICHOST) != 0) {
  308. buf[0] = '\0';
  309. strncat(buf, "<unknown>", buflen - 1);
  310. }
  311. #else
  312. struct in_addr a;
  313. SockAddrStep step;
  314. START_STEP(addr, step);
  315. assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
  316. a.s_addr = htonl(addr->addresses[0]);
  317. strncpy(buf, inet_ntoa(a), buflen);
  318. buf[buflen-1] = '\0';
  319. #endif
  320. }
  321. }
  322. int sk_addr_needs_port(SockAddr addr)
  323. {
  324. if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
  325. return FALSE;
  326. } else {
  327. return TRUE;
  328. }
  329. }
  330. int sk_hostname_is_local(const char *name)
  331. {
  332. return !strcmp(name, "localhost") ||
  333. !strcmp(name, "::1") ||
  334. !strncmp(name, "127.", 4);
  335. }
  336. #define ipv4_is_loopback(addr) \
  337. (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
  338. static int sockaddr_is_loopback(struct sockaddr *sa)
  339. {
  340. union sockaddr_union *u = (union sockaddr_union *)sa;
  341. switch (u->sa.sa_family) {
  342. case AF_INET:
  343. return ipv4_is_loopback(u->sin.sin_addr);
  344. #ifndef NO_IPV6
  345. case AF_INET6:
  346. return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
  347. #endif
  348. case AF_UNIX:
  349. return TRUE;
  350. default:
  351. return FALSE;
  352. }
  353. }
  354. int sk_address_is_local(SockAddr addr)
  355. {
  356. if (addr->superfamily == UNRESOLVED)
  357. return 0; /* we don't know; assume not */
  358. else if (addr->superfamily == UNIX)
  359. return 1;
  360. else {
  361. #ifndef NO_IPV6
  362. return sockaddr_is_loopback(addr->ais->ai_addr);
  363. #else
  364. struct in_addr a;
  365. SockAddrStep step;
  366. START_STEP(addr, step);
  367. assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
  368. a.s_addr = htonl(addr->addresses[0]);
  369. return ipv4_is_loopback(a);
  370. #endif
  371. }
  372. }
  373. int sk_address_is_special_local(SockAddr addr)
  374. {
  375. return addr->superfamily == UNIX;
  376. }
  377. int sk_addrtype(SockAddr addr)
  378. {
  379. SockAddrStep step;
  380. int family;
  381. START_STEP(addr, step);
  382. family = SOCKADDR_FAMILY(addr, step);
  383. return (family == AF_INET ? ADDRTYPE_IPV4 :
  384. #ifndef NO_IPV6
  385. family == AF_INET6 ? ADDRTYPE_IPV6 :
  386. #endif
  387. ADDRTYPE_NAME);
  388. }
  389. void sk_addrcopy(SockAddr addr, char *buf)
  390. {
  391. SockAddrStep step;
  392. int family;
  393. START_STEP(addr, step);
  394. family = SOCKADDR_FAMILY(addr, step);
  395. #ifndef NO_IPV6
  396. if (family == AF_INET)
  397. memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
  398. sizeof(struct in_addr));
  399. else if (family == AF_INET6)
  400. memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
  401. sizeof(struct in6_addr));
  402. else
  403. assert(FALSE);
  404. #else
  405. struct in_addr a;
  406. assert(family == AF_INET);
  407. a.s_addr = htonl(addr->addresses[step.curraddr]);
  408. memcpy(buf, (char*) &a.s_addr, 4);
  409. #endif
  410. }
  411. void sk_addr_free(SockAddr addr)
  412. {
  413. if (--addr->refcount > 0)
  414. return;
  415. #ifndef NO_IPV6
  416. if (addr->ais != NULL)
  417. freeaddrinfo(addr->ais);
  418. #else
  419. sfree(addr->addresses);
  420. #endif
  421. sfree(addr);
  422. }
  423. SockAddr sk_addr_dup(SockAddr addr)
  424. {
  425. addr->refcount++;
  426. return addr;
  427. }
  428. static Plug sk_tcp_plug(Socket sock, Plug p)
  429. {
  430. Actual_Socket s = (Actual_Socket) sock;
  431. Plug ret = s->plug;
  432. if (p)
  433. s->plug = p;
  434. return ret;
  435. }
  436. static void sk_tcp_flush(Socket s)
  437. {
  438. /*
  439. * We send data to the socket as soon as we can anyway,
  440. * so we don't need to do anything here. :-)
  441. */
  442. }
  443. static void sk_tcp_close(Socket s);
  444. static int sk_tcp_write(Socket s, const char *data, int len);
  445. static int sk_tcp_write_oob(Socket s, const char *data, int len);
  446. static void sk_tcp_write_eof(Socket s);
  447. static void sk_tcp_set_frozen(Socket s, int is_frozen);
  448. static char *sk_tcp_peer_info(Socket s);
  449. static const char *sk_tcp_socket_error(Socket s);
  450. static struct socket_function_table tcp_fn_table = {
  451. sk_tcp_plug,
  452. sk_tcp_close,
  453. sk_tcp_write,
  454. sk_tcp_write_oob,
  455. sk_tcp_write_eof,
  456. sk_tcp_flush,
  457. sk_tcp_set_frozen,
  458. sk_tcp_socket_error,
  459. sk_tcp_peer_info,
  460. };
  461. static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
  462. {
  463. int sockfd = ctx.i;
  464. Actual_Socket ret;
  465. /*
  466. * Create Socket structure.
  467. */
  468. ret = snew(struct Socket_tag);
  469. ret->fn = &tcp_fn_table;
  470. ret->error = NULL;
  471. ret->plug = plug;
  472. bufchain_init(&ret->output_data);
  473. ret->writable = 1; /* to start with */
  474. ret->sending_oob = 0;
  475. ret->frozen = 1;
  476. ret->localhost_only = 0; /* unused, but best init anyway */
  477. ret->pending_error = 0;
  478. ret->oobpending = FALSE;
  479. ret->outgoingeof = EOF_NO;
  480. ret->incomingeof = FALSE;
  481. ret->listener = 0;
  482. ret->parent = ret->child = NULL;
  483. ret->addr = NULL;
  484. ret->connected = 1;
  485. ret->s = sockfd;
  486. if (ret->s < 0) {
  487. ret->error = strerror(errno);
  488. return (Socket) ret;
  489. }
  490. ret->oobinline = 0;
  491. uxsel_tell(ret);
  492. add234(sktree, ret);
  493. return (Socket) ret;
  494. }
  495. static int try_connect(Actual_Socket sock)
  496. {
  497. int s;
  498. union sockaddr_union u;
  499. const union sockaddr_union *sa;
  500. int err = 0;
  501. short localport;
  502. int salen, family;
  503. /*
  504. * Remove the socket from the tree before we overwrite its
  505. * internal socket id, because that forms part of the tree's
  506. * sorting criterion. We'll add it back before exiting this
  507. * function, whether we changed anything or not.
  508. */
  509. del234(sktree, sock);
  510. if (sock->s >= 0)
  511. close(sock->s);
  512. plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
  513. /*
  514. * Open socket.
  515. */
  516. family = SOCKADDR_FAMILY(sock->addr, sock->step);
  517. assert(family != AF_UNSPEC);
  518. s = socket(family, SOCK_STREAM, 0);
  519. sock->s = s;
  520. if (s < 0) {
  521. err = errno;
  522. goto ret;
  523. }
  524. cloexec(s);
  525. if (sock->oobinline) {
  526. int b = TRUE;
  527. if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
  528. (void *) &b, sizeof(b)) < 0) {
  529. err = errno;
  530. close(s);
  531. goto ret;
  532. }
  533. }
  534. if (sock->nodelay) {
  535. int b = TRUE;
  536. if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
  537. (void *) &b, sizeof(b)) < 0) {
  538. err = errno;
  539. close(s);
  540. goto ret;
  541. }
  542. }
  543. if (sock->keepalive) {
  544. int b = TRUE;
  545. if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
  546. (void *) &b, sizeof(b)) < 0) {
  547. err = errno;
  548. close(s);
  549. goto ret;
  550. }
  551. }
  552. /*
  553. * Bind to local address.
  554. */
  555. if (sock->privport)
  556. localport = 1023; /* count from 1023 downwards */
  557. else
  558. localport = 0; /* just use port 0 (ie kernel picks) */
  559. /* BSD IP stacks need sockaddr_in zeroed before filling in */
  560. memset(&u,'\0',sizeof(u));
  561. /* We don't try to bind to a local address for UNIX domain sockets. (Why
  562. * do we bother doing the bind when localport == 0 anyway?) */
  563. if (family != AF_UNIX) {
  564. /* Loop round trying to bind */
  565. while (1) {
  566. int retcode;
  567. #ifndef NO_IPV6
  568. if (family == AF_INET6) {
  569. /* XXX use getaddrinfo to get a local address? */
  570. u.sin6.sin6_family = AF_INET6;
  571. u.sin6.sin6_addr = in6addr_any;
  572. u.sin6.sin6_port = htons(localport);
  573. retcode = bind(s, &u.sa, sizeof(u.sin6));
  574. } else
  575. #endif
  576. {
  577. assert(family == AF_INET);
  578. u.sin.sin_family = AF_INET;
  579. u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
  580. u.sin.sin_port = htons(localport);
  581. retcode = bind(s, &u.sa, sizeof(u.sin));
  582. }
  583. if (retcode >= 0) {
  584. err = 0;
  585. break; /* done */
  586. } else {
  587. err = errno;
  588. if (err != EADDRINUSE) /* failed, for a bad reason */
  589. break;
  590. }
  591. if (localport == 0)
  592. break; /* we're only looping once */
  593. localport--;
  594. if (localport == 0)
  595. break; /* we might have got to the end */
  596. }
  597. if (err)
  598. goto ret;
  599. }
  600. /*
  601. * Connect to remote address.
  602. */
  603. switch(family) {
  604. #ifndef NO_IPV6
  605. case AF_INET:
  606. /* XXX would be better to have got getaddrinfo() to fill in the port. */
  607. ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
  608. htons(sock->port);
  609. sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
  610. salen = sock->step.ai->ai_addrlen;
  611. break;
  612. case AF_INET6:
  613. ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
  614. htons(sock->port);
  615. sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
  616. salen = sock->step.ai->ai_addrlen;
  617. break;
  618. #else
  619. case AF_INET:
  620. u.sin.sin_family = AF_INET;
  621. u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
  622. u.sin.sin_port = htons((short) sock->port);
  623. sa = &u;
  624. salen = sizeof u.sin;
  625. break;
  626. #endif
  627. case AF_UNIX:
  628. assert(sock->port == 0); /* to catch confused people */
  629. assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path);
  630. u.su.sun_family = AF_UNIX;
  631. strcpy(u.su.sun_path, sock->addr->hostname);
  632. sa = &u;
  633. salen = sizeof u.su;
  634. break;
  635. default:
  636. assert(0 && "unknown address family");
  637. exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
  638. }
  639. nonblock(s);
  640. if ((connect(s, &(sa->sa), salen)) < 0) {
  641. if ( errno != EINPROGRESS ) {
  642. err = errno;
  643. goto ret;
  644. }
  645. } else {
  646. /*
  647. * If we _don't_ get EWOULDBLOCK, the connect has completed
  648. * and we should set the socket as connected and writable.
  649. */
  650. sock->connected = 1;
  651. sock->writable = 1;
  652. }
  653. uxsel_tell(sock);
  654. ret:
  655. /*
  656. * No matter what happened, put the socket back in the tree.
  657. */
  658. add234(sktree, sock);
  659. if (err)
  660. plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
  661. return err;
  662. }
  663. Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
  664. int nodelay, int keepalive, Plug plug)
  665. {
  666. Actual_Socket ret;
  667. int err;
  668. /*
  669. * Create Socket structure.
  670. */
  671. ret = snew(struct Socket_tag);
  672. ret->fn = &tcp_fn_table;
  673. ret->error = NULL;
  674. ret->plug = plug;
  675. bufchain_init(&ret->output_data);
  676. ret->connected = 0; /* to start with */
  677. ret->writable = 0; /* to start with */
  678. ret->sending_oob = 0;
  679. ret->frozen = 0;
  680. ret->localhost_only = 0; /* unused, but best init anyway */
  681. ret->pending_error = 0;
  682. ret->parent = ret->child = NULL;
  683. ret->oobpending = FALSE;
  684. ret->outgoingeof = EOF_NO;
  685. ret->incomingeof = FALSE;
  686. ret->listener = 0;
  687. ret->addr = addr;
  688. START_STEP(ret->addr, ret->step);
  689. ret->s = -1;
  690. ret->oobinline = oobinline;
  691. ret->nodelay = nodelay;
  692. ret->keepalive = keepalive;
  693. ret->privport = privport;
  694. ret->port = port;
  695. err = 0;
  696. do {
  697. err = try_connect(ret);
  698. } while (err && sk_nextaddr(ret->addr, &ret->step));
  699. if (err)
  700. ret->error = strerror(err);
  701. return (Socket) ret;
  702. }
  703. Socket sk_newlistener(const char *srcaddr, int port, Plug plug,
  704. int local_host_only, int orig_address_family)
  705. {
  706. int s;
  707. #ifndef NO_IPV6
  708. struct addrinfo hints, *ai = NULL;
  709. char portstr[6];
  710. #endif
  711. union sockaddr_union u;
  712. union sockaddr_union *addr;
  713. int addrlen;
  714. Actual_Socket ret;
  715. int retcode;
  716. int address_family;
  717. int on = 1;
  718. /*
  719. * Create Socket structure.
  720. */
  721. ret = snew(struct Socket_tag);
  722. ret->fn = &tcp_fn_table;
  723. ret->error = NULL;
  724. ret->plug = plug;
  725. bufchain_init(&ret->output_data);
  726. ret->writable = 0; /* to start with */
  727. ret->sending_oob = 0;
  728. ret->frozen = 0;
  729. ret->localhost_only = local_host_only;
  730. ret->pending_error = 0;
  731. ret->parent = ret->child = NULL;
  732. ret->oobpending = FALSE;
  733. ret->outgoingeof = EOF_NO;
  734. ret->incomingeof = FALSE;
  735. ret->listener = 1;
  736. ret->addr = NULL;
  737. ret->s = -1;
  738. /*
  739. * Translate address_family from platform-independent constants
  740. * into local reality.
  741. */
  742. address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
  743. #ifndef NO_IPV6
  744. orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  745. #endif
  746. AF_UNSPEC);
  747. #ifndef NO_IPV6
  748. /* Let's default to IPv6.
  749. * If the stack doesn't support IPv6, we will fall back to IPv4. */
  750. if (address_family == AF_UNSPEC) address_family = AF_INET6;
  751. #else
  752. /* No other choice, default to IPv4 */
  753. if (address_family == AF_UNSPEC) address_family = AF_INET;
  754. #endif
  755. /*
  756. * Open socket.
  757. */
  758. s = socket(address_family, SOCK_STREAM, 0);
  759. #ifndef NO_IPV6
  760. /* If the host doesn't support IPv6 try fallback to IPv4. */
  761. if (s < 0 && address_family == AF_INET6) {
  762. address_family = AF_INET;
  763. s = socket(address_family, SOCK_STREAM, 0);
  764. }
  765. #endif
  766. if (s < 0) {
  767. ret->error = strerror(errno);
  768. return (Socket) ret;
  769. }
  770. cloexec(s);
  771. ret->oobinline = 0;
  772. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  773. (const char *)&on, sizeof(on)) < 0) {
  774. ret->error = strerror(errno);
  775. close(s);
  776. return (Socket) ret;
  777. }
  778. retcode = -1;
  779. addr = NULL; addrlen = -1; /* placate optimiser */
  780. if (srcaddr != NULL) {
  781. #ifndef NO_IPV6
  782. hints.ai_flags = AI_NUMERICHOST;
  783. hints.ai_family = address_family;
  784. hints.ai_socktype = SOCK_STREAM;
  785. hints.ai_protocol = 0;
  786. hints.ai_addrlen = 0;
  787. hints.ai_addr = NULL;
  788. hints.ai_canonname = NULL;
  789. hints.ai_next = NULL;
  790. assert(port >= 0 && port <= 99999);
  791. sprintf(portstr, "%d", port);
  792. {
  793. char *trimmed_addr = host_strduptrim(srcaddr);
  794. retcode = getaddrinfo(trimmed_addr, portstr, &hints, &ai);
  795. sfree(trimmed_addr);
  796. }
  797. if (retcode == 0) {
  798. addr = (union sockaddr_union *)ai->ai_addr;
  799. addrlen = ai->ai_addrlen;
  800. }
  801. #else
  802. memset(&u,'\0',sizeof u);
  803. u.sin.sin_family = AF_INET;
  804. u.sin.sin_port = htons(port);
  805. u.sin.sin_addr.s_addr = inet_addr(srcaddr);
  806. if (u.sin.sin_addr.s_addr != (in_addr_t)(-1)) {
  807. /* Override localhost_only with specified listen addr. */
  808. ret->localhost_only = ipv4_is_loopback(u.sin.sin_addr);
  809. }
  810. addr = &u;
  811. addrlen = sizeof(u.sin);
  812. retcode = 0;
  813. #endif
  814. }
  815. if (retcode != 0) {
  816. memset(&u,'\0',sizeof u);
  817. #ifndef NO_IPV6
  818. if (address_family == AF_INET6) {
  819. u.sin6.sin6_family = AF_INET6;
  820. u.sin6.sin6_port = htons(port);
  821. if (local_host_only)
  822. u.sin6.sin6_addr = in6addr_loopback;
  823. else
  824. u.sin6.sin6_addr = in6addr_any;
  825. addr = &u;
  826. addrlen = sizeof(u.sin6);
  827. } else
  828. #endif
  829. {
  830. u.sin.sin_family = AF_INET;
  831. u.sin.sin_port = htons(port);
  832. if (local_host_only)
  833. u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  834. else
  835. u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
  836. addr = &u;
  837. addrlen = sizeof(u.sin);
  838. }
  839. }
  840. retcode = bind(s, &addr->sa, addrlen);
  841. #ifndef NO_IPV6
  842. if (ai)
  843. freeaddrinfo(ai);
  844. #endif
  845. if (retcode < 0) {
  846. close(s);
  847. ret->error = strerror(errno);
  848. return (Socket) ret;
  849. }
  850. if (listen(s, SOMAXCONN) < 0) {
  851. close(s);
  852. ret->error = strerror(errno);
  853. return (Socket) ret;
  854. }
  855. #ifndef NO_IPV6
  856. /*
  857. * If we were given ADDRTYPE_UNSPEC, we must also create an
  858. * IPv4 listening socket and link it to this one.
  859. */
  860. if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
  861. Actual_Socket other;
  862. other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
  863. local_host_only, ADDRTYPE_IPV4);
  864. if (other) {
  865. if (!other->error) {
  866. other->parent = ret;
  867. ret->child = other;
  868. } else {
  869. /* If we couldn't create a listening socket on IPv4 as well
  870. * as IPv6, we must return an error overall. */
  871. close(s);
  872. sfree(ret);
  873. return (Socket) other;
  874. }
  875. }
  876. }
  877. #endif
  878. ret->s = s;
  879. uxsel_tell(ret);
  880. add234(sktree, ret);
  881. return (Socket) ret;
  882. }
  883. static void sk_tcp_close(Socket sock)
  884. {
  885. Actual_Socket s = (Actual_Socket) sock;
  886. if (s->child)
  887. sk_tcp_close((Socket)s->child);
  888. uxsel_del(s->s);
  889. del234(sktree, s);
  890. close(s->s);
  891. if (s->addr)
  892. sk_addr_free(s->addr);
  893. sfree(s);
  894. }
  895. void *sk_getxdmdata(void *sock, int *lenp)
  896. {
  897. Actual_Socket s = (Actual_Socket) sock;
  898. union sockaddr_union u;
  899. socklen_t addrlen;
  900. char *buf;
  901. static unsigned int unix_addr = 0xFFFFFFFF;
  902. /*
  903. * We must check that this socket really _is_ an Actual_Socket.
  904. */
  905. if (s->fn != &tcp_fn_table)
  906. return NULL; /* failure */
  907. addrlen = sizeof(u);
  908. if (getsockname(s->s, &u.sa, &addrlen) < 0)
  909. return NULL;
  910. switch(u.sa.sa_family) {
  911. case AF_INET:
  912. *lenp = 6;
  913. buf = snewn(*lenp, char);
  914. PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
  915. PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
  916. break;
  917. #ifndef NO_IPV6
  918. case AF_INET6:
  919. *lenp = 6;
  920. buf = snewn(*lenp, char);
  921. if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
  922. memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
  923. PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
  924. } else
  925. /* This is stupid, but it's what XLib does. */
  926. memset(buf, 0, 6);
  927. break;
  928. #endif
  929. case AF_UNIX:
  930. *lenp = 6;
  931. buf = snewn(*lenp, char);
  932. PUT_32BIT_MSB_FIRST(buf, unix_addr--);
  933. PUT_16BIT_MSB_FIRST(buf+4, getpid());
  934. break;
  935. /* XXX IPV6 */
  936. default:
  937. return NULL;
  938. }
  939. return buf;
  940. }
  941. /*
  942. * Deal with socket errors detected in try_send().
  943. */
  944. static void socket_error_callback(void *vs)
  945. {
  946. Actual_Socket s = (Actual_Socket)vs;
  947. /*
  948. * Just in case other socket work has caused this socket to vanish
  949. * or become somehow non-erroneous before this callback arrived...
  950. */
  951. if (!find234(sktree, s, NULL) || !s->pending_error)
  952. return;
  953. /*
  954. * An error has occurred on this socket. Pass it to the plug.
  955. */
  956. plug_closing(s->plug, strerror(s->pending_error), s->pending_error, 0);
  957. }
  958. /*
  959. * The function which tries to send on a socket once it's deemed
  960. * writable.
  961. */
  962. void try_send(Actual_Socket s)
  963. {
  964. while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
  965. int nsent;
  966. int err;
  967. void *data;
  968. int len, urgentflag;
  969. if (s->sending_oob) {
  970. urgentflag = MSG_OOB;
  971. len = s->sending_oob;
  972. data = &s->oobdata;
  973. } else {
  974. urgentflag = 0;
  975. bufchain_prefix(&s->output_data, &data, &len);
  976. }
  977. nsent = send(s->s, data, len, urgentflag);
  978. noise_ultralight(nsent);
  979. if (nsent <= 0) {
  980. err = (nsent < 0 ? errno : 0);
  981. if (err == EWOULDBLOCK) {
  982. /*
  983. * Perfectly normal: we've sent all we can for the moment.
  984. */
  985. s->writable = FALSE;
  986. return;
  987. } else {
  988. /*
  989. * We unfortunately can't just call plug_closing(),
  990. * because it's quite likely that we're currently
  991. * _in_ a call from the code we'd be calling back
  992. * to, so we'd have to make half the SSH code
  993. * reentrant. Instead we flag a pending error on
  994. * the socket, to be dealt with (by calling
  995. * plug_closing()) at some suitable future moment.
  996. */
  997. s->pending_error = err;
  998. /*
  999. * Immediately cease selecting on this socket, so that
  1000. * we don't tight-loop repeatedly trying to do
  1001. * whatever it was that went wrong.
  1002. */
  1003. uxsel_tell(s);
  1004. /*
  1005. * Arrange to be called back from the top level to
  1006. * deal with the error condition on this socket.
  1007. */
  1008. queue_toplevel_callback(socket_error_callback, s);
  1009. return;
  1010. }
  1011. } else {
  1012. if (s->sending_oob) {
  1013. if (nsent < len) {
  1014. memmove(s->oobdata, s->oobdata+nsent, len-nsent);
  1015. s->sending_oob = len - nsent;
  1016. } else {
  1017. s->sending_oob = 0;
  1018. }
  1019. } else {
  1020. bufchain_consume(&s->output_data, nsent);
  1021. }
  1022. }
  1023. }
  1024. /*
  1025. * If we reach here, we've finished sending everything we might
  1026. * have needed to send. Send EOF, if we need to.
  1027. */
  1028. if (s->outgoingeof == EOF_PENDING) {
  1029. shutdown(s->s, SHUT_WR);
  1030. s->outgoingeof = EOF_SENT;
  1031. }
  1032. /*
  1033. * Also update the select status, because we don't need to select
  1034. * for writing any more.
  1035. */
  1036. uxsel_tell(s);
  1037. }
  1038. static int sk_tcp_write(Socket sock, const char *buf, int len)
  1039. {
  1040. Actual_Socket s = (Actual_Socket) sock;
  1041. assert(s->outgoingeof == EOF_NO);
  1042. /*
  1043. * Add the data to the buffer list on the socket.
  1044. */
  1045. bufchain_add(&s->output_data, buf, len);
  1046. /*
  1047. * Now try sending from the start of the buffer list.
  1048. */
  1049. if (s->writable)
  1050. try_send(s);
  1051. /*
  1052. * Update the select() status to correctly reflect whether or
  1053. * not we should be selecting for write.
  1054. */
  1055. uxsel_tell(s);
  1056. return bufchain_size(&s->output_data);
  1057. }
  1058. static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
  1059. {
  1060. Actual_Socket s = (Actual_Socket) sock;
  1061. assert(s->outgoingeof == EOF_NO);
  1062. /*
  1063. * Replace the buffer list on the socket with the data.
  1064. */
  1065. bufchain_clear(&s->output_data);
  1066. assert(len <= sizeof(s->oobdata));
  1067. memcpy(s->oobdata, buf, len);
  1068. s->sending_oob = len;
  1069. /*
  1070. * Now try sending from the start of the buffer list.
  1071. */
  1072. if (s->writable)
  1073. try_send(s);
  1074. /*
  1075. * Update the select() status to correctly reflect whether or
  1076. * not we should be selecting for write.
  1077. */
  1078. uxsel_tell(s);
  1079. return s->sending_oob;
  1080. }
  1081. static void sk_tcp_write_eof(Socket sock)
  1082. {
  1083. Actual_Socket s = (Actual_Socket) sock;
  1084. assert(s->outgoingeof == EOF_NO);
  1085. /*
  1086. * Mark the socket as pending outgoing EOF.
  1087. */
  1088. s->outgoingeof = EOF_PENDING;
  1089. /*
  1090. * Now try sending from the start of the buffer list.
  1091. */
  1092. if (s->writable)
  1093. try_send(s);
  1094. /*
  1095. * Update the select() status to correctly reflect whether or
  1096. * not we should be selecting for write.
  1097. */
  1098. uxsel_tell(s);
  1099. }
  1100. static int net_select_result(int fd, int event)
  1101. {
  1102. int ret;
  1103. char buf[20480]; /* nice big buffer for plenty of speed */
  1104. Actual_Socket s;
  1105. u_long atmark;
  1106. /* Find the Socket structure */
  1107. s = find234(sktree, &fd, cmpforsearch);
  1108. if (!s)
  1109. return 1; /* boggle */
  1110. noise_ultralight(event);
  1111. switch (event) {
  1112. case 4: /* exceptional */
  1113. if (!s->oobinline) {
  1114. /*
  1115. * On a non-oobinline socket, this indicates that we
  1116. * can immediately perform an OOB read and get back OOB
  1117. * data, which we will send to the back end with
  1118. * type==2 (urgent data).
  1119. */
  1120. ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
  1121. noise_ultralight(ret);
  1122. if (ret <= 0) {
  1123. return plug_closing(s->plug,
  1124. ret == 0 ? "Internal networking trouble" :
  1125. strerror(errno), errno, 0);
  1126. } else {
  1127. /*
  1128. * Receiving actual data on a socket means we can
  1129. * stop falling back through the candidate
  1130. * addresses to connect to.
  1131. */
  1132. if (s->addr) {
  1133. sk_addr_free(s->addr);
  1134. s->addr = NULL;
  1135. }
  1136. return plug_receive(s->plug, 2, buf, ret);
  1137. }
  1138. break;
  1139. }
  1140. /*
  1141. * If we reach here, this is an oobinline socket, which
  1142. * means we should set s->oobpending and then deal with it
  1143. * when we get called for the readability event (which
  1144. * should also occur).
  1145. */
  1146. s->oobpending = TRUE;
  1147. break;
  1148. case 1: /* readable; also acceptance */
  1149. if (s->listener) {
  1150. /*
  1151. * On a listening socket, the readability event means a
  1152. * connection is ready to be accepted.
  1153. */
  1154. union sockaddr_union su;
  1155. socklen_t addrlen = sizeof(su);
  1156. accept_ctx_t actx;
  1157. int t; /* socket of connection */
  1158. memset(&su, 0, addrlen);
  1159. t = accept(s->s, &su.sa, &addrlen);
  1160. if (t < 0) {
  1161. break;
  1162. }
  1163. nonblock(t);
  1164. actx.i = t;
  1165. if ((!s->addr || s->addr->superfamily != UNIX) &&
  1166. s->localhost_only && !sockaddr_is_loopback(&su.sa)) {
  1167. close(t); /* someone let nonlocal through?! */
  1168. } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
  1169. close(t); /* denied or error */
  1170. }
  1171. break;
  1172. }
  1173. /*
  1174. * If we reach here, this is not a listening socket, so
  1175. * readability really means readability.
  1176. */
  1177. /* In the case the socket is still frozen, we don't even bother */
  1178. if (s->frozen)
  1179. break;
  1180. /*
  1181. * We have received data on the socket. For an oobinline
  1182. * socket, this might be data _before_ an urgent pointer,
  1183. * in which case we send it to the back end with type==1
  1184. * (data prior to urgent).
  1185. */
  1186. if (s->oobinline && s->oobpending) {
  1187. atmark = 1;
  1188. if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
  1189. s->oobpending = FALSE; /* clear this indicator */
  1190. } else
  1191. atmark = 1;
  1192. ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
  1193. noise_ultralight(ret);
  1194. if (ret < 0) {
  1195. if (errno == EWOULDBLOCK) {
  1196. break;
  1197. }
  1198. }
  1199. if (ret < 0) {
  1200. /*
  1201. * An error at this point _might_ be an error reported
  1202. * by a non-blocking connect(). So before we return a
  1203. * panic status to the user, let's just see whether
  1204. * that's the case.
  1205. */
  1206. int err = errno;
  1207. if (s->addr) {
  1208. plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
  1209. while (s->addr && sk_nextaddr(s->addr, &s->step)) {
  1210. err = try_connect(s);
  1211. }
  1212. }
  1213. if (err != 0)
  1214. return plug_closing(s->plug, strerror(err), err, 0);
  1215. } else if (0 == ret) {
  1216. s->incomingeof = TRUE; /* stop trying to read now */
  1217. uxsel_tell(s);
  1218. return plug_closing(s->plug, NULL, 0, 0);
  1219. } else {
  1220. /*
  1221. * Receiving actual data on a socket means we can
  1222. * stop falling back through the candidate
  1223. * addresses to connect to.
  1224. */
  1225. if (s->addr) {
  1226. sk_addr_free(s->addr);
  1227. s->addr = NULL;
  1228. }
  1229. return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
  1230. }
  1231. break;
  1232. case 2: /* writable */
  1233. if (!s->connected) {
  1234. /*
  1235. * select() reports a socket as _writable_ when an
  1236. * asynchronous connection is completed.
  1237. */
  1238. s->connected = s->writable = 1;
  1239. uxsel_tell(s);
  1240. break;
  1241. } else {
  1242. int bufsize_before, bufsize_after;
  1243. s->writable = 1;
  1244. bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
  1245. try_send(s);
  1246. bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
  1247. if (bufsize_after < bufsize_before)
  1248. plug_sent(s->plug, bufsize_after);
  1249. }
  1250. break;
  1251. }
  1252. return 1;
  1253. }
  1254. /*
  1255. * Special error values are returned from sk_namelookup and sk_new
  1256. * if there's a problem. These functions extract an error message,
  1257. * or return NULL if there's no problem.
  1258. */
  1259. const char *sk_addr_error(SockAddr addr)
  1260. {
  1261. return addr->error;
  1262. }
  1263. static const char *sk_tcp_socket_error(Socket sock)
  1264. {
  1265. Actual_Socket s = (Actual_Socket) sock;
  1266. return s->error;
  1267. }
  1268. static void sk_tcp_set_frozen(Socket sock, int is_frozen)
  1269. {
  1270. Actual_Socket s = (Actual_Socket) sock;
  1271. if (s->frozen == is_frozen)
  1272. return;
  1273. s->frozen = is_frozen;
  1274. uxsel_tell(s);
  1275. }
  1276. static char *sk_tcp_peer_info(Socket sock)
  1277. {
  1278. Actual_Socket s = (Actual_Socket) sock;
  1279. union sockaddr_union addr;
  1280. socklen_t addrlen = sizeof(addr);
  1281. #ifndef NO_IPV6
  1282. char buf[INET6_ADDRSTRLEN];
  1283. #endif
  1284. if (getpeername(s->s, &addr.sa, &addrlen) < 0)
  1285. return NULL;
  1286. if (addr.storage.ss_family == AF_INET) {
  1287. return dupprintf
  1288. ("%s:%d",
  1289. inet_ntoa(addr.sin.sin_addr),
  1290. (int)ntohs(addr.sin.sin_port));
  1291. #ifndef NO_IPV6
  1292. } else if (addr.storage.ss_family == AF_INET6) {
  1293. return dupprintf
  1294. ("[%s]:%d",
  1295. inet_ntop(AF_INET6, &addr.sin6.sin6_addr, buf, sizeof(buf)),
  1296. (int)ntohs(addr.sin6.sin6_port));
  1297. #endif
  1298. } else if (addr.storage.ss_family == AF_UNIX) {
  1299. /*
  1300. * For Unix sockets, the source address is unlikely to be
  1301. * helpful. Instead, we try SO_PEERCRED and try to get the
  1302. * source pid.
  1303. */
  1304. int pid, uid, gid;
  1305. if (so_peercred(s->s, &pid, &uid, &gid)) {
  1306. char uidbuf[64], gidbuf[64];
  1307. sprintf(uidbuf, "%d", uid);
  1308. sprintf(gidbuf, "%d", gid);
  1309. struct passwd *pw = getpwuid(uid);
  1310. struct group *gr = getgrgid(gid);
  1311. return dupprintf("pid %d (%s:%s)", pid,
  1312. pw ? pw->pw_name : uidbuf,
  1313. gr ? gr->gr_name : gidbuf);
  1314. }
  1315. return NULL;
  1316. } else {
  1317. return NULL;
  1318. }
  1319. }
  1320. static void uxsel_tell(Actual_Socket s)
  1321. {
  1322. int rwx = 0;
  1323. if (!s->pending_error) {
  1324. if (s->listener) {
  1325. rwx |= 1; /* read == accept */
  1326. } else {
  1327. if (!s->connected)
  1328. rwx |= 2; /* write == connect */
  1329. if (s->connected && !s->frozen && !s->incomingeof)
  1330. rwx |= 1 | 4; /* read, except */
  1331. if (bufchain_size(&s->output_data))
  1332. rwx |= 2; /* write */
  1333. }
  1334. }
  1335. uxsel_set(s->s, rwx, net_select_result);
  1336. }
  1337. int net_service_lookup(char *service)
  1338. {
  1339. struct servent *se;
  1340. se = getservbyname(service, NULL);
  1341. if (se != NULL)
  1342. return ntohs(se->s_port);
  1343. else
  1344. return 0;
  1345. }
  1346. char *get_hostname(void)
  1347. {
  1348. int len = 128;
  1349. char *hostname = NULL;
  1350. do {
  1351. len *= 2;
  1352. hostname = sresize(hostname, len, char);
  1353. if ((gethostname(hostname, len) < 0) &&
  1354. (errno != ENAMETOOLONG)) {
  1355. sfree(hostname);
  1356. hostname = NULL;
  1357. break;
  1358. }
  1359. } while (strlen(hostname) >= len-1);
  1360. return hostname;
  1361. }
  1362. SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
  1363. {
  1364. SockAddr ret = snew(struct SockAddr_tag);
  1365. int n;
  1366. memset(ret, 0, sizeof *ret);
  1367. ret->superfamily = UNIX;
  1368. /*
  1369. * In special circumstances (notably Mac OS X Leopard), we'll
  1370. * have been passed an explicit Unix socket path.
  1371. */
  1372. if (sockpath) {
  1373. n = snprintf(ret->hostname, sizeof ret->hostname,
  1374. "%s", sockpath);
  1375. } else {
  1376. n = snprintf(ret->hostname, sizeof ret->hostname,
  1377. "%s%d", X11_UNIX_PATH, displaynum);
  1378. }
  1379. if (n < 0)
  1380. ret->error = "snprintf failed";
  1381. else if (n >= sizeof ret->hostname)
  1382. ret->error = "X11 UNIX name too long";
  1383. #ifndef NO_IPV6
  1384. ret->ais = NULL;
  1385. #else
  1386. ret->addresses = NULL;
  1387. ret->naddresses = 0;
  1388. #endif
  1389. ret->refcount = 1;
  1390. return ret;
  1391. }
  1392. SockAddr unix_sock_addr(const char *path)
  1393. {
  1394. SockAddr ret = snew(struct SockAddr_tag);
  1395. int n;
  1396. memset(ret, 0, sizeof *ret);
  1397. ret->superfamily = UNIX;
  1398. n = snprintf(ret->hostname, sizeof ret->hostname, "%s", path);
  1399. if (n < 0)
  1400. ret->error = "snprintf failed";
  1401. else if (n >= sizeof ret->hostname)
  1402. ret->error = "socket pathname too long";
  1403. #ifndef NO_IPV6
  1404. ret->ais = NULL;
  1405. #else
  1406. ret->addresses = NULL;
  1407. ret->naddresses = 0;
  1408. #endif
  1409. ret->refcount = 1;
  1410. return ret;
  1411. }
  1412. Socket new_unix_listener(SockAddr listenaddr, Plug plug)
  1413. {
  1414. int s;
  1415. union sockaddr_union u;
  1416. union sockaddr_union *addr;
  1417. int addrlen;
  1418. Actual_Socket ret;
  1419. int retcode;
  1420. /*
  1421. * Create Socket structure.
  1422. */
  1423. ret = snew(struct Socket_tag);
  1424. ret->fn = &tcp_fn_table;
  1425. ret->error = NULL;
  1426. ret->plug = plug;
  1427. bufchain_init(&ret->output_data);
  1428. ret->writable = 0; /* to start with */
  1429. ret->sending_oob = 0;
  1430. ret->frozen = 0;
  1431. ret->localhost_only = TRUE;
  1432. ret->pending_error = 0;
  1433. ret->parent = ret->child = NULL;
  1434. ret->oobpending = FALSE;
  1435. ret->outgoingeof = EOF_NO;
  1436. ret->incomingeof = FALSE;
  1437. ret->listener = 1;
  1438. ret->addr = listenaddr;
  1439. ret->s = -1;
  1440. assert(listenaddr->superfamily == UNIX);
  1441. /*
  1442. * Open socket.
  1443. */
  1444. s = socket(AF_UNIX, SOCK_STREAM, 0);
  1445. if (s < 0) {
  1446. ret->error = strerror(errno);
  1447. return (Socket) ret;
  1448. }
  1449. cloexec(s);
  1450. ret->oobinline = 0;
  1451. memset(&u, '\0', sizeof(u));
  1452. u.su.sun_family = AF_UNIX;
  1453. strncpy(u.su.sun_path, listenaddr->hostname, sizeof(u.su.sun_path)-1);
  1454. addr = &u;
  1455. addrlen = sizeof(u.su);
  1456. if (unlink(u.su.sun_path) < 0 && errno != ENOENT) {
  1457. close(s);
  1458. ret->error = strerror(errno);
  1459. return (Socket) ret;
  1460. }
  1461. retcode = bind(s, &addr->sa, addrlen);
  1462. if (retcode < 0) {
  1463. close(s);
  1464. ret->error = strerror(errno);
  1465. return (Socket) ret;
  1466. }
  1467. if (listen(s, SOMAXCONN) < 0) {
  1468. close(s);
  1469. ret->error = strerror(errno);
  1470. return (Socket) ret;
  1471. }
  1472. ret->s = s;
  1473. uxsel_tell(ret);
  1474. add234(sktree, ret);
  1475. return (Socket) ret;
  1476. }