user.c 68.3 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 36 37 38 39
/* -- user.c -- */

#include "x11vnc.h"
#include "solid.h"
#include "cleanup.h"
#include "scan.h"
#include "screen.h"
40
#include "unixpw.h"
41 42
#include "sslhelper.h"
#include "xwrappers.h"
runge's avatar
runge committed
43 44 45 46 47
#include "connections.h"
#include "inet.h"
#include "keyboard.h"
#include "cursor.h"
#include "remote.h"
48
#include "sslhelper.h"
49
#include "avahi.h"
runge's avatar
runge committed
50 51 52 53 54 55

void check_switched_user(void);
void lurk_loop(char *str);
int switch_user(char *user, int fb_mode);
int read_passwds(char *passfile);
void install_passwds(void);
56
void check_new_passwds(int force);
57
void progress_client(void);
58
int wait_for_client(int *argc, char** argv, int http);
59
rfbBool custom_passwd_check(rfbClientPtr cl, const char *response, int len);
60
char *xdmcp_insert = NULL;
runge's avatar
runge committed
61 62 63 64 65

static void switch_user_task_dummy(void);
static void switch_user_task_solid_bg(void);
static char *get_login_list(int with_display);
static char **user_list(char *user_str);
66
static void user2uid(char *user, uid_t *uid, gid_t *gid, char **name, char **home);
runge's avatar
runge committed
67 68
static int lurk(char **users);
static int guess_user_and_switch(char *str, int fb_mode);
69 70
static int try_user_and_display(uid_t uid, gid_t gid, char *dpystr);
static int switch_user_env(uid_t uid, gid_t gid, char *name, char *home, int fb_mode);
runge's avatar
runge committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
static void try_to_switch_users(void);


/* tasks for after we switch */
static void switch_user_task_dummy(void) {
	;	/* dummy does nothing */
}
static void switch_user_task_solid_bg(void) {
	/* we have switched users, some things to do. */
	if (use_solid_bg && client_count) {
		solid_bg(0);
	}
}

void check_switched_user(void) {
	static time_t sched_switched_user = 0;
	static int did_solid = 0;
	static int did_dummy = 0;
	int delay = 15;
90
	time_t now = time(NULL);
runge's avatar
runge committed
91

92 93
	if (unixpw_in_progress) return;

runge's avatar
runge committed
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 138 139 140 141 142 143 144 145 146 147 148 149 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 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
	if (started_as_root == 1 && users_list) {
		try_to_switch_users();
		if (started_as_root == 2) {
			/*
			 * schedule the switch_user_tasks() call
			 * 15 secs is for piggy desktops to start up.
			 * might not be enough for slow machines...
			 */
			sched_switched_user = now;
			did_dummy = 0;
			did_solid = 0;
			/* add other activities */
		}
	}
	if (! sched_switched_user) {
		return;
	}

	if (! did_dummy) {
		switch_user_task_dummy();
		did_dummy = 1;
	}
	if (! did_solid) {
		int doit = 0;
		char *ss = solid_str;
		if (now >= sched_switched_user + delay) {
			doit = 1;
		} else if (ss && strstr(ss, "root:") == ss) {
		    	if (now >= sched_switched_user + 3) {
				doit = 1;
			}
		} else if (strcmp("root", guess_desktop())) {
			usleep(1000 * 1000);
			doit = 1;
		}
		if (doit) {
			switch_user_task_solid_bg();
			did_solid = 1;
		}
	}

	if (did_dummy && did_solid) {
		sched_switched_user = 0;
	}
}

/* utilities for switching users */
static char *get_login_list(int with_display) {
	char *out;
#if LIBVNCSERVER_HAVE_UTMPX_H
	int i, cnt, max = 200, ut_namesize = 32;
	int dpymax = 1000, sawdpy[1000];
	struct utmpx *utx;

	/* size based on "username:999," * max */
	out = (char *) malloc(max * (ut_namesize+1+3+1) + 1);
	out[0] = '\0';

	for (i=0; i<dpymax; i++) {
		sawdpy[i] = 0;
	}

	setutxent();
	cnt = 0;
	while (1) {
		char *user, *line, *host, *id;
		char tmp[10];
		int d = -1;
		utx = getutxent();
		if (! utx) {
			break;
		}
		if (utx->ut_type != USER_PROCESS) {
			continue;
		}
		user = lblanks(utx->ut_user);
		if (*user == '\0') {
			continue;
		}
		if (strchr(user, ',')) {
			continue;	/* unlikely, but comma is our sep. */
		}

		line = lblanks(utx->ut_line);
		host = lblanks(utx->ut_host);
		id   = lblanks(utx->ut_id);

		if (with_display) {
			if (0 && line[0] != ':' && strcmp(line, "dtlocal")) {
				/* XXX useful? */
				continue;
			}

			if (line[0] == ':') {
				if (sscanf(line, ":%d", &d) != 1)  {
					d = -1;
				}
			}
			if (d < 0 && host[0] == ':') {
				if (sscanf(host, ":%d", &d) != 1)  {
					d = -1;
				}
			}
			if (d < 0 && id[0] == ':') {
				if (sscanf(id, ":%d", &d) != 1)  {
					d = -1;
				}
			}

			if (d < 0 || d >= dpymax || sawdpy[d]) {
				continue;
			}
			sawdpy[d] = 1;
			sprintf(tmp, ":%d", d);
		} else {
			/* try to eliminate repeats */
			int repeat = 0;
			char *q;

			q = out;
			while ((q = strstr(q, user)) != NULL) {
				char *p = q + strlen(user) + strlen(":DPY");
				if (q == out || *(q-1) == ',') {
					/* bounded on left. */
					if (*p == ',' || *p == '\0') {
						/* bounded on right. */
						repeat = 1;
						break;
					}
				}
				q = p;
			}
			if (repeat) {
				continue;
			}
			sprintf(tmp, ":DPY");
		}

		if (*out) {
			strcat(out, ",");
		}
		strcat(out, user);
		strcat(out, tmp);

		cnt++;
		if (cnt >= max) {
			break;
		}
	}
	endutxent();
#else
	out = strdup("");
#endif
	return out;
}

static char **user_list(char *user_str) {
	int n, i;
	char *p, **list;
	
	p = user_str;
	n = 1;
	while (*p++) {
		if (*p == ',') {
			n++;
		}
	}
261
	list = (char **) calloc((n+1)*sizeof(char *), 1);
runge's avatar
runge committed
262 263 264 265

	p = strtok(user_str, ",");
	i = 0;
	while (p) {
266
		list[i++] = strdup(p);
runge's avatar
runge committed
267 268 269 270 271 272
		p = strtok(NULL, ",");
	}
	list[i] = NULL;
	return list;
}

273
static void user2uid(char *user, uid_t *uid, gid_t *gid, char **name, char **home) {
274
	int numerical = 1, gotgroup = 0;
runge's avatar
runge committed
275 276 277 278 279 280 281 282
	char *q;

	*uid = (uid_t) -1;
	*name = NULL;
	*home = NULL;

	q = user;
	while (*q) {
283
		if (! isdigit((unsigned char) (*q++))) {
runge's avatar
runge committed
284 285 286 287 288
			numerical = 0;
			break;
		}
	}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	if (user2group != NULL) {
		static int *did = NULL;
		int i;

		if (did == NULL) {
			int n = 0;
			i = 0;
			while (user2group[i] != NULL) {
				n++;
				i++;
			}
			did = (int *) malloc((n+1) * sizeof(int)); 
			i = 0;
			for (i=0; i<n; i++) {
				did[i] = 0;
			}
		}
		i = 0;
		while (user2group[i] != NULL) {
			if (strstr(user2group[i], user) == user2group[i]) {
				char *w = user2group[i] + strlen(user);
				if (*w == '.') {
311 312 313
#if (SMALL_FOOTPRINT > 2)
					gotgroup = 0;
#else
314 315 316 317 318 319 320 321 322 323 324 325
					struct group* gr = getgrnam(++w);
					if (! gr) {
						rfbLog("Invalid group: %s\n", w);
						clean_up_exit(1);
					}
					*gid = gr->gr_gid;
					if (! did[i]) {
						rfbLog("user2uid: using group %s (%d) for %s\n",
						    w, (int) *gid, user);
						did[i] = 1;
					}
					gotgroup = 1;
326
#endif
327 328 329 330 331 332
				}
			}
			i++;
		}
	}

runge's avatar
runge committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
	if (numerical) {
		int u = atoi(user);

		if (u < 0) {
			return;
		}
		*uid = (uid_t) u;
	}

#if LIBVNCSERVER_HAVE_PWD_H
	if (1) {
		struct passwd *pw;
		if (numerical) {
			pw = getpwuid(*uid);
		} else {
			pw = getpwnam(user);
		}
		if (pw) {
			*uid  = pw->pw_uid;
352 353 354
			if (! gotgroup) {
				*gid  = pw->pw_gid;
			}
runge's avatar
runge committed
355 356 357 358 359 360 361 362 363 364
			*name = pw->pw_name;	/* n.b. use immediately */
			*home = pw->pw_dir;
		}
	}
#endif
}


static int lurk(char **users) {
	uid_t uid;
365
	gid_t gid;
runge's avatar
runge committed
366 367
	int success = 0, dmin = -1, dmax = -1;
	char *p, *logins, **u;
368 369
	char **list;
	int lind;
runge's avatar
runge committed
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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

	if ((u = users) != NULL && *u != NULL && *(*u) == ':') {
		int len;
		char *tmp;

		/* extract min and max display numbers */
		tmp = *u;
		if (strchr(tmp, '-')) {
			if (sscanf(tmp, ":%d-%d", &dmin, &dmax) != 2) {
				dmin = -1;
				dmax = -1;
			}
		}
		if (dmin < 0) {
			if (sscanf(tmp, ":%d", &dmin) != 1) {
				dmin = -1;
				dmax = -1;
			} else {
				dmax = dmin;
			}
		}
		if ((dmin < 0 || dmax < 0) || dmin > dmax || dmax > 10000) {
			dmin = -1;
			dmax = -1;
		}

		/* get user logins regardless of having a display: */
		logins = get_login_list(0);

		/*
		 * now we append the list in users (might as well try
		 * them) this will probably allow weird ways of starting
		 * xservers to work.
		 */
		len = strlen(logins);
		u++;
		while (*u != NULL) {
			len += strlen(*u) + strlen(":DPY,");
			u++;
		}
		tmp = (char *) malloc(len+1);
		strcpy(tmp, logins);

		/* now concatenate them: */
		u = users+1;
		while (*u != NULL) {
			char *q, chk[100];
			snprintf(chk, 100, "%s:DPY", *u);
			q = strstr(tmp, chk);
			if (q) {
				char *p = q + strlen(chk);
				
				if (q == tmp || *(q-1) == ',') {
					/* bounded on left. */
					if (*p == ',' || *p == '\0') {
						/* bounded on right. */
						u++;
						continue;
					}
				}
			}
			
			if (*tmp) {
				strcat(tmp, ",");
			}
			strcat(tmp, *u);
			strcat(tmp, ":DPY");
			u++;
		}
		free(logins);
		logins = tmp;
		
	} else {
		logins = get_login_list(1);
	}
445 446 447

	list = (char **) calloc((strlen(logins)+2)*sizeof(char *), 1);
	lind = 0;
runge's avatar
runge committed
448 449
	p = strtok(logins, ",");
	while (p) {
450 451 452 453 454 455 456
		list[lind++] = strdup(p);
		p = strtok(NULL, ",");
	}
	free(logins);

	lind = 0;
	while (list[lind] != NULL) {
runge's avatar
runge committed
457 458 459
		char *user, *name, *home, dpystr[10];
		char *q, *t;
		int ok = 1, dn;
460 461

		p = list[lind++];
runge's avatar
runge committed
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
		
		t = strdup(p);	/* bob:0 */
		q = strchr(t, ':'); 
		if (! q) {
			free(t);
			break;
		}
		*q = '\0';
		user = t;
		snprintf(dpystr, 10, ":%s", q+1);

		if (users) {
			u = users;
			ok = 0;
			while (*u != NULL) {
				if (*(*u) == ':') {
					u++;
					continue;
				}
				if (!strcmp(user, *u++)) {
					ok = 1;
					break;
				}
			}
		}

488
		user2uid(user, &uid, &gid, &name, &home);
runge's avatar
runge committed
489 490
		free(t);

491
		if (! uid || ! gid) {
runge's avatar
runge committed
492 493 494 495 496 497 498 499 500 501 502
			ok = 0;
		}

		if (! ok) {
			continue;
		}
		
		for (dn = dmin; dn <= dmax; dn++) {
			if (dn >= 0) {
				sprintf(dpystr, ":%d", dn);
			}
503 504
			if (try_user_and_display(uid, gid, dpystr)) {
				if (switch_user_env(uid, gid, name, home, 0)) {
runge's avatar
runge committed
505 506 507 508 509 510 511 512 513 514 515 516
					rfbLog("lurk: now user: %s @ %s\n",
					    name, dpystr);
					started_as_root = 2;
					success = 1;
				}
				set_env("DISPLAY", dpystr);
				break;
			}
		}
		if (success) {
			 break;
		}
517
	}
runge's avatar
runge committed
518

519 520 521 522
	lind = 0;
	while (list[lind] != NULL) {
		free(list[lind]);
		lind++;
runge's avatar
runge committed
523
	}
524

runge's avatar
runge committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
	return success;
}

void lurk_loop(char *str) {
	char *tstr = NULL, **users = NULL;

	if (strstr(str, "lurk=") != str) {
		exit(1);
	}
	rfbLog("lurking for logins using: '%s'\n", str);
	if (strlen(str) > strlen("lurk=")) {
		char *q = strchr(str, '=');
		tstr = strdup(q+1);
		users = user_list(tstr);
	}

	while (1) {
		if (lurk(users)) {
			break;
		}
		sleep(3);
	}
	if (tstr) {
		free(tstr);
	}
	if (users) {
		free(users);
	}
}

static int guess_user_and_switch(char *str, int fb_mode) {
556
	char *dstr, *d;
runge's avatar
runge committed
557 558
	char *p, *tstr = NULL, *allowed = NULL, *logins, **users = NULL;
	int dpy1, ret = 0;
559 560
	char **list;
	int lind;
runge's avatar
runge committed
561

562 563 564
	RAWFB_RET(0)

	d = DisplayString(dpy);
runge's avatar
runge committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
	/* pick out ":N" */
	dstr = strchr(d, ':');
	if (! dstr) {
		return 0;
	}
	if (sscanf(dstr, ":%d", &dpy1) != 1) {
		return 0;
	}
	if (dpy1 < 0) {
		return 0;
	}

	if (strstr(str, "guess=") == str && strlen(str) > strlen("guess=")) {
		allowed = strchr(str, '=');
		allowed++;

		tstr = strdup(allowed);
		users = user_list(tstr);
	}

	/* loop over the utmpx entries looking for this display */
	logins = get_login_list(1);
587 588 589

	list = (char **) calloc((strlen(logins)+2)*sizeof(char *), 1);
	lind = 0;
runge's avatar
runge committed
590 591
	p = strtok(logins, ",");
	while (p) {
592 593 594 595 596 597
		list[lind++] = strdup(p);
		p = strtok(NULL, ",");
	}

	lind = 0;
	while (list[lind] != NULL) {
runge's avatar
runge committed
598 599 600
		char *user, *q, *t;
		int dpy2, ok = 1;

601 602
		p = list[lind++];

runge's avatar
runge committed
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 628 629 630
		t = strdup(p);
		q = strchr(t, ':'); 
		if (! q) {
			free(t);
			break;
		}
		*q = '\0';
		user = t;
		dpy2 = atoi(q+1);

		if (users) {
			char **u = users;
			ok = 0;
			while (*u != NULL) {
				if (!strcmp(user, *u++)) {
					ok = 1;
					break;
				}
			}
		}
		if (dpy1 != dpy2) {
			ok = 0;
		}

		if (! ok) {
			free(t);
			continue;
		}
631

runge's avatar
runge committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
		if (switch_user(user, fb_mode)) {
			rfbLog("switched to guessed user: %s\n", user);
			free(t);
			ret = 1;
			break;
		}
	}
	if (tstr) {
		free(tstr);
	}
	if (users) {
		free(users);
	}
	if (logins) {
		free(logins);
	}
	return ret;
}

651
static int try_user_and_display(uid_t uid, gid_t gid, char *dpystr) {
runge's avatar
runge committed
652 653 654 655 656 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
	/* NO strtoks */
#if LIBVNCSERVER_HAVE_FORK && LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_PWD_H
	pid_t pid, pidw;
	char *home, *name;
	int st;
	struct passwd *pw;
	
	pw = getpwuid(uid);
	if (pw) {
		name = pw->pw_name;
		home = pw->pw_dir;
	} else {
		return 0;
	}

	/* 
	 * We fork here and try to open the display again as the
	 * new user.  Unreadable XAUTHORITY could be a problem...
	 * This is not really needed since we have DISPLAY open but:
	 * 1) is a good indicator this user owns the session and  2)
	 * some activities do spawn new X apps, e.g.  xmessage(1), etc.
	 */
	if ((pid = fork()) > 0) {
		;
	} else if (pid == -1) {
		fprintf(stderr, "could not fork\n");
		rfbLogPerror("fork");
		return 0;
	} else {
		/* child */
		Display *dpy2 = NULL;
		int rc;

685 686 687 688 689
		signal(SIGHUP,  SIG_DFL);
		signal(SIGINT,  SIG_DFL);
		signal(SIGQUIT, SIG_DFL);
		signal(SIGTERM, SIG_DFL);

690
		rc = switch_user_env(uid, gid, name, home, 0); 
runge's avatar
runge committed
691 692 693 694 695
		if (! rc) {
			exit(1);
		}

		fclose(stderr);
696
		dpy2 = XOpenDisplay_wr(dpystr);
runge's avatar
runge committed
697
		if (dpy2) {
698
			XCloseDisplay_wr(dpy2);
runge's avatar
runge committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
			exit(0);	/* success */
		} else {
			exit(2);	/* fail */
		}
	}

	/* see what the child says: */
	pidw = waitpid(pid, &st, 0);
	if (pidw == pid && WIFEXITED(st) && WEXITSTATUS(st) == 0) {
		return 1;
	}
#endif	/* LIBVNCSERVER_HAVE_FORK ... */
	return 0;
}

int switch_user(char *user, int fb_mode) {
	/* NO strtoks */
	int doit = 0;
	uid_t uid = 0;
718
	gid_t gid = 0;
runge's avatar
runge committed
719 720 721 722 723 724 725
	char *name, *home;

	if (*user == '+') {
		doit = 1;
		user++;
	}

726 727
	ssl_helper_pid(0, -2);	/* waitall */

runge's avatar
runge committed
728 729 730 731
	if (strstr(user, "guess=") == user) {
		return guess_user_and_switch(user, fb_mode);
	}

732
	user2uid(user, &uid, &gid, &name, &home);
runge's avatar
runge committed
733 734 735 736

	if (uid == (uid_t) -1 || uid == 0) {
		return 0;
	}
737 738 739
	if (gid == 0) {
		return 0;
	}
runge's avatar
runge committed
740 741 742 743

	if (! doit && dpy) {
		/* see if this display works: */
		char *dstr = DisplayString(dpy);
744
		doit = try_user_and_display(uid, gid, dstr);
runge's avatar
runge committed
745 746 747
	}

	if (doit) {
748
		int rc = switch_user_env(uid, gid, name, home, fb_mode);
runge's avatar
runge committed
749 750 751 752 753 754 755 756 757
		if (rc) {
			started_as_root = 2;
		}
		return rc;
	} else {
		return 0;
	}
}

758
static int switch_user_env(uid_t uid, gid_t gid, char *name, char *home, int fb_mode) {
runge's avatar
runge committed
759 760 761
	/* NO strtoks */
	char *xauth;
	int reset_fb = 0;
762
	int grp_ok = 0;
runge's avatar
runge committed
763 764 765 766 767

#if !LIBVNCSERVER_HAVE_SETUID
	return 0;
#else
	/*
768
	 * OK, tricky here, we need to free the shm... otherwise
runge's avatar
runge committed
769 770
	 * we won't be able to delete it as the other user...
	 */
771
	if (fb_mode == 1 && (using_shm && ! xform24to32)) {
runge's avatar
runge committed
772 773 774 775
		reset_fb = 1;
		clean_shm(0);
		free_tiles();
	}
776 777 778 779
#if LIBVNCSERVER_HAVE_INITGROUPS
#if LIBVNCSERVER_HAVE_PWD_H
	if (getpwuid(uid) != NULL && getenv("X11VNC_SINGLE_GROUP") == NULL) {
		struct passwd *p = getpwuid(uid);
780 781
		/* another possibility is p->pw_gid instead of gid */
		if (setgid(gid) == 0 && initgroups(p->pw_name, gid) == 0)  {
782 783 784 785
			grp_ok = 1;
		} else {
			rfbLogPerror("initgroups");
		}
786
		endgrent();
787 788 789 790 791 792 793 794 795
	}
#endif
#endif
	if (! grp_ok) {
		if (setgid(gid) == 0) {
			grp_ok = 1;
		}
	}
	if (! grp_ok) {
796 797 798 799 800 801
		if (reset_fb) {
			/* 2 means we did clean_shm and free_tiles */
			do_new_fb(2);
		}
		return 0;
	}
802

runge's avatar
runge committed
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	if (setuid(uid) != 0) {
		if (reset_fb) {
			/* 2 means we did clean_shm and free_tiles */
			do_new_fb(2);
		}
		return 0;
	}
#endif
	if (reset_fb) {
		do_new_fb(2);
	}

	xauth = getenv("XAUTHORITY");
	if (xauth && access(xauth, R_OK) != 0) {
		*(xauth-2) = '_';	/* yow */
	}
	
	set_env("USER", name);
	set_env("LOGNAME", name);
	set_env("HOME", home);
	return 1;
}

static void try_to_switch_users(void) {
	static time_t last_try = 0;
828
	time_t now = time(NULL);
runge's avatar
runge committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
	char *users, *p;

	if (getuid() && geteuid()) {
		rfbLog("try_to_switch_users: not root\n");
		started_as_root = 2;
		return;
	}
	if (!last_try) {
		last_try = now;
	} else if (now <= last_try + 2) {
		/* try every 3 secs or so */
		return;
	}
	last_try = now;

	users = strdup(users_list);

	if (strstr(users, "guess=") == users) {
		if (switch_user(users, 1)) {
			started_as_root = 2;
		}
		free(users);
		return;
	}

	p = strtok(users, ",");
	while (p) {
		if (switch_user(p, 1)) {
			started_as_root = 2;
			rfbLog("try_to_switch_users: now %s\n", p);
			break;
		}
		p = strtok(NULL, ",");
	}
	free(users);
}

int read_passwds(char *passfile) {
	char line[1024];
	char *filename;
	char **old_passwd_list = passwd_list;
870
	int linecount = 0, i, remove = 0, read_mode = 0, begin_vo = -1;
runge's avatar
runge committed
871
	struct stat sbuf;
872 873
	static int max = -1;
	FILE *in = NULL;
runge's avatar
runge committed
874 875 876 877
	static time_t last_read = 0;
	static int read_cnt = 0;
	int db_passwd = 0;

878 879 880 881 882 883 884
	if (max < 0) {
		max = 1000;
		if (getenv("X11VNC_MAX_PASSWDS")) {
			max = atoi(getenv("X11VNC_MAX_PASSWDS"));
		}
	}

runge's avatar
runge committed
885 886 887 888 889 890 891 892 893
	filename = passfile;
	if (strstr(filename, "rm:") == filename) {
		filename += strlen("rm:");
		remove = 1;
	} else if (strstr(filename, "read:") == filename) {
		filename += strlen("read:");
		read_mode = 1;
		if (stat(filename, &sbuf) == 0) {
			if (sbuf.st_mtime <= last_read) {
894
				return 1;
runge's avatar
runge committed
895 896 897
			}
			last_read = sbuf.st_mtime;
		}
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
	} else if (strstr(filename, "cmd:") == filename) {
		int rc;

		filename += strlen("cmd:");
		read_mode = 1;
		in = tmpfile();
		if (in == NULL) {
			rfbLog("run_user_command tmpfile() failed: %s\n",
			    filename);
			clean_up_exit(1);
		}
		rc = run_user_command(filename, latest_client, "read_passwds",
		    NULL, 0, in);
		if (rc != 0) {
			rfbLog("run_user_command command failed: %s\n",
			    filename);
			clean_up_exit(1);
		}
		rewind(in);
	} else if (strstr(filename, "custom:") == filename) {
		return 1;
runge's avatar
runge committed
919 920
	}

921
	if (in == NULL && stat(filename, &sbuf) == 0) {
runge's avatar
runge committed
922 923 924 925 926 927 928 929 930 931 932
		/* (poor...) upper bound to number of lines */
		max = (int) sbuf.st_size;
		last_read = sbuf.st_mtime;
	}

	/* create 1 more than max to have it be the ending NULL */
	passwd_list = (char **) malloc( (max+1) * (sizeof(char *)) );
	for (i=0; i<max+1; i++) {
		passwd_list[i] = NULL;
	}
	
933 934 935
	if (in == NULL) {
		in = fopen(filename, "r");
	}
runge's avatar
runge committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	if (in == NULL) {
		rfbLog("cannot open passwdfile: %s\n", passfile);
		rfbLogPerror("fopen");
		if (remove) {
			unlink(filename);
		}
		clean_up_exit(1);
	}

	if (getenv("DEBUG_PASSWDFILE") != NULL) {
		db_passwd = 1;
	}

	while (fgets(line, 1024, in) != NULL) {
		char *p;
		int blank = 1;
		int len = strlen(line); 

		if (db_passwd) {
			fprintf(stderr, "read_passwds: raw line: %s\n", line);
		}

		if (len == 0) {
			continue;
		} else if (line[len-1] == '\n') {
			line[len-1] = '\0';
		}
		if (line[0] == '\0') {
			continue;
		}
		if (strstr(line, "__SKIP__") != NULL) {
			continue;
		}
		if (strstr(line, "__COMM__") == line) {
			continue;
		}
		if (!strcmp(line, "__BEGIN_VIEWONLY__")) {
			if (begin_vo < 0) {
				begin_vo = linecount;
			}
			continue;
		}
		if (line[0] == '#') {
			/* commented out, cannot have password beginning with # */
			continue;
		}
		p = line;
		while (*p != '\0') {
984
			if (! isspace((unsigned char) (*p))) {
runge's avatar
runge committed
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
				blank = 0;
				break;
			}
			p++;
		}
		if (blank) {
			continue;
		}

		passwd_list[linecount++] = strdup(line);
		if (db_passwd) {
			fprintf(stderr, "read_passwds: keepline: %s\n", line);
			fprintf(stderr, "read_passwds: begin_vo: %d\n", begin_vo);
		}

		if (linecount >= max) {
1001
			rfbLog("read_passwds: hit max passwd: %d\n", max);
runge's avatar
runge committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
			break;
		}
	}
	fclose(in);

	for (i=0; i<1024; i++) {
		line[i] = '\0';
	}

	if (remove) {
		unlink(filename);
	}

	if (! linecount) {
		rfbLog("cannot read a valid line from passwdfile: %s\n",
		    passfile);
		if (read_cnt == 0) {
			clean_up_exit(1);
		} else {
			return 0;
		}
	}
	read_cnt++;

	for (i=0; i<linecount; i++) {
		char *q, *p = passwd_list[i];
		if (!strcmp(p, "__EMPTY__")) {
			*p = '\0';
		} else if ((q = strstr(p, "__COMM__")) != NULL) {
			*q = '\0';
		}
		passwd_list[i] = strdup(p);
		if (db_passwd) {
			fprintf(stderr, "read_passwds: trimline: %s\n", p);
		}
		strzero(p);
	}

	begin_viewonly = begin_vo;
	if (read_mode && read_cnt > 1) {
		if (viewonly_passwd) {
			free(viewonly_passwd);
			viewonly_passwd = NULL;
		}
	}

	if (begin_viewonly < 0 && linecount == 2) {
		/* for compatibility with previous 2-line usage: */
		viewonly_passwd = strdup(passwd_list[1]);
		if (db_passwd) {
			fprintf(stderr, "read_passwds: linecount is 2.\n");
		}
		if (screen) {
			char **apd = (char **) screen->authPasswdData;
			if (apd) {
				if (apd[0] != NULL) {
					strzero(apd[0]);
				}
				apd[0] = strdup(passwd_list[0]);
			}
		}
		begin_viewonly = 1;
	}

	if (old_passwd_list != NULL) {
		char *p;
		i = 0;
		while (old_passwd_list[i] != NULL) {
			p = old_passwd_list[i];
			strzero(p);
			free(old_passwd_list[i]);
			i++;
		}
		free(old_passwd_list);
	}
	return 1;
}

void install_passwds(void) {
	if (viewonly_passwd) {
		/* append the view only passwd after the normal passwd */
		char **passwds_new = (char **) malloc(3*sizeof(char *));
		char **passwds_old = (char **) screen->authPasswdData;
		passwds_new[0] = passwds_old[0];
		passwds_new[1] = viewonly_passwd;
		passwds_new[2] = NULL;
1088
		/* mutex */
runge's avatar
runge committed
1089 1090 1091 1092 1093 1094 1095 1096 1097
		screen->authPasswdData = (void*) passwds_new;
	} else if (passwd_list) {
		int i = 0;
		while(passwd_list[i] != NULL) {
			i++;
		}
		if (begin_viewonly < 0) {
			begin_viewonly = i+1;
		}
1098
		/* mutex */
runge's avatar
runge committed
1099 1100 1101 1102 1103
		screen->authPasswdData = (void*) passwd_list;
		screen->authPasswdFirstViewOnly = begin_viewonly;
	}
}

1104
void check_new_passwds(int force) {
runge's avatar
runge committed
1105 1106 1107 1108 1109 1110 1111 1112 1113
	static time_t last_check = 0;
	time_t now;

	if (! passwdfile) {
		return;
	}
	if (strstr(passwdfile, "read:") != passwdfile) {
		return;
	}
1114 1115
	if (unixpw_in_progress) return;

1116 1117 1118 1119
	if (force) {
		last_check = 0;
	}

1120
	now = time(NULL);
runge's avatar
runge committed
1121 1122 1123 1124 1125 1126 1127 1128
	if (now > last_check + 1) {
		if (read_passwds(passwdfile)) {
			install_passwds();
		}
		last_check = now;
	}
}

1129
rfbBool custom_passwd_check(rfbClientPtr cl, const char *response, int len) {
1130
	char *input, *cmd;
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	char num[16];
	int j, i, n, rc;

	rfbLog("custom_passwd_check: len=%d\n", len);

	if (!passwdfile || strstr(passwdfile, "custom:") != passwdfile) {
		return FALSE;
	}
	cmd = passwdfile + strlen("custom:");

	sprintf(num, "%d\n", len);

	input = (char *) malloc(2 * len + 16 + 1);
	
	input[0] = '\0';
	strcat(input, num);
	n = strlen(num);

	j = n;
	for (i=0; i < len; i++) {
		input[j] = cl->authChallenge[i];
		j++;
	}
	for (i=0; i < len; i++) {
		input[j] = response[i];
		j++;
	}
	rc = run_user_command(cmd, cl, "custom_passwd", input, n+2*len, NULL);
	free(input);
	if (rc == 0) {
		return TRUE;
	} else {
		return FALSE;
	}
}

1167 1168
static void handle_one_http_request(void) {
	rfbLog("handle_one_http_request: begin.\n");
1169 1170
	if (inetd || screen->httpPort == 0) {
		int port = find_free_port(5800, 5860);
1171
		if (port) {
1172
			/* mutex */
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
			screen->httpPort = port;
		} else {
			rfbLog("handle_one_http_request: no http port.\n");
			clean_up_exit(1);
		}
	}
	screen->autoPort = FALSE;
	screen->port = 0;

	http_connections(1);
1183

1184 1185
	rfbInitServer(screen);

1186
	if (!inetd) {
1187
		/* XXX ipv6 */
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
		int conn = 0;
		while (1) {
			if (0) fprintf(stderr, "%d %d %d  %d\n", conn, screen->listenSock, screen->httpSock, screen->httpListenSock);
			usleep(10 * 1000);
			rfbHttpCheckFds(screen);
			if (conn) {
				if (screen->httpSock < 0) {
					break;
				}
			} else {
				if (screen->httpSock >= 0) {
					conn = 1;
				}
			}
			if (!screen->httpDir) {
				break;
			}
			if (screen->httpListenSock < 0) {
				break;
			}
		}
		rfbLog("handle_one_http_request: finished.\n");
		return;
	} else {
1212
		/* inetd case: */
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
#if LIBVNCSERVER_HAVE_FORK
		pid_t pid;
		int s_in = screen->inetdSock;
		if (s_in < 0) {
			rfbLog("handle_one_http_request: inetdSock not set up.\n");
			clean_up_exit(1);
		}
		pid = fork();
		if (pid < 0) {
			rfbLog("handle_one_http_request: could not fork.\n");
			clean_up_exit(1);
		} else if (pid > 0) {
			int status;
			pid_t pidw;
			while (1) {
				rfbHttpCheckFds(screen);
				pidw = waitpid(pid, &status, WNOHANG); 
				if (pidw == pid && WIFEXITED(status)) {
					break;
				} else if (pidw < 0) {
					break;
				}
			}
			rfbLog("handle_one_http_request: finished.\n");
			return;
		} else {
1239
			int sock = connect_tcp("127.0.0.1", screen->httpPort);
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
			if (sock < 0) {
				exit(1);
			}
			raw_xfer(sock, s_in, s_in);
			exit(0);
		}
#else
		rfbLog("handle_one_http_request: fork not supported.\n");
		clean_up_exit(1);
#endif
	}
}

1253 1254 1255 1256
void user_supplied_opts(char *opts) {
	char *p, *str;
	char *allow[] = {
		"skip-display", "skip-auth", "skip-shared",
1257 1258
		"scale", "scale_cursor", "sc", "solid", "so", "id",
		"clear_mods", "cm", "clear_keys", "ck", "repeat",
1259
		"clear_all", "ca",
1260
		"speeds", "sp", "readtimeout", "rd",
runge's avatar
runge committed
1261
		"rotate", "ro",
1262
		"geometry", "geom", "ge",
1263
		"noncache", "nc",
1264
		"nodisplay", "nd",
1265
		"viewonly", "vo",
1266
		"tag",
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
		NULL
	};

	if (getenv("X11VNC_NO_UNIXPW_OPTS")) {
		return;
	}

	str = strdup(opts);

	p = strtok(str, ",");
	while (p) {
		char *q;
		int i, n, m, ok = 0;

		i = 0;
		while (allow[i] != NULL) {
			if (strstr(allow[i], "skip-")) {
				i++;
				continue;
			}
			if (strstr(p, allow[i]) == p) 	{
				ok = 1;
				break;
			}
			i++;
		}

1294 1295
		if (! ok && strpbrk(p, "0123456789") == p &&
		    sscanf(p, "%d/%d", &n, &m) == 2) {
1296 1297 1298
			if (scale_str) free(scale_str);
			scale_str = strdup(p);
		} else if (ok) {
1299
			if (0 && strstr(p, "display=") == p) {
1300 1301
				if (use_dpy) free(use_dpy);
				use_dpy = strdup(p + strlen("display="));
1302
			} else if (0 && strstr(p, "auth=") == p) {
1303 1304
				if (auth_file) free(auth_file);
				auth_file = strdup(p + strlen("auth="));
1305
			} else if (0 && !strcmp(p, "shared")) {
1306
				shared = 1;
1307 1308 1309
			} else if (strstr(p, "scale=") == p) {
				if (scale_str) free(scale_str);
				scale_str = strdup(p + strlen("scale="));
1310 1311
			} else if (strstr(p, "scale_cursor=") == p ||
			    strstr(p, "sc=") == p) {
1312
				if (scale_cursor_str) free(scale_cursor_str);
1313 1314
				q = strchr(p, '=') + 1;
				scale_cursor_str = strdup(q);
runge's avatar
runge committed
1315 1316 1317 1318 1319
			} else if (strstr(p, "rotate=") == p ||
			    strstr(p, "ro=") == p) {
				if (rotating_str) free(rotating_str);
				q = strchr(p, '=') + 1;
				rotating_str = strdup(q);
1320
			} else if (!strcmp(p, "solid") || !strcmp(p, "so")) {
1321 1322 1323 1324
				use_solid_bg = 1;
				if (!solid_str) {
					solid_str = strdup(solid_default);
				}
1325 1326
			} else if (!strcmp(p, "viewonly") || !strcmp(p, "vo")) {
				view_only = 1;
1327 1328
			} else if (strstr(p, "solid=") == p ||
			    strstr(p, "so=") == p) {
1329 1330
				use_solid_bg = 1;
				if (solid_str) free(solid_str);
1331 1332 1333 1334 1335 1336
				q = strchr(p, '=') + 1;
				if (!strcmp(q, "R")) {
					solid_str = strdup("root:");
				} else {
					solid_str = strdup(q);
				}
1337 1338 1339 1340 1341 1342 1343 1344
			} else if (strstr(p, "id=") == p) {
				unsigned long win;
				q = p + strlen("id=");
				if (strcmp(q, "pick")) {
					if (scan_hexdec(q, &win)) {
						subwin = win;
					}
				}
1345 1346
			} else if (!strcmp(p, "clear_mods") ||
			    !strcmp(p, "cm")) {
1347
				clear_mods = 1;
1348 1349
			} else if (!strcmp(p, "clear_keys") ||
			    !strcmp(p, "ck")) {
1350
				clear_mods = 2;
1351 1352 1353
			} else if (!strcmp(p, "clear_all") ||
			    !strcmp(p, "ca")) {
				clear_mods = 3;
1354 1355
			} else if (!strcmp(p, "noncache") ||
			    !strcmp(p, "nc")) {
1356
				ncache  = 0;
1357
				ncache0 = 0;
1358 1359 1360 1361 1362 1363 1364 1365 1366
			} else if (strstr(p, "nc=") == p) {
				int n2 = atoi(p + strlen("nc="));
				if (nabs(n2) < nabs(ncache)) {
					if (ncache < 0) {
						ncache = -nabs(n2);
					} else {
						ncache = nabs(n2);
					}
				}
1367 1368
			} else if (!strcmp(p, "repeat")) {
				no_autorepeat = 0;
1369 1370
			} else if (strstr(p, "speeds=") == p ||
			    strstr(p, "sp=") == p) {
1371
				if (speeds_str) free(speeds_str);
1372 1373
				q = strchr(p, '=') + 1;
				speeds_str = strdup(q);
1374 1375 1376 1377 1378 1379 1380
				q = speeds_str;
				while (*q != '\0') {
					if (*q == '-') {
						*q = ',';
					}
					q++;
				}
1381 1382 1383 1384
			} else if (strstr(p, "readtimeout=") == p ||
			    strstr(p, "rd=") == p) {
				q = strchr(p, '=') + 1;
				rfbMaxClientWait = atoi(q) * 1000;
1385
			}
1386 1387
		} else {
			rfbLog("skipping option: %s\n", p);
1388 1389 1390 1391 1392 1393
		}
		p = strtok(NULL, ",");
	}
	free(str);
}

1394 1395
static void vnc_redirect_timeout (int sig) {
	write(2, "timeout: no clients connected.\n", 31);
1396
	if (sig) {};
1397 1398 1399
	exit(0);
}

1400 1401 1402 1403 1404 1405 1406
static void do_chvt(int vt) {
	char chvt[100];
	sprintf(chvt, "chvt %d >/dev/null 2>/dev/null &", vt);
	rfbLog("running: %s\n", chvt);
	system(chvt);
	sleep(2);
}
1407

1408
static void setup_fake_fb(XImage* fb_image, int w, int h, int b) {
1409 1410 1411
	if (fake_fb) {
		free(fake_fb);
	}
1412
	fake_fb = (char *) calloc(w*h*b/8, 1);
1413 1414 1415 1416 1417 1418 1419 1420

	fb_image->data = fake_fb;
	fb_image->format = ZPixmap;
	fb_image->width  = w;
	fb_image->height = h;
	fb_image->bits_per_pixel = b;
	fb_image->bytes_per_line = w*b/8;
	fb_image->bitmap_unit = -1;
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
	if (b >= 24) {
		fb_image->depth = 24;
		fb_image->red_mask   = 0xff0000;
		fb_image->green_mask = 0x00ff00;
		fb_image->blue_mask  = 0x0000ff;
	} else if (b >= 16) {
		fb_image->depth = 16;
		fb_image->red_mask   = 0x003f;
		fb_image->green_mask = 0x07c0;
		fb_image->blue_mask  = 0xf800;
	} else if (b >= 2) {
		fb_image->depth = 8;
		fb_image->red_mask   = 0x07;
		fb_image->green_mask = 0x38;
		fb_image->blue_mask  = 0xc0;
	} else {
		fb_image->depth = 1;
		fb_image->red_mask   = 0x1;
		fb_image->green_mask = 0x1;
		fb_image->blue_mask  = 0x1;
	}
1442 1443 1444 1445 1446 1447 1448

	depth = fb_image->depth;

	dpy_x = wdpy_x = w;
	dpy_y = wdpy_y = h;
	off_x = 0;
	off_y = 0;
1449
}
1450

1451 1452 1453
void do_announce_http(void);
void do_mention_java_urls(void);

1454
static void setup_service(void) {
1455 1456 1457
	if (remote_direct) {
		return;
	}
1458
	if (!inetd) {
1459 1460
		do_mention_java_urls();
		do_announce_http();
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
		if (!use_openssl) {
			announce(screen->port, use_openssl, NULL);
			fprintf(stdout, "PORT=%d\n", screen->port);
		} else {
			fprintf(stdout, "PORT=%d\n", screen->port);
			if (stunnel_port) {
				fprintf(stdout, "SSLPORT=%d\n", stunnel_port);
			} else if (use_openssl) {
				fprintf(stdout, "SSLPORT=%d\n", screen->port);
			}
		}
		fflush(stdout);
	} else if (!use_openssl && avahi) {
		char *name = rfb_desktop_name;
		if (!name) {
			name = use_dpy;
		}
		avahi_initialise();
		avahi_advertise(name, this_host(), screen->port);
	}
1481
}
1482

1483
static void check_waitbg(void) {
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
	if (getenv("WAITBG")) {
#if LIBVNCSERVER_HAVE_FORK && LIBVNCSERVER_HAVE_SETSID
		int p, n;
		if ((p = fork()) > 0)  {
			exit(0);
		} else if (p == -1) {
			rfbLogEnable(1);
			fprintf(stderr, "could not fork\n");
			perror("fork");
			clean_up_exit(1);
		}
		if (setsid() == -1) {
			rfbLogEnable(1);
			fprintf(stderr, "setsid failed\n");
			perror("setsid");
			clean_up_exit(1);
		}
		/* adjust our stdio */
		n = open("/dev/null", O_RDONLY);
		dup2(n, 0);
		dup2(n, 1);
		if (! logfile) {
			dup2(n, 2);
		}
		if (n > 2) {
			close(n);
		}
#else
		clean_up_exit(1);
#endif
	}
1515
}
1516

1517
static void setup_client_connect(int *did_client_connect) {
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
	if (client_connect != NULL) {
		char *remainder = NULL;
		if (inetd) {
			rfbLog("wait_for_client: -connect disallowed in inetd mode: %s\n",
			    client_connect);
		} else if (screen && screen->clientHead) {
			rfbLog("wait_for_client: -connect disallowed: client exists: %s\n",
			    client_connect);
		} else if (strchr(client_connect, '=')) {
			rfbLog("wait_for_client: invalid -connect string: %s\n",
			    client_connect);
		} else {
			char *q = strchr(client_connect, ',');
			if (q) {
				rfbLog("wait_for_client: only using first"
				    " connect host in: %s\n", client_connect);
				remainder = strdup(q+1);
				*q = '\0';
			}
			rfbLog("wait_for_client: reverse_connect(%s)\n",
			    client_connect);
			reverse_connect(client_connect);
1540
			*did_client_connect = 1;
1541 1542 1543 1544 1545 1546 1547 1548 1549
		}
		free(client_connect);
		if (remainder != NULL) {
			/* reset to host2,host3,... */
			client_connect = remainder;
		} else {
			client_connect = NULL;
		}
	}
1550
}
1551

1552 1553 1554
static void loop_for_connect(int did_client_connect) {
	int loop = 0;
	time_t start = time(NULL);
1555

1556 1557 1558 1559
	if (first_conn_timeout < 0) {
		first_conn_timeout = -first_conn_timeout;
	}

1560
	while (1) {
1561
		loop++;
1562 1563 1564 1565
		if (first_conn_timeout && time(NULL) > start + first_conn_timeout) {
			rfbLog("no client connect after %d seconds.\n", first_conn_timeout);
			shut_down = 1;
		}
1566 1567
		if (shut_down) {
			clean_up_exit(0);
1568
		}
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
		if (loop < 2) {
			if (did_client_connect) {
				goto screen_check;
			}
			if (inetd) {
				goto screen_check;
			}
			if (screen && screen->clientHead) {
				goto screen_check;
			}
		}
1580 1581 1582 1583 1584 1585
		if ((use_openssl || use_stunnel) && !inetd) {
			int enc_none = (enc_str && !strcmp(enc_str, "none"));
			if (!use_stunnel || enc_none) {
				check_openssl();
				check_https();
			}
1586 1587 1588 1589
			/*
			 * This is to handle an initial verify cert from viewer,
			 * they disconnect right after fetching the cert.
			 */
1590 1591 1592 1593 1594
			if (use_threads) {
				usleep(10 * 1000);
			} else {
				rfbPE(-1);
			}
1595 1596 1597
			if (screen && screen->clientHead) {
				int i;
				if (unixpw) {
1598
					if (! unixpw_in_progress && !vencrypt_enable_plain_login) {
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
						rfbLog("unixpw but no unixpw_in_progress\n");
						clean_up_exit(1);
					}
					if (unixpw_client && unixpw_client->onHold) {
						rfbLog("taking unixpw_client off hold\n");
						unixpw_client->onHold = FALSE;
					}
				}
				for (i=0; i<10; i++) {
					if (shut_down) {
						clean_up_exit(0);
					}
					usleep(20 * 1000);
					if (0) rfbLog("wait_for_client: %d\n", i);

					if (! use_threads) {
						if (unixpw) {
							unixpw_in_rfbPE = 1;
						}
						rfbPE(-1);
						if (unixpw) {
							unixpw_in_rfbPE = 0;
						}
					}

					if (unixpw && !unixpw_in_progress) {
						/* XXX too soon. */
						goto screen_check;
					}
					if (!screen->clientHead) {
						break;
					}
				}
			}
		} else if (use_openssl) {
1634 1635
			check_openssl();
		}
1636

1637 1638 1639
		if (use_threads) {
			usleep(10 * 1000);
		} else {
1640 1641
			rfbPE(-1);
		}
1642

1643
		screen_check:
1644 1645 1646 1647
		if (! screen || ! screen->clientHead) {
			usleep(100 * 1000);
			continue;
		}
1648

1649 1650 1651
		rfbLog("wait_for_client: got client\n");
		break;
	}
1652
}
1653

1654
static void do_unixpw_loop(void) {
1655
	if (unixpw) {
1656
		if (! unixpw_in_progress && !vencrypt_enable_plain_login) {
1657 1658 1659
			rfbLog("unixpw but no unixpw_in_progress\n");
			clean_up_exit(1);
		}
1660 1661 1662 1663
		if (unixpw_client && unixpw_client->onHold) {
			rfbLog("taking unixpw_client off hold.\n");
			unixpw_client->onHold = FALSE;
		}
1664
		while (1) {
1665 1666 1667
			if (shut_down) {
				clean_up_exit(0);
			}
1668
			if (! use_threads) {
1669
				unixpw_in_rfbPE = 1;
1670
				rfbPE(-1);
1671
				unixpw_in_rfbPE = 0;
1672 1673
			}
			if (unixpw_in_progress) {
1674 1675 1676 1677 1678 1679 1680 1681 1682
				static double lping = 0.0;
				if (lping < dnow() + 5) {
					mark_rect_as_modified(0, 0, 1, 1, 1);
					lping = dnow();
				}
				if (time(NULL) > unixpw_last_try_time + 45) {
					rfbLog("unixpw_deny: timed out waiting for reply.\n");
					unixpw_deny();
				}
1683 1684 1685 1686 1687 1688 1689
				usleep(20 * 1000);
				continue;
			}
			rfbLog("wait_for_client: unixpw finished.\n");
			break;
		}
	}
1690
}
1691

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
static void vnc_redirect_loop(char *vnc_redirect_test, int *vnc_redirect_cnt) {
	if (unixpw) {
		rfbLog("wait_for_client: -unixpw and Xvnc.redirect not allowed\n");
		clean_up_exit(1);
	}
	if (client_connect) {
		rfbLog("wait_for_client: -connect and Xvnc.redirect not allowed\n");
		clean_up_exit(1);
	}
	if (inetd) {
		if (use_openssl) {
			accept_openssl(OPENSSL_INETD, -1);
		}
	} else {
		pid_t pid = 0;
1707
		/* XXX ipv6 */
1708 1709 1710 1711
		if (screen->httpListenSock >= 0) {
#if LIBVNCSERVER_HAVE_FORK
			if ((pid = fork()) > 0) {
				close(screen->httpListenSock);
1712
				/* mutex */
1713 1714 1715 1716 1717 1718 1719 1720
				screen->httpListenSock = -2;
				usleep(500 * 1000);
			} else {
				close(screen->listenSock);
				screen->listenSock = -1;
				while (1) {
					usleep(10 * 1000);
					rfbHttpCheckFds(screen);
1721
				}
1722
				exit(1);
1723
			}
1724 1725 1726 1727 1728 1729 1730
#else
			clean_up_exit(1);
#endif
		}
		if (first_conn_timeout) {
			if (first_conn_timeout < 0) {
				first_conn_timeout = -first_conn_timeout;
1731
			}
1732 1733 1734 1735 1736 1737 1738
			signal(SIGALRM, vnc_redirect_timeout);
			alarm(first_conn_timeout);
		}
		if (use_openssl) {
			int i;
			if (pid == 0) {
				accept_openssl(OPENSSL_VNC, -1);
1739
			} else {
1740 1741 1742 1743
				for (i=0; i < 16; i++) {
					accept_openssl(OPENSSL_VNC, -1);
					rfbLog("iter %d: vnc_redirect_sock: %d\n", i, vnc_redirect_sock);
					if (vnc_redirect_sock >= 0) {
1744 1745 1746 1747
						break;
					}
				}
			}
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
		} else {
			struct sockaddr_in addr;
#ifdef __hpux
			int addrlen = sizeof(addr);
#else
			socklen_t addrlen = sizeof(addr);
#endif
			if (screen->listenSock < 0) {
				rfbLog("wait_for_client: Xvnc.redirect not listening... sock=%d port=%d\n", screen->listenSock, screen->port);
				clean_up_exit(1);
1758
			}
1759
			vnc_redirect_sock = accept(screen->listenSock, (struct sockaddr *)&addr, &addrlen);
1760
		}
1761 1762
		if (first_conn_timeout) {
			alarm(0);
1763
		}
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
		if (pid > 0) {
#if LIBVNCSERVER_HAVE_FORK
			int rc;
			pid_t pidw;
			rfbLog("wait_for_client: kill TERM: %d\n", (int) pid);
			kill(pid, SIGTERM);
			usleep(1000 * 1000);	/* 1.0 sec */
			pidw = waitpid(pid, &rc, WNOHANG);
			if (pidw <= 0) {
				usleep(1000 * 1000);	/* 1.0 sec */
				pidw = waitpid(pid, &rc, WNOHANG);
1775
			}
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
#else
			clean_up_exit(1);
#endif
		}
	}
	if (vnc_redirect_sock < 0) {
		rfbLog("wait_for_client: vnc_redirect failed.\n");
		clean_up_exit(1);
	}
	if (!inetd && use_openssl) {
		/* check for Fetch Cert closing */
		fd_set rfds;
		struct timeval tv;
		int nfds;

		usleep(300*1000);

		FD_ZERO(&rfds);
		FD_SET(vnc_redirect_sock, &rfds);

		tv.tv_sec = 0;
		tv.tv_usec = 200000;
		nfds = select(vnc_redirect_sock+1, &rfds, NULL, NULL, &tv);

		rfbLog("wait_for_client: vnc_redirect nfds: %d\n", nfds);
		if (nfds > 0) {
			int n;
			n = read(vnc_redirect_sock, vnc_redirect_test, 1);
			if (n <= 0) {
				close(vnc_redirect_sock);
				vnc_redirect_sock = -1;
				rfbLog("wait_for_client: waiting for 2nd connection (Fetch Cert?)\n");
				accept_openssl(OPENSSL_VNC, -1);
				if (vnc_redirect_sock < 0) {
					rfbLog("wait_for_client: vnc_redirect failed.\n");
					clean_up_exit(1);
				}
1813
			} else {
1814 1815 1816 1817 1818
				*vnc_redirect_cnt = n;
			}
		}
	}
}
1819

1820 1821
static void do_vnc_redirect(int created_disp, char *vnc_redirect_host, int vnc_redirect_port,
    int vnc_redirect_cnt, char *vnc_redirect_test) {
1822
	char *q = strrchr(use_dpy, ':');
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
	int vdpy = -1, sock = -1;
	int s_in, s_out, i;
	if (vnc_redirect == 2) {
		char num[32];	
		sprintf(num, ":%d", vnc_redirect_port);
		q = num;
	}
	if (!q) {
		rfbLog("wait_for_client: can't find number in X display: %s\n", use_dpy);
		clean_up_exit(1);
	}
	if (sscanf(q+1, "%d", &vdpy) != 1) {
		rfbLog("wait_for_client: can't find number in X display: %s\n", q);
		clean_up_exit(1);
	}
	if (vdpy == -1 && vnc_redirect != 2) {
		rfbLog("wait_for_client: can't find number in X display: %s\n", q);
		clean_up_exit(1);
	}
	if (vnc_redirect == 2) {
		if (vdpy < 0) {
			vdpy = -vdpy;
		} else if (vdpy < 200) {
			vdpy += 5900;
		}
	} else {
		vdpy += 5900;
	}
	if (created_disp) {
		usleep(1000*1000);
	}
	for (i=0; i < 20; i++) {
1855
		sock = connect_tcp(vnc_redirect_host, vdpy);
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
		if (sock >= 0) {
			break;
		}
		rfbLog("wait_for_client: ...\n");
		usleep(500*1000);
	}
	if (sock < 0) {
		rfbLog("wait_for_client: could not connect to a VNC Server at %s:%d\n", vnc_redirect_host, vdpy);
		clean_up_exit(1);
	}
	if (inetd) {
		s_in  = fileno(stdin);
		s_out = fileno(stdout);
	} else {
		s_in = s_out = vnc_redirect_sock;
	}
	if (vnc_redirect_cnt > 0) {
		write(vnc_redirect_sock, vnc_redirect_test, vnc_redirect_cnt);
	}
	rfbLog("wait_for_client: switching control to VNC Server at %s:%d\n", vnc_redirect_host, vdpy);
	raw_xfer(sock, s_in, s_out);
}
1878

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
extern char find_display[];
extern char create_display[];

char *setup_cmd(char *str, int *vnc_redirect, char **vnc_redirect_host, int *vnc_redirect_port, int db) {
	char *cmd = NULL;
	
	if (no_external_cmds || !cmd_ok("WAIT")) {
		rfbLog("wait_for_client external cmds not allowed:"
		    " %s\n", use_dpy);
		clean_up_exit(1);
	}

	cmd = str + strlen("cmd=");
	if (!strcmp(cmd, "FINDDISPLAY-print")) {
		fprintf(stdout, "%s", find_display);
		clean_up_exit(0);
	}
	if (!strcmp(cmd, "FINDDISPLAY-run")) {
		char tmp[] = "/tmp/fd.XXXXXX";
		char com[100];
		int fd = mkstemp(tmp);
		if (fd >= 0) {
1901
			int ret;
1902 1903 1904
			write(fd, find_display, strlen(find_display));
			close(fd);
			set_env("FINDDISPLAY_run", "1");
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
			sprintf(com, "/bin/sh %s -n", tmp);
			ret = system(com);
			if (WIFEXITED(ret) && WEXITSTATUS(ret) != 0) {
				if (got_findauth && !getenv("FD_XDM")) {
					if (getuid() == 0 || geteuid() == 0) {
						set_env("FD_XDM", "1");
						system(com);
					}
				}
			}
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
		}
		unlink(tmp);
		exit(0);
	}
	if (!strcmp(str, "FINDCREATEDISPLAY-print")) {
		fprintf(stdout, "%s", create_display);
		clean_up_exit(0);
	}
	if (db) fprintf(stderr, "cmd: %s\n", cmd);
	if (strstr(str, "FINDCREATEDISPLAY") || strstr(str, "FINDDISPLAY")) {
		if (strstr(str, "Xvnc.redirect") || strstr(str, "X.redirect")) {
			*vnc_redirect = 1;
		}
	}
	if (strstr(cmd, "FINDDISPLAY-vnc_redirect") == cmd) {
		int p;
		char h[256];
		if (strlen(cmd) >= 256) {
			rfbLog("wait_for_client string too long: %s\n", str);
			clean_up_exit(1);
		}
		h[0] = '\0';
		if (sscanf(cmd, "FINDDISPLAY-vnc_redirect=%d", &p) == 1) {
			;
		} else if (sscanf(cmd, "FINDDISPLAY-vnc_redirect=%s %d", h, &p) == 2) {
			;
		} else {
			rfbLog("wait_for_client bad string: %s\n", cmd);
			clean_up_exit(1);
		}
		*vnc_redirect_port = p;
		if (strcmp(h, "")) {
			*vnc_redirect_host = strdup(h);
		}
		*vnc_redirect = 2;
		rfbLog("wait_for_client: vnc_redirect: %s:%d\n", *vnc_redirect_host, *vnc_redirect_port);
	}
	return cmd;
}

static char *build_create_cmd(char *cmd, int *saw_xdmcp, char *usslpeer, char *tmp) {
	char *create_cmd = NULL;
	char *opts = strchr(cmd, '-');
	char st[] = "";
1959
	char fdgeom[128], fdsess[128], fdopts[128], fdextra[256], fdprog[128];
1960
	char fdxsrv[128], fdxdum[128], fdcups[128], fdesd[128];
1961
	char fdnas[128], fdsmb[128], fdtag[128], fdxdmcpif[128];
1962
	char cdout[128];
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975

	if (opts) {
		opts++;
		if (strstr(opts, "xdmcp")) {
			*saw_xdmcp = 1;
		}
	} else {
		opts = st;
	}
	sprintf(fdgeom, "NONE");
	fdsess[0] = '\0';
	fdgeom[0] = '\0';
	fdopts[0] = '\0';
1976
	fdextra[0] = '\0';
1977 1978 1979 1980 1981 1982 1983 1984
	fdprog[0] = '\0';
	fdxsrv[0] = '\0';
	fdxdum[0] = '\0';
	fdcups[0] = '\0';
	fdesd[0]  = '\0';
	fdnas[0]  = '\0';
	fdsmb[0]  = '\0';
	fdtag[0]  = '\0';
1985
	fdxdmcpif[0]  = '\0';
1986
	cdout[0]  = '\0';
1987

runge's avatar
runge committed
1988
	if (unixpw && keep_unixpw_opts && !getenv("X11VNC_NO_UNIXPW_OPTS")) {
1989
		char *q, *p, *t = strdup(keep_unixpw_opts);
runge's avatar
runge committed
1990

1991 1992 1993 1994
		if (strstr(t, "gnome")) {
			sprintf(fdsess, "gnome");
		} else if (strstr(t, "kde")) {
			sprintf(fdsess, "kde");
1995 1996
		} else if (strstr(t, "lxde")) {
			sprintf(fdsess, "lxde");
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
		} else if (strstr(t, "twm")) {
			sprintf(fdsess, "twm");
		} else if (strstr(t, "fvwm")) {
			sprintf(fdsess, "fvwm");
		} else if (strstr(t, "mwm")) {
			sprintf(fdsess, "mwm");
		} else if (strstr(t, "cde")) {
			sprintf(fdsess, "cde");
		} else if (strstr(t, "dtwm")) {
			sprintf(fdsess, "dtwm");
		} else if (strstr(t, "xterm")) {
			sprintf(fdsess, "xterm");
		} else if (strstr(t, "wmaker")) {
			sprintf(fdsess, "wmaker");
		} else if (strstr(t, "xfce")) {
			sprintf(fdsess, "xfce");
		} else if (strstr(t, "enlightenment")) {
			sprintf(fdsess, "enlightenment");
		} else if (strstr(t, "Xsession")) {
			sprintf(fdsess, "Xsession");
		} else if (strstr(t, "failsafe")) {
			sprintf(fdsess, "failsafe");
		}

		q = strstr(t, "ge=");
		if (! q) q = strstr(t, "geom=");
		if (! q) q = strstr(t, "geometry=");
		if (q) {
			int ok = 1;
			q = strstr(q, "=");
			q++;
			p = strstr(q, ",");
			if (p) *p = '\0';
			p = q;
			while (*p) {
				if (*p == 'x') {
					;
				} else if (isdigit((int) *p)) {
					;
2036
				} else {
2037 2038
					ok = 0;
					break;
2039
				}
2040 2041 2042
				p++;
			}
			if (ok && strlen(q) < 32) {
2043
				sprintf(fdgeom, "%s", q);
2044 2045
				if (!quiet) {
					rfbLog("set create display geom: %s\n", fdgeom);
2046 2047
				}
			}
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
		}
		q = strstr(t, "cups=");
		if (q) {
			int p;
			if (sscanf(q, "cups=%d", &p) == 1) {
				sprintf(fdcups, "%d", p);
			}
		}
		q = strstr(t, "esd=");
		if (q) {
			int p;
			if (sscanf(q, "esd=%d", &p) == 1) {
				sprintf(fdesd, "%d", p);
			}
		}
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
		if (!getenv("FD_TAG")) {
			char *s = NULL;

			q = strstr(t, "tag=");
			if (q) s = strchr(q, ',');
			if (s) *s = '\0';

			if (q && strlen(q) < 120) {
				char *p;
				int ok = 1;
				q = strchr(q, '=') + 1;
				p = q;
				while (*p != '\0') {
					char c = *p;
					if (*p == '_' || *p == '-') {
						;
					} else if (!isalnum((int) c)) {
						ok = 0;
						rfbLog("bad tag char: '%c' in '%s'\n", c, q);
						break;
					}
					p++;
				}
				if (ok) {
					sprintf(fdtag, "%s", q);
				}
			}
			if (s) *s = ',';
		}
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
		free(t);
	}
	if (fdgeom[0] == '\0' && getenv("FD_GEOM")) {
		snprintf(fdgeom,  120, "%s", getenv("FD_GEOM"));
	}
	if (fdsess[0] == '\0' && getenv("FD_SESS")) {
		snprintf(fdsess, 120, "%s", getenv("FD_SESS"));
	}
	if (fdopts[0] == '\0' && getenv("FD_OPTS")) {
		snprintf(fdopts, 120, "%s", getenv("FD_OPTS"));
	}
2103 2104 2105 2106 2107
	if (fdextra[0] == '\0' && getenv("FD_EXTRA")) {
		if (!strchr(getenv("FD_EXTRA"), '\'')) {
			snprintf(fdextra, 250, "%s", getenv("FD_EXTRA"));
		}
	}
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
	if (fdprog[0] == '\0' && getenv("FD_PROG")) {
		snprintf(fdprog, 120, "%s", getenv("FD_PROG"));
	}
	if (fdxsrv[0] == '\0' && getenv("FD_XSRV")) {
		snprintf(fdxsrv, 120, "%s", getenv("FD_XSRV"));
	}
	if (fdcups[0] == '\0' && getenv("FD_CUPS")) {
		snprintf(fdcups, 120, "%s", getenv("FD_CUPS"));
	}
	if (fdesd[0] == '\0' && getenv("FD_ESD")) {
		snprintf(fdesd, 120, "%s", getenv("FD_ESD"));
	}
	if (fdnas[0] == '\0' && getenv("FD_NAS")) {
		snprintf(fdnas, 120, "%s", getenv("FD_NAS"));
	}
	if (fdsmb[0] == '\0' && getenv("FD_SMB")) {
		snprintf(fdsmb, 120, "%s", getenv("FD_SMB"));
	}
	if (fdtag[0] == '\0' && getenv("FD_TAG")) {
		snprintf(fdtag, 120, "%s", getenv("FD_TAG"));
	}
2129 2130 2131
	if (fdxdmcpif[0] == '\0' && getenv("FD_XDMCP_IF")) {
		snprintf(fdxdmcpif,  120, "%s", getenv("FD_XDMCP_IF"));
	}
2132 2133
	if (fdxdum[0] == '\0' && getenv("FD_XDUMMY_RUN_AS_ROOT")) {
		snprintf(fdxdum, 120, "%s", getenv("FD_XDUMMY_RUN_AS_ROOT"));
2134
	}
2135 2136 2137
	if (getenv("CREATE_DISPLAY_OUTPUT")) {
		snprintf(cdout, 120, "CREATE_DISPLAY_OUTPUT='%s'", getenv("CREATE_DISPLAY_OUTPUT"));
	}
2138

2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
	if (strchr(fdgeom, '\''))	fdgeom[0] = '\0';
	if (strchr(fdopts, '\''))	fdopts[0] = '\0';
	if (strchr(fdextra, '\''))	fdextra[0] = '\0';
	if (strchr(fdprog, '\''))	fdprog[0] = '\0';
	if (strchr(fdxsrv, '\''))	fdxsrv[0] = '\0';
	if (strchr(fdcups, '\''))	fdcups[0] = '\0';
	if (strchr(fdesd, '\''))	fdesd[0] = '\0';
	if (strchr(fdnas, '\''))	fdnas[0] = '\0';
	if (strchr(fdsmb, '\''))	fdsmb[0] = '\0';
	if (strchr(fdtag, '\''))	fdtag[0] = '\0';
2149
	if (strchr(fdxdmcpif, '\''))	fdxdmcpif[0] = '\0';
2150 2151 2152 2153
	if (strchr(fdxdum, '\''))	fdxdum[0] = '\0';
	if (strchr(fdsess, '\''))	fdsess[0] = '\0';
	if (strchr(cdout, '\''))	cdout[0] = '\0';

2154 2155
	set_env("FD_GEOM", fdgeom);
	set_env("FD_OPTS", fdopts);
2156
	set_env("FD_EXTRA", fdextra);
2157 2158 2159 2160 2161 2162 2163
	set_env("FD_PROG", fdprog);
	set_env("FD_XSRV", fdxsrv);
	set_env("FD_CUPS", fdcups);
	set_env("FD_ESD",  fdesd);
	set_env("FD_NAS",  fdnas);
	set_env("FD_SMB",  fdsmb);
	set_env("FD_TAG",  fdtag);
2164
	set_env("FD_XDMCP_IF",  fdxdmcpif);
2165
	set_env("FD_XDUMMY_RUN_AS_ROOT", fdxdum);
2166 2167 2168 2169 2170 2171 2172
	set_env("FD_SESS", fdsess);

	if (usslpeer || (unixpw && keep_unixpw_user)) {
		char *uu = usslpeer;
		if (!uu) {
			uu = keep_unixpw_user;
		}
2173 2174 2175
		if (strchr(uu, '\''))  {
			uu = "";
		}
2176 2177 2178 2179
		create_cmd = (char *) malloc(strlen(tmp)+1
		    + strlen("env USER='' ")
		    + strlen("FD_GEOM='' ")
		    + strlen("FD_OPTS='' ")
2180
		    + strlen("FD_EXTRA='' ")
2181 2182 2183 2184 2185 2186 2187
		    + strlen("FD_PROG='' ")
		    + strlen("FD_XSRV='' ")
		    + strlen("FD_CUPS='' ")
		    + strlen("FD_ESD='' ")
		    + strlen("FD_NAS='' ")
		    + strlen("FD_SMB='' ")
		    + strlen("FD_TAG='' ")
2188
		    + strlen("FD_XDMCP_IF='' ")
2189
		    + strlen("FD_XDUMMY_RUN_AS_ROOT='' ")
2190 2191 2192 2193
		    + strlen("FD_SESS='' /bin/sh ")
		    + strlen(uu) + 1
		    + strlen(fdgeom) + 1
		    + strlen(fdopts) + 1
2194
		    + strlen(fdextra) + 1
2195 2196 2197 2198 2199 2200 2201
		    + strlen(fdprog) + 1
		    + strlen(fdxsrv) + 1
		    + strlen(fdcups) + 1
		    + strlen(fdesd) + 1
		    + strlen(fdnas) + 1
		    + strlen(fdsmb) + 1
		    + strlen(fdtag) + 1
2202
		    + strlen(fdxdmcpif) + 1
2203 2204
		    + strlen(fdxdum) + 1
		    + strlen(fdsess) + 1
2205
		    + strlen(cdout) + 1
2206 2207
		    + strlen(opts) + 1);
		sprintf(create_cmd, "env USER='%s' FD_GEOM='%s' FD_SESS='%s' "
2208
		    "FD_OPTS='%s' FD_EXTRA='%s' FD_PROG='%s' FD_XSRV='%s' FD_CUPS='%s' "
2209
		    "FD_ESD='%s' FD_NAS='%s' FD_SMB='%s' FD_TAG='%s' FD_XDMCP_IF='%s' "
2210
		    "FD_XDUMMY_RUN_AS_ROOT='%s' %s /bin/sh %s %s",
2211
		    uu, fdgeom, fdsess, fdopts, fdextra, fdprog, fdxsrv,
2212
		    fdcups, fdesd, fdnas, fdsmb, fdtag, fdxdmcpif, fdxdum, cdout, tmp, opts);
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
	} else {
		create_cmd = (char *) malloc(strlen(tmp)
		    + strlen("/bin/sh ") + 1 + strlen(opts) + 1);
		sprintf(create_cmd, "/bin/sh %s %s", tmp, opts);
	}
	return create_cmd;
}

static char *certret_extract() {
	char *q, *p, *str = strdup(certret_str);
	char *upeer = NULL;
	int ok = 0;

	q = strstr(str, "Subject: ");
	if (! q) return NULL;

	p = strstr(q, "\n");
	if (p) *p = '\0';
2231

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
	q = strstr(q, "CN=");
	if (! q) return NULL;

	if (! getenv("X11VNC_SSLPEER_CN")) {
		p = q;
		q = strstr(q, "/emailAddress=");
		if (! q) q = strstr(p, "/Email=");
		if (! q) return NULL;
	}

	q = strstr(q, "=");
	if (! q) return NULL;

	q++;
	p = strstr(q, " ");
	if (p) *p = '\0';
	p = strstr(q, "@");
	if (p) *p = '\0';
	p = strstr(q, "/");
	if (p) *p = '\0';

	upeer = strdup(q);

	if (strcmp(upeer, "")) {
		p = upeer;
		while (*p != '\0') {
			char c = *p;
			if (!isalnum((int) c)) {
				*p = '\0';
				break;
			}
			p++;
		}
		if (strcmp(upeer, "")) {
			ok = 1;
2267
		}
2268 2269 2270 2271 2272 2273
	}
	if (! ok) {
		upeer = NULL;
	}
	return upeer;
}
2274

2275 2276 2277
static void check_nodisplay(char **nd, char **tag) {
	if (unixpw && !getenv("X11VNC_NO_UNIXPW_OPTS") && keep_unixpw_opts && keep_unixpw_opts[0] != '\0') {
		char *q, *t2, *t = keep_unixpw_opts;
2278 2279 2280 2281 2282 2283 2284 2285
		q = strstr(t, "nd=");
		if (! q) q = strstr(t, "nodisplay=");
		if (q) {
			q = strchr(q, '=') + 1;
			t = strdup(q);
			q = t;
			t2 = strchr(t, ',');
			if (t2) *t2 = '\0';
2286

2287
			while (*t != '\0') {
2288
				if (*t == '+') {
2289 2290 2291 2292
					*t = ',';
				}
				t++;
			}
2293
			if (!strchr(q, '\'') && !strpbrk(q, "[](){}`'\"$&*|<>")) {
2294 2295 2296 2297
				if (! quiet) rfbLog("set X11VNC_SKIP_DISPLAY: %s\n", q);
				*nd = q;
			}
		}
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327

		q = strstr(keep_unixpw_opts, "tag=");
		if (getenv("FD_TAG")) {
			*tag = strdup(getenv("FD_TAG"));
		} else if (q) {
			q = strchr(q, '=') + 1;
			t = strdup(q);
			q = t;
			t2 = strchr(t, ',');
			if (t2) *t2 = '\0';

			if (strlen(q) < 120) {
				int ok = 1;
				while (*t != '\0') {
					char c = *t;
					if (*t == '_' || *t == '-') {
						;
					} else if (!isalnum((int) c)) {
						ok = 0;
						rfbLog("bad tag char: '%c' in '%s'\n", c, q);
						break;
					}
					t++;
				}
				if (ok) {
					if (! quiet) rfbLog("set FD_TAG: %s\n", q);
					*tag = q;
				}
			}
		}
2328
	}
2329 2330 2331 2332 2333 2334
	if (unixpw_system_greeter_active == 2) {
		if (!keep_unixpw_user) {
			clean_up_exit(1);
		}
		*nd = strdup("all");
	}
2335
}
2336

2337 2338
static char *get_usslpeer() {
	char *u = NULL, *upeer = NULL;
2339

2340 2341 2342 2343 2344 2345 2346
	if (certret_str) {
		upeer = certret_extract();
	}
	if (!upeer) {
		return NULL;
	}
	rfbLog("sslpeer unix username extracted from x509 cert: %s\n", upeer);
2347

2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
	u = (char *) malloc(strlen(upeer+2));
	u[0] = '\0';
	if (!strcmp(users_list, "sslpeer=")) {
		sprintf(u, "+%s", upeer);
	} else {
		char *p, *str = strdup(users_list);
		p = strtok(str + strlen("sslpeer="), ",");
		while (p) {
			if (!strcmp(p, upeer)) {
				sprintf(u, "+%s", upeer);
				break;
2359
			}
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
			p = strtok(NULL, ",");
		}
		free(str);
	}
	if (u[0] == '\0') {
		rfbLog("sslpeer cannot determine user: %s\n", upeer);
		free(u);
		return NULL;
	}
	free(u);
	return upeer;
}

2373
static void do_try_switch(char *usslpeer, char *users_list_save) {
2374 2375 2376 2377
	if (unixpw_system_greeter_active == 2) {
		rfbLog("unixpw_system_greeter: not trying switch to user '%s'\n", usslpeer ? usslpeer : "");
		return;
	}
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
	if (usslpeer) {
		char *u = (char *) malloc(strlen(usslpeer+2));
		sprintf(u, "+%s", usslpeer);
		if (switch_user(u, 0)) {
			rfbLog("sslpeer switched to user: %s\n", usslpeer);
		} else {
			rfbLog("sslpeer failed to switch to user: %s\n", usslpeer);
		}
		free(u);
		
	} else if (users_list_save && keep_unixpw_user) {
		char *user = keep_unixpw_user;
		char *u = (char *)malloc(strlen(user)+1); 

		users_list = users_list_save;

		u[0] = '\0';
		if (!strcmp(users_list, "unixpw=")) {
			sprintf(u, "+%s", user);
		} else {
			char *p, *str = strdup(users_list);
			p = strtok(str + strlen("unixpw="), ",");
			while (p) {
				if (!strcmp(p, user)) {
					sprintf(u, "+%s", user);
					break;
				}
				p = strtok(NULL, ",");
			}
			free(str);
		}
		
		if (u[0] == '\0') {
			rfbLog("unixpw_accept skipping switch to user: %s (drc)\n", user);
		} else if (switch_user(u, 0)) {
			rfbLog("unixpw_accept switched to user: %s (drc)\n", user);
		} else {
			rfbLog("unixpw_accept failed to switch to user: %s (drc)\n", user);
		}
		free(u);
	}
}

2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
static void path_lookup(char *prog) {
	/* see create_display script */
	char *create_display_extra = "/usr/X11R6/bin:/usr/bin/X11:/usr/openwin/bin:/usr/dt/bin:/opt/kde4/bin:/opt/kde3/bin:/opt/gnome/bin:/usr/bin:/bin:/usr/sfw/bin:/usr/local/bin";
	char *path, *try, *p;
	int found = 0, len = strlen(create_display_extra);

	if (getenv("PATH")) {
		len += strlen(getenv("PATH")) + 1;
		path = (char *) malloc((len+1) * sizeof(char));
		sprintf(path, "%s:%s", getenv("PATH"), create_display_extra);
	} else {
		path = (char *) malloc((len+1) * sizeof(char));
		sprintf(path, "%s", create_display_extra);
	}
	try = (char *) malloc((len+2+strlen(prog)) * sizeof(char));

	p = strtok(path, ":");
	while (p) {
		struct stat sbuf;

		sprintf(try, "%s/%s", p, prog);
		if (stat(try, &sbuf) == 0) {
			found = 1;
			break;
		}
		p = strtok(NULL, ":");
	}

	free(path);
	free(try);

	if (!found) {
		fprintf(stderr, "\n");
		fprintf(stderr, "The program \"%s\" could not be found in PATH and standard locations.\n", prog);
		fprintf(stderr, "You probably need to install a package that provides the \"%s\" program.\n", prog);
		fprintf(stderr, "Without it FINDCREATEDISPLAY mode may not be able to create an X display.\n");
		fprintf(stderr, "\n");
	}
}

2461 2462 2463 2464 2465 2466
static int do_run_cmd(char *cmd, char *create_cmd, char *users_list_save, int created_disp, int db) {
	char tmp[] = "/tmp/x11vnc-find_display.XXXXXX";
	char line1[1024], line2[16384];
	char *q, *usslpeer = NULL;
	int n, nodisp = 0, saw_xdmcp = 0;
	int tmp_fd = -1;
2467 2468
	int internal_cmd = 0;
	int tried_switch = 0;
2469

2470 2471
	memset(line1, 0, sizeof(line1));
	memset(line2, 0, sizeof(line2));
2472 2473 2474 2475 2476 2477 2478

	if (users_list && strstr(users_list, "sslpeer=") == users_list) {
		usslpeer = get_usslpeer();
		if (! usslpeer) {
			return 0;
		}
	}
2479
	if (getenv("DEBUG_RUN_CMD")) db = 1;
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492

	/* only sets environment variables: */
	run_user_command("", latest_client, "env", NULL, 0, NULL);

	if (program_name) {
		set_env("X11VNC_PROG", program_name);
	} else {
		set_env("X11VNC_PROG", "x11vnc");
	}

	if (!strcmp(cmd, "FINDDISPLAY") ||
	    strstr(cmd, "FINDCREATEDISPLAY") == cmd) {
		char *nd = "";
2493
		char *tag = "";
2494
		char fdout[128];
2495 2496 2497

		internal_cmd = 1;

2498
		tmp_fd = mkstemp(tmp);
2499

2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
		if (tmp_fd < 0) {
			rfbLog("wait_for_client: open failed: %s\n", tmp);
			rfbLogPerror("mkstemp");
			clean_up_exit(1);
		}
		chmod(tmp, 0644);
		if (getenv("X11VNC_FINDDISPLAY_ALWAYS_FAILS")) {
			char *s = "#!/bin/sh\necho _FAIL_\nexit 1\n";
			write(tmp_fd, s, strlen(s));
		} else {
			write(tmp_fd, find_display, strlen(find_display));
		}
		close(tmp_fd);
		nodisp = 1;

		if (strstr(cmd, "FINDCREATEDISPLAY") == cmd) {
			create_cmd = build_create_cmd(cmd, &saw_xdmcp, usslpeer, tmp);
			if (db) fprintf(stderr, "create_cmd: %s\n", create_cmd);
		}
		if (getenv("X11VNC_SKIP_DISPLAY")) {
			nd = strdup(getenv("X11VNC_SKIP_DISPLAY"));
		}
2522
		check_nodisplay(&nd, &tag);
2523

2524 2525 2526 2527 2528
		fdout[0] = '\0';
		if (getenv("FIND_DISPLAY_OUTPUT")) {
			snprintf(fdout, 120, " FIND_DISPLAY_OUTPUT='%s' ", getenv("FIND_DISPLAY_OUTPUT"));
		}

2529
		cmd = (char *) malloc(strlen("env X11VNC_SKIP_DISPLAY='' ")
2530 2531 2532 2533 2534 2535 2536
		    + strlen(nd) + strlen(" FD_TAG='' ") + strlen(tag) + strlen(tmp) + strlen("/bin/sh ") + strlen(fdout) + 1);

		if (strcmp(tag, "")) {
			sprintf(cmd, "env X11VNC_SKIP_DISPLAY='%s' FD_TAG='%s' %s /bin/sh %s", nd, tag, fdout, tmp);
		} else {
			sprintf(cmd, "env X11VNC_SKIP_DISPLAY='%s' %s /bin/sh %s", nd, fdout, tmp);
		}
2537 2538 2539 2540
	}

	rfbLog("wait_for_client: running: %s\n", cmd);

2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
	if (create_cmd != NULL) {
		if (strstr(create_cmd, "Xvfb")) {
			path_lookup("Xvfb");
		}
		if (strstr(create_cmd, "Xvnc")) {
			path_lookup("Xvnc");
		}
		if (strstr(create_cmd, "Xdummy")) {
			path_lookup("Xdummy");
		}
	}

2553
	if (unixpw && !unixpw_nis) {
2554 2555 2556
		int res = 0, k, j, i;
		char line[18000];

2557
		memset(line, 0, sizeof(line));
2558

2559 2560 2561 2562
		if (unixpw_system_greeter_active == 2) {
			rfbLog("unixpw_system_greeter: forcing find display failure.\n");
			res = 0;
		} else if (keep_unixpw_user && keep_unixpw_pass) {
2563
			n = sizeof(line);
2564 2565
			if (unixpw_cmd != NULL) {
				res = unixpw_cmd_run(keep_unixpw_user,
2566
				    keep_unixpw_pass, cmd, line, &n);
2567 2568 2569 2570
			} else {
				res = su_verify(keep_unixpw_user,
				    keep_unixpw_pass, cmd, line, &n, nodisp);
			}
2571
		}
2572

2573
if (db) {fprintf(stderr, "line: "); write(2, line, n); write(2, "\n", 1); fprintf(stderr, "res=%d n=%d\n", res, n);}
2574
		if (! res) {
2575
			rfbLog("wait_for_client: find display cmd failed.\n");
2576
		}
2577

2578 2579 2580 2581 2582 2583 2584 2585 2586
		if (! res && create_cmd) {
			FILE *mt = fopen(tmp, "w");
			if (! mt) {
				rfbLog("wait_for_client: open failed: %s\n", tmp);
				rfbLogPerror("fopen");
				clean_up_exit(1);
			}
			fprintf(mt, "%s", create_display);
			fclose(mt);
2587

2588
			findcreatedisplay = 1;
2589

2590 2591
			if (unixpw_cmd != NULL) {
				/* let the external unixpw command do it: */
2592
				n = sizeof(line);
2593 2594
				close_exec_fds();
				res = unixpw_cmd_run(keep_unixpw_user,
2595 2596
				    keep_unixpw_pass, create_cmd, line, &n);
			} else if (getuid() != 0 && unixpw_system_greeter_active != 2) {
2597
				/* if not root, run as the other user... */
2598
				n = sizeof(line);
2599 2600 2601
				close_exec_fds();
				res = su_verify(keep_unixpw_user,
				    keep_unixpw_pass, create_cmd, line, &n, nodisp);
2602
if (db) fprintf(stderr, "c-res=%d n=%d line: '%s'\n", res, n, line);
2603

2604 2605 2606
			} else {
				FILE *p;
				close_exec_fds();
2607 2608 2609 2610
				if (unixpw_system_greeter_active == 2) {
					rfbLog("unixpw_system_greeter: not trying su_verify() to run\n");
					rfbLog("unixpw_system_greeter: create display command.\n");
				}
2611 2612 2613 2614 2615 2616 2617 2618
				rfbLog("wait_for_client: running: %s\n", create_cmd);
				p = popen(create_cmd, "r");
				if (! p) {
					rfbLog("wait_for_client: popen failed: %s\n", create_cmd);
					res = 0;
				} else if (fgets(line1, 1024, p) == NULL) {
					rfbLog("wait_for_client: read failed: %s\n", create_cmd);
					res = 0;
2619
				} else {
2620 2621
					n = fread(line2, 1, 16384, p);
					if (pclose(p) != 0) {
2622 2623
						res = 0;
					} else {
2624 2625
						strncpy(line, line1, 100);
						memcpy(line + strlen(line1), line2, n);
2626
if (db) fprintf(stderr, "line1: '%s'\n", line1);
2627 2628 2629
						n += strlen(line1);
						created_disp = 1;
						res = 1;
2630 2631 2632
					}
				}
			}
2633
			if (res && saw_xdmcp && unixpw_system_greeter_active != 2) {
2634
				xdmcp_insert = strdup(keep_unixpw_user);
2635
			}
2636
		}
2637

2638 2639 2640
		if (tmp_fd >= 0) {
			unlink(tmp);
		}
2641

2642 2643 2644 2645 2646
		if (! res) {
			rfbLog("wait_for_client: cmd failed: %s\n", cmd);
			unixpw_msg("No DISPLAY found.", 3);
			clean_up_exit(1);
		}
2647

2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
		/*
		 * we need to hunt for DISPLAY= since there may be
		 * a login banner or something at the beginning.
		 */
		q = strstr(line, "DISPLAY=");
		if (! q) {
			q = line;
		}
		n -= (q - line);

		for (k = 0; k < 1024; k++) {
			line1[k] = q[k];
			if (q[k] == '\n') {
				k++;
				break;
2663
			}
2664 2665 2666 2667 2668 2669 2670 2671
		}
		n -= k;
		i = 0;
		for (j = 0; j < 16384; j++) {
			if (j < 16384 - 1) {
				/* xauth data, assume pty added CR */
				if (q[k+j] == '\r' && q[k+j+1] == '\n') {
					continue;
2672
				}
2673
			}
2674 2675 2676 2677
			
			line2[i] = q[k+j];
			i++;
		}
2678 2679
if (db) write(2, line, 100);
if (db) fprintf(stderr, "\n");
2680

2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
	} else {
		FILE *p;
		int rc;
		close_exec_fds();

		if (usslpeer) {
			char *c;
			if (getuid() == 0) {
				c = (char *) malloc(strlen("su - '' -c \"")
				    + strlen(usslpeer) + strlen(cmd) + 1 + 1);
				sprintf(c, "su - '%s' -c \"%s\"", usslpeer, cmd);
			} else {
				c = strdup(cmd);
			}
			p = popen(c, "r");
			free(c);
			
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
		} else if (unixpw_nis && keep_unixpw_user) {
			char *c;
			if (getuid() == 0) {
				c = (char *) malloc(strlen("su - '' -c \"")
				    + strlen(keep_unixpw_user) + strlen(cmd) + 1 + 1);
				sprintf(c, "su - '%s' -c \"%s\"", keep_unixpw_user, cmd);
			} else {
				c = strdup(cmd);
			}
			p = popen(c, "r");
			free(c);
			
2710
		} else {
2711 2712
			p = popen(cmd, "r");
		}
2713

2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
		if (! p) {
			rfbLog("wait_for_client: cmd failed: %s\n", cmd);
			rfbLogPerror("popen");
			if (tmp_fd >= 0) {
				unlink(tmp);
			}
			clean_up_exit(1);
		}
		if (fgets(line1, 1024, p) == NULL) {
			rfbLog("wait_for_client: read failed: %s\n", cmd);
			rfbLogPerror("fgets");
			if (tmp_fd >= 0) {
				unlink(tmp);
			}
			clean_up_exit(1);
		}
		n = fread(line2, 1, 16384, p);
		rc = pclose(p);

		if (rc != 0) {
2734
			rfbLog("wait_for_client: find display cmd failed.\n");
2735 2736 2737 2738 2739 2740 2741 2742 2743
		}

		if (create_cmd && rc != 0) {
			FILE *mt = fopen(tmp, "w");
			if (! mt) {
				rfbLog("wait_for_client: open failed: %s\n", tmp);
				rfbLogPerror("fopen");
				if (tmp_fd >= 0) {
					unlink(tmp);
2744
				}
2745
				clean_up_exit(1);
2746
			}
2747 2748 2749 2750 2751 2752 2753 2754
			fprintf(mt, "%s", create_display);
			fclose(mt);

			findcreatedisplay = 1;

			rfbLog("wait_for_client: FINDCREATEDISPLAY cmd: %s\n", create_cmd);

			p = popen(create_cmd, "r");
2755
			if (! p) {
2756
				rfbLog("wait_for_client: cmd failed: %s\n", create_cmd);
2757
				rfbLogPerror("popen");
2758 2759 2760
				if (tmp_fd >= 0) {
					unlink(tmp);
				}
2761 2762 2763
				clean_up_exit(1);
			}
			if (fgets(line1, 1024, p) == NULL) {
2764
				rfbLog("wait_for_client: read failed: %s\n", create_cmd);
2765
				rfbLogPerror("fgets");
2766 2767 2768
				if (tmp_fd >= 0) {
					unlink(tmp);
				}
2769 2770 2771
				clean_up_exit(1);
			}
			n = fread(line2, 1, 16384, p);
2772
			pclose(p);
2773
		}
2774 2775 2776 2777
		if (tmp_fd >= 0) {
			unlink(tmp);
		}
	}
2778

2779
if (db) fprintf(stderr, "line1=%s\n", line1);
2780

2781 2782 2783 2784
	if (strstr(line1, "DISPLAY=") != line1) {
		rfbLog("wait_for_client: bad reply '%s'\n", line1);
		if (unixpw) {
			unixpw_msg("No DISPLAY found.", 3);
2785
		}
2786 2787
		clean_up_exit(1);
	}
2788

2789

2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
	if (strstr(line1, ",VT=")) {
		int vt;
		char *t = strstr(line1, ",VT=");
		vt = atoi(t + strlen(",VT="));
		*t = '\0';
		if (7 <= vt && vt <= 15) {
			do_chvt(vt);
		}
	} else if (strstr(line1, ",XPID=")) {
		int i, pvt, vt = -1;
		char *t = strstr(line1, ",XPID=");
		pvt = atoi(t + strlen(",XPID="));
		*t = '\0';
		if (pvt > 0) {
			for (i=3; i <= 10; i++) {
				int k;
				char proc[100];
				char buf[100];
				sprintf(proc, "/proc/%d/fd/%d", pvt, i);
2809
if (db) fprintf(stderr, "%d -- %s\n", i, proc);
2810 2811 2812 2813 2814 2815
				for (k=0; k < 100; k++) {
					buf[k] = '\0';
				}
	
				if (readlink(proc, buf, 100) != -1) {
					buf[100-1] = '\0';
2816
if (db) fprintf(stderr, "%d -- %s -- %s\n", i, proc, buf);
2817 2818 2819 2820
					if (strstr(buf, "/dev/tty") == buf) {
						vt = atoi(buf + strlen("/dev/tty"));
						if (vt > 0) {
							break;
2821 2822 2823 2824
						}
					}
				}
			}
2825
		}
2826 2827
		if (7 <= vt && vt <= 12) {
			do_chvt(vt);
2828
		}
2829
	}
2830

2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
	use_dpy = strdup(line1 + strlen("DISPLAY="));
	q = use_dpy;
	while (*q != '\0') {
		if (*q == '\n' || *q == '\r') *q = '\0';
		q++;
	}
	if (line2[0] != '\0') {
		if (strstr(line2, "XAUTHORITY=") == line2) {
			q = line2;
			while (*q != '\0') {
				if (*q == '\n' || *q == '\r') *q = '\0';
				q++;
			}
			if (auth_file) {
				free(auth_file);
			}
			auth_file = strdup(line2 + strlen("XAUTHORITY="));

		} else {
			xauth_raw_data = (char *)malloc(n);
			xauth_raw_len = n;
			memcpy(xauth_raw_data, line2, n);
2853 2854 2855
if (db) {fprintf(stderr, "xauth_raw_len: %d\n", n);
write(2, xauth_raw_data, n);
fprintf(stderr, "\n");}
2856
		}
2857
	}
2858

2859 2860 2861
	if (!tried_switch) {
		do_try_switch(usslpeer, users_list_save);
		tried_switch = 1;
2862 2863 2864
	}

	if (unixpw) {
2865
		/* Some cleanup and messaging for -unixpw case: */
2866 2867 2868 2869 2870 2871
		char str[32];

		if (keep_unixpw_user && keep_unixpw_pass) {
			strzero(keep_unixpw_user);
			strzero(keep_unixpw_pass);
			keep_unixpw = 0;
2872 2873
		}

2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
		if (created_disp) {
			snprintf(str, 30, "Created DISPLAY %s", use_dpy);
		} else {
			snprintf(str, 30, "Using DISPLAY %s", use_dpy);
		}
		unixpw_msg(str, 2);
	}
	return 1;
}

2884 2885
void ssh_remote_tunnel(char *, int);

2886 2887
static XImage ximage_struct;

2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
void progress_client(void) {
	int i, j = 0, progressed = 0, db = 0;
	double start = dnow();
	if (getenv("PROGRESS_CLIENT_DBG")) {
		rfbLog("progress_client: begin\n");
		db = 1;
	}
	for (i = 0; i < 15; i++) {
		if (latest_client) {
			for (j = 0; j < 10; j++) {
				if (latest_client->state != RFB_PROTOCOL_VERSION) {
					progressed = 1;
					break;
				}
				if (db) rfbLog("progress_client: calling-1 rfbCFD(1) %.6f\n", dnow()-start);
				rfbCFD(1);
			}
		}
		if (progressed) {
			break;
		}
		if (db) rfbLog("progress_client: calling-2 rfbCFD(1) %.6f\n", dnow()-start);
		rfbCFD(1);
	}
	if (!quiet) {
		rfbLog("client progressed=%d in %d/%d %.6f s\n",
		    progressed, i, j, dnow() - start);
	}
}

2918 2919 2920 2921
int wait_for_client(int *argc, char** argv, int http) {
	/* ugh, here we go... */
	XImage* fb_image;
	int w = 640, h = 480, b = 32;
2922
	int w0 = -1, h0 = -1, i, chg_raw_fb = 0;
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
	char *str, *q, *cmd = NULL;
	int db = 0, dt = 0;
	char *create_cmd = NULL;
	char *users_list_save = NULL;
	int created_disp = 0, ncache_save;
	int did_client_connect = 0;
	char *vnc_redirect_host = "localhost";
	int vnc_redirect_port = -1, vnc_redirect_cnt = 0;
	char vnc_redirect_test[10];

	if (getenv("WAIT_FOR_CLIENT_DB")) {
		db = 1;
	}

	vnc_redirect = 0;

	if (! use_dpy || strstr(use_dpy, "WAIT:") != use_dpy) {
		return 0;
	}

	for (i=0; i < *argc; i++) {
		if (!strcmp(argv[i], "-desktop")) {
			dt = 1;
		}
		if (db) fprintf(stderr, "args %d %s\n", i, argv[i]);
	}
	if (!quiet && !strstr(use_dpy, "FINDDISPLAY-run")) {
2950
		rfbLog("\n");
2951
		rfbLog("wait_for_client: %s\n", use_dpy);
2952
		rfbLog("\n");
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
	}

	str = strdup(use_dpy);
	str += strlen("WAIT");

	xdmcp_insert = NULL;

	/* get any leading geometry: */
	q = strchr(str+1, ':');
	if (q) {
		*q = '\0';
		if (sscanf(str+1, "%dx%d", &w0, &h0) == 2)  {
			w = w0;
			h = h0;
			rfbLog("wait_for_client set: w=%d h=%d\n", w, h);
2968 2969 2970
		} else {
			w0 = -1;
			h0 = -1;
2971 2972 2973 2974
		}
		*q = ':';
		str = q;
	}
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
	if ((w0 == -1 || h0 == -1) && pad_geometry != NULL) {
		int b0, del = 0;
		char *s = pad_geometry;
		if (strstr(s, "once:") == s) {
			del = 1;
			s += strlen("once:");
		}
		if (sscanf(s, "%dx%dx%d", &w0, &h0, &b0) == 3)  {
			w = nabs(w0);
			h = nabs(h0);
			b = nabs(b0);
		} else if (sscanf(s, "%dx%d", &w0, &h0) == 2)  {
			w = nabs(w0);
			h = nabs(h0);
		}
		if (del) {
			pad_geometry = NULL;
		}
	}
2994

2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026
	/* str currently begins with a ':' */
	if (strstr(str, ":cmd=") == str) {
		/* cmd=/path/to/mycommand */
		str++;
	} else if (strpbrk(str, "0123456789") == str+1) {
		/* :0.0 */
		;
	} else {
		/* hostname:0.0 */
		str++;
	}

	if (db) fprintf(stderr, "str: %s\n", str);

	if (strstr(str, "cmd=") == str) {
		cmd = setup_cmd(str, &vnc_redirect, &vnc_redirect_host, &vnc_redirect_port, db);
	}
	
	fb_image = &ximage_struct;
	setup_fake_fb(fb_image, w, h, b);

	if (! dt) {
		char *s;
		argv[*argc] = strdup("-desktop");
		*argc = (*argc) + 1;

		if (cmd) {
			char *q;
			s = choose_title(":0");
			q = strstr(s, ":0");
			if (q) {
				*q = '\0';
3027
			}
3028 3029 3030 3031 3032 3033 3034
		} else {
			s = choose_title(str);
		}
		rfb_desktop_name = strdup(s);
		argv[*argc] = s;
		*argc = (*argc) + 1;
	}
3035

3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
	ncache_save = ncache;
	ncache = 0;

	initialize_allowed_input();

	if (! multiple_cursors_mode) {
		multiple_cursors_mode = strdup("default");
	}
	initialize_cursors_mode();
	
	initialize_screen(argc, argv, fb_image);

3048 3049 3050 3051
	if (! inetd && ! use_openssl) {
		if (! screen->port || screen->listenSock < 0) {
			if (got_rfbport && got_rfbport_val == 0) {
				;
3052
			} else if (ipv6_listen && ipv6_listen_fd >= 0) {
3053
				rfbLog("Info: listening on IPv6 interface only.  (wait for client)\n");
3054 3055
			} else {
				rfbLogEnable(1);
3056 3057
				rfbLog("Error: could not obtain listening port.  (wait for client)\n");
				if (!got_rfbport && !got_ipv6_listen) {
3058 3059
					rfbLog("If this system is IPv6-only, use the -6 option.\n");
				}
3060 3061 3062 3063 3064
				clean_up_exit(1);
			}
		}
	}

3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
	initialize_signals();

	if (ssh_str != NULL) {
		ssh_remote_tunnel(ssh_str, screen->port);
	}

	if (! raw_fb) {
		chg_raw_fb = 1;
		/* kludge to get RAWFB_RET with dpy == NULL guards */
		raw_fb = (char *) 0x1;
	}

	if (cmd && !strcmp(cmd, "HTTPONCE")) {
		handle_one_http_request();	
		clean_up_exit(0);
	}

	if (http && check_httpdir()) {
		http_connections(1);
	}

	if (cmd && unixpw) {
		keep_unixpw = 1;
	}

	setup_service();

	check_waitbg();

	if (vnc_redirect) {
		vnc_redirect_loop(vnc_redirect_test, &vnc_redirect_cnt);
	} else {
3097 3098 3099 3100 3101 3102

		if (use_threads && !started_rfbRunEventLoop) {
			started_rfbRunEventLoop = 1;
			rfbRunEventLoop(screen, -1, TRUE);
		}

3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
		if (inetd && use_openssl) {
			accept_openssl(OPENSSL_INETD, -1);
		}

		setup_client_connect(&did_client_connect);

		loop_for_connect(did_client_connect);

		if (unixpw) {
			if (cmd && strstr(cmd, "FINDCREATEDISPLAY") == cmd) {
				if (users_list && strstr(users_list, "unixpw=") == users_list) {
					users_list_save = users_list;
					users_list = NULL;
				}
3117
			}
3118
			do_unixpw_loop();
3119 3120 3121
		} else if (cmd && !use_threads) {
			/* try to get RFB proto done now. */
			progress_client();
3122 3123 3124 3125 3126 3127 3128 3129
		}
	}

	if (vnc_redirect == 2) {
		;
	} else if (cmd) {
		if (!do_run_cmd(cmd, create_cmd, users_list_save, created_disp, db)) {
			return 0;
3130
		}
3131 3132 3133 3134 3135 3136
	} else {
		use_dpy = strdup(str);
	}
	if (chg_raw_fb) {
		raw_fb = NULL;
	}
3137 3138 3139

	ncache = ncache_save;

3140 3141 3142
	if (unixpw && keep_unixpw_opts && keep_unixpw_opts[0] != '\0') {
		user_supplied_opts(keep_unixpw_opts);
	}
3143 3144 3145
	if (create_cmd) {
		free(create_cmd);
	}
3146

3147
	if (vnc_redirect) {
3148 3149
		do_vnc_redirect(created_disp, vnc_redirect_host, vnc_redirect_port,
		    vnc_redirect_cnt, vnc_redirect_test);
3150 3151
		clean_up_exit(0);
	}
3152

3153 3154
	return 1;
}
runge's avatar
runge committed
3155