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.

vncviewer.cxx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2011 Pierre Ossman <ossman@cendio.se> for Cendio AB
  3. * Copyright (C) 2011 D. R. Commander. All Rights Reserved.
  4. *
  5. * This is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This software is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this software; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  18. * USA.
  19. */
  20. #ifdef HAVE_CONFIG_H
  21. #include <config.h>
  22. #endif
  23. #include <string.h>
  24. #include <stdio.h>
  25. #include <ctype.h>
  26. #include <stdlib.h>
  27. #include <errno.h>
  28. #include <signal.h>
  29. #include <locale.h>
  30. #include <fcntl.h>
  31. #include <sys/stat.h>
  32. #ifdef WIN32
  33. #include <os/winerrno.h>
  34. #include <direct.h>
  35. #define mkdir(path, mode) _mkdir(path)
  36. #endif
  37. #if !defined(WIN32) && !defined(__APPLE__)
  38. #include <X11/Xlib.h>
  39. #include <X11/XKBlib.h>
  40. #endif
  41. #include <rfb/Logger_stdio.h>
  42. #include <rfb/SecurityClient.h>
  43. #include <rfb/Security.h>
  44. #ifdef HAVE_GNUTLS
  45. #include <rfb/CSecurityTLS.h>
  46. #endif
  47. #include <rfb/LogWriter.h>
  48. #include <rfb/Timer.h>
  49. #include <rfb/Exception.h>
  50. #include <network/TcpSocket.h>
  51. #include <os/os.h>
  52. #include <FL/Fl.H>
  53. #include <FL/Fl_Widget.H>
  54. #include <FL/Fl_PNG_Image.H>
  55. #include <FL/fl_ask.H>
  56. #include <FL/x.H>
  57. #include "i18n.h"
  58. #include "parameters.h"
  59. #include "CConn.h"
  60. #include "ServerDialog.h"
  61. #include "UserDialog.h"
  62. #include "vncviewer.h"
  63. #ifdef WIN32
  64. #include "resource.h"
  65. #include "win32.h"
  66. #endif
  67. rfb::LogWriter vlog("main");
  68. using namespace network;
  69. using namespace rfb;
  70. using namespace std;
  71. static char aboutText[1024];
  72. char vncServerName[VNCSERVERNAMELEN] = { '\0' };
  73. static bool exitMainloop = false;
  74. static const char *exitError = NULL;
  75. void exit_vncviewer(const char *error)
  76. {
  77. // Prioritise the first error we get as that is probably the most
  78. // relevant one.
  79. if ((error != NULL) && (exitError == NULL))
  80. exitError = strdup(error);
  81. exitMainloop = true;
  82. }
  83. void about_vncviewer()
  84. {
  85. fl_message_title(_("About TigerVNC Viewer"));
  86. fl_message("%s", aboutText);
  87. }
  88. static void about_callback(Fl_Widget *widget, void *data)
  89. {
  90. about_vncviewer();
  91. }
  92. static void CleanupSignalHandler(int sig)
  93. {
  94. // CleanupSignalHandler allows C++ object cleanup to happen because it calls
  95. // exit() rather than the default which is to abort.
  96. vlog.info(_("Termination signal %d has been received. TigerVNC Viewer will now exit."), sig);
  97. exit(1);
  98. }
  99. static void init_fltk()
  100. {
  101. // Basic text size (10pt @ 96 dpi => 13px)
  102. FL_NORMAL_SIZE = 13;
  103. #ifndef __APPLE__
  104. // Select a FLTK scheme and background color that looks somewhat
  105. // close to modern Linux and Windows.
  106. Fl::scheme("gtk+");
  107. Fl::background(220, 220, 220);
  108. #else
  109. // On Mac OS X there is another scheme that fits better though.
  110. Fl::scheme("plastic");
  111. #endif
  112. // Proper Gnome Shell integration requires that we set a sensible
  113. // WM_CLASS for the window.
  114. Fl_Window::default_xclass("vncviewer");
  115. // Set the default icon for all windows.
  116. #ifdef HAVE_FLTK_ICONS
  117. #ifdef WIN32
  118. HICON lg, sm;
  119. lg = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON),
  120. IMAGE_ICON, GetSystemMetrics(SM_CXICON),
  121. GetSystemMetrics(SM_CYICON),
  122. LR_DEFAULTCOLOR | LR_SHARED);
  123. sm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON),
  124. IMAGE_ICON, GetSystemMetrics(SM_CXSMICON),
  125. GetSystemMetrics(SM_CYSMICON),
  126. LR_DEFAULTCOLOR | LR_SHARED);
  127. Fl_Window::default_icons(lg, sm);
  128. #elif ! defined(__APPLE__)
  129. const int icon_sizes[] = {48, 32, 24, 16};
  130. Fl_PNG_Image *icons[4];
  131. int count;
  132. count = 0;
  133. // FIXME: Follow icon theme specification
  134. for (size_t i = 0;i < sizeof(icon_sizes)/sizeof(icon_sizes[0]);i++) {
  135. char icon_path[PATH_MAX];
  136. bool exists;
  137. sprintf(icon_path, "%s/icons/hicolor/%dx%d/apps/tigervnc.png",
  138. DATA_DIR, icon_sizes[i], icon_sizes[i]);
  139. #ifndef WIN32
  140. struct stat st;
  141. if (stat(icon_path, &st) != 0)
  142. #else
  143. struct _stat st;
  144. if (_stat(icon_path, &st) != 0)
  145. return(false);
  146. #endif
  147. exists = false;
  148. else
  149. exists = true;
  150. if (exists) {
  151. icons[count] = new Fl_PNG_Image(icon_path);
  152. if (icons[count]->w() == 0 ||
  153. icons[count]->h() == 0 ||
  154. icons[count]->d() != 4) {
  155. delete icons[count];
  156. continue;
  157. }
  158. count++;
  159. }
  160. }
  161. Fl_Window::default_icons((const Fl_RGB_Image**)icons, count);
  162. for (int i = 0;i < count;i++)
  163. delete icons[i];
  164. #endif
  165. #endif // FLTK_HAVE_ICONS
  166. // This makes the "icon" in dialogs rounded, which fits better
  167. // with the above schemes.
  168. fl_message_icon()->box(FL_UP_BOX);
  169. // Turn off the annoying behaviour where popups track the mouse.
  170. fl_message_hotspot(false);
  171. // Avoid empty titles for popups
  172. fl_message_title_default(_("TigerVNC Viewer"));
  173. #ifdef WIN32
  174. // Most "normal" Windows apps use this font for UI elements.
  175. Fl::set_font(FL_HELVETICA, "Tahoma");
  176. #endif
  177. // FLTK exposes these so that we can translate them.
  178. fl_no = _("No");
  179. fl_yes = _("Yes");
  180. fl_ok = _("OK");
  181. fl_cancel = _("Cancel");
  182. fl_close = _("Close");
  183. #ifdef __APPLE__
  184. /* Needs trailing space */
  185. static char fltk_about[16];
  186. snprintf(fltk_about, sizeof(fltk_about), "%s ", _("About"));
  187. Fl_Mac_App_Menu::about = fltk_about;
  188. static char fltk_hide[16];
  189. snprintf(fltk_hide, sizeof(fltk_hide), "%s ", _("Hide"));
  190. Fl_Mac_App_Menu::hide = fltk_hide;
  191. static char fltk_quit[16];
  192. snprintf(fltk_quit, sizeof(fltk_quit), "%s ", _("Quit"));
  193. Fl_Mac_App_Menu::quit = fltk_quit;
  194. Fl_Mac_App_Menu::print = ""; // Don't want the print item
  195. Fl_Mac_App_Menu::services = _("Services");
  196. Fl_Mac_App_Menu::hide_others = _("Hide Others");
  197. Fl_Mac_App_Menu::show = _("Show All");
  198. fl_mac_set_about(about_callback, NULL);
  199. #endif
  200. }
  201. static void mkvnchomedir()
  202. {
  203. // Create .vnc in the user's home directory if it doesn't already exist
  204. char* homeDir = NULL;
  205. if (getvnchomedir(&homeDir) == -1) {
  206. vlog.error(_("Could not create VNC home directory: can't obtain home "
  207. "directory path."));
  208. } else {
  209. int result = mkdir(homeDir, 0755);
  210. if (result == -1 && errno != EEXIST)
  211. vlog.error(_("Could not create VNC home directory: %s."), strerror(errno));
  212. delete [] homeDir;
  213. }
  214. }
  215. static void usage(const char *programName)
  216. {
  217. #ifdef WIN32
  218. // If we don't have a console then we need to create one for output
  219. if (GetConsoleWindow() == NULL) {
  220. HANDLE handle;
  221. int fd;
  222. AllocConsole();
  223. handle = GetStdHandle(STD_ERROR_HANDLE);
  224. fd = _open_osfhandle((intptr_t)handle, O_TEXT);
  225. *stderr = *fdopen(fd, "w");
  226. }
  227. #endif
  228. fprintf(stderr,
  229. "\nusage: %s [parameters] [host:displayNum] [parameters]\n"
  230. " %s [parameters] -listen [port] [parameters]\n",
  231. programName, programName);
  232. fprintf(stderr,"\n"
  233. "Parameters can be turned on with -<param> or off with -<param>=0\n"
  234. "Parameters which take a value can be specified as "
  235. "-<param> <value>\n"
  236. "Other valid forms are <param>=<value> -<param>=<value> "
  237. "--<param>=<value>\n"
  238. "Parameter names are case-insensitive. The parameters are:\n\n");
  239. Configuration::listParams(79, 14);
  240. #ifdef WIN32
  241. // Just wait for the user to kill the console window
  242. Sleep(INFINITE);
  243. #endif
  244. exit(1);
  245. }
  246. #ifndef WIN32
  247. static int
  248. interpretViaParam(char *remoteHost, int *remotePort, int localPort)
  249. {
  250. const int SERVER_PORT_OFFSET = 5900;
  251. char *pos = strchr(vncServerName, ':');
  252. if (pos == NULL)
  253. *remotePort = SERVER_PORT_OFFSET;
  254. else {
  255. int portOffset = SERVER_PORT_OFFSET;
  256. size_t len;
  257. *pos++ = '\0';
  258. len = strlen(pos);
  259. if (*pos == ':') {
  260. /* Two colons is an absolute port number, not an offset. */
  261. pos++;
  262. len--;
  263. portOffset = 0;
  264. }
  265. if (!len || strspn (pos, "-0123456789") != len )
  266. return 1;
  267. *remotePort = atoi(pos) + portOffset;
  268. }
  269. if (*vncServerName != '\0')
  270. strncpy(remoteHost, vncServerName, VNCSERVERNAMELEN);
  271. else
  272. strncpy(remoteHost, "localhost", VNCSERVERNAMELEN);
  273. remoteHost[VNCSERVERNAMELEN - 1] = '\0';
  274. snprintf(vncServerName, VNCSERVERNAMELEN, "localhost::%d", localPort);
  275. vncServerName[VNCSERVERNAMELEN - 1] = '\0';
  276. return 0;
  277. }
  278. static void
  279. createTunnel(const char *gatewayHost, const char *remoteHost,
  280. int remotePort, int localPort)
  281. {
  282. const char *cmd = getenv("VNC_VIA_CMD");
  283. char *cmd2, *percent;
  284. char lport[10], rport[10];
  285. sprintf(lport, "%d", localPort);
  286. sprintf(rport, "%d", remotePort);
  287. setenv("G", gatewayHost, 1);
  288. setenv("H", remoteHost, 1);
  289. setenv("R", rport, 1);
  290. setenv("L", lport, 1);
  291. if (!cmd)
  292. cmd = "/usr/bin/ssh -f -L \"$L\":\"$H\":\"$R\" \"$G\" sleep 20";
  293. /* Compatibility with TigerVNC's method. */
  294. cmd2 = strdup(cmd);
  295. while ((percent = strchr(cmd2, '%')) != NULL)
  296. *percent = '$';
  297. system(cmd2);
  298. free(cmd2);
  299. }
  300. static int mktunnel()
  301. {
  302. const char *gatewayHost;
  303. char remoteHost[VNCSERVERNAMELEN];
  304. int localPort = findFreeTcpPort();
  305. int remotePort;
  306. gatewayHost = strDup(via.getValueStr());
  307. if (interpretViaParam(remoteHost, &remotePort, localPort) != 0)
  308. return 1;
  309. createTunnel(gatewayHost, remoteHost, remotePort, localPort);
  310. return 0;
  311. }
  312. #endif /* !WIN32 */
  313. int main(int argc, char** argv)
  314. {
  315. UserDialog dlg;
  316. setlocale(LC_ALL, "");
  317. bindtextdomain(PACKAGE_NAME, LOCALE_DIR);
  318. textdomain(PACKAGE_NAME);
  319. // Generate the about string now that we get the proper translation
  320. snprintf(aboutText, sizeof(aboutText),
  321. _("TigerVNC Viewer %d-bit v%s\n"
  322. "Built on: %s\n"
  323. "Copyright (C) 1999-%d TigerVNC Team and many others (see README.txt)\n"
  324. "See http://www.tigervnc.org for information on TigerVNC."),
  325. (int)sizeof(size_t)*8, PACKAGE_VERSION,
  326. BUILD_TIMESTAMP, 2015);
  327. rfb::SecurityClient::setDefaults();
  328. // Write about text to console, still using normal locale codeset
  329. fprintf(stderr,"\n%s\n", aboutText);
  330. // Set gettext codeset to what our GUI toolkit uses. Since we are
  331. // passing strings from strerror/gai_strerror to the GUI, these must
  332. // be in GUI codeset as well.
  333. bind_textdomain_codeset(PACKAGE_NAME, "UTF-8");
  334. bind_textdomain_codeset("libc", "UTF-8");
  335. rfb::initStdIOLoggers();
  336. #ifdef WIN32
  337. rfb::initFileLogger("C:\\temp\\vncviewer.log");
  338. #else
  339. rfb::initFileLogger("/tmp/vncviewer.log");
  340. #endif
  341. rfb::LogWriter::setLogParams("*:stderr:30");
  342. #ifdef SIGHUP
  343. signal(SIGHUP, CleanupSignalHandler);
  344. #endif
  345. signal(SIGINT, CleanupSignalHandler);
  346. signal(SIGTERM, CleanupSignalHandler);
  347. init_fltk();
  348. #if !defined(WIN32) && !defined(__APPLE__)
  349. fl_open_display();
  350. XkbSetDetectableAutoRepeat(fl_display, True, NULL);
  351. #endif
  352. Configuration::enableViewerParams();
  353. /* Load the default parameter settings */
  354. const char* defaultServerName;
  355. try {
  356. defaultServerName = loadViewerParameters(NULL);
  357. } catch (rfb::Exception& e) {
  358. defaultServerName = "";
  359. fl_alert("%s", e.str());
  360. }
  361. int i = 1;
  362. if (!Fl::args(argc, argv, i) || i < argc)
  363. for (; i < argc; i++) {
  364. if (Configuration::setParam(argv[i]))
  365. continue;
  366. if (argv[i][0] == '-') {
  367. if (i+1 < argc) {
  368. if (Configuration::setParam(&argv[i][1], argv[i+1])) {
  369. i++;
  370. continue;
  371. }
  372. }
  373. usage(argv[0]);
  374. }
  375. strncpy(vncServerName, argv[i], VNCSERVERNAMELEN);
  376. vncServerName[VNCSERVERNAMELEN - 1] = '\0';
  377. }
  378. if (!::autoSelect.hasBeenSet()) {
  379. // Default to AutoSelect=0 if -PreferredEncoding or -FullColor is used
  380. if (::preferredEncoding.hasBeenSet() || ::fullColour.hasBeenSet() ||
  381. ::fullColourAlias.hasBeenSet()) {
  382. ::autoSelect.setParam(false);
  383. }
  384. }
  385. if (!::fullColour.hasBeenSet() && !::fullColourAlias.hasBeenSet()) {
  386. // Default to FullColor=0 if AutoSelect=0 && LowColorLevel is set
  387. if (!::autoSelect && (::lowColourLevel.hasBeenSet() ||
  388. ::lowColourLevelAlias.hasBeenSet())) {
  389. ::fullColour.setParam(false);
  390. }
  391. }
  392. if (!::customCompressLevel.hasBeenSet()) {
  393. // Default to CustomCompressLevel=1 if CompressLevel is used.
  394. if(::compressLevel.hasBeenSet()) {
  395. ::customCompressLevel.setParam(true);
  396. }
  397. }
  398. mkvnchomedir();
  399. CSecurity::upg = &dlg;
  400. #ifdef HAVE_GNUTLS
  401. CSecurityTLS::msg = &dlg;
  402. #endif
  403. Socket *sock = NULL;
  404. #ifndef WIN32
  405. /* Specifying -via and -listen together is nonsense */
  406. if (listenMode && strlen(via.getValueStr()) > 0) {
  407. // TRANSLATORS: "Parameters" are command line arguments, or settings
  408. // from a file or the Windows registry.
  409. vlog.error(_("Parameters -listen and -via are incompatible"));
  410. fl_alert(_("Parameters -listen and -via are incompatible"));
  411. exit_vncviewer();
  412. return 1;
  413. }
  414. #endif
  415. if (listenMode) {
  416. try {
  417. int port = 5500;
  418. if (isdigit(vncServerName[0]))
  419. port = atoi(vncServerName);
  420. TcpListener listener(NULL, port);
  421. vlog.info(_("Listening on port %d\n"), port);
  422. sock = listener.accept();
  423. } catch (rdr::Exception& e) {
  424. vlog.error("%s", e.str());
  425. fl_alert("%s", e.str());
  426. exit_vncviewer();
  427. return 1;
  428. }
  429. } else {
  430. if (vncServerName[0] == '\0') {
  431. ServerDialog::run(defaultServerName, vncServerName);
  432. if (vncServerName[0] == '\0')
  433. return 1;
  434. }
  435. #ifndef WIN32
  436. if (strlen (via.getValueStr()) > 0 && mktunnel() != 0)
  437. usage(argv[0]);
  438. #endif
  439. }
  440. CConn *cc = new CConn(vncServerName, sock);
  441. while (!exitMainloop) {
  442. int next_timer;
  443. next_timer = Timer::checkTimeouts();
  444. if (next_timer == 0)
  445. next_timer = INT_MAX;
  446. if (Fl::wait((double)next_timer / 1000.0) < 0.0) {
  447. vlog.error(_("Internal FLTK error. Exiting."));
  448. break;
  449. }
  450. }
  451. delete cc;
  452. if (exitError != NULL)
  453. fl_alert("%s", exitError);
  454. return 0;
  455. }