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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. #include <strings.h>
  22. #include <sys/types.h>
  23. #include <sys/stat.h>
  24. #include <unistd.h>
  25. #include <errno.h>
  26. #include <rfb/Logger_stdio.h>
  27. #include <rfb/LogWriter.h>
  28. #include <rfb/VNCServerST.h>
  29. #include <rfb/Configuration.h>
  30. #include <rfb/Timer.h>
  31. #include <network/TcpSocket.h>
  32. #include <network/UnixSocket.h>
  33. #include <signal.h>
  34. #include <X11/X.h>
  35. #include <X11/Xlib.h>
  36. #include <X11/Xutil.h>
  37. #include <x0vncserver/XDesktop.h>
  38. #include <x0vncserver/Geometry.h>
  39. #include <x0vncserver/Image.h>
  40. #include <x0vncserver/PollingScheduler.h>
  41. extern char buildtime[];
  42. using namespace rfb;
  43. using namespace network;
  44. static LogWriter vlog("Main");
  45. IntParameter pollingCycle("PollingCycle", "Milliseconds per one polling "
  46. "cycle; actual interval may be dynamically "
  47. "adjusted to satisfy MaxProcessorUsage setting", 30);
  48. IntParameter maxProcessorUsage("MaxProcessorUsage", "Maximum percentage of "
  49. "CPU time to be consumed", 35);
  50. StringParameter displayname("display", "The X display", "");
  51. IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",5900);
  52. StringParameter rfbunixpath("rfbunixpath", "Unix socket to listen for RFB protocol", "");
  53. IntParameter rfbunixmode("rfbunixmode", "Unix socket access mode", 0600);
  54. StringParameter hostsFile("HostsFile", "File with IP access control rules", "");
  55. //
  56. // Allow the main loop terminate itself gracefully on receiving a signal.
  57. //
  58. static bool caughtSignal = false;
  59. static void CleanupSignalHandler(int sig)
  60. {
  61. caughtSignal = true;
  62. }
  63. class FileTcpFilter : public TcpFilter
  64. {
  65. public:
  66. FileTcpFilter(const char *fname)
  67. : TcpFilter("-"), fileName(NULL), lastModTime(0)
  68. {
  69. if (fname != NULL)
  70. fileName = strdup((char *)fname);
  71. }
  72. virtual ~FileTcpFilter()
  73. {
  74. if (fileName != NULL)
  75. free(fileName);
  76. }
  77. virtual bool verifyConnection(Socket* s)
  78. {
  79. if (!reloadRules()) {
  80. vlog.error("Could not read IP filtering rules: rejecting all clients");
  81. filter.clear();
  82. filter.push_back(parsePattern("-"));
  83. return false;
  84. }
  85. return TcpFilter::verifyConnection(s);
  86. }
  87. protected:
  88. bool reloadRules()
  89. {
  90. if (fileName == NULL)
  91. return true;
  92. struct stat st;
  93. if (stat(fileName, &st) != 0)
  94. return false;
  95. if (st.st_mtime != lastModTime) {
  96. // Actually reload only if the file was modified
  97. FILE *fp = fopen(fileName, "r");
  98. if (fp == NULL)
  99. return false;
  100. // Remove all the rules from the parent class
  101. filter.clear();
  102. // Parse the file contents adding rules to the parent class
  103. char buf[32];
  104. while (readLine(buf, 32, fp)) {
  105. if (buf[0] && strchr("+-?", buf[0])) {
  106. filter.push_back(parsePattern(buf));
  107. }
  108. }
  109. fclose(fp);
  110. lastModTime = st.st_mtime;
  111. }
  112. return true;
  113. }
  114. protected:
  115. char *fileName;
  116. time_t lastModTime;
  117. private:
  118. //
  119. // NOTE: we silently truncate long lines in this function.
  120. //
  121. bool readLine(char *buf, int bufSize, FILE *fp)
  122. {
  123. if (fp == NULL || buf == NULL || bufSize == 0)
  124. return false;
  125. if (fgets(buf, bufSize, fp) == NULL)
  126. return false;
  127. char *ptr = strchr(buf, '\n');
  128. if (ptr != NULL) {
  129. *ptr = '\0'; // remove newline at the end
  130. } else {
  131. if (!feof(fp)) {
  132. int c;
  133. do { // skip the rest of a long line
  134. c = getc(fp);
  135. } while (c != '\n' && c != EOF);
  136. }
  137. }
  138. return true;
  139. }
  140. };
  141. char* programName;
  142. static void printVersion(FILE *fp)
  143. {
  144. fprintf(fp, "TigerVNC Server version %s, built %s\n",
  145. PACKAGE_VERSION, buildtime);
  146. }
  147. static void usage()
  148. {
  149. printVersion(stderr);
  150. fprintf(stderr, "\nUsage: %s [<parameters>]\n", programName);
  151. fprintf(stderr, " %s --version\n", programName);
  152. fprintf(stderr,"\n"
  153. "Parameters can be turned on with -<param> or off with -<param>=0\n"
  154. "Parameters which take a value can be specified as "
  155. "-<param> <value>\n"
  156. "Other valid forms are <param>=<value> -<param>=<value> "
  157. "--<param>=<value>\n"
  158. "Parameter names are case-insensitive. The parameters are:\n\n");
  159. Configuration::listParams(79, 14);
  160. exit(1);
  161. }
  162. int main(int argc, char** argv)
  163. {
  164. initStdIOLoggers();
  165. LogWriter::setLogParams("*:stderr:30");
  166. programName = argv[0];
  167. Display* dpy;
  168. Configuration::enableServerParams();
  169. // Disable configuration parameters which we do not support
  170. Configuration::removeParam("AcceptSetDesktopSize");
  171. for (int i = 1; i < argc; i++) {
  172. if (Configuration::setParam(argv[i]))
  173. continue;
  174. if (argv[i][0] == '-') {
  175. if (i+1 < argc) {
  176. if (Configuration::setParam(&argv[i][1], argv[i+1])) {
  177. i++;
  178. continue;
  179. }
  180. }
  181. if (strcmp(argv[i], "-v") == 0 ||
  182. strcmp(argv[i], "-version") == 0 ||
  183. strcmp(argv[i], "--version") == 0) {
  184. printVersion(stdout);
  185. return 0;
  186. }
  187. usage();
  188. }
  189. usage();
  190. }
  191. CharArray dpyStr(displayname.getData());
  192. if (!(dpy = XOpenDisplay(dpyStr.buf[0] ? dpyStr.buf : 0))) {
  193. // FIXME: Why not vlog.error(...)?
  194. fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
  195. programName, XDisplayName(dpyStr.buf));
  196. exit(1);
  197. }
  198. signal(SIGHUP, CleanupSignalHandler);
  199. signal(SIGINT, CleanupSignalHandler);
  200. signal(SIGTERM, CleanupSignalHandler);
  201. std::list<SocketListener*> listeners;
  202. try {
  203. TXWindow::init(dpy,"x0vncserver");
  204. Geometry geo(DisplayWidth(dpy, DefaultScreen(dpy)),
  205. DisplayHeight(dpy, DefaultScreen(dpy)));
  206. if (geo.getRect().is_empty()) {
  207. vlog.error("Exiting with error");
  208. return 1;
  209. }
  210. XDesktop desktop(dpy, &geo);
  211. VNCServerST server("x0vncserver", &desktop);
  212. if (rfbunixpath.getValueStr()[0] != '\0') {
  213. listeners.push_back(new network::UnixListener(rfbunixpath, rfbunixmode));
  214. vlog.info("Listening on %s (mode %04o)", (const char*)rfbunixpath, (int)rfbunixmode);
  215. } else {
  216. createTcpListeners(&listeners, 0, (int)rfbport);
  217. vlog.info("Listening on port %d", (int)rfbport);
  218. }
  219. const char *hostsData = hostsFile.getData();
  220. FileTcpFilter fileTcpFilter(hostsData);
  221. if (strlen(hostsData) != 0)
  222. for (std::list<SocketListener*>::iterator i = listeners.begin();
  223. i != listeners.end();
  224. i++)
  225. (*i)->setFilter(&fileTcpFilter);
  226. delete[] hostsData;
  227. PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
  228. while (!caughtSignal) {
  229. int wait_ms;
  230. struct timeval tv;
  231. fd_set rfds, wfds;
  232. std::list<Socket*> sockets;
  233. std::list<Socket*>::iterator i;
  234. // Process any incoming X events
  235. TXWindow::handleXEvents(dpy);
  236. FD_ZERO(&rfds);
  237. FD_ZERO(&wfds);
  238. FD_SET(ConnectionNumber(dpy), &rfds);
  239. for (std::list<SocketListener*>::iterator i = listeners.begin();
  240. i != listeners.end();
  241. i++)
  242. FD_SET((*i)->getFd(), &rfds);
  243. server.getSockets(&sockets);
  244. int clients_connected = 0;
  245. for (i = sockets.begin(); i != sockets.end(); i++) {
  246. if ((*i)->isShutdown()) {
  247. server.removeSocket(*i);
  248. delete (*i);
  249. } else {
  250. FD_SET((*i)->getFd(), &rfds);
  251. if ((*i)->outStream().bufferUsage() > 0)
  252. FD_SET((*i)->getFd(), &wfds);
  253. clients_connected++;
  254. }
  255. }
  256. if (!clients_connected)
  257. sched.reset();
  258. wait_ms = 0;
  259. if (sched.isRunning()) {
  260. wait_ms = sched.millisRemaining();
  261. if (wait_ms > 500) {
  262. wait_ms = 500;
  263. }
  264. }
  265. soonestTimeout(&wait_ms, Timer::checkTimeouts());
  266. tv.tv_sec = wait_ms / 1000;
  267. tv.tv_usec = (wait_ms % 1000) * 1000;
  268. // Do the wait...
  269. sched.sleepStarted();
  270. int n = select(FD_SETSIZE, &rfds, &wfds, 0,
  271. wait_ms ? &tv : NULL);
  272. sched.sleepFinished();
  273. if (n < 0) {
  274. if (errno == EINTR) {
  275. vlog.debug("Interrupted select() system call");
  276. continue;
  277. } else {
  278. throw rdr::SystemException("select", errno);
  279. }
  280. }
  281. // Accept new VNC connections
  282. for (std::list<SocketListener*>::iterator i = listeners.begin();
  283. i != listeners.end();
  284. i++) {
  285. if (FD_ISSET((*i)->getFd(), &rfds)) {
  286. Socket* sock = (*i)->accept();
  287. if (sock) {
  288. sock->outStream().setBlocking(false);
  289. server.addSocket(sock);
  290. } else {
  291. vlog.status("Client connection rejected");
  292. }
  293. }
  294. }
  295. Timer::checkTimeouts();
  296. // Client list could have been changed.
  297. server.getSockets(&sockets);
  298. // Nothing more to do if there are no client connections.
  299. if (sockets.empty())
  300. continue;
  301. // Process events on existing VNC connections
  302. for (i = sockets.begin(); i != sockets.end(); i++) {
  303. if (FD_ISSET((*i)->getFd(), &rfds))
  304. server.processSocketReadEvent(*i);
  305. if (FD_ISSET((*i)->getFd(), &wfds))
  306. server.processSocketWriteEvent(*i);
  307. }
  308. if (desktop.isRunning() && sched.goodTimeToPoll()) {
  309. sched.newPass();
  310. desktop.poll();
  311. }
  312. }
  313. } catch (rdr::Exception &e) {
  314. vlog.error("%s", e.str());
  315. return 1;
  316. }
  317. TXWindow::handleXEvents(dpy);
  318. vlog.info("Terminated");
  319. return 0;
  320. }