xconnect.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Connect to host at port using address resolution from getaddrinfo
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. #include <sys/types.h>
  10. #include <sys/socket.h> /* netinet/in.h needs it */
  11. #include <netinet/in.h>
  12. #include <net/if.h>
  13. #include <sys/un.h>
  14. #if ENABLE_IFPLUGD || ENABLE_FEATURE_MDEV_DAEMON || ENABLE_UEVENT
  15. # include <linux/netlink.h>
  16. #endif
  17. #include "libbb.h"
  18. int FAST_FUNC setsockopt_int(int fd, int level, int optname, int optval)
  19. {
  20. return setsockopt(fd, level, optname, &optval, sizeof(int));
  21. }
  22. int FAST_FUNC setsockopt_1(int fd, int level, int optname)
  23. {
  24. return setsockopt_int(fd, level, optname, 1);
  25. }
  26. int FAST_FUNC setsockopt_SOL_SOCKET_int(int fd, int optname, int optval)
  27. {
  28. return setsockopt_int(fd, SOL_SOCKET, optname, optval);
  29. }
  30. int FAST_FUNC setsockopt_SOL_SOCKET_1(int fd, int optname)
  31. {
  32. return setsockopt_SOL_SOCKET_int(fd, optname, 1);
  33. }
  34. void FAST_FUNC setsockopt_reuseaddr(int fd)
  35. {
  36. setsockopt_SOL_SOCKET_1(fd, SO_REUSEADDR);
  37. }
  38. int FAST_FUNC setsockopt_broadcast(int fd)
  39. {
  40. return setsockopt_SOL_SOCKET_1(fd, SO_BROADCAST);
  41. }
  42. int FAST_FUNC setsockopt_keepalive(int fd)
  43. {
  44. return setsockopt_SOL_SOCKET_1(fd, SO_KEEPALIVE);
  45. }
  46. #ifdef SO_BINDTODEVICE
  47. int FAST_FUNC setsockopt_bindtodevice(int fd, const char *iface)
  48. {
  49. int r;
  50. struct ifreq ifr;
  51. strncpy_IFNAMSIZ(ifr.ifr_name, iface);
  52. /* NB: passing (iface, strlen(iface) + 1) does not work!
  53. * (maybe it works on _some_ kernels, but not on 2.6.26)
  54. * Actually, ifr_name is at offset 0, and in practice
  55. * just giving char[IFNAMSIZ] instead of struct ifreq works too.
  56. * But just in case it's not true on some obscure arch... */
  57. r = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
  58. if (r)
  59. bb_perror_msg("can't bind to interface %s", iface);
  60. return r;
  61. }
  62. #else
  63. int FAST_FUNC setsockopt_bindtodevice(int fd UNUSED_PARAM,
  64. const char *iface UNUSED_PARAM)
  65. {
  66. bb_simple_error_msg("SO_BINDTODEVICE is not supported on this system");
  67. return -1;
  68. }
  69. #endif
  70. static len_and_sockaddr* get_lsa(int fd, int (*get_name)(int fd, struct sockaddr *addr, socklen_t *addrlen))
  71. {
  72. len_and_sockaddr lsa;
  73. len_and_sockaddr *lsa_ptr;
  74. lsa.len = LSA_SIZEOF_SA;
  75. if (get_name(fd, &lsa.u.sa, &lsa.len) != 0)
  76. return NULL;
  77. lsa_ptr = xzalloc(LSA_LEN_SIZE + lsa.len);
  78. if (lsa.len > LSA_SIZEOF_SA) { /* rarely (if ever) happens */
  79. lsa_ptr->len = lsa.len;
  80. get_name(fd, &lsa_ptr->u.sa, &lsa_ptr->len);
  81. } else {
  82. memcpy(lsa_ptr, &lsa, LSA_LEN_SIZE + lsa.len);
  83. }
  84. return lsa_ptr;
  85. }
  86. len_and_sockaddr* FAST_FUNC get_sock_lsa(int fd)
  87. {
  88. return get_lsa(fd, getsockname);
  89. }
  90. len_and_sockaddr* FAST_FUNC get_peer_lsa(int fd)
  91. {
  92. return get_lsa(fd, getpeername);
  93. }
  94. void FAST_FUNC xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen)
  95. {
  96. if (connect(s, s_addr, addrlen) < 0) {
  97. if (ENABLE_FEATURE_CLEAN_UP)
  98. close(s);
  99. if (s_addr->sa_family == AF_INET)
  100. bb_perror_msg_and_die("%s (%s)",
  101. "can't connect to remote host",
  102. inet_ntoa(((struct sockaddr_in *)s_addr)->sin_addr));
  103. bb_simple_perror_msg_and_die("can't connect to remote host");
  104. }
  105. }
  106. /* Return port number for a service.
  107. * If "port" is a number use it as the port.
  108. * If "port" is a name it is looked up in /etc/services,
  109. * if it isnt found return default_port
  110. */
  111. unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned default_port)
  112. {
  113. unsigned port_nr = default_port;
  114. if (port) {
  115. int old_errno;
  116. /* Since this is a lib function, we're not allowed to reset errno to 0.
  117. * Doing so could break an app that is deferring checking of errno. */
  118. old_errno = errno;
  119. port_nr = bb_strtou(port, NULL, 10);
  120. if (errno || port_nr > 65535) {
  121. struct servent *tserv = getservbyname(port, protocol);
  122. port_nr = default_port;
  123. if (tserv)
  124. port_nr = ntohs(tserv->s_port);
  125. //FIXME: else: port string was garbage, but we don't report that???
  126. }
  127. errno = old_errno;
  128. }
  129. return (uint16_t)port_nr;
  130. }
  131. /* "New" networking API */
  132. int FAST_FUNC get_nport(const struct sockaddr *sa)
  133. {
  134. #if ENABLE_FEATURE_IPV6
  135. if (sa->sa_family == AF_INET6) {
  136. return ((struct sockaddr_in6*)sa)->sin6_port;
  137. }
  138. #endif
  139. if (sa->sa_family == AF_INET) {
  140. return ((struct sockaddr_in*)sa)->sin_port;
  141. }
  142. /* What? UNIX socket? IPX?? :) */
  143. return -1;
  144. }
  145. void FAST_FUNC set_nport(struct sockaddr *sa, unsigned port)
  146. {
  147. #if ENABLE_FEATURE_IPV6
  148. if (sa->sa_family == AF_INET6) {
  149. struct sockaddr_in6 *sin6 = (void*) sa;
  150. sin6->sin6_port = port;
  151. return;
  152. }
  153. #endif
  154. if (sa->sa_family == AF_INET) {
  155. struct sockaddr_in *sin = (void*) sa;
  156. sin->sin_port = port;
  157. return;
  158. }
  159. /* What? UNIX socket? IPX?? :) */
  160. }
  161. /* We hijack this constant to mean something else */
  162. /* It doesn't hurt because we will remove this bit anyway */
  163. #define DIE_ON_ERROR AI_CANONNAME
  164. /* host: "1.2.3.4[:port]", "www.google.com[:port]"
  165. * port: if neither of above specifies port # */
  166. static len_and_sockaddr* str2sockaddr(
  167. const char *host, int port,
  168. IF_FEATURE_IPV6(sa_family_t af,)
  169. int ai_flags)
  170. {
  171. IF_NOT_FEATURE_IPV6(sa_family_t af = AF_INET;)
  172. int rc;
  173. len_and_sockaddr *r;
  174. struct addrinfo *result = NULL;
  175. struct addrinfo *used_res;
  176. const char *org_host = host; /* only for error msg */
  177. const char *cp;
  178. struct addrinfo hint;
  179. if (ENABLE_FEATURE_UNIX_LOCAL && is_prefixed_with(host, "local:")) {
  180. struct sockaddr_un *sun;
  181. r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_un));
  182. r->len = sizeof(struct sockaddr_un);
  183. r->u.sa.sa_family = AF_UNIX;
  184. sun = (struct sockaddr_un *)&r->u.sa;
  185. safe_strncpy(sun->sun_path, host + 6, sizeof(sun->sun_path));
  186. return r;
  187. }
  188. r = NULL;
  189. /* Ugly parsing of host:addr */
  190. if (ENABLE_FEATURE_IPV6 && host[0] == '[') {
  191. /* Even uglier parsing of [xx]:nn */
  192. host++;
  193. cp = strchr(host, ']');
  194. if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
  195. /* Malformed: must be [xx]:nn or [xx] */
  196. bb_error_msg("bad address '%s'", org_host);
  197. if (ai_flags & DIE_ON_ERROR)
  198. xfunc_die();
  199. return NULL;
  200. }
  201. } else {
  202. cp = strrchr(host, ':');
  203. if (ENABLE_FEATURE_IPV6 && cp && strchr(host, ':') != cp) {
  204. /* There is more than one ':' (e.g. "::1") */
  205. cp = NULL; /* it's not a port spec */
  206. }
  207. }
  208. if (cp) { /* points to ":" or "]:" */
  209. int sz = cp - host + 1;
  210. host = safe_strncpy(alloca(sz), host, sz);
  211. if (ENABLE_FEATURE_IPV6 && *cp != ':') {
  212. cp++; /* skip ']' */
  213. if (*cp == '\0') /* [xx] without port */
  214. goto skip;
  215. }
  216. cp++; /* skip ':' */
  217. port = bb_strtou(cp, NULL, 10);
  218. if (errno || (unsigned)port > 0xffff) {
  219. bb_error_msg("bad port spec '%s'", org_host);
  220. if (ai_flags & DIE_ON_ERROR)
  221. xfunc_die();
  222. return NULL;
  223. }
  224. skip: ;
  225. }
  226. /* Next two if blocks allow to skip getaddrinfo()
  227. * in case host name is a numeric IP(v6) address.
  228. * getaddrinfo() initializes DNS resolution machinery,
  229. * scans network config and such - tens of syscalls.
  230. */
  231. /* If we were not asked specifically for IPv6,
  232. * check whether this is a numeric IPv4 */
  233. IF_FEATURE_IPV6(if(af != AF_INET6)) {
  234. struct in_addr in4;
  235. if (inet_aton(host, &in4) != 0) {
  236. r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_in));
  237. r->len = sizeof(struct sockaddr_in);
  238. r->u.sa.sa_family = AF_INET;
  239. r->u.sin.sin_addr = in4;
  240. goto set_port;
  241. }
  242. }
  243. #if ENABLE_FEATURE_IPV6
  244. /* If we were not asked specifically for IPv4,
  245. * check whether this is a numeric IPv6 */
  246. if (af != AF_INET) {
  247. struct in6_addr in6;
  248. if (inet_pton(AF_INET6, host, &in6) > 0) {
  249. r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_in6));
  250. r->len = sizeof(struct sockaddr_in6);
  251. r->u.sa.sa_family = AF_INET6;
  252. r->u.sin6.sin6_addr = in6;
  253. goto set_port;
  254. }
  255. }
  256. #endif
  257. memset(&hint, 0 , sizeof(hint));
  258. hint.ai_family = af;
  259. /* Need SOCK_STREAM, or else we get each address thrice (or more)
  260. * for each possible socket type (tcp,udp,raw...): */
  261. hint.ai_socktype = SOCK_STREAM;
  262. hint.ai_flags = ai_flags & ~DIE_ON_ERROR;
  263. rc = getaddrinfo(host, NULL, &hint, &result);
  264. if (rc || !result) {
  265. bb_error_msg("bad address '%s'", org_host);
  266. if (ai_flags & DIE_ON_ERROR)
  267. xfunc_die();
  268. goto ret;
  269. }
  270. used_res = result;
  271. #if ENABLE_FEATURE_PREFER_IPV4_ADDRESS
  272. while (1) {
  273. if (used_res->ai_family == AF_INET)
  274. break;
  275. used_res = used_res->ai_next;
  276. if (!used_res) {
  277. used_res = result;
  278. break;
  279. }
  280. }
  281. #endif
  282. r = xmalloc(LSA_LEN_SIZE + used_res->ai_addrlen);
  283. r->len = used_res->ai_addrlen;
  284. memcpy(&r->u.sa, used_res->ai_addr, used_res->ai_addrlen);
  285. set_port:
  286. set_nport(&r->u.sa, htons(port));
  287. ret:
  288. if (result)
  289. freeaddrinfo(result);
  290. return r;
  291. }
  292. #if !ENABLE_FEATURE_IPV6
  293. #define str2sockaddr(host, port, af, ai_flags) str2sockaddr(host, port, ai_flags)
  294. #endif
  295. #if ENABLE_FEATURE_IPV6
  296. len_and_sockaddr* FAST_FUNC host_and_af2sockaddr(const char *host, int port, sa_family_t af)
  297. {
  298. return str2sockaddr(host, port, af, 0);
  299. }
  300. len_and_sockaddr* FAST_FUNC xhost_and_af2sockaddr(const char *host, int port, sa_family_t af)
  301. {
  302. return str2sockaddr(host, port, af, DIE_ON_ERROR);
  303. }
  304. #endif
  305. len_and_sockaddr* FAST_FUNC host2sockaddr(const char *host, int port)
  306. {
  307. return str2sockaddr(host, port, AF_UNSPEC, 0);
  308. }
  309. len_and_sockaddr* FAST_FUNC xhost2sockaddr(const char *host, int port)
  310. {
  311. return str2sockaddr(host, port, AF_UNSPEC, DIE_ON_ERROR);
  312. }
  313. len_and_sockaddr* FAST_FUNC xdotted2sockaddr(const char *host, int port)
  314. {
  315. return str2sockaddr(host, port, AF_UNSPEC, AI_NUMERICHOST | DIE_ON_ERROR);
  316. }
  317. int FAST_FUNC xsocket_type(len_and_sockaddr **lsap, int family, int sock_type)
  318. {
  319. len_and_sockaddr *lsa;
  320. int fd;
  321. int len;
  322. if (family == AF_UNSPEC) {
  323. #if ENABLE_FEATURE_IPV6
  324. fd = socket(AF_INET6, sock_type, 0);
  325. if (fd >= 0) {
  326. family = AF_INET6;
  327. goto done;
  328. }
  329. #endif
  330. family = AF_INET;
  331. }
  332. fd = xsocket(family, sock_type, 0);
  333. len = sizeof(struct sockaddr_in);
  334. if (family == AF_UNIX)
  335. len = sizeof(struct sockaddr_un);
  336. #if ENABLE_FEATURE_IPV6
  337. if (family == AF_INET6) {
  338. done:
  339. len = sizeof(struct sockaddr_in6);
  340. }
  341. #endif
  342. lsa = xzalloc(LSA_LEN_SIZE + len);
  343. lsa->len = len;
  344. lsa->u.sa.sa_family = family;
  345. *lsap = lsa;
  346. return fd;
  347. }
  348. int FAST_FUNC xsocket_stream(len_and_sockaddr **lsap)
  349. {
  350. return xsocket_type(lsap, AF_UNSPEC, SOCK_STREAM);
  351. }
  352. static int create_and_bind_or_die(const char *bindaddr, int port, int sock_type)
  353. {
  354. int fd;
  355. len_and_sockaddr *lsa;
  356. if (bindaddr && bindaddr[0]) {
  357. lsa = xdotted2sockaddr(bindaddr, port);
  358. /* user specified bind addr dictates family */
  359. fd = xsocket(lsa->u.sa.sa_family, sock_type, 0);
  360. } else {
  361. fd = xsocket_type(&lsa, AF_UNSPEC, sock_type);
  362. set_nport(&lsa->u.sa, htons(port));
  363. }
  364. setsockopt_reuseaddr(fd);
  365. xbind(fd, &lsa->u.sa, lsa->len);
  366. free(lsa);
  367. return fd;
  368. }
  369. int FAST_FUNC create_and_bind_stream_or_die(const char *bindaddr, int port)
  370. {
  371. return create_and_bind_or_die(bindaddr, port, SOCK_STREAM);
  372. }
  373. int FAST_FUNC create_and_bind_dgram_or_die(const char *bindaddr, int port)
  374. {
  375. return create_and_bind_or_die(bindaddr, port, SOCK_DGRAM);
  376. }
  377. #if ENABLE_IFPLUGD || ENABLE_FEATURE_MDEV_DAEMON || ENABLE_UEVENT
  378. int FAST_FUNC create_and_bind_to_netlink(int proto, int grp, unsigned rcvbuf)
  379. {
  380. struct sockaddr_nl sa;
  381. int fd;
  382. memset(&sa, 0, sizeof(sa));
  383. sa.nl_family = AF_NETLINK;
  384. sa.nl_pid = getpid();
  385. sa.nl_groups = grp;
  386. fd = xsocket(AF_NETLINK, SOCK_DGRAM, proto);
  387. xbind(fd, (struct sockaddr *) &sa, sizeof(sa));
  388. close_on_exec_on(fd);
  389. if (rcvbuf != 0) {
  390. // SO_RCVBUFFORCE (root only) can go above net.core.rmem_max sysctl
  391. setsockopt_SOL_SOCKET_int(fd, SO_RCVBUF, rcvbuf);
  392. setsockopt_SOL_SOCKET_int(fd, SO_RCVBUFFORCE, rcvbuf);
  393. # if 0
  394. {
  395. int z;
  396. socklen_t zl = sizeof(z);
  397. getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &z, &zl);
  398. bb_error_msg("SO_RCVBUF:%d", z);
  399. }
  400. # endif
  401. }
  402. return fd;
  403. }
  404. #endif
  405. int FAST_FUNC create_and_connect_stream_or_die(const char *peer, int port)
  406. {
  407. int fd;
  408. len_and_sockaddr *lsa;
  409. lsa = xhost2sockaddr(peer, port);
  410. fd = xsocket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
  411. setsockopt_reuseaddr(fd);
  412. xconnect(fd, &lsa->u.sa, lsa->len);
  413. free(lsa);
  414. return fd;
  415. }
  416. int FAST_FUNC xconnect_stream(const len_and_sockaddr *lsa)
  417. {
  418. int fd = xsocket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
  419. xconnect(fd, &lsa->u.sa, lsa->len);
  420. return fd;
  421. }
  422. /* We hijack this constant to mean something else */
  423. /* It doesn't hurt because we will add this bit anyway */
  424. #define IGNORE_PORT NI_NUMERICSERV
  425. static char* FAST_FUNC sockaddr2str(const struct sockaddr *sa, int flags)
  426. {
  427. char host[128];
  428. char serv[16];
  429. int rc;
  430. socklen_t salen;
  431. if (ENABLE_FEATURE_UNIX_LOCAL && sa->sa_family == AF_UNIX) {
  432. struct sockaddr_un *sun = (struct sockaddr_un *)sa;
  433. return xasprintf("local:%.*s",
  434. (int) sizeof(sun->sun_path),
  435. sun->sun_path);
  436. }
  437. salen = LSA_SIZEOF_SA;
  438. #if ENABLE_FEATURE_IPV6
  439. if (sa->sa_family == AF_INET)
  440. salen = sizeof(struct sockaddr_in);
  441. if (sa->sa_family == AF_INET6)
  442. salen = sizeof(struct sockaddr_in6);
  443. #endif
  444. rc = getnameinfo(sa, salen,
  445. host, sizeof(host),
  446. /* can do ((flags & IGNORE_PORT) ? NULL : serv) but why bother? */
  447. serv, sizeof(serv),
  448. /* do not resolve port# into service _name_ */
  449. flags | NI_NUMERICSERV
  450. );
  451. if (rc)
  452. return NULL;
  453. if (flags & IGNORE_PORT)
  454. return xstrdup(host);
  455. #if ENABLE_FEATURE_IPV6
  456. if (sa->sa_family == AF_INET6) {
  457. if (strchr(host, ':')) /* heh, it's not a resolved hostname */
  458. return xasprintf("[%s]:%s", host, serv);
  459. /*return xasprintf("%s:%s", host, serv);*/
  460. /* - fall through instead */
  461. }
  462. #endif
  463. /* For now we don't support anything else, so it has to be INET */
  464. /*if (sa->sa_family == AF_INET)*/
  465. return xasprintf("%s:%s", host, serv);
  466. /*return xstrdup(host);*/
  467. }
  468. char* FAST_FUNC xmalloc_sockaddr2host(const struct sockaddr *sa)
  469. {
  470. return sockaddr2str(sa, 0);
  471. }
  472. char* FAST_FUNC xmalloc_sockaddr2host_noport(const struct sockaddr *sa)
  473. {
  474. return sockaddr2str(sa, IGNORE_PORT);
  475. }
  476. char* FAST_FUNC xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa)
  477. {
  478. return sockaddr2str(sa, NI_NAMEREQD | IGNORE_PORT);
  479. }
  480. #ifndef NI_NUMERICSCOPE
  481. # define NI_NUMERICSCOPE 0
  482. #endif
  483. char* FAST_FUNC xmalloc_sockaddr2dotted(const struct sockaddr *sa)
  484. {
  485. return sockaddr2str(sa, NI_NUMERICHOST | NI_NUMERICSCOPE);
  486. }
  487. char* FAST_FUNC xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa)
  488. {
  489. return sockaddr2str(sa, NI_NUMERICHOST | NI_NUMERICSCOPE | IGNORE_PORT);
  490. }