You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vncserver 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. #!/usr/bin/env perl
  2. #
  3. # Copyright (C) 2009-2010 D. R. Commander. All Rights Reserved.
  4. # Copyright (C) 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
  5. # Copyright (C) 2002-2003 Constantin Kaplinsky. All Rights Reserved.
  6. # Copyright (C) 2002-2005 RealVNC Ltd.
  7. # Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
  8. #
  9. # This is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This software is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this software; if not, write to the Free Software
  21. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  22. # USA.
  23. #
  24. #
  25. # vncserver - wrapper script to start an X VNC server.
  26. #
  27. # First make sure we're operating in a sane environment.
  28. $exedir = "";
  29. $slashndx = rindex($0, "/");
  30. if($slashndx>=0) {
  31. $exedir = substr($0, 0, $slashndx+1);
  32. }
  33. &SanityCheck();
  34. #
  35. # Global variables. You may want to configure some of these for
  36. # your site
  37. #
  38. $geometry = "1024x768";
  39. #$depth = 16;
  40. $vncUserDir = "$ENV{HOME}/.vnc";
  41. $vncUserConfig = "$vncUserDir/config";
  42. $vncSystemConfigDir = "/etc/tigervnc";
  43. $vncSystemConfigDefaultsFile = "$vncSystemConfigDir/vncserver-config-defaults";
  44. $vncSystemConfigMandatoryFile = "$vncSystemConfigDir/vncserver-config-mandatory";
  45. $skipxstartup = 0;
  46. $xauthorityFile = "$ENV{XAUTHORITY}" || "$ENV{HOME}/.Xauthority";
  47. $xstartupFile = $vncUserDir . "/xstartup";
  48. $defaultXStartup
  49. = ("#!/bin/sh\n\n".
  50. "unset SESSION_MANAGER\n".
  51. "unset DBUS_SESSION_BUS_ADDRESS\n".
  52. "OS=`uname -s`\n".
  53. "if [ \$OS = 'Linux' ]; then\n".
  54. " case \"\$WINDOWMANAGER\" in\n".
  55. " \*gnome\*)\n".
  56. " if [ -e /etc/SuSE-release ]; then\n".
  57. " PATH=\$PATH:/opt/gnome/bin\n".
  58. " export PATH\n".
  59. " fi\n".
  60. " ;;\n".
  61. " esac\n".
  62. "fi\n".
  63. "if [ -x /etc/X11/xinit/xinitrc ]; then\n".
  64. " exec /etc/X11/xinit/xinitrc\n".
  65. "fi\n".
  66. "if [ -f /etc/X11/xinit/xinitrc ]; then\n".
  67. " exec sh /etc/X11/xinit/xinitrc\n".
  68. "fi\n".
  69. "[ -r \$HOME/.Xresources ] && xrdb \$HOME/.Xresources\n".
  70. "xsetroot -solid grey\n".
  71. "xterm -geometry 80x24+10+10 -ls -title \"\$VNCDESKTOP Desktop\" &\n".
  72. "twm &\n");
  73. $defaultConfig
  74. = ("## Supported server options to pass to vncserver upon invocation can be listed\n".
  75. "## in this file. See the following manpages for more: vncserver(1) Xvnc(1).\n".
  76. "## Several common ones are shown below. Uncomment and modify to your liking.\n".
  77. "##\n".
  78. "# securitytypes=vncauth,tlsvnc\n".
  79. "# desktop=sandbox\n".
  80. "# geometry=2000x1200\n".
  81. "# localhost\n".
  82. "# alwaysshared\n");
  83. chop($host = `uname -n`);
  84. if (-d "/etc/X11/fontpath.d") {
  85. $fontPath = "catalogue:/etc/X11/fontpath.d";
  86. }
  87. @fontpaths = ('/usr/share/X11/fonts', '/usr/share/fonts', '/usr/share/fonts/X11/');
  88. if (! -l "/usr/lib/X11") {push(@fontpaths, '/usr/lib/X11/fonts');}
  89. if (! -l "/usr/X11") {push(@fontpaths, '/usr/X11/lib/X11/fonts');}
  90. if (! -l "/usr/X11R6") {push(@fontpaths, '/usr/X11R6/lib/X11/fonts');}
  91. push(@fontpaths, '/usr/share/fonts/default');
  92. @fonttypes = ('misc',
  93. '75dpi',
  94. '100dpi',
  95. 'Speedo',
  96. 'Type1');
  97. foreach $_fpath (@fontpaths) {
  98. foreach $_ftype (@fonttypes) {
  99. if (-f "$_fpath/$_ftype/fonts.dir") {
  100. if (! -l "$_fpath/$_ftype") {
  101. $defFontPath .= "$_fpath/$_ftype,";
  102. }
  103. }
  104. }
  105. }
  106. if ($defFontPath) {
  107. if (substr($defFontPath, -1, 1) == ',') {
  108. chop $defFontPath;
  109. }
  110. }
  111. if ($fontPath eq "") {
  112. $fontPath = $defFontPath;
  113. }
  114. # Check command line options
  115. &ParseOptions("-geometry",1,"-depth",1,"-pixelformat",1,"-name",1,"-kill",1,
  116. "-help",0,"-h",0,"--help",0,"-fp",1,"-list",0,"-fg",0,"-autokill",0,"-noxstartup",0,"-xstartup",1);
  117. &Usage() if ($opt{'-help'} || $opt{'-h'} || $opt{'--help'});
  118. &Kill() if ($opt{'-kill'});
  119. &List() if ($opt{'-list'});
  120. # Uncomment this line if you want default geometry, depth and pixelformat
  121. # to match the current X display:
  122. # &GetXDisplayDefaults();
  123. if ($opt{'-geometry'}) {
  124. $geometry = $opt{'-geometry'};
  125. }
  126. if ($opt{'-depth'}) {
  127. $depth = $opt{'-depth'};
  128. $pixelformat = "";
  129. }
  130. if ($opt{'-pixelformat'}) {
  131. $pixelformat = $opt{'-pixelformat'};
  132. }
  133. if ($opt{'-noxstartup'}) {
  134. $skipxstartup = 1;
  135. }
  136. if ($opt{'-xstartup'}) {
  137. $xstartupFile = $opt{'-xstartup'};
  138. }
  139. if ($opt{'-fp'}) {
  140. $fontPath = $opt{'-fp'};
  141. $fpArgSpecified = 1;
  142. }
  143. &CheckGeometryAndDepth();
  144. # Create the user's vnc directory if necessary.
  145. if (!(-e $vncUserDir)) {
  146. if (!mkdir($vncUserDir,0755)) {
  147. die "$prog: Could not create $vncUserDir.\n";
  148. }
  149. }
  150. # Find display number.
  151. if ((@ARGV > 0) && ($ARGV[0] =~ /^:(\d+)$/)) {
  152. $displayNumber = $1;
  153. shift(@ARGV);
  154. if (!&CheckDisplayNumber($displayNumber)) {
  155. die "A VNC server is already running as :$displayNumber\n";
  156. }
  157. } elsif ((@ARGV > 0) && ($ARGV[0] !~ /^-/) && ($ARGV[0] !~ /^\+/)) {
  158. &Usage();
  159. } else {
  160. $displayNumber = &GetDisplayNumber();
  161. }
  162. $vncPort = 5900 + $displayNumber;
  163. if ($opt{'-name'}) {
  164. $desktopName = $opt{'-name'};
  165. } else {
  166. $desktopName = "$host:$displayNumber ($ENV{USER})";
  167. }
  168. my %default_opts;
  169. my %config;
  170. # We set some reasonable defaults. Config file settings
  171. # override these where present.
  172. $default_opts{desktop} = &quotedString($desktopName);
  173. $default_opts{auth} = &quotedString($xauthorityFile);
  174. $default_opts{geometry} = $geometry if ($geometry);
  175. $default_opts{depth} = $depth if ($depth);
  176. $default_opts{pixelformat} = $pixelformat if ($pixelformat);
  177. $default_opts{rfbwait} = 30000;
  178. $default_opts{rfbauth} = "$vncUserDir/passwd";
  179. $default_opts{rfbport} = $vncPort;
  180. $default_opts{fp} = $fontPath if ($fontPath);
  181. $default_opts{pn} = "";
  182. # Load user-overrideable system defaults
  183. LoadConfig($vncSystemConfigDefaultsFile);
  184. # Then the user's settings
  185. LoadConfig($vncUserConfig);
  186. # And then override anything set above if mandatory settings exist.
  187. # WARNING: "Mandatory" is used loosely here! As the man page says,
  188. # there is nothing stopping someone from EASILY subverting the
  189. # settings in $vncSystemConfigMandatoryFile by simply passing
  190. # CLI args to vncserver, which trump config files! To properly
  191. # hard force policy in a non-subvertible way would require major
  192. # development work that touches Xvnc itself.
  193. LoadConfig($vncSystemConfigMandatoryFile, 1);
  194. #
  195. # Check whether VNC authentication is enabled, and if so, prompt the user to
  196. # create a VNC password if they don't already have one.
  197. #
  198. $securityTypeArgSpecified = 0;
  199. $vncAuthEnabled = 0;
  200. $passwordArgSpecified = 0;
  201. @vncAuthStrings = ("vncauth", "tlsvnc", "x509vnc");
  202. # ...first we check our configuration files' settings
  203. if ($config{'securitytypes'}) {
  204. $securityTypeArgSpecified = 1;
  205. foreach $arg2 (split(',', $config{'securitytypes'})) {
  206. if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
  207. $vncAuthEnabled = 1;
  208. }
  209. }
  210. }
  211. # ...and finally we check CLI args, which in the case of the topic at
  212. # hand (VNC auth or not), override anything found in configuration files
  213. # (even so-called "mandatory" settings).
  214. for ($i = 0; $i < @ARGV; ++$i) {
  215. # -SecurityTypes can be followed by a space or "="
  216. my @splitargs = split('=', $ARGV[$i]);
  217. if (@splitargs <= 1 && $i < @ARGV - 1) {
  218. push(@splitargs, $ARGV[$i + 1]);
  219. }
  220. if (lc(@splitargs[0]) eq "-securitytypes") {
  221. if (@splitargs > 1) {
  222. $securityTypeArgSpecified = 1;
  223. }
  224. foreach $arg2 (split(',', @splitargs[1])) {
  225. if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
  226. $vncAuthEnabled = 1;
  227. }
  228. }
  229. }
  230. if ((lc(@splitargs[0]) eq "-password")
  231. || (lc(@splitargs[0]) eq "-passwordfile"
  232. || (lc(@splitargs[0]) eq "-rfbauth"))) {
  233. $passwordArgSpecified = 1;
  234. }
  235. }
  236. if ((!$securityTypeArgSpecified || $vncAuthEnabled) && !$passwordArgSpecified) {
  237. ($z,$z,$mode) = stat("$vncUserDir/passwd");
  238. if (!(-e "$vncUserDir/passwd") || ($mode & 077)) {
  239. warn "\nYou will require a password to access your desktops.\n\n";
  240. system($exedir."vncpasswd -q $vncUserDir/passwd");
  241. if (($? >> 8) != 0) {
  242. exit 1;
  243. }
  244. }
  245. }
  246. $desktopLog = "$vncUserDir/$host:$displayNumber.log";
  247. unlink($desktopLog);
  248. # Make an X server cookie and set up the Xauthority file
  249. # mcookie is a part of util-linux, usually only GNU/Linux systems have it.
  250. $cookie = `mcookie`;
  251. # Fallback for non GNU/Linux OS - use /dev/urandom on systems that have it,
  252. # otherwise use perl's random number generator, seeded with the sum
  253. # of the current time, our PID and part of the encrypted form of the password.
  254. if ($cookie eq "" && open(URANDOM, '<', '/dev/urandom')) {
  255. my $randata;
  256. if (sysread(URANDOM, $randata, 16) == 16) {
  257. $cookie = unpack 'h*', $randata;
  258. }
  259. close(URANDOM);
  260. }
  261. if ($cookie eq "") {
  262. srand(time+$$+unpack("L",`cat $vncUserDir/passwd`));
  263. for (1..16) {
  264. $cookie .= sprintf("%02x", int(rand(256)) % 256);
  265. }
  266. }
  267. open(XAUTH, "|xauth -f $xauthorityFile source -");
  268. print XAUTH "add $host:$displayNumber . $cookie\n";
  269. print XAUTH "add $host/unix:$displayNumber . $cookie\n";
  270. close(XAUTH);
  271. # Now start the X VNC Server
  272. # We build up our Xvnc command with options
  273. $cmd = $exedir."Xvnc :$displayNumber";
  274. foreach my $k (sort keys %config) {
  275. $cmd .= " -$k $config{$k}";
  276. delete $default_opts{$k}; # file options take precedence
  277. }
  278. foreach my $k (sort keys %default_opts) {
  279. $cmd .= " -$k $default_opts{$k}";
  280. }
  281. # Add color database stuff here, e.g.:
  282. # $cmd .= " -co /usr/lib/X11/rgb";
  283. foreach $arg (@ARGV) {
  284. $cmd .= " " . &quotedString($arg);
  285. }
  286. $cmd .= " >> " . &quotedString($desktopLog) . " 2>&1";
  287. # Run $cmd and record the process ID.
  288. $pidFile = "$vncUserDir/$host:$displayNumber.pid";
  289. system("$cmd & echo \$! >$pidFile");
  290. # Give Xvnc a chance to start up
  291. sleep(3);
  292. if ($fontPath ne $defFontPath) {
  293. unless (kill 0, `cat $pidFile`) {
  294. if ($fpArgSpecified) {
  295. warn "\nWARNING: The first attempt to start Xvnc failed, probably because the font\n";
  296. warn "path you specified using the -fp argument is incorrect. Attempting to\n";
  297. warn "determine an appropriate font path for this system and restart Xvnc using\n";
  298. warn "that font path ...\n";
  299. } else {
  300. warn "\nWARNING: The first attempt to start Xvnc failed, possibly because the font\n";
  301. warn "catalog is not properly configured. Attempting to determine an appropriate\n";
  302. warn "font path for this system and restart Xvnc using that font path ...\n";
  303. }
  304. $cmd =~ s@-fp [^ ]+@@;
  305. $cmd .= " -fp $defFontPath" if ($defFontPath);
  306. system("$cmd & echo \$! >$pidFile");
  307. sleep(3);
  308. }
  309. }
  310. unless (kill 0, `cat $pidFile`) {
  311. warn "Could not start Xvnc.\n\n";
  312. unlink $pidFile;
  313. open(LOG, "<$desktopLog");
  314. while (<LOG>) { print; }
  315. close(LOG);
  316. die "\n";
  317. }
  318. warn "\nNew '$desktopName' desktop is $host:$displayNumber\n\n";
  319. # Create the user's xstartup script if necessary.
  320. if (! $skipxstartup) {
  321. if (!(-e "$xstartupFile")) {
  322. warn "Creating default startup script $xstartupFile\n";
  323. open(XSTARTUP, ">$xstartupFile");
  324. print XSTARTUP $defaultXStartup;
  325. close(XSTARTUP);
  326. chmod 0755, "$xstartupFile";
  327. }
  328. }
  329. # Create the user's config file if necessary.
  330. if (!(-e "$vncUserDir/config")) {
  331. warn "Creating default config $vncUserDir/config\n";
  332. open(VNCUSERCONFIG, ">$vncUserDir/config");
  333. print VNCUSERCONFIG $defaultConfig;
  334. close(VNCUSERCONFIG);
  335. chmod 0644, "$vncUserDir/config";
  336. }
  337. # Run the X startup script.
  338. if (! $skipxstartup) {
  339. warn "Starting applications specified in $xstartupFile\n";
  340. }
  341. warn "Log file is $desktopLog\n\n";
  342. # If the unix domain socket exists then use that (DISPLAY=:n) otherwise use
  343. # TCP (DISPLAY=host:n)
  344. if (-e "/tmp/.X11-unix/X$displayNumber" ||
  345. -e "/usr/spool/sockets/X11/$displayNumber")
  346. {
  347. $ENV{DISPLAY}= ":$displayNumber";
  348. } else {
  349. $ENV{DISPLAY}= "$host:$displayNumber";
  350. }
  351. $ENV{VNCDESKTOP}= $desktopName;
  352. if ($opt{'-fg'}) {
  353. if (! $skipxstartup) {
  354. system("$xstartupFile >> " . &quotedString($desktopLog) . " 2>&1");
  355. }
  356. if (kill 0, `cat $pidFile`) {
  357. $opt{'-kill'} = ':'.$displayNumber;
  358. &Kill();
  359. }
  360. } else {
  361. if ($opt{'-autokill'}) {
  362. if (! $skipxstartup) {
  363. system("($xstartupFile; $0 -kill :$displayNumber) >> "
  364. . &quotedString($desktopLog) . " 2>&1 &");
  365. }
  366. } else {
  367. if (! $skipxstartup) {
  368. system("$xstartupFile >> " . &quotedString($desktopLog)
  369. . " 2>&1 &");
  370. }
  371. }
  372. }
  373. exit;
  374. ###############################################################################
  375. # Functions
  376. ###############################################################################
  377. #
  378. # Populate the global %config hash with settings from a specified
  379. # vncserver configuration file if it exists
  380. #
  381. # Args: 1. file path
  382. # 2. optional boolean flag to enable warning when a previously
  383. # set configuration setting is being overridden
  384. #
  385. sub LoadConfig {
  386. local ($configFile, $warnoverride) = @_;
  387. local ($toggle) = undef;
  388. if (stat($configFile)) {
  389. if (open(IN, $configFile)) {
  390. while (<IN>) {
  391. next if /^#/;
  392. if (my ($k, $v) = /^\s*(\w+)\s*=\s*(.+)$/) {
  393. $k = lc($k); # must normalize key case
  394. if ($warnoverride && $config{$k}) {
  395. print("Warning: $configFile is overriding previously defined '$k' to be '$v'\n");
  396. }
  397. $config{$k} = $v;
  398. } elsif ($_ =~ m/^\s*(\S+)/) {
  399. # We can't reasonably warn on override of toggles (e.g. AlwaysShared)
  400. # because it would get crazy to do so. We'd have to check if the
  401. # current config file being loaded defined the logical opposite setting
  402. # (NeverShared vs. AlwaysShared, etc etc).
  403. $toggle = lc($1); # must normalize key case
  404. $config{$toggle} = $k;
  405. }
  406. }
  407. close(IN);
  408. }
  409. }
  410. }
  411. #
  412. # CheckGeometryAndDepth simply makes sure that the geometry and depth values
  413. # are sensible.
  414. #
  415. sub CheckGeometryAndDepth
  416. {
  417. if ($geometry =~ /^(\d+)x(\d+)$/) {
  418. $width = $1; $height = $2;
  419. if (($width<1) || ($height<1)) {
  420. die "$prog: geometry $geometry is invalid\n";
  421. }
  422. $geometry = "${width}x$height";
  423. } else {
  424. die "$prog: geometry $geometry is invalid\n";
  425. }
  426. if ($depth && (($depth < 8) || ($depth > 32))) {
  427. die "Depth must be between 8 and 32\n";
  428. }
  429. }
  430. #
  431. # GetDisplayNumber gets the lowest available display number. A display number
  432. # n is taken if something is listening on the VNC server port (5900+n) or the
  433. # X server port (6000+n).
  434. #
  435. sub GetDisplayNumber
  436. {
  437. foreach $n (1..99) {
  438. if (&CheckDisplayNumber($n)) {
  439. return $n+0; # Bruce Mah's workaround for bug in perl 5.005_02
  440. }
  441. }
  442. die "$prog: no free display number on $host.\n";
  443. }
  444. #
  445. # CheckDisplayNumber checks if the given display number is available. A
  446. # display number n is taken if something is listening on the VNC server port
  447. # (5900+n) or the X server port (6000+n).
  448. #
  449. sub CheckDisplayNumber
  450. {
  451. local ($n) = @_;
  452. socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
  453. eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
  454. if (!bind(S, pack('S n x12', $AF_INET, 6000 + $n))) {
  455. close(S);
  456. return 0;
  457. }
  458. close(S);
  459. socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
  460. eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
  461. if (!bind(S, pack('S n x12', $AF_INET, 5900 + $n))) {
  462. close(S);
  463. return 0;
  464. }
  465. close(S);
  466. if (-e "/tmp/.X$n-lock") {
  467. warn "\nWarning: $host:$n is taken because of /tmp/.X$n-lock\n";
  468. warn "Remove this file if there is no X server $host:$n\n";
  469. return 0;
  470. }
  471. if (-e "/tmp/.X11-unix/X$n") {
  472. warn "\nWarning: $host:$n is taken because of /tmp/.X11-unix/X$n\n";
  473. warn "Remove this file if there is no X server $host:$n\n";
  474. return 0;
  475. }
  476. if (-e "/usr/spool/sockets/X11/$n") {
  477. warn("\nWarning: $host:$n is taken because of ".
  478. "/usr/spool/sockets/X11/$n\n");
  479. warn "Remove this file if there is no X server $host:$n\n";
  480. return 0;
  481. }
  482. return 1;
  483. }
  484. #
  485. # GetXDisplayDefaults uses xdpyinfo to find out the geometry, depth and pixel
  486. # format of the current X display being used. If successful, it sets the
  487. # options as appropriate so that the X VNC server will use the same settings
  488. # (minus an allowance for window manager decorations on the geometry). Using
  489. # the same depth and pixel format means that the VNC server won't have to
  490. # translate pixels when the desktop is being viewed on this X display (for
  491. # TrueColor displays anyway).
  492. #
  493. sub GetXDisplayDefaults
  494. {
  495. local (@lines, @matchlines, $width, $height, $defaultVisualId, $i,
  496. $red, $green, $blue);
  497. $wmDecorationWidth = 4; # a guess at typical size for window manager
  498. $wmDecorationHeight = 24; # decoration size
  499. return if (!defined($ENV{DISPLAY}));
  500. @lines = `xdpyinfo 2>/dev/null`;
  501. return if ($? != 0);
  502. @matchlines = grep(/dimensions/, @lines);
  503. if (@matchlines) {
  504. ($width, $height) = ($matchlines[0] =~ /(\d+)x(\d+) pixels/);
  505. $width -= $wmDecorationWidth;
  506. $height -= $wmDecorationHeight;
  507. $geometry = "${width}x$height";
  508. }
  509. @matchlines = grep(/default visual id/, @lines);
  510. if (@matchlines) {
  511. ($defaultVisualId) = ($matchlines[0] =~ /id:\s+(\S+)/);
  512. for ($i = 0; $i < @lines; $i++) {
  513. if ($lines[$i] =~ /^\s*visual id:\s+$defaultVisualId$/) {
  514. if (($lines[$i+1] !~ /TrueColor/) ||
  515. ($lines[$i+2] !~ /depth/) ||
  516. ($lines[$i+4] !~ /red, green, blue masks/))
  517. {
  518. return;
  519. }
  520. last;
  521. }
  522. }
  523. return if ($i >= @lines);
  524. ($depth) = ($lines[$i+2] =~ /depth:\s+(\d+)/);
  525. ($red,$green,$blue)
  526. = ($lines[$i+4]
  527. =~ /masks:\s+0x([0-9a-f]+), 0x([0-9a-f]+), 0x([0-9a-f]+)/);
  528. $red = hex($red);
  529. $green = hex($green);
  530. $blue = hex($blue);
  531. if ($red > $blue) {
  532. $red = int(log($red) / log(2)) - int(log($green) / log(2));
  533. $green = int(log($green) / log(2)) - int(log($blue) / log(2));
  534. $blue = int(log($blue) / log(2)) + 1;
  535. $pixelformat = "rgb$red$green$blue";
  536. } else {
  537. $blue = int(log($blue) / log(2)) - int(log($green) / log(2));
  538. $green = int(log($green) / log(2)) - int(log($red) / log(2));
  539. $red = int(log($red) / log(2)) + 1;
  540. $pixelformat = "bgr$blue$green$red";
  541. }
  542. }
  543. }
  544. #
  545. # quotedString returns a string which yields the original string when parsed
  546. # by a shell.
  547. #
  548. sub quotedString
  549. {
  550. local ($in) = @_;
  551. $in =~ s/\'/\'\"\'\"\'/g;
  552. return "'$in'";
  553. }
  554. #
  555. # removeSlashes turns slashes into underscores for use as a file name.
  556. #
  557. sub removeSlashes
  558. {
  559. local ($in) = @_;
  560. $in =~ s|/|_|g;
  561. return "$in";
  562. }
  563. #
  564. # Usage
  565. #
  566. sub Usage
  567. {
  568. die("\nusage: $prog [:<number>] [-name <desktop-name>] [-depth <depth>]\n".
  569. " [-geometry <width>x<height>]\n".
  570. " [-pixelformat rgbNNN|bgrNNN]\n".
  571. " [-fp <font-path>]\n".
  572. " [-fg]\n".
  573. " [-autokill]\n".
  574. " [-noxstartup]\n".
  575. " [-xstartup <file>]\n".
  576. " <Xvnc-options>...\n\n".
  577. " $prog -kill <X-display>\n\n".
  578. " $prog -list\n\n");
  579. }
  580. #
  581. # List
  582. #
  583. sub List
  584. {
  585. opendir(dir, $vncUserDir);
  586. my @filelist = readdir(dir);
  587. closedir(dir);
  588. print "\nTigerVNC server sessions:\n\n";
  589. print "X DISPLAY #\tPROCESS ID\n";
  590. foreach my $file (@filelist) {
  591. if ($file =~ /$host:(\d+)$\.pid/) {
  592. chop($tmp_pid = `cat $vncUserDir/$file`);
  593. if (kill 0, $tmp_pid) {
  594. print ":".$1."\t\t".`cat $vncUserDir/$file`;
  595. } else {
  596. unlink ($vncUserDir . "/" . $file);
  597. }
  598. }
  599. }
  600. exit;
  601. }
  602. #
  603. # Kill
  604. #
  605. sub Kill
  606. {
  607. $opt{'-kill'} =~ s/(:\d+)\.\d+$/$1/; # e.g. turn :1.0 into :1
  608. if ($opt{'-kill'} =~ /^:\d+$/) {
  609. $pidFile = "$vncUserDir/$host$opt{'-kill'}.pid";
  610. } else {
  611. if ($opt{'-kill'} !~ /^$host:/) {
  612. die "\nCan't tell if $opt{'-kill'} is on $host\n".
  613. "Use -kill :<number> instead\n\n";
  614. }
  615. $pidFile = "$vncUserDir/$opt{'-kill'}.pid";
  616. }
  617. if (! -r $pidFile) {
  618. die "\nCan't find file $pidFile\n".
  619. "You'll have to kill the Xvnc process manually\n\n";
  620. }
  621. $SIG{'HUP'} = 'IGNORE';
  622. chop($pid = `cat $pidFile`);
  623. warn "Killing Xvnc process ID $pid\n";
  624. if (kill 0, $pid) {
  625. system("kill $pid");
  626. sleep(1);
  627. if (kill 0, $pid) {
  628. print "Xvnc seems to be deadlocked. Kill the process manually and then re-run\n";
  629. print " ".$0." -kill ".$opt{'-kill'}."\n";
  630. print "to clean up the socket files.\n";
  631. exit
  632. }
  633. } else {
  634. warn "Xvnc process ID $pid already killed\n";
  635. $opt{'-kill'} =~ s/://;
  636. if (-e "/tmp/.X11-unix/X$opt{'-kill'}") {
  637. print "Xvnc did not appear to shut down cleanly.";
  638. print " Removing /tmp/.X11-unix/X$opt{'-kill'}\n";
  639. unlink "/tmp/.X11-unix/X$opt{'-kill'}";
  640. }
  641. if (-e "/tmp/.X$opt{'-kill'}-lock") {
  642. print "Xvnc did not appear to shut down cleanly.";
  643. print " Removing /tmp/.X$opt{'-kill'}-lock\n";
  644. unlink "/tmp/.X$opt{'-kill'}-lock";
  645. }
  646. }
  647. unlink $pidFile;
  648. exit;
  649. }
  650. #
  651. # ParseOptions takes a list of possible options and a boolean indicating
  652. # whether the option has a value following, and sets up an associative array
  653. # %opt of the values of the options given on the command line. It removes all
  654. # the arguments it uses from @ARGV and returns them in @optArgs.
  655. #
  656. sub ParseOptions
  657. {
  658. local (@optval) = @_;
  659. local ($opt, @opts, %valFollows, @newargs);
  660. while (@optval) {
  661. $opt = shift(@optval);
  662. push(@opts,$opt);
  663. $valFollows{$opt} = shift(@optval);
  664. }
  665. @optArgs = ();
  666. %opt = ();
  667. arg: while (defined($arg = shift(@ARGV))) {
  668. foreach $opt (@opts) {
  669. if ($arg eq $opt) {
  670. push(@optArgs, $arg);
  671. if ($valFollows{$opt}) {
  672. if (@ARGV == 0) {
  673. &Usage();
  674. }
  675. $opt{$opt} = shift(@ARGV);
  676. push(@optArgs, $opt{$opt});
  677. } else {
  678. $opt{$opt} = 1;
  679. }
  680. next arg;
  681. }
  682. }
  683. push(@newargs,$arg);
  684. }
  685. @ARGV = @newargs;
  686. }
  687. # Routine to make sure we're operating in a sane environment.
  688. sub SanityCheck
  689. {
  690. local ($cmd);
  691. # Get the program name
  692. ($prog) = ($0 =~ m|([^/]+)$|);
  693. #
  694. # Check we have all the commands we'll need on the path.
  695. #
  696. cmd:
  697. foreach $cmd ("uname","xauth") {
  698. for (split(/:/,$ENV{PATH})) {
  699. if (-x "$_/$cmd") {
  700. next cmd;
  701. }
  702. }
  703. die "$prog: couldn't find \"$cmd\" on your PATH.\n";
  704. }
  705. if($exedir eq "") {
  706. cmd2:
  707. foreach $cmd ("Xvnc","vncpasswd") {
  708. for (split(/:/,$ENV{PATH})) {
  709. if (-x "$_/$cmd") {
  710. next cmd2;
  711. }
  712. }
  713. die "$prog: couldn't find \"$cmd\" on your PATH.\n";
  714. }
  715. }
  716. else {
  717. cmd3:
  718. foreach $cmd ($exedir."Xvnc",$exedir."vncpasswd") {
  719. for (split(/:/,$ENV{PATH})) {
  720. if (-x "$cmd") {
  721. next cmd3;
  722. }
  723. }
  724. die "$prog: couldn't find \"$cmd\".\n";
  725. }
  726. }
  727. if (!defined($ENV{HOME})) {
  728. die "$prog: The HOME environment variable is not set.\n";
  729. }
  730. #
  731. # Find socket constants. 'use Socket' is a perl5-ism, so we wrap it in an
  732. # eval, and if it fails we try 'require "sys/socket.ph"'. If this fails,
  733. # we just guess at the values. If you find perl moaning here, just
  734. # hard-code the values of AF_INET and SOCK_STREAM. You can find these out
  735. # for your platform by looking in /usr/include/sys/socket.h and related
  736. # files.
  737. #
  738. chop($os = `uname`);
  739. chop($osrev = `uname -r`);
  740. eval 'use Socket';
  741. if ($@) {
  742. eval 'require "sys/socket.ph"';
  743. if ($@) {
  744. if (($os eq "SunOS") && ($osrev !~ /^4/)) {
  745. $AF_INET = 2;
  746. $SOCK_STREAM = 2;
  747. } else {
  748. $AF_INET = 2;
  749. $SOCK_STREAM = 1;
  750. }
  751. } else {
  752. $AF_INET = &AF_INET;
  753. $SOCK_STREAM = &SOCK_STREAM;
  754. }
  755. } else {
  756. $AF_INET = &AF_INET;
  757. $SOCK_STREAM = &SOCK_STREAM;
  758. }
  759. }