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.

x0vncserver.cxx 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright (C) 2004-2008 Constantin Kaplinsky. All Rights Reserved.
  3. *
  4. * This is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This software is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this software; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  17. * USA.
  18. */
  19. // FIXME: Check cases when screen width/height is not a multiply of 32.
  20. // e.g. 800x600.
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <strings.h>
  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <unistd.h>
  28. #include <errno.h>
  29. #include <pwd.h>
  30. #include <rfb/Logger_stdio.h>
  31. #include <rfb/LogWriter.h>
  32. #include <rfb/VNCServerST.h>
  33. #include <rfb/Configuration.h>
  34. #include <rfb/Timer.h>
  35. #include <network/TcpSocket.h>
  36. #include <network/UnixSocket.h>
  37. #include <signal.h>
  38. #include <X11/X.h>
  39. #include <X11/Xlib.h>
  40. #include <X11/Xutil.h>
  41. #include <x0vncserver/XDesktop.h>
  42. #include <x0vncserver/Geometry.h>
  43. #include <x0vncserver/Image.h>
  44. #include <x0vncserver/PollingScheduler.h>
  45. extern char buildtime[];
  46. using namespace rfb;
  47. using namespace network;
  48. static LogWriter vlog("Main");
  49. static const char* defaultDesktopName();
  50. IntParameter pollingCycle("PollingCycle", "Milliseconds per one polling "
  51. "cycle; actual interval may be dynamically "
  52. "adjusted to satisfy MaxProcessorUsage setting", 30);
  53. IntParameter maxProcessorUsage("MaxProcessorUsage", "Maximum percentage of "
  54. "CPU time to be consumed", 35);
  55. StringParameter desktopName("desktop", "Name of VNC desktop", defaultDesktopName());
  56. StringParameter displayname("display", "The X display", "");
  57. IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",5900);
  58. StringParameter rfbunixpath("rfbunixpath", "Unix socket to listen for RFB protocol", "");
  59. IntParameter rfbunixmode("rfbunixmode", "Unix socket access mode", 0600);
  60. StringParameter hostsFile("HostsFile", "File with IP access control rules", "");
  61. BoolParameter localhostOnly("localhost",
  62. "Only allow connections from localhost",
  63. false);
  64. StringParameter interface("interface",
  65. "listen on the specified network address",
  66. "all");
  67. static const char* defaultDesktopName()
  68. {
  69. long host_max = sysconf(_SC_HOST_NAME_MAX);
  70. if (host_max < 0)
  71. return "";
  72. std::vector<char> hostname(host_max + 1);
  73. if (gethostname(hostname.data(), hostname.size()) == -1)
  74. return "";
  75. struct passwd* pwent = getpwuid(getuid());
  76. if (pwent == NULL)
  77. return "";
  78. int len = snprintf(NULL, 0, "%s@%s", pwent->pw_name, hostname.data());
  79. if (len < 0)
  80. return "";
  81. char* name = new char[len + 1];
  82. snprintf(name, len + 1, "%s@%s", pwent->pw_name, hostname.data());
  83. return name;
  84. }
  85. //
  86. // Allow the main loop terminate itself gracefully on receiving a signal.
  87. //
  88. static bool caughtSignal = false;
  89. static void CleanupSignalHandler(int /*sig*/)
  90. {
  91. caughtSignal = true;
  92. }
  93. class FileTcpFilter : public TcpFilter
  94. {
  95. public:
  96. FileTcpFilter(const char *fname)
  97. : TcpFilter("-"), fileName(NULL), lastModTime(0)
  98. {
  99. if (fname != NULL)
  100. fileName = strdup((char *)fname);
  101. }
  102. virtual ~FileTcpFilter()
  103. {
  104. if (fileName != NULL)
  105. free(fileName);
  106. }
  107. virtual bool verifyConnection(Socket* s)
  108. {
  109. if (!reloadRules()) {
  110. vlog.error("Could not read IP filtering rules: rejecting all clients");
  111. filter.clear();
  112. filter.push_back(parsePattern("-"));
  113. return false;
  114. }
  115. return TcpFilter::verifyConnection(s);
  116. }
  117. protected:
  118. bool reloadRules()
  119. {
  120. if (fileName == NULL)
  121. return true;
  122. struct stat st;
  123. if (stat(fileName, &st) != 0)
  124. return false;
  125. if (st.st_mtime != lastModTime) {
  126. // Actually reload only if the file was modified
  127. FILE *fp = fopen(fileName, "r");
  128. if (fp == NULL)
  129. return false;
  130. // Remove all the rules from the parent class
  131. filter.clear();
  132. // Parse the file contents adding rules to the parent class
  133. char buf[32];
  134. while (readLine(buf, 32, fp)) {
  135. if (buf[0] && strchr("+-?", buf[0])) {
  136. filter.push_back(parsePattern(buf));
  137. }
  138. }
  139. fclose(fp);
  140. lastModTime = st.st_mtime;
  141. }
  142. return true;
  143. }
  144. protected:
  145. char *fileName;
  146. time_t lastModTime;
  147. private:
  148. //
  149. // NOTE: we silently truncate long lines in this function.
  150. //
  151. bool readLine(char *buf, int bufSize, FILE *fp)
  152. {
  153. if (fp == NULL || buf == NULL || bufSize == 0)
  154. return false;
  155. if (fgets(buf, bufSize, fp) == NULL)
  156. return false;
  157. char *ptr = strchr(buf, '\n');
  158. if (ptr != NULL) {
  159. *ptr = '\0'; // remove newline at the end
  160. } else {
  161. if (!feof(fp)) {
  162. int c;
  163. do { // skip the rest of a long line
  164. c = getc(fp);
  165. } while (c != '\n' && c != EOF);
  166. }
  167. }
  168. return true;
  169. }
  170. };
  171. char* programName;
  172. static void printVersion(FILE *fp)
  173. {
  174. fprintf(fp, "TigerVNC Server version %s, built %s\n",
  175. PACKAGE_VERSION, buildtime);
  176. }
  177. static void usage()
  178. {
  179. printVersion(stderr);
  180. fprintf(stderr, "\nUsage: %s [<parameters>]\n", programName);
  181. fprintf(stderr, " %s --version\n", programName);
  182. fprintf(stderr,"\n"
  183. "Parameters can be turned on with -<param> or off with -<param>=0\n"
  184. "Parameters which take a value can be specified as "
  185. "-<param> <value>\n"
  186. "Other valid forms are <param>=<value> -<param>=<value> "
  187. "--<param>=<value>\n"
  188. "Parameter names are case-insensitive. The parameters are:\n\n");
  189. Configuration::listParams(79, 14);
  190. exit(1);
  191. }
  192. int main(int argc, char** argv)
  193. {
  194. initStdIOLoggers();
  195. LogWriter::setLogParams("*:stderr:30");
  196. programName = argv[0];
  197. Display* dpy;
  198. Configuration::enableServerParams();
  199. // FIXME: We don't support clipboard yet
  200. Configuration::removeParam("AcceptCutText");
  201. Configuration::removeParam("SendCutText");
  202. Configuration::removeParam("MaxCutText");
  203. for (int i = 1; i < argc; i++) {
  204. if (Configuration::setParam(argv[i]))
  205. continue;
  206. if (argv[i][0] == '-') {
  207. if (i+1 < argc) {
  208. if (Configuration::setParam(&argv[i][1], argv[i+1])) {
  209. i++;
  210. continue;
  211. }
  212. }
  213. if (strcmp(argv[i], "-v") == 0 ||
  214. strcmp(argv[i], "-version") == 0 ||
  215. strcmp(argv[i], "--version") == 0) {
  216. printVersion(stdout);
  217. return 0;
  218. }
  219. usage();
  220. }
  221. usage();
  222. }
  223. if (!(dpy = XOpenDisplay(displayname))) {
  224. // FIXME: Why not vlog.error(...)?
  225. fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
  226. programName, XDisplayName(displayname));
  227. exit(1);
  228. }
  229. signal(SIGHUP, CleanupSignalHandler);
  230. signal(SIGINT, CleanupSignalHandler);
  231. signal(SIGTERM, CleanupSignalHandler);
  232. std::list<SocketListener*> listeners;
  233. try {
  234. TXWindow::init(dpy,"x0vncserver");
  235. Geometry geo(DisplayWidth(dpy, DefaultScreen(dpy)),
  236. DisplayHeight(dpy, DefaultScreen(dpy)));
  237. if (geo.getRect().is_empty()) {
  238. vlog.error("Exiting with error");
  239. return 1;
  240. }
  241. XDesktop desktop(dpy, &geo);
  242. VNCServerST server(desktopName, &desktop);
  243. if (rfbunixpath.getValueStr()[0] != '\0') {
  244. listeners.push_back(new network::UnixListener(rfbunixpath, rfbunixmode));
  245. vlog.info("Listening on %s (mode %04o)", (const char*)rfbunixpath, (int)rfbunixmode);
  246. }
  247. if ((int)rfbport != -1) {
  248. const char *addr = interface;
  249. if (strcasecmp(addr, "all") == 0)
  250. addr = 0;
  251. if (localhostOnly)
  252. createLocalTcpListeners(&listeners, (int)rfbport);
  253. else
  254. createTcpListeners(&listeners, addr, (int)rfbport);
  255. vlog.info("Listening for VNC connections on %s interface(s), port %d",
  256. localhostOnly ? "local" : (const char*)interface,
  257. (int)rfbport);
  258. }
  259. FileTcpFilter fileTcpFilter(hostsFile);
  260. if (strlen(hostsFile) != 0)
  261. for (std::list<SocketListener*>::iterator i = listeners.begin();
  262. i != listeners.end();
  263. i++)
  264. (*i)->setFilter(&fileTcpFilter);
  265. PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
  266. while (!caughtSignal) {
  267. int wait_ms;
  268. struct timeval tv;
  269. fd_set rfds, wfds;
  270. std::list<Socket*> sockets;
  271. std::list<Socket*>::iterator i;
  272. // Process any incoming X events
  273. TXWindow::handleXEvents(dpy);
  274. FD_ZERO(&rfds);
  275. FD_ZERO(&wfds);
  276. FD_SET(ConnectionNumber(dpy), &rfds);
  277. for (std::list<SocketListener*>::iterator i = listeners.begin();
  278. i != listeners.end();
  279. i++)
  280. FD_SET((*i)->getFd(), &rfds);
  281. server.getSockets(&sockets);
  282. int clients_connected = 0;
  283. for (i = sockets.begin(); i != sockets.end(); i++) {
  284. if ((*i)->isShutdown()) {
  285. server.removeSocket(*i);
  286. delete (*i);
  287. } else {
  288. FD_SET((*i)->getFd(), &rfds);
  289. if ((*i)->outStream().hasBufferedData())
  290. FD_SET((*i)->getFd(), &wfds);
  291. clients_connected++;
  292. }
  293. }
  294. if (!clients_connected)
  295. sched.reset();
  296. wait_ms = 0;
  297. if (sched.isRunning()) {
  298. wait_ms = sched.millisRemaining();
  299. if (wait_ms > 500) {
  300. wait_ms = 500;
  301. }
  302. }
  303. soonestTimeout(&wait_ms, Timer::checkTimeouts());
  304. tv.tv_sec = wait_ms / 1000;
  305. tv.tv_usec = (wait_ms % 1000) * 1000;
  306. // Do the wait...
  307. sched.sleepStarted();
  308. int n = select(FD_SETSIZE, &rfds, &wfds, 0,
  309. wait_ms ? &tv : NULL);
  310. sched.sleepFinished();
  311. if (n < 0) {
  312. if (errno == EINTR) {
  313. vlog.debug("Interrupted select() system call");
  314. continue;
  315. } else {
  316. throw rdr::SystemException("select", errno);
  317. }
  318. }
  319. // Accept new VNC connections
  320. for (std::list<SocketListener*>::iterator i = listeners.begin();
  321. i != listeners.end();
  322. i++) {
  323. if (FD_ISSET((*i)->getFd(), &rfds)) {
  324. Socket* sock = (*i)->accept();
  325. if (sock) {
  326. server.addSocket(sock);
  327. } else {
  328. vlog.status("Client connection rejected");
  329. }
  330. }
  331. }
  332. Timer::checkTimeouts();
  333. // Client list could have been changed.
  334. server.getSockets(&sockets);
  335. // Nothing more to do if there are no client connections.
  336. if (sockets.empty())
  337. continue;
  338. // Process events on existing VNC connections
  339. for (i = sockets.begin(); i != sockets.end(); i++) {
  340. if (FD_ISSET((*i)->getFd(), &rfds))
  341. server.processSocketReadEvent(*i);
  342. if (FD_ISSET((*i)->getFd(), &wfds))
  343. server.processSocketWriteEvent(*i);
  344. }
  345. if (desktop.isRunning() && sched.goodTimeToPoll()) {
  346. sched.newPass();
  347. desktop.poll();
  348. }
  349. }
  350. } catch (rdr::Exception &e) {
  351. vlog.error("%s", e.str());
  352. return 1;
  353. }
  354. TXWindow::handleXEvents(dpy);
  355. // Run listener destructors; remove UNIX sockets etc
  356. for (std::list<SocketListener*>::iterator i = listeners.begin();
  357. i != listeners.end();
  358. i++) {
  359. delete *i;
  360. }
  361. vlog.info("Terminated");
  362. return 0;
  363. }