sock.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. #include <sys/socket.h>
  2. #include <sys/un.h>
  3. #include <netinet/in.h>
  4. #include <arpa/inet.h>
  5. #include <assert.h>
  6. #include <errno.h>
  7. #include <fcntl.h>
  8. #include <netdb.h>
  9. #include <stdint.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include "imalloc.h"
  14. #include "parsenum.h"
  15. #include "warnp.h"
  16. #include "sock.h"
  17. #include "sock_internal.h"
  18. #include "sock_util.h"
  19. /* Convert a path into a socket address. */
  20. static struct sock_addr **
  21. sock_resolve_unix(const char * addr)
  22. {
  23. struct sock_addr ** sas;
  24. struct sock_addr * sa;
  25. struct sockaddr_un * sa_un;
  26. /* Allocate and populate a sockaddr_un structure. */
  27. if ((sa_un = calloc(1, sizeof(struct sockaddr_un))) == NULL)
  28. goto err0;
  29. sa_un->sun_family = AF_UNIX;
  30. /* Safely copy addr into the structure. */
  31. if (strlen(addr) >= sizeof(sa_un->sun_path)) {
  32. warn0("socket path too long: %s", addr);
  33. goto err1;
  34. }
  35. strcpy(sa_un->sun_path, addr);
  36. /* Allocate and populate our wrapper. */
  37. if ((sa = malloc(sizeof(struct sock_addr))) == NULL)
  38. goto err1;
  39. sa->ai_family = AF_UNIX;
  40. sa->ai_socktype = SOCK_STREAM;
  41. sa->name = (struct sockaddr *)sa_un;
  42. sa->namelen = sizeof(struct sockaddr_un);
  43. /* Allocate and populate an array of pointers. */
  44. if ((sas = malloc(2 * sizeof(struct sock_addr *))) == NULL)
  45. goto err2;
  46. sas[0] = sa;
  47. sas[1] = NULL;
  48. /* Success! */
  49. return (sas);
  50. err2:
  51. free(sa);
  52. err1:
  53. free(sa_un);
  54. err0:
  55. /* Failure! */
  56. return (NULL);
  57. }
  58. /* Resolve a host into a list of socket addresses. */
  59. static struct sock_addr **
  60. sock_resolve_host(const char * addr, const char * ports)
  61. {
  62. struct addrinfo hints;
  63. struct addrinfo * res;
  64. struct addrinfo * r;
  65. struct sock_addr ** sas;
  66. size_t n;
  67. int error;
  68. /* Create hints structure. */
  69. memset(&hints, 0, sizeof(hints));
  70. hints.ai_family = AF_UNSPEC;
  71. hints.ai_socktype = SOCK_STREAM;
  72. hints.ai_protocol = IPPROTO_TCP;
  73. /* Perform DNS lookup. */
  74. if ((error = getaddrinfo(addr, ports, &hints, &res)) != 0) {
  75. warn0("Error looking up %s: %s", addr, gai_strerror(error));
  76. goto err0;
  77. }
  78. /* Count addresses returned. */
  79. for (n = 0, r = res; r != NULL; r = r->ai_next)
  80. n++;
  81. /* Sanity check. */
  82. assert(n < SIZE_MAX);
  83. /* Allocate our response array. */
  84. if (IMALLOC(sas, n + 1, struct sock_addr *))
  85. goto err1;
  86. /* Create address structures. */
  87. for (n = 0, r = res; r != NULL; n++, r = r->ai_next) {
  88. /* Allocate a structure. */
  89. if ((sas[n] = malloc(sizeof(struct sock_addr))) == NULL)
  90. goto err2;
  91. /* Copy in the address metadata. */
  92. sas[n]->ai_family = r->ai_family;
  93. sas[n]->ai_socktype = r->ai_socktype;
  94. sas[n]->namelen = r->ai_addrlen;
  95. /* Duplicate the address. */
  96. if ((sas[n]->name = malloc(sas[n]->namelen)) == NULL)
  97. goto err3;
  98. memcpy(sas[n]->name, r->ai_addr, sas[n]->namelen);
  99. }
  100. /* Terminate array with a NULL. */
  101. sas[n] = NULL;
  102. /* Free the linked list of addresses returned by getaddrinfo. */
  103. freeaddrinfo(res);
  104. /* Success! */
  105. return (sas);
  106. err3:
  107. free(sas[n]);
  108. err2:
  109. for (; n > 0; n--)
  110. sock_addr_free(sas[n - 1]);
  111. free(sas);
  112. err1:
  113. freeaddrinfo(res);
  114. err0:
  115. /* Failure! */
  116. return (NULL);
  117. }
  118. /* Parse an IPv6 address into a socket address. */
  119. static struct sock_addr **
  120. sock_resolve_ipv6(const char * addr, in_port_t p)
  121. {
  122. struct sock_addr ** sas;
  123. struct sock_addr * sa;
  124. struct sockaddr_in6 * sin6;
  125. /* Allocate and populate a sockaddr_in6 structure. */
  126. if ((sin6 = calloc(1, sizeof(struct sockaddr_in6))) == NULL)
  127. goto err0;
  128. sin6->sin6_family = AF_INET6;
  129. sin6->sin6_port = htons(p);
  130. if (inet_pton(AF_INET6, addr, &sin6->sin6_addr) != 1) {
  131. warn0("Error parsing IP address: %s", addr);
  132. goto err1;
  133. }
  134. /* Allocate and populate our wrapper. */
  135. if ((sa = malloc(sizeof(struct sock_addr))) == NULL)
  136. goto err1;
  137. sa->ai_family = AF_INET6;
  138. sa->ai_socktype = SOCK_STREAM;
  139. sa->name = (struct sockaddr *)sin6;
  140. sa->namelen = sizeof(struct sockaddr_in6);
  141. /* Allocate and populate an array of pointers. */
  142. if ((sas = malloc(2 * sizeof(struct sock_addr *))) == NULL)
  143. goto err2;
  144. sas[0] = sa;
  145. sas[1] = NULL;
  146. /* Success! */
  147. return (sas);
  148. err2:
  149. free(sa);
  150. err1:
  151. free(sin6);
  152. err0:
  153. /* Failure! */
  154. return (NULL);
  155. }
  156. /* Parse an IPv4 address into a socket address. */
  157. static struct sock_addr **
  158. sock_resolve_ipv4(const char * addr, in_port_t p)
  159. {
  160. struct sock_addr ** sas;
  161. struct sock_addr * sa;
  162. struct sockaddr_in * sin;
  163. /* Allocate and populate a sockaddr_in structure. */
  164. if ((sin = calloc(1, sizeof(struct sockaddr_in))) == NULL)
  165. goto err0;
  166. sin->sin_family = AF_INET;
  167. sin->sin_port = htons(p);
  168. if (inet_pton(AF_INET, addr, &sin->sin_addr) != 1) {
  169. warn0("Error parsing IP address: %s", addr);
  170. goto err1;
  171. }
  172. /* Allocate and populate our wrapper. */
  173. if ((sa = malloc(sizeof(struct sock_addr))) == NULL)
  174. goto err1;
  175. sa->ai_family = AF_INET;
  176. sa->ai_socktype = SOCK_STREAM;
  177. sa->name = (struct sockaddr *)sin;
  178. sa->namelen = sizeof(struct sockaddr_in);
  179. /* Allocate and populate an array of pointers. */
  180. if ((sas = malloc(2 * sizeof(struct sock_addr *))) == NULL)
  181. goto err2;
  182. sas[0] = sa;
  183. sas[1] = NULL;
  184. /* Success! */
  185. return (sas);
  186. err2:
  187. free(sa);
  188. err1:
  189. free(sin);
  190. err0:
  191. /* Failure! */
  192. return (NULL);
  193. }
  194. /**
  195. * sock_resolve(addr):
  196. * Return a NULL-terminated array of pointers to sock_addr structures.
  197. */
  198. struct sock_addr **
  199. sock_resolve(const char * addr)
  200. {
  201. struct sock_addr ** res;
  202. char * s;
  203. char * ports;
  204. char * ips;
  205. long p;
  206. /* Check syntax. */
  207. if (sock_addr_validate(addr))
  208. goto err0;
  209. /* If the address starts with '/', it's a Unix domain socket. */
  210. if (addr[0] == '/') {
  211. res = sock_resolve_unix(addr);
  212. goto done0;
  213. }
  214. /* Copy the address so that we can mangle it. */
  215. if ((s = strdup(addr)) == NULL)
  216. goto err0;
  217. /* The address should end with :port. Look for the last ':'. */
  218. if ((ports = strrchr(s, ':')) == NULL) {
  219. warn0("Address must contain port number: %s", s);
  220. goto err1;
  221. }
  222. *ports++ = '\0';
  223. /* If the address doesn't start with '[', it's a host name. */
  224. if (s[0] != '[') {
  225. res = sock_resolve_host(s, ports);
  226. goto done1;
  227. }
  228. /* The address (sans :port) should end with ']'. */
  229. if (s[strlen(s) - 1] != ']') {
  230. warn0("Invalid [IP address]: %s", s);
  231. goto err1;
  232. }
  233. /* Extract the IP address string. */
  234. ips = &s[1];
  235. ips[strlen(ips) - 1] = '\0';
  236. /* Parse the port number in base 10, no trailing characters. */
  237. if (PARSENUM_EX(&p, ports, 1, 65535, 10, 0)) {
  238. warn0("Invalid port number: %s", ports);
  239. goto err1;
  240. }
  241. /* If the IP address contains ':', it's IPv6; otherwise, IPv4. */
  242. if (strchr(ips, ':') != NULL)
  243. res = sock_resolve_ipv6(ips, (in_port_t)p);
  244. else
  245. res = sock_resolve_ipv4(ips, (in_port_t)p);
  246. done1:
  247. /* Free string allocated by strdup. */
  248. free(s);
  249. done0:
  250. /* Return result from sock_resolve_foo. */
  251. return (res);
  252. err1:
  253. free(s);
  254. err0:
  255. /* Failure! */
  256. return (NULL);
  257. }
  258. /**
  259. * sock_resolve_one(addr, addport):
  260. * Return a single sock_addr structure, or NULL if there are no addresses.
  261. * Warn if there is more than one address, and return the first one.
  262. * If ${addport} is non-zero, use sock_addr_ensure_port() to add a port number
  263. * of ":0" if appropriate.
  264. */
  265. struct sock_addr *
  266. sock_resolve_one(const char * addr, int addport)
  267. {
  268. struct sock_addr ** sas;
  269. struct sock_addr * sa;
  270. struct sock_addr ** sa_tmp;
  271. char * addr_alloc = NULL;
  272. /* Prepare the address to resolve. */
  273. if (addport &&
  274. ((addr = addr_alloc = sock_addr_ensure_port(addr)) == NULL)) {
  275. warnp("sock_addr_ensure_port");
  276. goto err0;
  277. }
  278. /* Resolve target address. */
  279. if ((sas = sock_resolve(addr)) == NULL) {
  280. warnp("Error resolving socket address: %s", addr);
  281. goto err1;
  282. }
  283. /* Check that the array is not empty. */
  284. if (sas[0] == NULL) {
  285. warn0("No addresses found for %s", addr);
  286. goto err2;
  287. }
  288. /* If there's more than one address, give a warning. */
  289. if (sas[1] != NULL)
  290. warn0("Using the first of multiple addresses found for %s",
  291. addr);
  292. /* Keep the address we want. */
  293. sa = sas[0];
  294. /* Free the other addresses and list. */
  295. for (sa_tmp = &sas[1]; *sa_tmp != NULL; sa_tmp++)
  296. sock_addr_free(*sa_tmp);
  297. free(sas);
  298. /* Clean up. */
  299. free(addr_alloc);
  300. /* Success! */
  301. return (sa);
  302. err2:
  303. sock_addr_freelist(sas);
  304. err1:
  305. free(addr_alloc);
  306. err0:
  307. /* Failure! */
  308. return (NULL);
  309. }
  310. /**
  311. * sock_listener(sa):
  312. * Create a socket, attempt to set SO_REUSEADDR, bind it to the socket address
  313. * ${sa}, mark it for listening, and mark it as non-blocking.
  314. */
  315. int
  316. sock_listener(const struct sock_addr * sa)
  317. {
  318. int s;
  319. int val = 1;
  320. /* Create a socket. */
  321. if ((s = socket(sa->ai_family, sa->ai_socktype, 0)) == -1) {
  322. warnp("socket(%d, %d)", sa->ai_family, sa->ai_socktype);
  323. goto err0;
  324. }
  325. /* Attempt to set SO_REUSEADDR. */
  326. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) {
  327. /* ENOPROTOOPT is ok. */
  328. if (errno != ENOPROTOOPT) {
  329. warnp("setsockopt(SO_REUSEADDR)");
  330. goto err1;
  331. }
  332. }
  333. /* Bind the socket. */
  334. if (bind(s, sa->name, sa->namelen)) {
  335. warnp("Error binding socket");
  336. goto err1;
  337. }
  338. /* Mark the socket as listening. */
  339. if (listen(s, 10)) {
  340. warnp("Error marking socket as listening");
  341. goto err1;
  342. }
  343. /* Mark the socket as non-blocking. */
  344. if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
  345. warnp("Error marking socket as non-blocking");
  346. goto err1;
  347. }
  348. /* Success! */
  349. return (s);
  350. err1:
  351. if (close(s))
  352. warnp("close");
  353. err0:
  354. /* Failure! */
  355. return (-1);
  356. }
  357. /**
  358. * sock_connect(sas):
  359. * Iterate through the addresses in ${sas}, attempting to create a socket and
  360. * connect (blockingly). Once connected, stop iterating, mark the socket as
  361. * non-blocking, and return it.
  362. */
  363. int
  364. sock_connect(struct sock_addr * const * sas)
  365. {
  366. int s = -1;
  367. /* Iterate through the addresses provided. */
  368. for (; sas[0] != NULL; sas++) {
  369. /* Create a socket. */
  370. if ((s = socket(sas[0]->ai_family,
  371. sas[0]->ai_socktype, 0)) == -1)
  372. continue;
  373. /* Attempt to connect. */
  374. if (connect(s, sas[0]->name, sas[0]->namelen) == 0)
  375. break;
  376. /* Close the socket; this address didn't work. */
  377. if (close(s))
  378. warnp("close");
  379. }
  380. /* Did we manage to connect? */
  381. if (sas[0] == NULL) {
  382. warn0("Could not connect");
  383. goto err0;
  384. }
  385. /* Mark the socket as non-blocking. */
  386. if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
  387. warnp("Cannot make connection non-blocking");
  388. goto err1;
  389. }
  390. /* Success! */
  391. return (s);
  392. err1:
  393. if (close(s))
  394. warnp("close");
  395. err0:
  396. /* Failure! */
  397. return (-1);
  398. }
  399. /**
  400. * sock_connect_nb(sa):
  401. * Create a socket, mark it as non-blocking, and attempt to connect to the
  402. * address ${sa}. Return the socket (connected or in the process of
  403. * connecting) or -1 on error.
  404. */
  405. int
  406. sock_connect_nb(const struct sock_addr * sa)
  407. {
  408. /* Let sock_connect_bind_nb handle this. */
  409. return (sock_connect_bind_nb(sa, NULL));
  410. }
  411. /**
  412. * sock_connect_bind_nb(sa, sa_b):
  413. * Create a socket, mark it as non-blocking, and attempt to connect to the
  414. * address ${sa}. If ${sa_b} is not NULL, attempt to set SO_REUSEADDR on the
  415. * socket and bind it to ${sa_b} immediately after creating it. Return the
  416. * socket (connected or in the process of connecting) or -1 on error.
  417. */
  418. int
  419. sock_connect_bind_nb(const struct sock_addr * sa,
  420. const struct sock_addr * sa_b)
  421. {
  422. int s;
  423. int val = 1;
  424. /* Create a socket. */
  425. if ((s = socket(sa->ai_family, sa->ai_socktype, 0)) == -1) {
  426. warnp("socket(%d, %d)", sa->ai_family, sa->ai_socktype);
  427. goto err0;
  428. }
  429. /* Bind the socket to sa_b (if applicable). */
  430. if (sa_b) {
  431. /* Attempt to set SO_REUSEADDR. */
  432. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val,
  433. sizeof(val))) {
  434. /* ENOPROTOOPT is ok. */
  435. if (errno != ENOPROTOOPT) {
  436. warnp("setsockopt(SO_REUSEADDR)");
  437. goto err1;
  438. }
  439. }
  440. /* Bind socket. */
  441. if ((bind(s, sa_b->name, sa_b->namelen)) == -1) {
  442. warnp("Error binding socket");
  443. goto err1;
  444. }
  445. }
  446. /* Mark the socket as non-blocking. */
  447. if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
  448. warnp("Cannot make socket non-blocking");
  449. goto err1;
  450. }
  451. /* Attempt to connect. */
  452. if ((connect(s, sa->name, sa->namelen) == -1) &&
  453. (errno != EINPROGRESS) &&
  454. (errno != EINTR)) {
  455. warnp("connect");
  456. goto err1;
  457. }
  458. /* We have a connect(ed|ing) socket. */
  459. return (s);
  460. err1:
  461. if (close(s))
  462. warnp("close");
  463. err0:
  464. /* We failed to connect to this address. */
  465. return (-1);
  466. }
  467. /**
  468. * sock_addr_free(sa):
  469. * Free the provided sock_addr structure.
  470. */
  471. void
  472. sock_addr_free(struct sock_addr * sa)
  473. {
  474. /* Behave consistently with free(NULL). */
  475. if (sa == NULL)
  476. return;
  477. /* Free the protocol-specific address structure and our struct. */
  478. free(sa->name);
  479. free(sa);
  480. }
  481. /**
  482. * sock_addr_freelist(sas):
  483. * Free the provided NULL-terminated array of sock_addr structures.
  484. */
  485. void
  486. sock_addr_freelist(struct sock_addr ** sas)
  487. {
  488. struct sock_addr ** p;
  489. /* Behave consistently with free(NULL). */
  490. if (sas == NULL)
  491. return;
  492. /* Free structures until we hit NULL. */
  493. for (p = sas; *p != NULL; p++)
  494. sock_addr_free(*p);
  495. /* Free the list. */
  496. free(sas);
  497. }