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

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