network.c 47 KB

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