1 /*-------------------------------------------------------------------------
2  *
3  * ip.c
4  *	  IPv6-aware network access.
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/libpq/ip.c
12  *
13  * This file and the IPV6 implementation were initially provided by
14  * Nigel Kukard <nkukard@lbsd.net>, Linux Based Systems Design
15  * http://www.lbsd.net.
16  *
17  *-------------------------------------------------------------------------
18  */
19 
20 /* This is intended to be used in both frontend and backend, so use c.h */
21 #include "c.h"
22 
23 #include <unistd.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/socket.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #ifdef HAVE_NETINET_TCP_H
30 #include <netinet/tcp.h>
31 #endif
32 #include <arpa/inet.h>
33 #include <sys/file.h>
34 
35 #include "libpq/ip.h"
36 
37 
38 static int range_sockaddr_AF_INET(const struct sockaddr_in * addr,
39 					   const struct sockaddr_in * netaddr,
40 					   const struct sockaddr_in * netmask);
41 
42 #ifdef HAVE_IPV6
43 static int range_sockaddr_AF_INET6(const struct sockaddr_in6 * addr,
44 						const struct sockaddr_in6 * netaddr,
45 						const struct sockaddr_in6 * netmask);
46 #endif
47 
48 #ifdef	HAVE_UNIX_SOCKETS
49 static int getaddrinfo_unix(const char *path,
50 				 const struct addrinfo * hintsp,
51 				 struct addrinfo ** result);
52 
53 static int getnameinfo_unix(const struct sockaddr_un * sa, int salen,
54 				 char *node, int nodelen,
55 				 char *service, int servicelen,
56 				 int flags);
57 #endif
58 
59 
60 /*
61  *	pg_getaddrinfo_all - get address info for Unix, IPv4 and IPv6 sockets
62  */
63 int
pg_getaddrinfo_all(const char * hostname,const char * servname,const struct addrinfo * hintp,struct addrinfo ** result)64 pg_getaddrinfo_all(const char *hostname, const char *servname,
65 				   const struct addrinfo * hintp, struct addrinfo ** result)
66 {
67 	int			rc;
68 
69 	/* not all versions of getaddrinfo() zero *result on failure */
70 	*result = NULL;
71 
72 #ifdef HAVE_UNIX_SOCKETS
73 	if (hintp->ai_family == AF_UNIX)
74 		return getaddrinfo_unix(servname, hintp, result);
75 #endif
76 
77 	/* NULL has special meaning to getaddrinfo(). */
78 	rc = getaddrinfo((!hostname || hostname[0] == '\0') ? NULL : hostname,
79 					 servname, hintp, result);
80 
81 	return rc;
82 }
83 
84 
85 /*
86  *	pg_freeaddrinfo_all - free addrinfo structures for IPv4, IPv6, or Unix
87  *
88  * Note: the ai_family field of the original hint structure must be passed
89  * so that we can tell whether the addrinfo struct was built by the system's
90  * getaddrinfo() routine or our own getaddrinfo_unix() routine.  Some versions
91  * of getaddrinfo() might be willing to return AF_UNIX addresses, so it's
92  * not safe to look at ai_family in the addrinfo itself.
93  */
94 void
pg_freeaddrinfo_all(int hint_ai_family,struct addrinfo * ai)95 pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo * ai)
96 {
97 #ifdef HAVE_UNIX_SOCKETS
98 	if (hint_ai_family == AF_UNIX)
99 	{
100 		/* struct was built by getaddrinfo_unix (see pg_getaddrinfo_all) */
101 		while (ai != NULL)
102 		{
103 			struct addrinfo *p = ai;
104 
105 			ai = ai->ai_next;
106 			free(p->ai_addr);
107 			free(p);
108 		}
109 	}
110 	else
111 #endif   /* HAVE_UNIX_SOCKETS */
112 	{
113 		/* struct was built by getaddrinfo() */
114 		if (ai != NULL)
115 			freeaddrinfo(ai);
116 	}
117 }
118 
119 
120 /*
121  *	pg_getnameinfo_all - get name info for Unix, IPv4 and IPv6 sockets
122  *
123  * The API of this routine differs from the standard getnameinfo() definition
124  * in two ways: first, the addr parameter is declared as sockaddr_storage
125  * rather than struct sockaddr, and second, the node and service fields are
126  * guaranteed to be filled with something even on failure return.
127  */
128 int
pg_getnameinfo_all(const struct sockaddr_storage * addr,int salen,char * node,int nodelen,char * service,int servicelen,int flags)129 pg_getnameinfo_all(const struct sockaddr_storage * addr, int salen,
130 				   char *node, int nodelen,
131 				   char *service, int servicelen,
132 				   int flags)
133 {
134 	int			rc;
135 
136 #ifdef HAVE_UNIX_SOCKETS
137 	if (addr && addr->ss_family == AF_UNIX)
138 		rc = getnameinfo_unix((const struct sockaddr_un *) addr, salen,
139 							  node, nodelen,
140 							  service, servicelen,
141 							  flags);
142 	else
143 #endif
144 		rc = getnameinfo((const struct sockaddr *) addr, salen,
145 						 node, nodelen,
146 						 service, servicelen,
147 						 flags);
148 
149 	if (rc != 0)
150 	{
151 		if (node)
152 			strlcpy(node, "???", nodelen);
153 		if (service)
154 			strlcpy(service, "???", servicelen);
155 	}
156 
157 	return rc;
158 }
159 
160 
161 #if defined(HAVE_UNIX_SOCKETS)
162 
163 /* -------
164  *	getaddrinfo_unix - get unix socket info using IPv6-compatible API
165  *
166  *	Bugs: only one addrinfo is set even though hintsp is NULL or
167  *		  ai_socktype is 0
168  *		  AI_CANONNAME is not supported.
169  * -------
170  */
171 static int
getaddrinfo_unix(const char * path,const struct addrinfo * hintsp,struct addrinfo ** result)172 getaddrinfo_unix(const char *path, const struct addrinfo * hintsp,
173 				 struct addrinfo ** result)
174 {
175 	struct addrinfo hints;
176 	struct addrinfo *aip;
177 	struct sockaddr_un *unp;
178 
179 	*result = NULL;
180 
181 	MemSet(&hints, 0, sizeof(hints));
182 
183 	if (strlen(path) >= sizeof(unp->sun_path))
184 		return EAI_FAIL;
185 
186 	if (hintsp == NULL)
187 	{
188 		hints.ai_family = AF_UNIX;
189 		hints.ai_socktype = SOCK_STREAM;
190 	}
191 	else
192 		memcpy(&hints, hintsp, sizeof(hints));
193 
194 	if (hints.ai_socktype == 0)
195 		hints.ai_socktype = SOCK_STREAM;
196 
197 	if (hints.ai_family != AF_UNIX)
198 	{
199 		/* shouldn't have been called */
200 		return EAI_FAIL;
201 	}
202 
203 	aip = calloc(1, sizeof(struct addrinfo));
204 	if (aip == NULL)
205 		return EAI_MEMORY;
206 
207 	unp = calloc(1, sizeof(struct sockaddr_un));
208 	if (unp == NULL)
209 	{
210 		free(aip);
211 		return EAI_MEMORY;
212 	}
213 
214 	aip->ai_family = AF_UNIX;
215 	aip->ai_socktype = hints.ai_socktype;
216 	aip->ai_protocol = hints.ai_protocol;
217 	aip->ai_next = NULL;
218 	aip->ai_canonname = NULL;
219 	*result = aip;
220 
221 	unp->sun_family = AF_UNIX;
222 	aip->ai_addr = (struct sockaddr *) unp;
223 	aip->ai_addrlen = sizeof(struct sockaddr_un);
224 
225 	strcpy(unp->sun_path, path);
226 
227 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
228 	unp->sun_len = sizeof(struct sockaddr_un);
229 #endif
230 
231 	return 0;
232 }
233 
234 /*
235  * Convert an address to a hostname.
236  */
237 static int
getnameinfo_unix(const struct sockaddr_un * sa,int salen,char * node,int nodelen,char * service,int servicelen,int flags)238 getnameinfo_unix(const struct sockaddr_un * sa, int salen,
239 				 char *node, int nodelen,
240 				 char *service, int servicelen,
241 				 int flags)
242 {
243 	int			ret;
244 
245 	/* Invalid arguments. */
246 	if (sa == NULL || sa->sun_family != AF_UNIX ||
247 		(node == NULL && service == NULL))
248 		return EAI_FAIL;
249 
250 	if (node)
251 	{
252 		ret = snprintf(node, nodelen, "%s", "[local]");
253 		if (ret < 0 || ret >= nodelen)
254 			return EAI_MEMORY;
255 	}
256 
257 	if (service)
258 	{
259 		ret = snprintf(service, servicelen, "%s", sa->sun_path);
260 		if (ret < 0 || ret >= servicelen)
261 			return EAI_MEMORY;
262 	}
263 
264 	return 0;
265 }
266 #endif   /* HAVE_UNIX_SOCKETS */
267 
268 
269 /*
270  * pg_range_sockaddr - is addr within the subnet specified by netaddr/netmask ?
271  *
272  * Note: caller must already have verified that all three addresses are
273  * in the same address family; and AF_UNIX addresses are not supported.
274  */
275 int
pg_range_sockaddr(const struct sockaddr_storage * addr,const struct sockaddr_storage * netaddr,const struct sockaddr_storage * netmask)276 pg_range_sockaddr(const struct sockaddr_storage * addr,
277 				  const struct sockaddr_storage * netaddr,
278 				  const struct sockaddr_storage * netmask)
279 {
280 	if (addr->ss_family == AF_INET)
281 		return range_sockaddr_AF_INET((const struct sockaddr_in *) addr,
282 									  (const struct sockaddr_in *) netaddr,
283 									  (const struct sockaddr_in *) netmask);
284 #ifdef HAVE_IPV6
285 	else if (addr->ss_family == AF_INET6)
286 		return range_sockaddr_AF_INET6((const struct sockaddr_in6 *) addr,
287 									   (const struct sockaddr_in6 *) netaddr,
288 									   (const struct sockaddr_in6 *) netmask);
289 #endif
290 	else
291 		return 0;
292 }
293 
294 static int
range_sockaddr_AF_INET(const struct sockaddr_in * addr,const struct sockaddr_in * netaddr,const struct sockaddr_in * netmask)295 range_sockaddr_AF_INET(const struct sockaddr_in * addr,
296 					   const struct sockaddr_in * netaddr,
297 					   const struct sockaddr_in * netmask)
298 {
299 	if (((addr->sin_addr.s_addr ^ netaddr->sin_addr.s_addr) &
300 		 netmask->sin_addr.s_addr) == 0)
301 		return 1;
302 	else
303 		return 0;
304 }
305 
306 
307 #ifdef HAVE_IPV6
308 
309 static int
range_sockaddr_AF_INET6(const struct sockaddr_in6 * addr,const struct sockaddr_in6 * netaddr,const struct sockaddr_in6 * netmask)310 range_sockaddr_AF_INET6(const struct sockaddr_in6 * addr,
311 						const struct sockaddr_in6 * netaddr,
312 						const struct sockaddr_in6 * netmask)
313 {
314 	int			i;
315 
316 	for (i = 0; i < 16; i++)
317 	{
318 		if (((addr->sin6_addr.s6_addr[i] ^ netaddr->sin6_addr.s6_addr[i]) &
319 			 netmask->sin6_addr.s6_addr[i]) != 0)
320 			return 0;
321 	}
322 
323 	return 1;
324 }
325 #endif   /* HAVE_IPV6 */
326 
327 /*
328  *	pg_sockaddr_cidr_mask - make a network mask of the appropriate family
329  *	  and required number of significant bits
330  *
331  * numbits can be null, in which case the mask is fully set.
332  *
333  * The resulting mask is placed in *mask, which had better be big enough.
334  *
335  * Return value is 0 if okay, -1 if not.
336  */
337 int
pg_sockaddr_cidr_mask(struct sockaddr_storage * mask,char * numbits,int family)338 pg_sockaddr_cidr_mask(struct sockaddr_storage * mask, char *numbits, int family)
339 {
340 	long		bits;
341 	char	   *endptr;
342 
343 	if (numbits == NULL)
344 	{
345 		bits = (family == AF_INET) ? 32 : 128;
346 	}
347 	else
348 	{
349 		bits = strtol(numbits, &endptr, 10);
350 		if (*numbits == '\0' || *endptr != '\0')
351 			return -1;
352 	}
353 
354 	switch (family)
355 	{
356 		case AF_INET:
357 			{
358 				struct sockaddr_in mask4;
359 				long		maskl;
360 
361 				if (bits < 0 || bits > 32)
362 					return -1;
363 				memset(&mask4, 0, sizeof(mask4));
364 				/* avoid "x << 32", which is not portable */
365 				if (bits > 0)
366 					maskl = (0xffffffffUL << (32 - (int) bits))
367 						& 0xffffffffUL;
368 				else
369 					maskl = 0;
370 				mask4.sin_addr.s_addr = htonl(maskl);
371 				memcpy(mask, &mask4, sizeof(mask4));
372 				break;
373 			}
374 
375 #ifdef HAVE_IPV6
376 		case AF_INET6:
377 			{
378 				struct sockaddr_in6 mask6;
379 				int			i;
380 
381 				if (bits < 0 || bits > 128)
382 					return -1;
383 				memset(&mask6, 0, sizeof(mask6));
384 				for (i = 0; i < 16; i++)
385 				{
386 					if (bits <= 0)
387 						mask6.sin6_addr.s6_addr[i] = 0;
388 					else if (bits >= 8)
389 						mask6.sin6_addr.s6_addr[i] = 0xff;
390 					else
391 					{
392 						mask6.sin6_addr.s6_addr[i] =
393 							(0xff << (8 - (int) bits)) & 0xff;
394 					}
395 					bits -= 8;
396 				}
397 				memcpy(mask, &mask6, sizeof(mask6));
398 				break;
399 			}
400 #endif
401 		default:
402 			return -1;
403 	}
404 
405 	mask->ss_family = family;
406 	return 0;
407 }
408 
409 
410 /*
411  * Run the callback function for the addr/mask, after making sure the
412  * mask is sane for the addr.
413  */
414 static void
run_ifaddr_callback(PgIfAddrCallback callback,void * cb_data,struct sockaddr * addr,struct sockaddr * mask)415 run_ifaddr_callback(PgIfAddrCallback callback, void *cb_data,
416 					struct sockaddr * addr, struct sockaddr * mask)
417 {
418 	struct sockaddr_storage fullmask;
419 
420 	if (!addr)
421 		return;
422 
423 	/* Check that the mask is valid */
424 	if (mask)
425 	{
426 		if (mask->sa_family != addr->sa_family)
427 		{
428 			mask = NULL;
429 		}
430 		else if (mask->sa_family == AF_INET)
431 		{
432 			if (((struct sockaddr_in *) mask)->sin_addr.s_addr == INADDR_ANY)
433 				mask = NULL;
434 		}
435 #ifdef HAVE_IPV6
436 		else if (mask->sa_family == AF_INET6)
437 		{
438 			if (IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *) mask)->sin6_addr))
439 				mask = NULL;
440 		}
441 #endif
442 	}
443 
444 	/* If mask is invalid, generate our own fully-set mask */
445 	if (!mask)
446 	{
447 		pg_sockaddr_cidr_mask(&fullmask, NULL, addr->sa_family);
448 		mask = (struct sockaddr *) & fullmask;
449 	}
450 
451 	(*callback) (addr, mask, cb_data);
452 }
453 
454 #ifdef WIN32
455 
456 #include <winsock2.h>
457 #include <ws2tcpip.h>
458 
459 /*
460  * Enumerate the system's network interface addresses and call the callback
461  * for each one.  Returns 0 if successful, -1 if trouble.
462  *
463  * This version is for Win32.  Uses the Winsock 2 functions (ie: ws2_32.dll)
464  */
465 int
pg_foreach_ifaddr(PgIfAddrCallback callback,void * cb_data)466 pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data)
467 {
468 	INTERFACE_INFO *ptr,
469 			   *ii = NULL;
470 	unsigned long length,
471 				i;
472 	unsigned long n_ii = 0;
473 	SOCKET		sock;
474 	int			error;
475 
476 	sock = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
477 	if (sock == INVALID_SOCKET)
478 		return -1;
479 
480 	while (n_ii < 1024)
481 	{
482 		n_ii += 64;
483 		ptr = realloc(ii, sizeof(INTERFACE_INFO) * n_ii);
484 		if (!ptr)
485 		{
486 			free(ii);
487 			closesocket(sock);
488 			errno = ENOMEM;
489 			return -1;
490 		}
491 
492 		ii = ptr;
493 		if (WSAIoctl(sock, SIO_GET_INTERFACE_LIST, 0, 0,
494 					 ii, n_ii * sizeof(INTERFACE_INFO),
495 					 &length, 0, 0) == SOCKET_ERROR)
496 		{
497 			error = WSAGetLastError();
498 			if (error == WSAEFAULT || error == WSAENOBUFS)
499 				continue;		/* need to make the buffer bigger */
500 			closesocket(sock);
501 			free(ii);
502 			return -1;
503 		}
504 
505 		break;
506 	}
507 
508 	for (i = 0; i < length / sizeof(INTERFACE_INFO); ++i)
509 		run_ifaddr_callback(callback, cb_data,
510 							(struct sockaddr *) & ii[i].iiAddress,
511 							(struct sockaddr *) & ii[i].iiNetmask);
512 
513 	closesocket(sock);
514 	free(ii);
515 	return 0;
516 }
517 #elif HAVE_GETIFADDRS			/* && !WIN32 */
518 
519 #ifdef HAVE_IFADDRS_H
520 #include <ifaddrs.h>
521 #endif
522 
523 /*
524  * Enumerate the system's network interface addresses and call the callback
525  * for each one.  Returns 0 if successful, -1 if trouble.
526  *
527  * This version uses the getifaddrs() interface, which is available on
528  * BSDs, AIX, and modern Linux.
529  */
530 int
pg_foreach_ifaddr(PgIfAddrCallback callback,void * cb_data)531 pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data)
532 {
533 	struct ifaddrs *ifa,
534 			   *l;
535 
536 	if (getifaddrs(&ifa) < 0)
537 		return -1;
538 
539 	for (l = ifa; l; l = l->ifa_next)
540 		run_ifaddr_callback(callback, cb_data,
541 							l->ifa_addr, l->ifa_netmask);
542 
543 	freeifaddrs(ifa);
544 	return 0;
545 }
546 #else							/* !HAVE_GETIFADDRS && !WIN32 */
547 
548 #ifdef HAVE_SYS_IOCTL_H
549 #include <sys/ioctl.h>
550 #endif
551 
552 #ifdef HAVE_NET_IF_H
553 #include <net/if.h>
554 #endif
555 
556 #ifdef HAVE_SYS_SOCKIO_H
557 #include <sys/sockio.h>
558 #endif
559 
560 /*
561  * SIOCGIFCONF does not return IPv6 addresses on Solaris
562  * and HP/UX. So we prefer SIOCGLIFCONF if it's available.
563  *
564  * On HP/UX, however, it *only* returns IPv6 addresses,
565  * and the structs are named slightly differently too.
566  * We'd have to do another call with SIOCGIFCONF to get the
567  * IPv4 addresses as well. We don't currently bother, just
568  * fall back to SIOCGIFCONF on HP/UX.
569  */
570 
571 #if defined(SIOCGLIFCONF) && !defined(__hpux)
572 
573 /*
574  * Enumerate the system's network interface addresses and call the callback
575  * for each one.  Returns 0 if successful, -1 if trouble.
576  *
577  * This version uses ioctl(SIOCGLIFCONF).
578  */
579 int
pg_foreach_ifaddr(PgIfAddrCallback callback,void * cb_data)580 pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data)
581 {
582 	struct lifconf lifc;
583 	struct lifreq *lifr,
584 				lmask;
585 	struct sockaddr *addr,
586 			   *mask;
587 	char	   *ptr,
588 			   *buffer = NULL;
589 	size_t		n_buffer = 1024;
590 	pgsocket	sock,
591 				fd;
592 
593 #ifdef HAVE_IPV6
594 	pgsocket	sock6;
595 #endif
596 	int			i,
597 				total;
598 
599 	sock = socket(AF_INET, SOCK_DGRAM, 0);
600 	if (sock == PGINVALID_SOCKET)
601 		return -1;
602 
603 	while (n_buffer < 1024 * 100)
604 	{
605 		n_buffer += 1024;
606 		ptr = realloc(buffer, n_buffer);
607 		if (!ptr)
608 		{
609 			free(buffer);
610 			close(sock);
611 			errno = ENOMEM;
612 			return -1;
613 		}
614 
615 		memset(&lifc, 0, sizeof(lifc));
616 		lifc.lifc_family = AF_UNSPEC;
617 		lifc.lifc_buf = buffer = ptr;
618 		lifc.lifc_len = n_buffer;
619 
620 		if (ioctl(sock, SIOCGLIFCONF, &lifc) < 0)
621 		{
622 			if (errno == EINVAL)
623 				continue;
624 			free(buffer);
625 			close(sock);
626 			return -1;
627 		}
628 
629 		/*
630 		 * Some Unixes try to return as much data as possible, with no
631 		 * indication of whether enough space allocated. Don't believe we have
632 		 * it all unless there's lots of slop.
633 		 */
634 		if (lifc.lifc_len < n_buffer - 1024)
635 			break;
636 	}
637 
638 #ifdef HAVE_IPV6
639 	/* We'll need an IPv6 socket too for the SIOCGLIFNETMASK ioctls */
640 	sock6 = socket(AF_INET6, SOCK_DGRAM, 0);
641 	if (sock6 == PGINVALID_SOCKET)
642 	{
643 		free(buffer);
644 		close(sock);
645 		return -1;
646 	}
647 #endif
648 
649 	total = lifc.lifc_len / sizeof(struct lifreq);
650 	lifr = lifc.lifc_req;
651 	for (i = 0; i < total; ++i)
652 	{
653 		addr = (struct sockaddr *) & lifr[i].lifr_addr;
654 		memcpy(&lmask, &lifr[i], sizeof(struct lifreq));
655 #ifdef HAVE_IPV6
656 		fd = (addr->sa_family == AF_INET6) ? sock6 : sock;
657 #else
658 		fd = sock;
659 #endif
660 		if (ioctl(fd, SIOCGLIFNETMASK, &lmask) < 0)
661 			mask = NULL;
662 		else
663 			mask = (struct sockaddr *) & lmask.lifr_addr;
664 		run_ifaddr_callback(callback, cb_data, addr, mask);
665 	}
666 
667 	free(buffer);
668 	close(sock);
669 #ifdef HAVE_IPV6
670 	close(sock6);
671 #endif
672 	return 0;
673 }
674 #elif defined(SIOCGIFCONF)
675 
676 /*
677  * Remaining Unixes use SIOCGIFCONF. Some only return IPv4 information
678  * here, so this is the least preferred method. Note that there is no
679  * standard way to iterate the struct ifreq returned in the array.
680  * On some OSs the structures are padded large enough for any address,
681  * on others you have to calculate the size of the struct ifreq.
682  */
683 
684 /* Some OSs have _SIZEOF_ADDR_IFREQ, so just use that */
685 #ifndef _SIZEOF_ADDR_IFREQ
686 
687 /* Calculate based on sockaddr.sa_len */
688 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
689 #define _SIZEOF_ADDR_IFREQ(ifr) \
690 		((ifr).ifr_addr.sa_len > sizeof(struct sockaddr) ? \
691 		 (sizeof(struct ifreq) - sizeof(struct sockaddr) + \
692 		  (ifr).ifr_addr.sa_len) : sizeof(struct ifreq))
693 
694 /* Padded ifreq structure, simple */
695 #else
696 #define _SIZEOF_ADDR_IFREQ(ifr) \
697 	sizeof (struct ifreq)
698 #endif
699 #endif   /* !_SIZEOF_ADDR_IFREQ */
700 
701 /*
702  * Enumerate the system's network interface addresses and call the callback
703  * for each one.  Returns 0 if successful, -1 if trouble.
704  *
705  * This version uses ioctl(SIOCGIFCONF).
706  */
707 int
pg_foreach_ifaddr(PgIfAddrCallback callback,void * cb_data)708 pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data)
709 {
710 	struct ifconf ifc;
711 	struct ifreq *ifr,
712 			   *end,
713 				addr,
714 				mask;
715 	char	   *ptr,
716 			   *buffer = NULL;
717 	size_t		n_buffer = 1024;
718 	pgsocket	sock;
719 
720 	sock = socket(AF_INET, SOCK_DGRAM, 0);
721 	if (sock == PGINVALID_SOCKET)
722 		return -1;
723 
724 	while (n_buffer < 1024 * 100)
725 	{
726 		n_buffer += 1024;
727 		ptr = realloc(buffer, n_buffer);
728 		if (!ptr)
729 		{
730 			free(buffer);
731 			close(sock);
732 			errno = ENOMEM;
733 			return -1;
734 		}
735 
736 		memset(&ifc, 0, sizeof(ifc));
737 		ifc.ifc_buf = buffer = ptr;
738 		ifc.ifc_len = n_buffer;
739 
740 		if (ioctl(sock, SIOCGIFCONF, &ifc) < 0)
741 		{
742 			if (errno == EINVAL)
743 				continue;
744 			free(buffer);
745 			close(sock);
746 			return -1;
747 		}
748 
749 		/*
750 		 * Some Unixes try to return as much data as possible, with no
751 		 * indication of whether enough space allocated. Don't believe we have
752 		 * it all unless there's lots of slop.
753 		 */
754 		if (ifc.ifc_len < n_buffer - 1024)
755 			break;
756 	}
757 
758 	end = (struct ifreq *) (buffer + ifc.ifc_len);
759 	for (ifr = ifc.ifc_req; ifr < end;)
760 	{
761 		memcpy(&addr, ifr, sizeof(addr));
762 		memcpy(&mask, ifr, sizeof(mask));
763 		if (ioctl(sock, SIOCGIFADDR, &addr, sizeof(addr)) == 0 &&
764 			ioctl(sock, SIOCGIFNETMASK, &mask, sizeof(mask)) == 0)
765 			run_ifaddr_callback(callback, cb_data,
766 								&addr.ifr_addr, &mask.ifr_addr);
767 		ifr = (struct ifreq *) ((char *) ifr + _SIZEOF_ADDR_IFREQ(*ifr));
768 	}
769 
770 	free(buffer);
771 	close(sock);
772 	return 0;
773 }
774 #else							/* !defined(SIOCGIFCONF) */
775 
776 /*
777  * Enumerate the system's network interface addresses and call the callback
778  * for each one.  Returns 0 if successful, -1 if trouble.
779  *
780  * This version is our fallback if there's no known way to get the
781  * interface addresses.  Just return the standard loopback addresses.
782  */
783 int
pg_foreach_ifaddr(PgIfAddrCallback callback,void * cb_data)784 pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data)
785 {
786 	struct sockaddr_in addr;
787 	struct sockaddr_storage mask;
788 
789 #ifdef HAVE_IPV6
790 	struct sockaddr_in6 addr6;
791 #endif
792 
793 	/* addr 127.0.0.1/8 */
794 	memset(&addr, 0, sizeof(addr));
795 	addr.sin_family = AF_INET;
796 	addr.sin_addr.s_addr = ntohl(0x7f000001);
797 	memset(&mask, 0, sizeof(mask));
798 	pg_sockaddr_cidr_mask(&mask, "8", AF_INET);
799 	run_ifaddr_callback(callback, cb_data,
800 						(struct sockaddr *) & addr,
801 						(struct sockaddr *) & mask);
802 
803 #ifdef HAVE_IPV6
804 	/* addr ::1/128 */
805 	memset(&addr6, 0, sizeof(addr6));
806 	addr6.sin6_family = AF_INET6;
807 	addr6.sin6_addr.s6_addr[15] = 1;
808 	memset(&mask, 0, sizeof(mask));
809 	pg_sockaddr_cidr_mask(&mask, "128", AF_INET6);
810 	run_ifaddr_callback(callback, cb_data,
811 						(struct sockaddr *) & addr6,
812 						(struct sockaddr *) & mask);
813 #endif
814 
815 	return 0;
816 }
817 #endif   /* !defined(SIOCGIFCONF) */
818 
819 #endif   /* !HAVE_GETIFADDRS */
820