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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 <vncconfig/QueryConnectDialog.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. IntParameter queryConnectTimeout("QueryConnectTimeout",
  53. "Number of seconds to show the Accept Connection dialog before "
  54. "rejecting the connection",
  55. 10);
  56. StringParameter hostsFile("HostsFile", "File with IP access control rules", "");
  57. //
  58. // Allow the main loop terminate itself gracefully on receiving a signal.
  59. //
  60. static bool caughtSignal = false;
  61. static void CleanupSignalHandler(int sig)
  62. {
  63. caughtSignal = true;
  64. }
  65. class QueryConnHandler : public VNCServerST::QueryConnectionHandler,
  66. public QueryResultCallback {
  67. public:
  68. QueryConnHandler(Display* dpy, VNCServerST* vs)
  69. : display(dpy), server(vs), queryConnectDialog(0), queryConnectSock(0) {}
  70. ~QueryConnHandler() { delete queryConnectDialog; }
  71. // -=- VNCServerST::QueryConnectionHandler interface
  72. virtual VNCServerST::queryResult queryConnection(network::Socket* sock,
  73. const char* userName,
  74. char** reason) {
  75. if (queryConnectSock) {
  76. *reason = strDup("Another connection is currently being queried.");
  77. return VNCServerST::REJECT;
  78. }
  79. if (!userName) userName = "(anonymous)";
  80. queryConnectSock = sock;
  81. CharArray address(sock->getPeerAddress());
  82. delete queryConnectDialog;
  83. queryConnectDialog = new QueryConnectDialog(display, address.buf,
  84. userName, queryConnectTimeout,
  85. this);
  86. queryConnectDialog->map();
  87. return VNCServerST::PENDING;
  88. }
  89. // -=- QueryResultCallback interface
  90. virtual void queryApproved() {
  91. server->approveConnection(queryConnectSock, true, 0);
  92. queryConnectSock = 0;
  93. }
  94. virtual void queryRejected() {
  95. server->approveConnection(queryConnectSock, false,
  96. "Connection rejected by local user");
  97. queryConnectSock = 0;
  98. }
  99. private:
  100. Display* display;
  101. VNCServerST* server;
  102. QueryConnectDialog* queryConnectDialog;
  103. network::Socket* queryConnectSock;
  104. };
  105. class FileTcpFilter : public TcpFilter
  106. {
  107. public:
  108. FileTcpFilter(const char *fname)
  109. : TcpFilter("-"), fileName(NULL), lastModTime(0)
  110. {
  111. if (fname != NULL)
  112. fileName = strdup((char *)fname);
  113. }
  114. virtual ~FileTcpFilter()
  115. {
  116. if (fileName != NULL)
  117. free(fileName);
  118. }
  119. virtual bool verifyConnection(Socket* s)
  120. {
  121. if (!reloadRules()) {
  122. vlog.error("Could not read IP filtering rules: rejecting all clients");
  123. filter.clear();
  124. filter.push_back(parsePattern("-"));
  125. return false;
  126. }
  127. return TcpFilter::verifyConnection(s);
  128. }
  129. protected:
  130. bool reloadRules()
  131. {
  132. if (fileName == NULL)
  133. return true;
  134. struct stat st;
  135. if (stat(fileName, &st) != 0)
  136. return false;
  137. if (st.st_mtime != lastModTime) {
  138. // Actually reload only if the file was modified
  139. FILE *fp = fopen(fileName, "r");
  140. if (fp == NULL)
  141. return false;
  142. // Remove all the rules from the parent class
  143. filter.clear();
  144. // Parse the file contents adding rules to the parent class
  145. char buf[32];
  146. while (readLine(buf, 32, fp)) {
  147. if (buf[0] && strchr("+-?", buf[0])) {
  148. filter.push_back(parsePattern(buf));
  149. }
  150. }
  151. fclose(fp);
  152. lastModTime = st.st_mtime;
  153. }
  154. return true;
  155. }
  156. protected:
  157. char *fileName;
  158. time_t lastModTime;
  159. private:
  160. //
  161. // NOTE: we silently truncate long lines in this function.
  162. //
  163. bool readLine(char *buf, int bufSize, FILE *fp)
  164. {
  165. if (fp == NULL || buf == NULL || bufSize == 0)
  166. return false;
  167. if (fgets(buf, bufSize, fp) == NULL)
  168. return false;
  169. char *ptr = strchr(buf, '\n');
  170. if (ptr != NULL) {
  171. *ptr = '\0'; // remove newline at the end
  172. } else {
  173. if (!feof(fp)) {
  174. int c;
  175. do { // skip the rest of a long line
  176. c = getc(fp);
  177. } while (c != '\n' && c != EOF);
  178. }
  179. }
  180. return true;
  181. }
  182. };
  183. char* programName;
  184. static void printVersion(FILE *fp)
  185. {
  186. fprintf(fp, "TigerVNC Server version %s, built %s\n",
  187. PACKAGE_VERSION, buildtime);
  188. }
  189. static void usage()
  190. {
  191. printVersion(stderr);
  192. fprintf(stderr, "\nUsage: %s [<parameters>]\n", programName);
  193. fprintf(stderr, " %s --version\n", programName);
  194. fprintf(stderr,"\n"
  195. "Parameters can be turned on with -<param> or off with -<param>=0\n"
  196. "Parameters which take a value can be specified as "
  197. "-<param> <value>\n"
  198. "Other valid forms are <param>=<value> -<param>=<value> "
  199. "--<param>=<value>\n"
  200. "Parameter names are case-insensitive. The parameters are:\n\n");
  201. Configuration::listParams(79, 14);
  202. exit(1);
  203. }
  204. int main(int argc, char** argv)
  205. {
  206. initStdIOLoggers();
  207. LogWriter::setLogParams("*:stderr:30");
  208. programName = argv[0];
  209. Display* dpy;
  210. Configuration::enableServerParams();
  211. // Disable configuration parameters which we do not support
  212. Configuration::removeParam("AcceptSetDesktopSize");
  213. for (int i = 1; i < argc; i++) {
  214. if (Configuration::setParam(argv[i]))
  215. continue;
  216. if (argv[i][0] == '-') {
  217. if (i+1 < argc) {
  218. if (Configuration::setParam(&argv[i][1], argv[i+1])) {
  219. i++;
  220. continue;
  221. }
  222. }
  223. if (strcmp(argv[i], "-v") == 0 ||
  224. strcmp(argv[i], "-version") == 0 ||
  225. strcmp(argv[i], "--version") == 0) {
  226. printVersion(stdout);
  227. return 0;
  228. }
  229. usage();
  230. }
  231. usage();
  232. }
  233. CharArray dpyStr(displayname.getData());
  234. if (!(dpy = XOpenDisplay(dpyStr.buf[0] ? dpyStr.buf : 0))) {
  235. // FIXME: Why not vlog.error(...)?
  236. fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
  237. programName, XDisplayName(dpyStr.buf));
  238. exit(1);
  239. }
  240. signal(SIGHUP, CleanupSignalHandler);
  241. signal(SIGINT, CleanupSignalHandler);
  242. signal(SIGTERM, CleanupSignalHandler);
  243. std::list<SocketListener*> listeners;
  244. try {
  245. TXWindow::init(dpy,"x0vncserver");
  246. Geometry geo(DisplayWidth(dpy, DefaultScreen(dpy)),
  247. DisplayHeight(dpy, DefaultScreen(dpy)));
  248. if (geo.getRect().is_empty()) {
  249. vlog.error("Exiting with error");
  250. return 1;
  251. }
  252. XDesktop desktop(dpy, &geo);
  253. VNCServerST server("x0vncserver", &desktop);
  254. QueryConnHandler qcHandler(dpy, &server);
  255. server.setQueryConnectionHandler(&qcHandler);
  256. createTcpListeners(&listeners, 0, (int)rfbport);
  257. vlog.info("Listening on port %d", (int)rfbport);
  258. const char *hostsData = hostsFile.getData();
  259. FileTcpFilter fileTcpFilter(hostsData);
  260. if (strlen(hostsData) != 0)
  261. for (std::list<SocketListener*>::iterator i = listeners.begin();
  262. i != listeners.end();
  263. i++)
  264. (*i)->setFilter(&fileTcpFilter);
  265. delete[] hostsData;
  266. PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
  267. while (!caughtSignal) {
  268. int wait_ms;
  269. struct timeval tv;
  270. fd_set rfds, wfds;
  271. std::list<Socket*> sockets;
  272. std::list<Socket*>::iterator i;
  273. // Process any incoming X events
  274. TXWindow::handleXEvents(dpy);
  275. FD_ZERO(&rfds);
  276. FD_ZERO(&wfds);
  277. FD_SET(ConnectionNumber(dpy), &rfds);
  278. for (std::list<SocketListener*>::iterator i = listeners.begin();
  279. i != listeners.end();
  280. i++)
  281. FD_SET((*i)->getFd(), &rfds);
  282. server.getSockets(&sockets);
  283. int clients_connected = 0;
  284. for (i = sockets.begin(); i != sockets.end(); i++) {
  285. if ((*i)->isShutdown()) {
  286. server.removeSocket(*i);
  287. delete (*i);
  288. } else {
  289. FD_SET((*i)->getFd(), &rfds);
  290. if ((*i)->outStream().bufferUsage() > 0)
  291. FD_SET((*i)->getFd(), &wfds);
  292. clients_connected++;
  293. }
  294. }
  295. if (!clients_connected)
  296. sched.reset();
  297. wait_ms = 0;
  298. if (sched.isRunning()) {
  299. wait_ms = sched.millisRemaining();
  300. if (wait_ms > 500) {
  301. wait_ms = 500;
  302. }
  303. }
  304. soonestTimeout(&wait_ms, server.checkTimeouts());
  305. tv.tv_sec = wait_ms / 1000;
  306. tv.tv_usec = (wait_ms % 1000) * 1000;
  307. // Do the wait...
  308. sched.sleepStarted();
  309. int n = select(FD_SETSIZE, &rfds, &wfds, 0,
  310. wait_ms ? &tv : NULL);
  311. sched.sleepFinished();
  312. if (n < 0) {
  313. if (errno == EINTR) {
  314. vlog.debug("Interrupted select() system call");
  315. continue;
  316. } else {
  317. throw rdr::SystemException("select", errno);
  318. }
  319. }
  320. // Accept new VNC connections
  321. for (std::list<SocketListener*>::iterator i = listeners.begin();
  322. i != listeners.end();
  323. i++) {
  324. if (FD_ISSET((*i)->getFd(), &rfds)) {
  325. Socket* sock = (*i)->accept();
  326. if (sock) {
  327. sock->outStream().setBlocking(false);
  328. server.addSocket(sock);
  329. } else {
  330. vlog.status("Client connection rejected");
  331. }
  332. }
  333. }
  334. server.checkTimeouts();
  335. // Client list could have been changed.
  336. server.getSockets(&sockets);
  337. // Nothing more to do if there are no client connections.
  338. if (sockets.empty())
  339. continue;
  340. // Process events on existing VNC connections
  341. for (i = sockets.begin(); i != sockets.end(); i++) {
  342. if (FD_ISSET((*i)->getFd(), &rfds))
  343. server.processSocketReadEvent(*i);
  344. if (FD_ISSET((*i)->getFd(), &wfds))
  345. server.processSocketWriteEvent(*i);
  346. }
  347. if (desktop.isRunning() && sched.goodTimeToPoll()) {
  348. sched.newPass();
  349. desktop.poll();
  350. }
  351. }
  352. } catch (rdr::Exception &e) {
  353. vlog.error("%s", e.str());
  354. return 1;
  355. }
  356. TXWindow::handleXEvents(dpy);
  357. vlog.info("Terminated");
  358. return 0;
  359. }