Xdummy 42.1 KB
Newer Older
1 2
#!/bin/sh
#
3
# Xdummy: an LD_PRELOAD hack to run a stock Xorg(1) or XFree86(1) server
4 5 6 7 8 9
# with the "dummy" video driver to make it avoid Linux VT switching, etc.
#
# Run "Xdummy -help" for more info.
#
install=""
uninstall=""
10 11 12
runit=1
prconf=""
notweak=""
13
root=""
14 15 16 17
nosudo=""
xserver=""
geom=""
depth=""
18 19
debug=""
strace=""
20
cmdline_config=""
21 22 23 24 25 26 27

PATH=$PATH:/bin:/usr/bin
export PATH

program=`basename "$0"`

help () {
28
	${PAGER:-more} << END
29
$program:
30

31 32 33 34
    A hack to run a stock Xorg(1) or XFree86(1) X server with the "dummy"
    (RAM-only framebuffer) video driver such that it AVOIDS the Linux VT
    switching, opening device files in /dev, keyboard and mouse conflicts,
    and other problems associated with the normal use of "dummy".
35

36 37
    In other words, it tries to make Xorg/XFree86 with the "dummy"
    device driver act more like Xvfb(1).
38

39 40 41 42 43
    The primary motivation for the Xdummy script is to provide a virtual X
    server for x11vnc but with more features than Xvfb (or Xvnc); however
    it could be used for other reasons (e.g. better automated testing
    than with Xvfb.)  One nice thing is the dummy server supports RANDR
    dynamic resizing while Xvfb does not.
44

45 46
    So, for example, x11vnc+Xdummy terminal services are a little better
    than x11vnc+Xvfb.
47

48 49 50 51 52
    To achieve this, while running the real Xserver $program intercepts
    system and library calls via the LD_PRELOAD method and modifies
    the behavior to make it work correctly (e.g. avoid the VT stuff.)
    LD_PRELOAD tricks are usually "clever hacks" and so might not work
    in all situations or break when something changes.
53

54 55 56
    This program does not need to be run as root as of 12/2009.  However,
    if there are problems for certain situations (usually older servers)
    it may perform better if run as root (use the -root option.)
57

58 59 60
    Also, gcc/cc and other build tools are required for this script to
    be able to compile the LD_PRELOAD shared object.  Be sure they are
    installed on the system.  See -install and -uninstall described below.
61

62 63
    Your Linux distribution may not install the dummy driver by default,
    e.g:
64

65 66 67 68
        /usr/lib/xorg/modules/drivers/dummy_drv.so
    
    some have it in a package named xserver-xorg-video-dummy you that
    need to install.
69

70 71
Usage:

72
	$program <${program}-args> <Xserver-args>
73

74
	(actually, the arguments can be supplied in any order.)
75 76 77

Examples:

78 79
	$program -install

80 81
	$program :1

82
	$program -debug :1
83

84
	$program -tmpdir ~/mytmp :1 -nolisten tcp
85 86 87 88 89

startx example:

	startx -e bash -- $program :2 -depth 16

90 91
	(if startx needs to be run as root, you can su(1) to a normal
	user in the bash shell and then launch ~/.xinitrc or ~/.xsession,
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
	gnome-session, startkde, startxfce4, etc.)

xdm example:

	xdm -config /usr/local/dummy/xdm-config -nodaemon

	where the xdm-config file has line:

	     DisplayManager.servers:         /usr/local/dummy/Xservers

	and /usr/local/dummy/Xservers has lines:

	     :1 local /usr/local/dummy/Xdummy :1 -debug
	     :2 local /usr/local/dummy/Xdummy :2 -debug

107 108
        (-debug is optional)

109 110 111 112
gdm/kdm example:

	TBD.

113 114
Root permission and x11vnc:

115
	Update: as of 12/2009 this program no longer must be run as root.
116 117
	So try it as non-root before running it as root and/or the
	following schemes.
118

119 120 121
	In some circumstances X server program may need to be run as root.
	If so, one could run x11vnc as root with -unixpw (it switches
	to the user that logs in) and that may be OK, some other ideas:
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

	- add this to sudo via visudo:

		ALL ALL = NOPASSWD: /usr/local/bin/Xdummy

	- use this little suid wrapper:
/* 
 * xdummy.c
 *
   cc -o ./xdummy xdummy.c
   sudo cp ./xdummy /usr/local/bin/xdummy
   sudo chown root:root /usr/local/bin/xdummy
   sudo chmod u+s /usr/local/bin/xdummy
 *
 */
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>

int main (int argc, char *argv[]) {
	extern char **environ;
	char str[100];
	sprintf(str, "XDUMMY_UID=%d", (int) getuid());
	putenv(str);
	setuid(0);  
	setgid(0);
	execv("/usr/local/bin/Xdummy", argv); 
	exit(1);
	return 1;
}

154 155 156 157 158 159

Options:

    ${program}-args:

	-install	Compile the LD_PRELOAD shared object and install it
160 161 162
			next to the $program script file as:

			  $0.so
163 164 165 166

			When that file exists it is used as the LD_PRELOAD
			shared object without recompiling.  Otherwise,
			each time $program is run the LD_PRELOAD shared
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
			object is compiled as a file in /tmp (or -tmpdir)

			If you set the environment variable
			INTERPOSE_GETUID=1 when building, then when
			$program is run as an ordinary user, the shared
			object will interpose getuid() calls and pretend
			to be root.  Otherwise it doesn't pretend to
			be root.

			You can also set the CFLAGS environment variable
			to anything else you want on the compile cmdline.

	-uninstall	Remove the file:

			  $0.so
182 183 184 185

			The LD_PRELOAD shared object will then be compiled
			each time this program is run.

186
	The X server is not started under -install, -uninstall, or -prconf.
187 188


189 190 191
	:N		The DISPLAY (e.g. :15) is often the first
			argument.  It is passed to the real X server and
			also used by the Xdummy script as an identifier.
192 193 194 195 196 197 198

	-geom geom1[,geom2...]  Take the geometry (e.g. 1024x768) or
			list of geometries and insert them into the
			Screen section of the tweaked X server 
			config file.  Use this to have a smaller geometry
			than the one in the system config file.

199 200 201 202 203 204 205
	-depth n	Use pixel color depth n (e.g. 8, 16, or 24). This
			makes sure the X config file has a Screen.Display
			subsection of this depth.  Note this option is
			ALSO passed to the X server.

	-DEPTH n	Same as -depth, except not passed to X server.

206 207
	-tmpdir dir	Specify a temporary directory, owned by you and
			only writable by you.  This is used in place of
208
			/tmp/Xdummy.\$USER/..  to place the $program.so
209 210
			shared object, tweaked config files, etc.

211 212 213
	-nonroot	Run in non-root mode (working 12/2009, now default)

	-root		Run as root (may still be needed in some
214
			environments.)  Same as XDUMMY_RUN_AS_ROOT=1.
215

216 217 218
	-nosudo		Do not try to use sudo(1) when re-running as root,
			use su(1) instead.

219 220
	-xserver path	Specify the path to the Xserver to use.  Default
			is to try "Xorg" first and then "XFree86".  If
221 222
			those are not in \$PATH, it tries these locations:
				/usr/bin/Xorg
223 224 225 226 227 228
				/usr/X11R6/bin/Xorg
				/usr/X11R6/bin/XFree86

	-n		Do not run the command to start the X server,
			just show the command that $program would run.
			The LD_PRELOAD shared object will be built,
229 230
			if needed.  Also note any XDUMMY* environment
			variables that need to be set.
231

232
	-prconf		Print, to stdout, the tweaked Xorg/XFree86
233
			config file (-config and -xf86config server
234
			options, respectively.)  The Xserver is not
235 236
			started.

237 238 239 240 241 242 243 244
	-notweak	Do not tweak (modify) the Xorg/XFree86 config file
			(system or server command line) at all.  The -geom
			and similar config file modifications are ignored.

			It is up to you to make sure it is a working
			config file (e.g. "dummy" driver, etc.)
			Perhaps you want to use a file based on the
			-prconf output.
245 246 247

	-debug		Extra debugging output.

248 249
	-strace		strace(1) the Xserver process (for troubleshooting.)
	-ltrace		ltrace(1) instead of strace (can be slow.)
250 251 252 253 254 255

	-h, -help	Print out this help.


    Xserver-args:

256 257 258
	Most of the Xorg and XFree86 options will work and are simply
	passed along if you supply them.  Important ones that may be
	supplied if missing:
259 260 261 262

	:N		X Display number for server to use.

	vtNN		Linux virtual terminal (VT) to use (a VT is currently
263
			still used, just not switched to and from.)
264 265 266 267

	-config file		Driver "dummy" tweaked config file, a
	-xf86config file	number of settings are tweaked besides Driver.

268 269 270 271 272 273 274 275 276 277
	If -config/-xf86config is not given, the system one
	(e.g. /etc/X11/xorg.conf) is used.  If the system one cannot be
	found, a built-in one is used.	Any settings in the config file
	that are not consistent with "dummy" mode will be overwritten
	(unless -notweak is specified.)

	If "file" is only a basename (e.g. "xorg.dummy.conf") with no /'s,
	then no tweaking of it is done: the X server will look for that
	basename via its normal search algorithm.  If the found file does
	not refer to the "dummy" driver, etc, then the X server will fail.
278 279 280

Notes:

281 282 283
    The Xorg/XFree86 "dummy" driver is currently undocumented.  It works
    well in this mode, but it is evidently not intended for end-users.
    So it could be removed or broken at any time.
284

285 286 287
    If the display Xserver-arg (e.g. :1) is not given, or ":" is given
    that indicates $program should try to find a free one (based on
    tcp ports.)
288 289

    If the display virtual terminal, VT, (e.g. vt9) is not given that
290
    indicates $program should try to find a free one (or guess a high one.) 
291
    
292
    This program is not completely secure WRT files in /tmp (but it tries
293
    to a good degree.)  Better is to use the -tmpdir option to supply a
294 295
    directory only writable by you.  Even better is to get rid of users
    on the local machine you do not trust :-)
296

297 298
    Set XDUMMY_SET_XV=1 to turn on debugging output for this script.

299 300 301 302 303 304
END
}

warn() {
	echo "$*" 1>&2
}
305 306 307 308

if [ "X$XDUMMY_SET_XV" != "X" ]; then
	set -xv
fi
309 310 311 312 313 314 315 316 317 318 319

if [ "X$XDUMMY_UID" = "X" ]; then
	XDUMMY_UID=`id -u`
	export XDUMMY_UID
fi
if [ "X$XDUMMY_UID" = "X0" ]; then
	if [ "X$SUDO_UID" != "X" ]; then
		XDUMMY_UID=$SUDO_UID
		export XDUMMY_UID
	fi
fi
320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
# check if root=1 first:
#
if [ "X$XDUMMY_RUN_AS_ROOT" = "X1" ]; then
	root=1
fi
for arg in $*
do
	if [ "X$arg" = "X-nonroot" ]; then
		root=""
	elif [ "X$arg" = "X-root" ]; then
		root=1
	fi
done

# See if it really needs to be run as root:
#
if [ "X$XDUMMY_SU_EXEC" = "X" -a "X$root" = "X1" -a "X`id -u`" != "X0"  ]; then
	# this is to prevent infinite loop in case su/sudo doesn't work:
339 340
	XDUMMY_SU_EXEC=1
	export XDUMMY_SU_EXEC
341 342 343 344

	dosu=1
	nosudo=""

345 346 347 348
	for arg in $*
	do
		if [ "X$arg" = "X-nonroot" ]; then
			dosu=""
349 350
		elif [ "X$arg" = "X-nosudo" ]; then
			nosudo="1"
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
		elif [ "X$arg" = "X-help" ]; then
			dosu=""
		elif [ "X$arg" = "X-h" ]; then
			dosu=""
		elif [ "X$arg" = "X-install" ]; then
			dosu=""
		elif [ "X$arg" = "X-uninstall" ]; then
			dosu=""
		elif [ "X$arg" = "X-n" ]; then
			dosu=""
		elif [ "X$arg" = "X-prconf" ]; then
			dosu=""
		fi
	done
	if [ $dosu ]; then
366
		# we need to restart it with su/sudo:
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
		if type sudo > /dev/null 2>&1; then
			:
		else
			nosudo=1
		fi
		if [ "X$nosudo" = "X" ]; then
			warn "$program: supply the sudo password to restart as root:"
			if [ "X$XDUMMY_UID" != "X" ]; then
				exec sudo $0 -uid $XDUMMY_UID "$@"
			else
				exec sudo $0 "$@"
			fi
		else
			warn "$program: supply the root password to restart as root:"
			if [ "X$XDUMMY_UID" != "X" ]; then
				exec su -c "$0 -uid $XDUMMY_UID $*"
			else
				exec su -c "$0 $*"
			fi
		fi
387
		# DONE:
388 389 390 391
		exit
	fi
fi

392 393
# This will hold the X display, e.g. :20
#
394
disp=""
395
args=""
396
cmdline_config=""
397

398
# Process Xdummy args:
399
#
400 401
while [ "X$1" != "X" ]
do
402 403 404
    if [ "X$1" = "X-config" -o "X$1" = "X-xf86config" ]; then
    	cmdline_config="$2"
    fi
405 406 407
    case $1 in 
	":"*)	disp=$1
                ;;
408
	"-install") install=1; runit=""
409
                ;;
410
	"-uninstall") uninstall=1; runit=""
411
                ;;
412 413 414 415 416 417
	"-n")  runit=""
                ;;
	"-no") runit=""
                ;;
	"-norun") runit=""
                ;;
418
	"-prconf") prconf=1; runit=""
419
                ;;
420 421 422
	"-notweak") notweak=1
                ;;
	"-noconf")  notweak=1
423
                ;;
424 425
	"-nonroot") root=""
                ;;
426
	"-root")    root=1
427 428 429
                ;;
	"-nosudo") nosudo=1
                ;;
430 431
	"-xserver") xserver="$2"; shift
                ;;
432 433 434
	"-uid") XDUMMY_UID="$2"; shift
		export XDUMMY_UID
                ;;
435 436 437 438
	"-geom") geom="$2"; shift
                ;;
	"-depth") depth="$2"; args="$args -depth $2";
		  shift
439
                ;;
440
	"-DEPTH") depth="$2"; shift
441
                ;;
442
	"-tmpdir") XDUMMY_TMPDIR="$2"; shift
443
                ;;
444
	"-debug")   debug=1
445 446 447 448 449
                ;;
	"-nodebug") debug=""
                ;;
	"-strace") strace=1
                ;;
450
	"-ltrace") strace=2
451
                ;;
452 453 454
	"-h")	 help; exit 0
                ;;
	"-help") help; exit 0
455
                ;;
456
	*)	args="$args $1"
457 458 459 460 461 462
                ;;
    esac
    shift
done

# Try to get a username for use in our tmp directory, etc.
463
#
464 465 466 467 468 469 470 471
user=""
if [ X`id -u` = "X0"  ]; then
	user=root	# this will also be used below for id=0
elif [ "X$USER" != "X" ]; then
	user=$USER
elif [ "X$LOGNAME" != "X" ]; then
	user=$LOGNAME
fi
472 473 474

# Keep trying...
#
475 476 477 478
if [ "X$user" = "X" ]; then
	user=`whoami 2>/dev/null`
fi
if [ "X$user" = "X" ]; then
479
	user=`basename "$HOME"`
480 481 482 483 484
fi
if [ "X$user" = "X" -o "X$user" = "X." ]; then
	user="u$$"
fi

485
if [ "X$debug" = "X1" -a "X$runit" != "X" ]; then
486 487
	echo ""
	echo "/usr/bin/env:"
488
	env | egrep -v '^(LS_COLORS|TERMCAP)' | sort
489 490 491
	echo ""
fi

492
# Function to compile the LD_PRELOAD shared object:
493
#
494 495 496 497 498 499 500
make_so() {
	# extract code embedded in this script into a tmp C file: 
	n1=`grep -n '^#code_begin' $0 | head -1 | awk -F: '{print $1}'`
	n2=`grep -n '^#code_end'   $0 | head -1 | awk -F: '{print $1}'`
	n1=`expr $n1 + 1`
	dn=`expr $n2 - $n1`

501
	tmp=$tdir/Xdummy.$RANDOM$$.c
502 503 504 505 506
	rm -f $tmp
	if [ -e $tmp -o -h $tmp ]; then
		warn "$tmp still exists."
		exit 1
	fi
507
	touch $tmp || exit 1
508
	tail -n +$n1 $0 | head -n $dn > $tmp
509 510

	# compile it to Xdummy.so:
511 512 513 514
	if [ -f $SO ]; then
		mv $SO $SO.$$
		rm -f $SO.$$
	fi
515 516 517 518
	rm -f $SO
	touch $SO
	if [ ! -f $SO ]; then
		SO=$tdir/Xdummy.$user.so
519
		warn "warning switching LD_PRELOAD shared object to: $SO"
520
	fi
521 522 523 524 525

	if [ -f $SO ]; then
		mv $SO $SO.$$
		rm -f $SO.$$
	fi
526 527 528
	rm -f $SO

	# we assume gcc:
529 530 531 532 533
	if [ "X$INTERPOSE_GETUID" = "X1" ]; then
		CFLAGS="$CFLAGS -DINTERPOSE_GETUID"
	fi
	echo "$program:" cc -shared -fPIC $CFLAGS -o $SO $tmp
                         cc -shared -fPIC $CFLAGS -o $SO $tmp
534 535 536 537 538 539 540
	rc=$?
	rm -f $tmp
	if [ $rc != 0 ]; then
		warn "$program: cannot build $SO"
		exit 1
	fi
	if [ "X$debug" != "X" -o "X$install" != "X" ]; then
541
		warn "$program: created  $SO"
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
		ls -l "$SO"
	fi
}

# Set tdir to tmp dir for make_so():
if [ "X$XDUMMY_TMPDIR" != "X" ]; then
	tdir=$XDUMMY_TMPDIR
	mkdir -p $tdir
else
	tdir="/tmp"
fi

# Handle -install/-uninstall case:
SO=$0.so
if [ "X$install" != "X" -o "X$uninstall" != "X" ]; then
	if [ -e $SO -o -h $SO ]; then
558
		warn "$program: removing $SO"
559
	fi
560 561 562 563
	if [ -f $SO ]; then
		mv $SO $SO.$$
		rm -f $SO.$$
	fi
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
	rm -f $SO
	if [ -e $SO -o -h $SO ]; then
		warn "warning: $SO still exists."
		exit 1
	fi
	if [ $install ]; then
		make_so
		if [ ! -f $SO ]; then
			exit 1
		fi
	fi
	exit 0
fi

# We need a tmp directory for the .so, tweaked config file, and for
579
# redirecting filenames we cannot create (under -nonroot)
580
#
581
tack=""
582 583
if [ "X$XDUMMY_TMPDIR" = "X" ]; then
	XDUMMY_TMPDIR="/tmp/Xdummy.$user"
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

	# try to tack on a unique subdir (display number or pid)
	# to allow multiple instances
	#
	if [ "X$disp" != "X" ]; then
		t0=$disp
	else
		t0=$1
	fi
	tack=`echo "$t0" | sed -e 's/^.*://'`
	if echo "$tack" | grep '^[0-9][0-9]*$' > /dev/null; then
		:
	else
		tack=$$
	fi
	if [ "X$tack" != "X" ]; then
		XDUMMY_TMPDIR="$XDUMMY_TMPDIR/$tack"
	fi
602
fi
603

604 605 606 607 608 609 610 611 612 613 614 615 616 617
tmp=$XDUMMY_TMPDIR
if echo "$tmp" | grep '^/tmp' > /dev/null; then
	if [ "X$tmp" != "X/tmp" -a "X$tmp" != "X/tmp/" ]; then
		# clean this subdir of /tmp out, otherwise leave it...
		rm -rf $XDUMMY_TMPDIR
		if [ -e $XDUMMY_TMPDIR ]; then
			warn "$XDUMMY_TMPDIR still exists"
			exit 1
		fi
	fi
fi

mkdir -p $XDUMMY_TMPDIR
chmod 700 $XDUMMY_TMPDIR
618 619 620
if [ "X$tack" != "X" ]; then
	chmod 700 `dirname "$XDUMMY_TMPDIR"` 2>/dev/null
fi
621

622 623
# See if we can write something there:
#
624 625 626 627 628 629 630 631 632 633 634 635
tfile="$XDUMMY_TMPDIR/test.file"
touch $tfile
if [ ! -f $tfile ]; then
	XDUMMY_TMPDIR="/tmp/Xdummy.$$.$USER"
	warn "warning: setting tmpdir to $XDUMMY_TMPDIR ..."
	rm -rf $XDUMMY_TMPDIR || exit 1
	mkdir -p $XDUMMY_TMPDIR || exit 1
fi
rm -f $tfile

export XDUMMY_TMPDIR

636 637
# Compile the LD_PRELOAD shared object if needed (needs XDUMMY_TMPDIR)
#
638 639 640 641 642
if [ ! -f $SO ]; then
	SO="$XDUMMY_TMPDIR/Xdummy.so"
	make_so
fi

643 644
# Decide which X server to use:
#
645 646 647 648 649
if [ "X$xserver" = "X" ]; then
	if type Xorg >/dev/null 2>&1; then
		xserver="Xorg"
	elif type XFree86 >/dev/null 2>&1; then
		xserver="XFree86"
650 651
	elif -x /usr/bin/Xorg; then
		xserver="/usr/bin/Xorg"
652 653
	elif -x /usr/X11R6/bin/Xorg; then
		xserver="/usr/X11R6/bin/Xorg"
654 655 656 657 658
	elif -x /usr/X11R6/bin/XFree86; then
		xserver="/usr/X11R6/bin/XFree86"
	fi
	if [ "X$xserver" = "X" ]; then
		# just let it fail below.
659
		xserver="/usr/bin/Xorg"
660 661 662 663
		warn "$program: cannot locate a stock Xserver... assuming $xserver"
	fi
fi

664 665 666 667 668 669 670
# See if the binary is suid or not readable under -nonroot mode:
#
if [ "X$BASH_VERSION" != "X" ]; then
	xserver_path=`type -p $xserver 2>/dev/null`
else
	xserver_path=`type $xserver 2>/dev/null | awk '{print $NF}'`
fi
671
if [ -e "$xserver_path" -a "X$root" = "X" -a "X$runit" != "X" ]; then
672
	if [ ! -r $xserver_path -o -u $xserver_path -o -g $xserver_path ]; then
673
		# XXX not quite correct with rm -rf $XDUMMY_TMPDIR ...
674
		# we keep on a filesystem we know root can write to.
675
		base=`basename "$xserver_path"`
676 677 678 679 680 681 682 683 684 685 686 687
		new="/tmp/$base.$user.bin"
		if [ -e $new ]; then
			snew=`ls -l $new          | awk '{print $5}' | grep '^[0-9][0-9]*$'`
			sold=`ls -l $xserver_path | awk '{print $5}' | grep '^[0-9][0-9]*$'`
			if [ "X$snew" != "X" -a "X$sold" != "X" -a "X$sold" != "X$snew" ]; then
				warn "removing different sized copy:"
				ls -l $new $xserver_path
				rm -f $new
			fi
		fi
		if [ ! -e $new -o ! -s $new ]; then
			rm -f $new
688 689
			touch $new || exit 1
			chmod 700 $new || exit 1
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
			if [ ! -r $xserver_path ]; then
				warn ""
				warn "NEED TO COPY UNREADABLE $xserver_path to $new as root:"
				warn ""
				ls -l $xserver_path 1>&2
				warn ""
				warn "This only needs to be done once:"
				warn "    cat $xserver_path > $new"
				warn ""
				nos=$nosudo
				if type sudo > /dev/null 2>&1; then
					:
				else
					nos=1
				fi
				if [ "X$nos" = "X1" ]; then
					warn "Please supply root passwd to 'su -c'"
					su -c "cat $xserver_path > $new"
				else
					warn "Please supply the sudo passwd if asked:"
					sudo /bin/sh -c "cat $xserver_path > $new"
				fi
			else
				warn ""
				warn "COPYING SETUID $xserver_path to $new"
				warn ""
				ls -l $xserver_path 1>&2
				warn ""
				cat $xserver_path > $new
			fi
720
			ls -l $new
721 722 723 724 725 726 727 728 729
			if [ -s $new ]; then
				:
			else
				rm -f $new
				ls -l $new
				exit 1
			fi
			warn ""
			warn "Please restart Xdummy now."
730
			exit 0
731 732
		fi
		if [ ! -O $new ]; then
733 734 735 736 737 738 739 740
			warn "file \"$new\" not owned by us!"
			ls -l $new
			exit 1
		fi
		xserver=$new
	fi 
fi

741 742
# Work out display:
#
743 744 745 746 747 748 749 750 751 752 753 754 755
if [ "X$disp" != "X" ]; then
	:
elif [ "X$1" != "X" ]; then
	if echo "$1" | grep '^:[0-9]' > /dev/null; then
		disp=$1
		shift
	elif [ "X$1" = "X:" ]; then
		# ":" means for us to find one.
		shift
	fi
fi
if [ "X$disp" = "X" -o "X$disp" = "X:" ]; then
	# try to find an open display port:
756
	# (tcp outdated...)
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
	ports=`netstat -ant | grep LISTEN | awk '{print $4}' | sed -e 's/^.*://'`
	n=0
	while [ $n -le 20 ]
	do
		port=`printf "60%02d" $n`
		if echo "$ports" | grep "^${port}\$" > /dev/null; then
			:
		else
			disp=":$n"
			warn "$program: auto-selected DISPLAY $disp"
			break	
		fi
		n=`expr $n + 1`
	done
fi

773 774
# Work out which vt to use, try to find/guess an open one if necessary.
#
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
vt=""
for arg in $*
do
	if echo "$arg" | grep '^vt' > /dev/null; then
		vt=$arg
		break
	fi
done
if [ "X$vt" = "X" ]; then
	if [ "X$user" = "Xroot" ]; then
		# root can user fuser(1) to see if it is in use:
		if type fuser >/dev/null 2>&1; then
			# try /dev/tty17 thru /dev/tty32
			n=17
			while [ $n -le 32 ]
			do
				dev="/dev/tty$n"
				if fuser $dev >/dev/null 2>&1; then
					:
				else
					vt="vt$n"
					warn "$program: auto-selected VT $vt => $dev"
					break
				fi
				n=`expr $n + 1`
			done
		fi
	fi
	if [ "X$vt" = "X" ]; then
		# take a wild guess...
		vt=vt16
806
		warn "$program: selected fallback VT $vt"
807 808 809 810 811
	fi
else
	vt=""
fi

812 813
# Decide flavor of Xserver:
#
814
stype=`basename "$xserver"`
815
if echo "$stype" | grep -i xfree86 > /dev/null; then
816
	stype=xfree86
817 818
else
	stype=xorg
819 820 821 822
fi

tweak_config() {
    in="$1"
823
    config2="$XDUMMY_TMPDIR/xdummy_modified_xconfig.conf"
824
    if [ "X$disp" != "X" ]; then
825
    	d=`echo "$disp" | sed -e 's,/,,g' -e 's/:/_/g'`
826 827 828 829
	config2="$config2$d"
    fi
    
    # perl script to tweak the config file... add/delete options, etc.
830 831 832 833
    #
    env XDUMMY_GEOM=$geom \
        XDUMMY_DEPTH=$depth \
        perl > $config2 < $in -e '
834
    $n = 0;
835 836 837 838 839
    $geom  = $ENV{XDUMMY_GEOM};
    $depth = $ENV{XDUMMY_DEPTH};
    $videoram = "24000";
    $HorizSync   = "30.0 - 130.0";
    $VertRefresh = "50.0 - 250.0";
840
    if ($geom ne "") {
841
    	my $tmp = "";
842 843 844 845 846 847 848
	foreach $g (split(/,/, $geom)) {
		$tmp .= "\"$g\" ";
	}
	$tmp =~ s/\s*$//;
	$geom = $tmp;
    }
    while (<>) {
849 850 851 852
	if ($ENV{XDUMMY_NOTWEAK}) {
		print $_;
		next;
	}
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	$n++;
	if (/^\s*#/) {
		# pass comments straight thru
		print;
		next;
	}
	if (/^\s*Section\s+(\S+)/i) {
		# start of Section
		$sect = $1;
		$sect =~ s/\W//g;
		$sect =~ y/A-Z/a-z/;
		$sects{$sect} = 1;
		print;
		next;
	}
868
	if (/^\s*EndSection/i) {
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
		# end of Section
		if ($sect eq "serverflags") {
			if (!$got_DontVTSwitch) {
				print "  ##Xdummy:##\n";
				print "  Option \"DontVTSwitch\" \"true\"\n";
			}
			if (!$got_AllowMouseOpenFail) {
				print "  ##Xdummy:##\n";
				print "  Option \"AllowMouseOpenFail\" \"true\"\n";
			}
			if (!$got_PciForceNone) {
				print "  ##Xdummy:##\n";
				print "  Option \"PciForceNone\" \"true\"\n";
			}
		} elsif ($sect eq "device") {
			if (!$got_Driver) {
				print "  ##Xdummy:##\n";
				print "  Driver \"dummy\"\n";
			}
			if (!$got_VideoRam) {
				print "  ##Xdummy:##\n";
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
				print "  VideoRam $videoram\n";
			}
		} elsif ($sect eq "screen") {
			if ($depth ne "" && !got_DefaultDepth) {
				print "  ##Xdummy:##\n";
				print "  DefaultDepth $depth\n";
			}
			if ($got_Monitor eq "") {
				print "  ##Xdummy:##\n";
				print "  Monitor \"Monitor0\"\n";
			}
		} elsif ($sect eq "monitor") {
			if (!got_HorizSync) {
				print "  ##Xdummy:##\n";
				print "  HorizSync   $HorizSync\n";
			}
			if (!got_VertRefresh) {
				print "  ##Xdummy:##\n";
				print "  VertRefresh $VertRefresh\n";
909 910 911 912 913 914
			}
		}
		$sect = "";
		print;
		next;
	}
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

	if (/^\s*SubSection\s+(\S+)/i) {
		# start of Section
		$subsect = $1;
		$subsect =~ s/\W//g;
		$subsect =~ y/A-Z/a-z/;
		$subsects{$subsect} = 1;
		if ($sect eq "screen" && $subsect eq "display") {
			$got_Mode = 0;
		}
		print;
		next;
	}
	if (/^\s*EndSubSection/i) {
		# end of SubSection
		if ($sect eq "screen") {
			if ($subsect eq "display") {
				if ($depth ne "" && !$set_Depth) {
					print "          ##Xdummy:##\n";
					print "          Depth\t$depth\n";
				}
				if ($geom ne "" && ! $got_Mode) {
					print "          ##Xdummy:##\n";
					print "          Modes\t$geom\n";
				}
			}
		}
		$subsect = "";
		print;
		next;
	}

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
	$l = $_;
	$l =~ s/#.*$//;
	if ($sect eq "serverflags") {
		if ($l =~ /^\s*Option.*DontVTSwitch/i) {
			$_ =~ s/false/true/ig;
			$got_DontVTSwitch = 1;
		}
		if ($l =~ /^\s*Option.*AllowMouseOpenFail/i) {
			$_ =~ s/false/true/ig;
			$got_AllowMouseOpenFail = 1;
		}
		if ($l =~ /^\s*Option.*PciForceNone/i) {
			$_ =~ s/false/true/ig;
			$got_PciForceNone= 1;
		}
	}
	if ($sect eq "module") {
		if ($l =~ /^\s*Load.*\b(dri|fbdevhw)\b/i) {
			$_ = "##Xdummy## $_";
		}
	}
968 969 970 971 972 973 974 975
	if ($sect eq "monitor") {
		if ($l =~ /^\s*HorizSync/i) {
			$got_HorizSync = 1;
		}
		if ($l =~ /^\s*VertRefresh/i) {
			$got_VertRefresh = 1;
		}
	}
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
	if ($sect eq "device") {
		if ($l =~ /^(\s*Driver)\b/i) {
			$_ = "$1 \"dummy\"\n";
			$got_Driver = 1;
		}
		if ($l =~ /^\s*VideoRam/i) {
			$got_VideoRam= 1;
		}
	}
	if ($sect eq "inputdevice") {
		if ($l =~ /^\s*Option.*\bDevice\b/i) {
			print "  ##Xdummy:##\n";
			$_ = "  Option \"Device\" \"/dev/dilbert$n\"\n";
		}
	}
	if ($sect eq "screen") {
992 993
		if ($l =~ /^\s*DefaultDepth\s+(\d+)/i) {
			if ($depth ne "") {
994
				print "  ##Xdummy:##\n";
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
				$_ = "  DefaultDepth\t$depth\n";
			}
			$got_DefaultDepth = 1;
		}
		if ($l =~ /^\s*Monitor\s+(\S+)/i) {
			$got_Monitor = $1;
			$got_Monitor =~ s/"//g;
		}
		if ($subsect eq "display") {
			if ($geom ne "") {
				if ($l =~ /^(\s*Modes)\b/i) {
					print "          ##Xdummy:##\n";
					$_ = "$1 $geom\n";
					$got_Modes = 1;
				}
			}
			if ($l =~ /^\s*Depth\s+(\d+)/i) {
				my $d = $1;
				if (!$set_Depth && $depth ne "") {
					$set_Depth = 1;
					if ($depth != $d) {
						print "          ##Xdummy:##\n";
						$_ =  "          Depth\t$depth\n";
					}
				}
1020 1021 1022 1023 1024
			}
		}
	}
	print;
    }
1025 1026 1027
    if ($ENV{XDUMMY_NOTWEAK}) {
	exit;
    }
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    # create any crucial sections that are missing:
    if (! exists($sects{serverflags})) {
	print "\n##Xdummy:##\n";
    	print "Section \"ServerFlags\"\n";
    	print "  Option \"DontVTSwitch\" \"true\"\n";
    	print "  Option \"AllowMouseOpenFail\" \"true\"\n";
    	print "  Option \"PciForceNone\" \"true\"\n";
    	print "EndSection\n";
    }
    if (! exists($sects{device})) {
	print "\n##Xdummy:##\n";
    	print "Section \"Device\"\n";
    	print "  Identifier \"Videocard0\"\n";
    	print "  Driver \"dummy\"\n";
1042
	print "  VideoRam $videoram\n";
1043 1044 1045 1046 1047 1048
    	print "EndSection\n";
    }
    if (! exists($sects{monitor})) {
	print "\n##Xdummy:##\n";
    	print "Section \"Monitor\"\n";
    	print "  Identifier \"Monitor0\"\n";
1049 1050
    	print "  HorizSync   $HorizSync\n";
    	print "  VertRefresh $VertRefresh\n";
1051 1052 1053 1054 1055 1056 1057
    	print "EndSection\n";
    }
    if (! exists($sects{screen})) {
	print "\n##Xdummy:##\n";
    	print "Section \"Screen\"\n";
    	print "  Identifier \"Screen0\"\n";
    	print "  Device \"Videocard0\"\n";
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
	if ($got_Monitor ne "") {
    		print "  Monitor \"$got_Monitor\"\n";
	} else {
    		print "  Monitor \"Monitor0\"\n";
	}
	if ($depth ne "") {
    		print "  DefaultDepth $depth\n";
	} else {
    		print "  DefaultDepth 24\n";
	}
1068 1069
    	print "  SubSection \"Display\"\n";
    	print "    Viewport 0 0\n";
1070 1071 1072 1073 1074 1075
    	print "    Depth 24\n";
	if ($geom ne "") {
    		print "    Modes $geom\n";
	} else {
    		print "    Modes \"1280x1024\" \"1024x768\" \"800x600\"\n";
	}
1076 1077 1078 1079 1080 1081
    	print "  EndSubSection\n";
    	print "EndSection\n";
    }
';
}

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
# Work out config file and tweak it.
#
if [ "X$cmdline_config" = "X" ]; then
	:
elif echo "$cmdline_config" | grep '/' > /dev/null; then
	:
else
	# ignore basename only case (let server handle it)
	cmdline_config=""
	notweak=1
fi

config=$cmdline_config

if [ "X$notweak" = "X1" -a "X$root" = "X" -a  -f "$cmdline_config" ]; then
	# if not root we need to copy (but not tweak) the specified config.
	XDUMMY_NOTWEAK=1
	export XDUMMY_NOTWEAK
	notweak=""
fi

if [ ! $notweak ]; then
1104 1105
	# tweaked config will be put in $config2:
	config2=""
1106
	if [ "X$config" = "X" ]; then
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
		# use the default one:
		if [ "X$stype" = "Xxorg" ]; then
			config=/etc/X11/xorg.conf
		else
			if [ -f "/etc/X11/XF86Config-4" ]; then
				config="/etc/X11/XF86Config-4"
			else
				config="/etc/X11/XF86Config"
			fi
		fi
		if [ ! -f $config ]; then
			for c in /etc/X11/xorg.conf /etc/X11/XF86Config-4 /etc/X11/XF86Config
			do
				if [ -f $c ]; then
					config=$c
					break
				fi
			done
		fi
	fi

1128 1129
	if [ ! -f $config ]; then
		config="$XDUMMY_TMPDIR/xorg.conf"
1130
		warn "$program: using minimal built-in xorg.conf settings."
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 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
		cat > $config <<END

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
EndSection

Section "Module"
    Load           "dbe"
    Load           "extmod"
    Load           "freetype"
    Load           "glx"
EndSection

Section "InputDevice"
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    HorizSync       30.0 - 130.0
    VertRefresh     50.0 - 250.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "foovideo"
    VendorName     "foovideo Corporation"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
        Modes           "1280x1024"
    EndSubSection
EndSection

END
	fi

1193 1194 1195 1196 1197
	if [ -f $config ]; then
		tweak_config $config
	fi

	# now we need to get our tweaked config file onto the command line:
1198
	if [ "X$cmdline_config" = "X" ]; then
1199
		# append to cmdline (FUBAR will be substituted below.)
1200 1201 1202 1203 1204 1205 1206 1207
		if [ "X$stype" = "Xxorg" ]; then
			args="$args -config FUBAR"
		else
			args="$args -xf86config FUBAR"
		fi
	fi
	if [ "X$config2" != "X" ]; then
		# or modify $args:
1208 1209 1210 1211 1212
		c2=$config2
		if [ "X$root" = "X" ]; then
			# ordinary user cannot use absolute path.
			c2=`basename $config2`
		fi
1213
		args=`echo "$args" | sed \
1214 1215
			-e "s,-config  *[^ ][^ ]*,-config $c2,g" \
			-e "s,-xf86config  *[^ ][^ ]*,-xf86config $c2,g"`
1216 1217 1218 1219 1220
	fi
fi

if [ $prconf ]; then
	warn ""
1221
	warn "Printing out the Xorg/XFree86 server config file:"
1222 1223 1224
	warn ""
	if [ "X$config2" = "X" ]; then
		warn "NO CONFIG GENERATED."
1225
		exit 1
1226 1227 1228
	else
		cat "$config2"
	fi
1229
	exit 0
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
fi

if [ $debug ]; then
	XDUMMY_DEBUG=1
	export XDUMMY_DEBUG
fi
if [ $root ]; then
	XDUMMY_ROOT=1
	export XDUMMY_ROOT
fi

1241 1242
# Finally, run it:
#
1243
if [ "X$debug" != "X" -o "X$runit" = "X" ]; then
1244 1245 1246 1247 1248 1249 1250 1251 1252
	if [ ! $runit ]; then
		echo ""
		echo "/usr/bin/env:"
		env | egrep -v '^(LS_COLORS|TERMCAP)' | sort
		echo ""
		echo "XDUMMY*:"
		env | grep '^XDUMMY' | sort
		echo ""
	fi
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
	warn ""
	warn "The command to run is:"
	warn ""
	so=$SO
	pwd=`pwd`
	if echo "$so" | grep '^\./' > /dev/null; then
		so=`echo "$so" | sed -e "s,^\.,$pwd,"`
	fi
	if echo "$so" | grep '/' > /dev/null; then
		:
	else
		so="$pwd/$so"
	fi
	warn "env LD_PRELOAD=$so $xserver $disp $args $vt"
	warn ""
	if [ ! $runit ]; then
		exit 0
	fi
fi
1272

1273
if [ $strace ]; then
1274 1275 1276 1277 1278
	if [ "X$strace" = "X2" ]; then
		ltrace -f env LD_PRELOAD=$SO $xserver $disp $args $vt
	else
		strace -f env LD_PRELOAD=$SO $xserver $disp $args $vt
	fi
1279 1280 1281 1282 1283
else
	exec env LD_PRELOAD=$SO $xserver $disp $args $vt
fi

exit $?
1284

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
#########################################################################

code() {
#code_begin
#include <stdio.h>
#define O_ACCMODE          0003
#define O_RDONLY             00
#define O_WRONLY             01
#define O_RDWR               02
#define O_CREAT            0100 /* not fcntl */
#define O_EXCL             0200 /* not fcntl */
#define O_NOCTTY           0400 /* not fcntl */
#define O_TRUNC           01000 /* not fcntl */
#define O_APPEND          02000
#define O_NONBLOCK        04000
#define O_NDELAY        O_NONBLOCK
#define O_SYNC           010000
#define O_FSYNC          O_SYNC
#define O_ASYNC          020000

#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include <linux/vt.h>
#include <linux/kd.h>

#define __USE_GNU
#include <dlfcn.h>

1315 1316 1317
static char tmpdir[4096];
static char str1[4096];
static char str2[4096];
1318 1319 1320 1321

static char devs[256][1024];
static int debug = -1;
static int root = -1;
1322 1323
static int changed_uid = 0;
static int saw_fonts = 0;
1324
static int saw_lib_modules = 0;
1325 1326

static time_t start = 0; 
1327 1328 1329 1330 1331 1332 1333 1334

void check_debug(void) {
	if (debug < 0) {
		if (getenv("XDUMMY_DEBUG") != NULL) {
			debug = 1;
		} else {
			debug = 0;
		}
1335
		/* prevent other processes using the preload: */
1336 1337 1338 1339 1340
		putenv("LD_PRELOAD=");
	}
}
void check_root(void) {
	if (root < 0) {
1341
		/* script tells us if we are root */
1342 1343 1344 1345 1346 1347 1348
		if (getenv("XDUMMY_ROOT") != NULL) {
			root = 1;
		} else {
			root = 0;
		}
	}
}
1349 1350 1351 1352

void check_uid(void) {
	if (start == 0) {
		start = time(NULL);
1353
		if (debug) fprintf(stderr, "START: %u\n", (unsigned int) start);
1354 1355 1356 1357 1358
		return;
	} else if (changed_uid == 0) {
		if (saw_fonts || time(NULL) > start + 20) {
			if (getenv("XDUMMY_UID")) {
				int uid = atoi(getenv("XDUMMY_UID"));
1359
				if (debug) fprintf(stderr, "SETREUID: %d saw_fonts=%d\n", uid, saw_fonts);
1360
				if (uid >= 0) {
1361
					/* this will simply fail in -nonroot mode: */
1362 1363 1364 1365 1366 1367 1368 1369
					setreuid(uid, -1);
				}
			}
			changed_uid = 1;
		}
	}
}

1370
#define CHECKIT if (debug < 0) check_debug(); \
1371 1372
		if (root  < 0) check_root(); \
		check_uid();
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

static void set_tmpdir(void) {
	char *s;
	static int didset = 0;
	if (didset) {
		return;
	}
	s = getenv("XDUMMY_TMPDIR");
	if (! s) {
		s = "/tmp";
	}
	tmpdir[0] = '\0';
	strcat(tmpdir, s);
	strcat(tmpdir, "/");
	didset = 1;
}

static char *tmpdir_path(const char *path) {
	char *str;
	set_tmpdir();
	strcpy(str2, path);
	str = str2;
	while (*str) {
		if (*str == '/') {
			*str = '_';
		}
		str++;
	}
	strcpy(str1, tmpdir);
	strcat(str1, str2);
	return str1;
}

int open(const char *pathname, int flags, unsigned short mode) {
	int fd;
	char *store_dev = NULL;
	static int (*real_open)(const char *, int , unsigned short) = NULL;

	CHECKIT
	if (! real_open) {
		real_open = (int (*)(const char *, int , unsigned short))
			dlsym(RTLD_NEXT, "open");
	}

1417 1418 1419 1420 1421 1422 1423
	if (strstr(pathname, "lib/modules/")) {
		/* not currently used. */
		saw_lib_modules = 1;
	}

	if (!root) {
		if (strstr(pathname, "/dev/") == pathname) {
1424
			store_dev = strdup(pathname);
1425 1426
		}
		if (strstr(pathname, "/dev/tty") == pathname && strcmp(pathname, "/dev/tty")) {
1427
			pathname = tmpdir_path(pathname);
1428 1429 1430 1431 1432 1433
			if (debug) fprintf(stderr, "OPEN: %s -> %s (as FIFO)\n", store_dev, pathname);
			/* we make it a FIFO so ioctl on it does not fail */
			unlink(pathname);
			mkfifo(pathname, 0666);
		} else if (0) {
			/* we used to handle more /dev files ... */
1434 1435 1436 1437 1438 1439 1440
			fd = real_open(pathname, O_WRONLY|O_CREAT, 0777);
			close(fd);
		}
	}

	fd = real_open(pathname, flags, mode);

1441
	if (debug) fprintf(stderr, "OPEN: %s %d %d fd=%d\n", pathname, flags, mode, fd);
1442 1443

	if (! root) {
1444
		if (store_dev) {
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
			if (fd < 256) {
				strcpy(devs[fd], store_dev);
			}
			free(store_dev);
		}
	}

	return(fd);
}

int open64(const char *pathname, int flags, unsigned short mode) {
	int fd;

	CHECKIT
	if (debug) fprintf(stderr, "OPEN64: %s %d %d\n", pathname, flags, mode);

	fd = open(pathname, flags, mode);
	return(fd);
}

1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
int rename(const char *oldpath, const char *newpath) {
	static int (*real_rename)(const char *, const char *) = NULL;

	CHECKIT
	if (! real_rename) {
		real_rename = (int (*)(const char *, const char *))
			dlsym(RTLD_NEXT, "rename");
	}

	if (debug) fprintf(stderr, "RENAME: %s %s\n", oldpath, newpath);

	if (root) {
		return(real_rename(oldpath, newpath));
	}

	if (strstr(oldpath, "/var/log") == oldpath) {
		if (debug) fprintf(stderr, "RENAME: returning 0\n");
		return 0;
	}
	return(real_rename(oldpath, newpath));
}

1487 1488 1489 1490
FILE *fopen(const char *pathname, const char *mode) {
	static FILE* (*real_fopen)(const char *, const char *) = NULL;
	char *str;

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
	if (! saw_fonts) {
		if (strstr(pathname, "/fonts/")) {
			if (strstr(pathname, "fonts.dir")) {
				saw_fonts = 1;
			} else if (strstr(pathname, "fonts.alias")) {
				saw_fonts = 1;
			}
		}
	}

1501 1502 1503 1504 1505
	CHECKIT
	if (! real_fopen) {
		real_fopen = (FILE* (*)(const char *, const char *))
			dlsym(RTLD_NEXT, "fopen");
	}
1506

1507 1508
	if (debug) fprintf(stderr, "FOPEN: %s %s\n", pathname, mode);

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
	if (strstr(pathname, "xdummy_modified_xconfig.conf")) {
		/* make our config appear to be in /etc/X11, etc. */
		char *q = strrchr(pathname, '/');
		if (q != NULL && getenv("XDUMMY_TMPDIR") != NULL) {
			strcpy(str1, getenv("XDUMMY_TMPDIR"));
			strcat(str1, q);
			if (debug) fprintf(stderr, "FOPEN: %s -> %s\n", pathname, str1);
			pathname = str1;
		}
	}

1520 1521 1522 1523 1524 1525 1526
	if (root) {
		return(real_fopen(pathname, mode));
	}

	str = (char *) pathname;
	if (strstr(pathname, "/var/log") == pathname) {
		str = tmpdir_path(pathname);
1527
		if (debug) fprintf(stderr, "FOPEN: %s -> %s\n", pathname, str);
1528
	}
1529
	return(real_fopen(str, mode));
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
}


#define RETURN0 if (debug) \
	{fprintf(stderr, "IOCTL: covered %d 0x%x\n", fd, req);} return 0;
#define RETURN1 if (debug) \
	{fprintf(stderr, "IOCTL: covered %d 0x%x\n", fd, req);} return -1;

int ioctl(int fd, int req, void *ptr) {
	static int closed_xf86Info_consoleFd = 0;
	static int (*real_ioctl)(int, int , void *) = NULL;

	CHECKIT
	if (! real_ioctl) {
		real_ioctl = (int (*)(int, int , void *))
			dlsym(RTLD_NEXT, "open");
	}
	if (debug) fprintf(stderr, "IOCTL: %d 0x%x %p\n", fd, req, ptr);

	/* based on xorg-x11-6.8.1-dualhead.patch */
	if (req == VT_GETMODE) {
		/* close(xf86Info.consoleFd) */
		if (0 && ! closed_xf86Info_consoleFd) {
			/* I think better not to close it... */
			close(fd);
			closed_xf86Info_consoleFd = 1;
		}
		RETURN0
	} else if (req == VT_SETMODE) {
		RETURN0
	} else if (req == VT_GETSTATE) {
		RETURN0
	} else if (req == KDSETMODE) {
		RETURN0
	} else if (req == KDSETLED) {
		RETURN0
	} else if (req == KDGKBMODE) {
		RETURN0
1568 1569
	} else if (req == KDSKBMODE) {
		RETURN0
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
	} else if (req == VT_ACTIVATE) {
		RETURN0
	} else if (req == VT_WAITACTIVE) {
		RETURN0
	} else if (req == VT_RELDISP) {
		if (ptr == (void *) 1) {
			RETURN1
		} else if (ptr == (void *) VT_ACKACQ) {
			RETURN0
		}
	}

	return(real_ioctl(fd, req, ptr));
}

typedef void (*sighandler_t)(int);
#define SIGUSR1       10
#define SIG_DFL       ((sighandler_t)0)

sighandler_t signal(int signum, sighandler_t handler) {
	static sighandler_t (*real_signal)(int, sighandler_t) = NULL;

	CHECKIT
	if (! real_signal) {
		real_signal = (sighandler_t (*)(int, sighandler_t))
			dlsym(RTLD_NEXT, "signal");
	}

	if (debug) fprintf(stderr, "SIGNAL: %d %p\n", signum, handler);

	if (signum == SIGUSR1) {
		if (debug) fprintf(stderr, "SIGNAL: skip SIGUSR1\n");
		return SIG_DFL;
	}
	
	return(real_signal(signum, handler));
}

int close(int fd) {
	static int (*real_close)(int) = NULL;

	CHECKIT
	if (! real_close) {
		real_close = (int (*)(int)) dlsym(RTLD_NEXT, "close");
	}

	if (debug) fprintf(stderr, "CLOSE: %d\n", fd);
1617
	if (!root) {
1618 1619 1620 1621 1622 1623 1624
		if (fd < 256) {
			devs[fd][0] = '\0';
		}
	}
	return(real_close(fd));
}

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
struct stat {
	int foo;
};

int stat(const char *path, struct stat *buf) {
	static int (*real_stat)(const char *, struct stat *) = NULL;

	CHECKIT
	if (! real_stat) {
		real_stat = (int (*)(const char *, struct stat *))
			dlsym(RTLD_NEXT, "stat");
	}

	if (debug) fprintf(stderr, "STAT: %s\n", path);

	return(real_stat(path, buf));
}

int stat64(const char *path, struct stat *buf) {
	static int (*real_stat64)(const char *, struct stat *) = NULL;

	CHECKIT
	if (! real_stat64) {
		real_stat64 = (int (*)(const char *, struct stat *))
			dlsym(RTLD_NEXT, "stat64");
	}

	if (debug) fprintf(stderr, "STAT64: %s\n", path);

	return(real_stat64(path, buf));
}

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
int chown(const char *path, uid_t owner, gid_t group) {
	static int (*real_chown)(const char *, uid_t, gid_t) = NULL;

	CHECKIT
	if (! real_chown) {
		real_chown = (int (*)(const char *, uid_t, gid_t))
			dlsym(RTLD_NEXT, "chown");
	}

	if (root) {
		return(real_chown(path, owner, group));
	}

	if (debug) fprintf(stderr, "CHOWN: %s %d %d\n", path, owner, group);

	if (strstr(path, "/dev") == path) {
		if (debug) fprintf(stderr, "CHOWN: return 0\n");
		return 0;
	}

	return(real_chown(path, owner, group));
}

1680 1681 1682 1683
extern int *__errno_location (void);
#ifndef ENODEV
#define ENODEV 19
#endif
1684 1685 1686

int ioperm(unsigned long from, unsigned long num, int turn_on) {
	static int (*real_ioperm)(unsigned long, unsigned long, int) = NULL;
1687

1688 1689 1690 1691 1692
	CHECKIT
	if (! real_ioperm) {
		real_ioperm = (int (*)(unsigned long, unsigned long, int))
			dlsym(RTLD_NEXT, "ioperm");
	}
1693
	if (debug) fprintf(stderr, "IOPERM: %d %d %d\n", (int) from, (int) num, turn_on);
1694 1695 1696
	if (root) {
		return(real_ioperm(from, num, turn_on));
	}
1697 1698 1699 1700 1701 1702
	if (from == 0 && num == 1024 && turn_on == 1) {
		/* we want xf86EnableIO to fail */
		if (debug) fprintf(stderr, "IOPERM: setting ENODEV.\n");
		*__errno_location() = ENODEV;
		return -1;
	}
1703 1704 1705 1706 1707
	return 0;
}

int iopl(int level) {
	static int (*real_iopl)(int) = NULL;
1708

1709 1710 1711 1712
	CHECKIT
	if (! real_iopl) {
		real_iopl = (int (*)(int)) dlsym(RTLD_NEXT, "iopl");
	}
1713
	if (debug) fprintf(stderr, "IOPL: %d\n", level);
1714 1715 1716 1717 1718 1719
	if (root) {
		return(real_iopl(level));
	}
	return 0;
}

1720
#ifdef INTERPOSE_GETUID 
1721 1722 1723 1724 1725 1726

/*
 * we got things to work w/o pretending to be root.
 * so we no longer interpose getuid(), etc.
 */

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
uid_t getuid(void) {
	static uid_t (*real_getuid)(void) = NULL;
	CHECKIT
	if (! real_getuid) {
		real_getuid = (uid_t (*)(void)) dlsym(RTLD_NEXT, "getuid");
	}
	if (root) {
		return(real_getuid());
	}
	if (debug) fprintf(stderr, "GETUID: 0\n");
	return 0;
}
uid_t geteuid(void) {
	static uid_t (*real_geteuid)(void) = NULL;
	CHECKIT
	if (! real_geteuid) {
		real_geteuid = (uid_t (*)(void)) dlsym(RTLD_NEXT, "geteuid");
	}
	if (root) {
		return(real_geteuid());
	}
	if (debug) fprintf(stderr, "GETEUID: 0\n");
	return 0;
}
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
uid_t geteuid_kludge1(void) {
	static uid_t (*real_geteuid)(void) = NULL;
	CHECKIT
	if (! real_geteuid) {
		real_geteuid = (uid_t (*)(void)) dlsym(RTLD_NEXT, "geteuid");
	}
	if (debug) fprintf(stderr, "GETEUID: 0 saw_libmodules=%d\n", saw_lib_modules);
	if (root && !saw_lib_modules) {
		return(real_geteuid());
	} else {
		saw_lib_modules = 0;
		return 0;
	}
}

1766 1767 1768 1769 1770 1771 1772 1773 1774 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 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
uid_t getuid32(void) {
	static uid_t (*real_getuid32)(void) = NULL;
	CHECKIT
	if (! real_getuid32) {
		real_getuid32 = (uid_t (*)(void)) dlsym(RTLD_NEXT, "getuid32");
	}
	if (root) {
		return(real_getuid32());
	}
	if (debug) fprintf(stderr, "GETUID32: 0\n");
	return 0;
}
uid_t geteuid32(void) {
	static uid_t (*real_geteuid32)(void) = NULL;
	CHECKIT
	if (! real_geteuid32) {
		real_geteuid32 = (uid_t (*)(void)) dlsym(RTLD_NEXT, "geteuid32");
	}
	if (root) {
		return(real_geteuid32());
	}
	if (debug) fprintf(stderr, "GETEUID32: 0\n");
	return 0;
}

gid_t getgid(void) {
	static gid_t (*real_getgid)(void) = NULL;
	CHECKIT
	if (! real_getgid) {
		real_getgid = (gid_t (*)(void)) dlsym(RTLD_NEXT, "getgid");
	}
	if (root) {
		return(real_getgid());
	}
	if (debug) fprintf(stderr, "GETGID: 0\n");
	return 0;
}
gid_t getegid(void) {
	static gid_t (*real_getegid)(void) = NULL;
	CHECKIT
	if (! real_getegid) {
		real_getegid = (gid_t (*)(void)) dlsym(RTLD_NEXT, "getegid");
	}
	if (root) {
		return(real_getegid());
	}
	if (debug) fprintf(stderr, "GETEGID: 0\n");
	return 0;
}
gid_t getgid32(void) {
	static gid_t (*real_getgid32)(void) = NULL;
	CHECKIT
	if (! real_getgid32) {
		real_getgid32 = (gid_t (*)(void)) dlsym(RTLD_NEXT, "getgid32");
	}
	if (root) {
		return(real_getgid32());
	}
	if (debug) fprintf(stderr, "GETGID32: 0\n");
	return 0;
}
gid_t getegid32(void) {
	static gid_t (*real_getegid32)(void) = NULL;
	CHECKIT
	if (! real_getegid32) {
		real_getegid32 = (gid_t (*)(void)) dlsym(RTLD_NEXT, "getegid32");
	}
	if (root) {
		return(real_getegid32());
	}
	if (debug) fprintf(stderr, "GETEGID32: 0\n");
	return 0;
}
1839 1840 1841
#endif

#if 0
1842
/* maybe we need to interpose on strcmp someday... here is the template */
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
int strcmp(const char *s1, const char *s2) {
	static int (*real_strcmp)(const char *, const char *) = NULL;
	CHECKIT
	if (! real_strcmp) {
		real_strcmp = (int (*)(const char *, const char *)) dlsym(RTLD_NEXT, "strcmp");
	}
	if (debug) fprintf(stderr, "STRCMP: '%s' '%s'\n", s1, s2);
	return(real_strcmp(s1, s2));
}
#endif

1854 1855
#code_end
}