inet.c 20.2 KB
Newer Older
1
/*
2
   Copyright (C) 2002-2010 Karl J. Runge <runge@karlrunge.com> 
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   All rights reserved.

This file is part of x11vnc.

x11vnc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

x11vnc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with x11vnc; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA
or see <http://www.gnu.org/licenses/>.

In addition, as a special exception, Karl J. Runge
gives permission to link the code of its release of x11vnc with the
OpenSSL project's "OpenSSL" library (or with modified versions of it
that use the same license as the "OpenSSL" library), and distribute
the linked executables.  You must obey the GNU General Public License
in all respects for all of the code used other than "OpenSSL".  If you
modify this file, you may extend this exception to your version of the
file, but you are not obligated to do so.  If you do not wish to do
so, delete this exception statement from your version.
*/

runge's avatar
runge committed
33 34 35
/* -- inet.c -- */

#include "x11vnc.h"
36 37
#include "unixpw.h"
#include "sslhelper.h"
runge's avatar
runge committed
38 39 40 41 42 43 44 45 46

/*
 * Simple utility to map host name to dotted IP address.  Ignores aliases.
 * Up to caller to free returned string.
 */
char *host2ip(char *host);
char *raw2host(char *raw, int len);
char *raw2ip(char *raw);
char *ip2host(char *ip);
47
int ipv6_ip(char *host);
48
int dotted_ip(char *host, int partial);
runge's avatar
runge committed
49 50 51 52 53
int get_remote_port(int sock);
int get_local_port(int sock);
char *get_remote_host(int sock);
char *get_local_host(int sock);
char *ident_username(rfbClientPtr client);
54
int find_free_port(int start, int end);
55
int find_free_port6(int start, int end);
56
int have_ssh_env(void);
57 58 59
char *ipv6_getnameinfo(struct sockaddr *paddr, int addrlen);
char *ipv6_getipaddr(struct sockaddr *paddr, int addrlen);
int listen6(int port);
60 61
int listen_unix(char *file);
int accept_unix(int s);
62 63
int connect_tcp(char *host, int port);
int listen_tcp(int port, in_addr_t iface, int try6);
runge's avatar
runge committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

static int get_port(int sock, int remote);
static char *get_host(int sock, int remote);

char *host2ip(char *host) {
	struct hostent *hp;
	struct sockaddr_in addr;
	char *str;

	if (! host_lookup) {
		return NULL;
	}

	hp = gethostbyname(host);
	if (!hp) {
		return NULL;
	}
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr =  *(unsigned long *)hp->h_addr;
	str = strdup(inet_ntoa(addr.sin_addr));
	return str;
}

char *raw2host(char *raw, int len) {
	char *str;
#if LIBVNCSERVER_HAVE_NETDB_H && LIBVNCSERVER_HAVE_NETINET_IN_H
	struct hostent *hp;

	if (! host_lookup) {
		return strdup("unknown");
	}

	hp = gethostbyaddr(raw, len, AF_INET);
	if (!hp) {
		return strdup(inet_ntoa(*((struct in_addr *)raw)));
	}
	str = strdup(hp->h_name);
#else
	str = strdup("unknown");
#endif
	return str;
}

char *raw2ip(char *raw) {
	return strdup(inet_ntoa(*((struct in_addr *)raw)));
}

char *ip2host(char *ip) {
	char *str;
#if LIBVNCSERVER_HAVE_NETDB_H && LIBVNCSERVER_HAVE_NETINET_IN_H
	struct hostent *hp;
	in_addr_t iaddr;

	if (! host_lookup) {
		return strdup("unknown");
	}

	iaddr = inet_addr(ip);
	if (iaddr == htonl(INADDR_NONE)) {
		return strdup("unknown");
	}

	hp = gethostbyaddr((char *)&iaddr, sizeof(in_addr_t), AF_INET);
	if (!hp) {
		return strdup("unknown");
	}
	str = strdup(hp->h_name);
#else
	str = strdup("unknown");
#endif
	return str;
}

138 139 140 141 142 143 144 145 146 147
int ipv6_ip(char *host_in) {
	char *p, *host, a[2];
	int ncol = 0, nhex = 0;

	if (host_in[0] == '[')  {
		host = host_in + 1;
	} else {
		host = host_in;
	}

148 149
	if (strstr(host, "::ffff:") == host || strstr(host, "::FFFF:") == host) {
		return dotted_ip(host + strlen("::ffff:"), 0);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
	}

	a[1] = '\0';

	p = host;
	while (*p != '\0' && *p != '%' && *p != ']') {
		if (*p == ':') {
			ncol++;
		} else {
			nhex++;
		}
		a[0] = *p;
		if (strpbrk(a, ":abcdef0123456789") == a) {
			p++;
			continue;
		}
		return 0;
	}
	if (ncol < 2 || ncol > 8 || nhex == 0) {
		return 0;
	} else {
		return 1;
	}
}

175 176
int dotted_ip(char *host, int partial) {
	int len, dots = 0;
runge's avatar
runge committed
177
	char *p = host;
178 179 180 181 182 183 184 185 186 187 188 189 190 191

	if (!host) {
		return 0;
	}

	if (!isdigit((unsigned char) host[0])) {
		return 0;
	}

	len = strlen(host);
	if (!partial && !isdigit((unsigned char) host[len-1])) {
		return 0;
	}

runge's avatar
runge committed
192
	while (*p != '\0') {
193
		if (*p == '.') dots++;
194
		if (*p == '.' || isdigit((unsigned char) (*p))) {
runge's avatar
runge committed
195 196 197 198 199
			p++;
			continue;
		}
		return 0;
	}
200 201 202
	if (!partial && dots != 3) {
		return 0;	
	}
runge's avatar
runge committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	return 1;
}

static int get_port(int sock, int remote) {
	struct sockaddr_in saddr;
	unsigned int saddr_len;
	int saddr_port;
	
	saddr_len = sizeof(saddr);
	memset(&saddr, 0, sizeof(saddr));
	saddr_port = -1;
	if (remote) {
		if (!getpeername(sock, (struct sockaddr *)&saddr, &saddr_len)) {
			saddr_port = ntohs(saddr.sin_port);
		}
	} else {
		if (!getsockname(sock, (struct sockaddr *)&saddr, &saddr_len)) {
			saddr_port = ntohs(saddr.sin_port);
		}
	}
	return saddr_port;
}

int get_remote_port(int sock) {
	return get_port(sock, 1);
}

int get_local_port(int sock) {
	return get_port(sock, 0);
}

static char *get_host(int sock, int remote) {
	struct sockaddr_in saddr;
	unsigned int saddr_len;
	int saddr_port;
	char *saddr_ip_str = NULL;
	
	saddr_len = sizeof(saddr);
	memset(&saddr, 0, sizeof(saddr));
	saddr_port = -1;
#if LIBVNCSERVER_HAVE_NETINET_IN_H
	if (remote) {
		if (!getpeername(sock, (struct sockaddr *)&saddr, &saddr_len)) {
			saddr_ip_str = inet_ntoa(saddr.sin_addr);
		}
	} else {
		if (!getsockname(sock, (struct sockaddr *)&saddr, &saddr_len)) {
			saddr_ip_str = inet_ntoa(saddr.sin_addr);
		}
	}
#endif
	if (! saddr_ip_str) {
		saddr_ip_str = "unknown";
	}
	return strdup(saddr_ip_str);
}

char *get_remote_host(int sock) {
	return get_host(sock, 1);
}

char *get_local_host(int sock) {
	return get_host(sock, 0);
}

char *ident_username(rfbClientPtr client) {
	ClientData *cd = (ClientData *) client->clientData;
	char *str, *newhost, *user = NULL, *newuser = NULL;
	int len;

	if (cd) {
		user = cd->username;
	}
	if (!user || *user == '\0') {
		int n, sock, ok = 0;
278
		int block = 0;
279
		int refused = 0;
280 281 282 283 284 285 286 287 288

		/*
		 * need to check to see if the operation will block for
		 * a long time: a firewall may just ignore our packets.
		 */
#if LIBVNCSERVER_HAVE_FORK
	    {	pid_t pid, pidw;
		int rc;
		if ((pid = fork()) > 0) {
289
			usleep(100 * 1000);	/* 0.1 sec for quick success or refusal */
290 291
			pidw = waitpid(pid, &rc, WNOHANG);
			if (pidw <= 0) {
292
				usleep(1500 * 1000);	/* 1.5 sec */
293 294
				pidw = waitpid(pid, &rc, WNOHANG);
				if (pidw <= 0) {
295 296
					int rc2;
					rfbLog("ident_username: set block=1 (hung)\n");
297 298
					block = 1;
					kill(pid, SIGTERM);
299 300 301 302 303 304 305 306
					usleep(100 * 1000);
					waitpid(pid, &rc2, WNOHANG);
				}
			}
			if (pidw > 0 && !block) {
				if (WIFEXITED(rc) && WEXITSTATUS(rc) == 1) {
					rfbLog("ident_username: set refused=1 (exit)\n");
					refused = 1;
307 308 309 310 311 312 313 314 315 316 317
				}
			}
		} else if (pid == -1) {
			;
		} else {
			/* child */
			signal(SIGHUP,  SIG_DFL);
			signal(SIGINT,  SIG_DFL);
			signal(SIGQUIT, SIG_DFL);
			signal(SIGTERM, SIG_DFL);

318
			if ((sock = connect_tcp(client->host, 113)) < 0) {
319 320 321 322 323 324 325 326
				exit(1);
			} else {
				close(sock);
				exit(0);
			}
		}
	    }
#endif
327
		if (block || refused) {
328
			;
329
		} else if ((sock = connect_tcp(client->host, 113)) < 0) {
330
			rfbLog("ident_username: could not connect to ident: %s:%d\n",
runge's avatar
runge committed
331 332
			    client->host, 113);
		} else {
333
			char msg[128];
runge's avatar
runge committed
334 335 336 337 338 339 340 341 342 343 344
			int ret;
			fd_set rfds;
			struct timeval tv;
			int rport = get_remote_port(client->sock);
			int lport = get_local_port(client->sock);

			sprintf(msg, "%d, %d\r\n", rport, lport);
			n = write(sock, msg, strlen(msg));

			FD_ZERO(&rfds);
			FD_SET(sock, &rfds);
345
			tv.tv_sec  = 3;
runge's avatar
runge committed
346 347 348 349 350 351
			tv.tv_usec = 0;
			ret = select(sock+1, &rfds, NULL, NULL, &tv); 

			if (ret > 0) {
				int i;
				char *q, *p;
runge's avatar
runge committed
352
				for (i=0; i < (int) sizeof(msg); i++) {
runge's avatar
runge committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
					msg[i] = '\0';
				}
				usleep(250*1000);
				n = read(sock, msg, 127);
				close(sock);
				if (n <= 0) goto badreply;

				/* 32782 , 6000 : USERID : UNIX :runge */
				q = strstr(msg, "USERID");
				if (!q) goto badreply;
				q = strstr(q, ":");
				if (!q) goto badreply;
				q++;
				q = strstr(q, ":");
				if (!q) goto badreply;
				q++;
				q = lblanks(q);
				p = q;
				while (*p) {
					if (*p == '\r' || *p == '\n') {
						*p = '\0';
					}
					p++;
				}
				ok = 1;
				if (strlen(q) > 24) {
					*(q+24) = '\0';
				}
				newuser = strdup(q);

				badreply:
				n = 0;	/* avoid syntax error */
			} else {
				close(sock);
			}
		}
		if (! ok || !newuser) {
			newuser = strdup("unknown-user");
		}
		if (cd) {
			if (cd->username) {
				free(cd->username);
			}
			cd->username = newuser;
		}
		user = newuser;
	}
400 401 402
	if (!strcmp(user, "unknown-user") && cd && cd->unixname[0] != '\0') {
		user = cd->unixname;
	}
403 404 405 406 407
	if (unixpw && openssl_last_ip && strstr("UNIX:", user) != user) {
		newhost = ip2host(openssl_last_ip);
	} else {
		newhost = ip2host(client->host);
	}
runge's avatar
runge committed
408 409 410 411 412 413 414
	len = strlen(user) + 1 + strlen(newhost) + 1;
	str = (char *) malloc(len);
	sprintf(str, "%s@%s", user, newhost);
	free(newhost);
	return str;
}

415 416 417 418 419 420 421 422 423
int find_free_port(int start, int end) {
	int port;
	if (start <= 0) {
		start = 1024;
	}
	if (end <= 0) {
		end = 65530;
	}
	for (port = start; port <= end; port++)  {
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
		int sock = listen_tcp(port, htonl(INADDR_ANY), 0);
		if (sock >= 0) {
			close(sock);
			return port;
		}
	}
	return 0;
}

int find_free_port6(int start, int end) {
	int port;
	if (start <= 0) {
		start = 1024;
	}
	if (end <= 0) {
		end = 65530;
	}
	for (port = start; port <= end; port++)  {
		int sock = listen6(port);
443 444 445 446 447 448 449
		if (sock >= 0) {
			close(sock);
			return port;
		}
	}
	return 0;
}
runge's avatar
runge committed
450

451 452 453 454
int have_ssh_env(void) {
	char *str, *p = getenv("SSH_CONNECTION");
	char *rhost, *rport, *lhost, *lport;
	
455 456 457 458 459 460 461 462 463 464 465 466 467 468
	if (! p) {
		char *q = getenv("SSH_CLIENT");
		if (! q) {
			return 0;
		}
		if (strstr(q, "127.0.0.1") != NULL) {
			return 0;
		}
		return 1;
	}

	if (strstr(p, "127.0.0.1") != NULL) {
		return 0;
	}
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

	str = strdup(p);
	
	p = strtok(str, " ");
	rhost = p;

	p = strtok(NULL, " ");
	if (! p) goto fail;

	rport = p;

	p = strtok(NULL, " ");
	if (! p) goto fail;

	lhost = p;
	
	p = strtok(NULL, " ");
	if (! p) goto fail;

	lport = p;

if (0) fprintf(stderr, "%d/%d - '%s' '%s'\n", atoi(rport), atoi(lport), rhost, lhost);

492
	if (atoi(rport) <= 16 || atoi(rport) > 65535) {
493 494
		goto fail;
	}
495
	if (atoi(lport) <= 16 || atoi(lport) > 65535) {
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
		goto fail;
	}

	if (!strcmp(rhost, lhost)) {
		goto fail;
	}

	free(str);

	return 1;
	
	fail:

	free(str);

	return 0;
}

514 515 516 517 518 519 520 521 522 523 524 525 526 527
char *ipv6_getnameinfo(struct sockaddr *paddr, int addrlen) {
#if X11VNC_IPV6
	char name[200];
	if (noipv6) {
		return strdup("unknown");
	}
	if (getnameinfo(paddr, addrlen, name, sizeof(name), NULL, 0, 0) == 0) {
		return strdup(name);
	}
#endif
	return strdup("unknown");
}

char *ipv6_getipaddr(struct sockaddr *paddr, int addrlen) {
528
#if X11VNC_IPV6 && defined(NI_NUMERICHOST)
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
	char name[200];
	if (noipv6) {
		return strdup("unknown");
	}
	if (getnameinfo(paddr, addrlen, name, sizeof(name), NULL, 0, NI_NUMERICHOST) == 0) {
		return strdup(name);
	}
#endif
	return strdup("unknown");
}

int listen6(int port) {
#if X11VNC_IPV6
	struct sockaddr_in6 sin;
	int fd = -1, one = 1;

	if (noipv6) {
		return -1;
	}
548 549 550 551
	if (port <= 0 || 65535 < port) {
		/* for us, invalid port means do not listen. */
		return -1;
	}
552 553 554 555

	fd = socket(AF_INET6, SOCK_STREAM, 0);
	if (fd < 0) {
		rfbLogPerror("listen6: socket");
556
		rfbLog("(Ignore the above error if this system is IPv4-only.)\n");
557 558 559 560
		return -1;
	}

	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)) < 0) {
561
		rfbLogPerror("listen6: setsockopt SO_REUSEADDR"); 
562 563 564 565 566 567
		close(fd);
		return -1;
	}

#if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
	if (setsockopt(fd, SOL_IPV6, IPV6_V6ONLY, (char *)&one, sizeof(one)) < 0) {
568
		rfbLogPerror("listen6: setsockopt IPV6_V6ONLY"); 
569 570 571 572 573 574 575 576 577 578 579
		close(fd);
		return -1;
	}
#endif

	memset((char *)&sin, 0, sizeof(sin));
	sin.sin6_family = AF_INET6;
	sin.sin6_port   = htons(port);
	sin.sin6_addr   = in6addr_any;

	if (listen_str6) {
580
		if (!strcmp(listen_str6, "localhost") || !strcmp(listen_str6, "::1")) {
581
			sin.sin6_addr = in6addr_loopback;
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
		} else {
			int err;
			struct addrinfo *ai;
			struct addrinfo hints;
			char service[32];

			memset(&hints, 0, sizeof(hints));
			sprintf(service, "%d", port);

			hints.ai_family = AF_INET6;
			hints.ai_socktype = SOCK_STREAM;
#ifdef AI_ADDRCONFIG
			hints.ai_flags |= AI_ADDRCONFIG;
#endif
#ifdef AI_NUMERICHOST
			if(ipv6_ip(listen_str6)) {
				hints.ai_flags |= AI_NUMERICHOST;
			}
#endif
#ifdef AI_NUMERICSERV
			hints.ai_flags |= AI_NUMERICSERV;
#endif
			err = getaddrinfo(listen_str6, service, &hints, &ai);
			if (err == 0) {
				struct addrinfo *ap = ai;
				err = 1;
				while (ap != NULL) {
					char *s = ipv6_getipaddr(ap->ai_addr, ap->ai_addrlen);
					if (!s) s = strdup("unknown");

					rfbLog("listen6: checking: %s family: %d\n", s, ap->ai_family); 
					if (ap->ai_family == AF_INET6) {
						memcpy((char *)&sin, ap->ai_addr, sizeof(sin));
						rfbLog("listen6: using:    %s scope_id: %d\n", s, sin.sin6_scope_id); 
						err = 0;
						free(s);
						break;
					}
					free(s);
					ap = ap->ai_next;
				}
				freeaddrinfo(ai);
			}

			if (err != 0) {
				rfbLog("Invalid or Unsupported -listen6 string: %s\n", listen_str6);
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
				close(fd);
				return -1;
			}
		}
	} else if (allow_list && !strcmp(allow_list, "127.0.0.1")) {
		sin.sin6_addr = in6addr_loopback;
	} else if (listen_str) {
		if (!strcmp(listen_str, "localhost")) {
			sin.sin6_addr = in6addr_loopback;
		}
	}

	if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		rfbLogPerror("listen6: bind"); 
		close(fd);
		return -1;
	}
	if (listen(fd, 32) < 0) {
		rfbLogPerror("listen6: listen");
		close(fd);
		return -1;
	}
	return fd;
#else
	if (port) {}
	return -1;
#endif
}

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
#ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H
#include <sys/un.h>
#endif

int listen_unix(char *file) {
#if !defined(AF_UNIX) || !defined(LIBVNCSERVER_HAVE_SYS_SOCKET_H)
	if (sock) {}
	return -1;
#else
	int s, len;
	struct sockaddr_un saun;

	s = socket(AF_UNIX, SOCK_STREAM, 0);
	if (s < 0) {
		rfbLogPerror("listen_unix: socket");
		return -1;
	}
	saun.sun_family = AF_UNIX;
	strcpy(saun.sun_path, file);
	unlink(file);

	len = sizeof(saun.sun_family) + strlen(saun.sun_path);

	if (bind(s, (struct sockaddr *)&saun, len) < 0) {
		rfbLogPerror("listen_unix: bind");
		close(s);
		return -1;
	}

	if (listen(s, 32) < 0) {
		rfbLogPerror("listen_unix: listen");
		close(s);
		return -1;
	}
	rfbLog("listening on unix socket: %s fd=%d\n", file, s);
	return s;
#endif
}

int accept_unix(int s) {
#if !defined(AF_UNIX) || !defined(LIBVNCSERVER_HAVE_SYS_SOCKET_H)
	if (s) {}
	return -1;
#else
	int fd, fromlen;
	struct sockaddr_un fsaun;

	fd = accept(s, (struct sockaddr *)&fsaun, &fromlen);
	if (fd < 0) {
		rfbLogPerror("accept_unix: accept");
		return -1;
	}
	return fd;
#endif
}

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
int connect_tcp(char *host, int port) {
	double t0 = dnow();
	int fd = -1;
	int fail4 = noipv4;
	if (getenv("IPV4_FAILS")) {
		fail4 = 2;
	}

	rfbLog("connect_tcp: trying:   %s %d\n", host, port);

	if (fail4) {
		if (fail4 > 1) {
			rfbLog("TESTING: IPV4_FAILS for connect_tcp.\n");
		}
	} else {
		fd = rfbConnectToTcpAddr(host, port);
	}

	if (fd >= 0) {
		return fd;
	}
	rfbLogPerror("connect_tcp: connection failed");

	if (dnow() - t0 < 4.0) {
		rfbLog("connect_tcp: re-trying %s %d\n", host, port);
		usleep (100 * 1000);
		if (!fail4) {
			fd = rfbConnectToTcpAddr(host, port);
		}
		if (fd < 0) {
			rfbLogPerror("connect_tcp: connection failed");
		}
	}

	if (fd < 0 && !noipv6) {
748
#if X11VNC_IPV6
749 750 751 752 753 754 755 756 757 758 759 760
		int err;
		struct addrinfo *ai;
		struct addrinfo hints;
		char service[32], *host2, *q;

		rfbLog("connect_tcp: trying IPv6 %s %d\n", host, port);

		memset(&hints, 0, sizeof(hints));
		sprintf(service, "%d", port);

		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
761 762 763
#ifdef AI_ADDRCONFIG
		hints.ai_flags |= AI_ADDRCONFIG;
#endif
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
		if(ipv6_ip(host)) {
#ifdef AI_NUMERICHOST
			rfbLog("connect_tcp[ipv6]: setting AI_NUMERICHOST for %s\n", host);
			hints.ai_flags |= AI_NUMERICHOST;
#endif
		}
#ifdef AI_NUMERICSERV
		hints.ai_flags |= AI_NUMERICSERV;
#endif

		if (!strcmp(host, "127.0.0.1")) {
			host2 = strdup("::1");
		} else if (host[0] == '[') {
			host2 = strdup(host+1);
		} else {
			host2 = strdup(host);
		}
		q = strrchr(host2, ']');
		if (q) {
			*q = '\0';
		}

		err = getaddrinfo(host2, service, &hints, &ai);
		if (err != 0) {
			rfbLog("connect_tcp[ipv6]: getaddrinfo[%d]: %s\n", err, gai_strerror(err));
			usleep(100 * 1000);
			err = getaddrinfo(host2, service, &hints, &ai);
		}
		free(host2);

		if (err != 0) {
			rfbLog("connect_tcp[ipv6]: getaddrinfo[%d]: %s\n", err, gai_strerror(err));
		} else {
			struct addrinfo *ap = ai;
			while (ap != NULL) {
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
				int sock;

				if (fail4) {
					struct sockaddr_in6 *s6ptr;
					if (ap->ai_family != AF_INET6) {
						rfbLog("connect_tcp[ipv6]: skipping AF_INET address under -noipv4\n");
						ap = ap->ai_next;
						continue;
					}
#ifdef IN6_IS_ADDR_V4MAPPED
					s6ptr = (struct sockaddr_in6 *) ap->ai_addr;
					if (IN6_IS_ADDR_V4MAPPED(&(s6ptr->sin6_addr))) {
						rfbLog("connect_tcp[ipv6]: skipping V4MAPPED address under -noipv4\n");
						ap = ap->ai_next;
						continue;
					}
#endif
				}

				sock = socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol);

820 821
				if (sock == -1) {
					rfbLogPerror("connect_tcp[ipv6]: socket");
822
					if (0) rfbLog("(Ignore the above error if this system is IPv4-only.)\n");
823
				} else {
824
					int res = -1, dmsg = 0;
825 826
					char *s = ipv6_getipaddr(ap->ai_addr, ap->ai_addrlen);
					if (!s) s = strdup("unknown");
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

					rfbLog("connect_tcp[ipv6]: trying sock=%d fam=%d proto=%d using %s\n",
					    sock, ap->ai_family, ap->ai_protocol, s);
					res = connect(sock, ap->ai_addr, ap->ai_addrlen);
#if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
					if (res != 0) {
						int zero = 0;
						rfbLogPerror("connect_tcp[ipv6]: connect");
						dmsg = 1;
						if (setsockopt(sock, SOL_IPV6, IPV6_V6ONLY, (char *)&zero, sizeof(zero)) == 0) {
							rfbLog("connect_tcp[ipv6]: trying again with IPV6_V6ONLY=0\n");
							res = connect(sock, ap->ai_addr, ap->ai_addrlen);
							dmsg = 0;
						} else {
							rfbLogPerror("connect_tcp[ipv6]: setsockopt IPV6_V6ONLY");
						}
					}
#endif
					if (res == 0) {
846 847 848 849 850 851 852 853
						rfbLog("connect_tcp[ipv6]: connect OK\n");
						fd = sock;
						if (!ipv6_client_ip_str) {
							ipv6_client_ip_str = strdup(s);
						}
						free(s);
						break;
					} else {
854
						if (!dmsg) rfbLogPerror("connect_tcp[ipv6]: connect");
855 856 857 858 859 860 861 862 863 864
						close(sock);
					}
					free(s);
				}
				ap = ap->ai_next;
			}
			freeaddrinfo(ai);
		}
#endif
	}
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
	if (fd < 0 && !fail4) {
		/* this is a kludge for IPv4-only machines getting v4mapped string. */
		char *q, *host2;
		if (host[0] == '[') {
			host2 = strdup(host+1);
		} else {
			host2 = strdup(host);
		}
		q = strrchr(host2, ']');
		if (q) {
			*q = '\0';
		}
		if (strstr(host2, "::ffff:") == host2 || strstr(host2, "::FFFF:") == host2) {
			char *host3 = host2 + strlen("::ffff:");
			if (dotted_ip(host3, 0)) {
				rfbLog("connect_tcp[ipv4]: trying fallback to IPv4 for %s\n", host2);
				fd = rfbConnectToTcpAddr(host3, port);
				if (fd < 0) {
					rfbLogPerror("connect_tcp[ipv4]: connection failed");
				}
			}
		}
		free(host2);
	}
889 890 891 892 893 894 895 896 897 898
	return fd;
}

int listen_tcp(int port, in_addr_t iface, int try6) {
	int fd = -1;
	int fail4 = noipv4;
	if (getenv("IPV4_FAILS")) {
		fail4 = 2;
	}

899 900 901 902 903
	if (port <= 0 || 65535 < port) {
		/* for us, invalid port means do not listen. */
		return -1;
	}

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
	if (fail4) {
		if (fail4 > 1) {
			rfbLog("TESTING: IPV4_FAILS for listen_tcp: port=%d try6=%d\n", port, try6);
		}
	} else {
		fd = rfbListenOnTCPPort(port, iface);
	}

	if (fd >= 0) {
		return fd;
	}
	if (fail4 > 1) {
		rfbLogPerror("listen_tcp: listen failed");
	}

	if (fd < 0 && try6 && ipv6_listen && !noipv6) {
#if X11VNC_IPV6
		char *save = listen_str6;
		if (iface == htonl(INADDR_LOOPBACK)) {
			listen_str6 = "localhost";
			rfbLog("listen_tcp: retrying on IPv6 in6addr_loopback ...\n");
			fd = listen6(port);
		} else if (iface == htonl(INADDR_ANY)) {
			listen_str6 = NULL;
			rfbLog("listen_tcp: retrying on IPv6 in6addr_any ...\n");
			fd = listen6(port);
		}
		listen_str6 = save;
#endif
	}
	return fd;
}