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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. CharArray dpyStr(displayname.getData());
  224. if (!(dpy = XOpenDisplay(dpyStr.buf[0] ? dpyStr.buf : 0))) {
  225. // FIXME: Why not vlog.error(...)?
  226. fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
  227. programName, XDisplayName(dpyStr.buf));
  228. exit(1);
  229. }
  230. signal(SIGHUP, CleanupSignalHandler);
  231. signal(SIGINT, CleanupSignalHandler);
  232. signal(SIGTERM, CleanupSignalHandler);
  233. std::list<SocketListener*> listeners;
  234. try {
  235. TXWindow::init(dpy,"x0vncserver");
  236. Geometry geo(DisplayWidth(dpy, DefaultScreen(dpy)),
  237. DisplayHeight(dpy, DefaultScreen(dpy)));
  238. if (geo.getRect().is_empty()) {
  239. vlog.error("Exiting with error");
  240. return 1;
  241. }
  242. XDesktop desktop(dpy, &geo);
  243. VNCServerST server(desktopName, &desktop);
  244. if (rfbunixpath.getValueStr()[0] != '\0') {
  245. listeners.push_back(new network::UnixListener(rfbunixpath, rfbunixmode));
  246. vlog.info("Listening on %s (mode %04o)", (const char*)rfbunixpath, (int)rfbunixmode);
  247. }
  248. if ((int)rfbport != -1) {
  249. const char *addr = interface;
  250. if (strcasecmp(addr, "all") == 0)
  251. addr = 0;
  252. if (localhostOnly)
  253. createLocalTcpListeners(&listeners, (int)rfbport);
  254. else
  255. createTcpListeners(&listeners, addr, (int)rfbport);
  256. vlog.info("Listening for VNC connections on %s interface(s), port %d",
  257. localhostOnly ? "local" : (const char*)interface,
  258. (int)rfbport);
  259. }
  260. const char *hostsData = hostsFile.getData();
  261. FileTcpFilter fileTcpFilter(hostsData);
  262. if (strlen(hostsData) != 0)
  263. for (std::list<SocketListener*>::iterator i = listeners.begin();
  264. i != listeners.end();
  265. i++)
  266. (*i)->setFilter(&fileTcpFilter);
  267. delete[] hostsData;
  268. PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
  269. while (!caughtSignal) {
  270. int wait_ms;
  271. struct timeval tv;
  272. fd_set rfds, wfds;
  273. std::list<Socket*> sockets;
  274. std::list<Socket*>::iterator i;
  275. // Process any incoming X events
  276. TXWindow::handleXEvents(dpy);
  277. FD_ZERO(&rfds);
  278. FD_ZERO(&wfds);
  279. FD_SET(ConnectionNumber(dpy), &rfds);
  280. for (std::list<SocketListener*>::iterator i = listeners.begin();
  281. i != listeners.end();
  282. i++)
  283. FD_SET((*i)->getFd(), &rfds);
  284. server.getSockets(&sockets);
  285. int clients_connected = 0;
  286. for (i = sockets.begin(); i != sockets.end(); i++) {
  287. if ((*i)->isShutdown()) {
  288. server.removeSocket(*i);
  289. delete (*i);
  290. } else {
  291. FD_SET((*i)->getFd(), &rfds);
  292. if ((*i)->outStream().hasBufferedData())
  293. FD_SET((*i)->getFd(), &wfds);
  294. clients_connected++;
  295. }
  296. }
  297. if (!clients_connected)
  298. sched.reset();
  299. wait_ms = 0;
  300. if (sched.isRunning()) {
  301. wait_ms = sched.millisRemaining();
  302. if (wait_ms > 500) {
  303. wait_ms = 500;
  304. }
  305. }
  306. soonestTimeout(&wait_ms, Timer::checkTimeouts());
  307. tv.tv_sec = wait_ms / 1000;
  308. tv.tv_usec = (wait_ms % 1000) * 1000;
  309. // Do the wait...
  310. sched.sleepStarted();
  311. int n = select(FD_SETSIZE, &rfds, &wfds, 0,
  312. wait_ms ? &tv : NULL);
  313. sched.sleepFinished();
  314. if (n < 0) {
  315. if (errno == EINTR) {
  316. vlog.debug("Interrupted select() system call");
  317. continue;
  318. } else {
  319. throw rdr::SystemException("select", errno);
  320. }
  321. }
  322. // Accept new VNC connections
  323. for (std::list<SocketListener*>::iterator i = listeners.begin();
  324. i != listeners.end();
  325. i++) {
  326. if (FD_ISSET((*i)->getFd(), &rfds)) {
  327. Socket* sock = (*i)->accept();
  328. if (sock) {
  329. server.addSocket(sock);
  330. } else {
  331. vlog.status("Client connection rejected");
  332. }
  333. }
  334. }
  335. Timer::checkTimeouts();
  336. // Client list could have been changed.
  337. server.getSockets(&sockets);
  338. // Nothing more to do if there are no client connections.
  339. if (sockets.empty())
  340. continue;
  341. // Process events on existing VNC connections
  342. for (i = sockets.begin(); i != sockets.end(); i++) {
  343. if (FD_ISSET((*i)->getFd(), &rfds))
  344. server.processSocketReadEvent(*i);
  345. if (FD_ISSET((*i)->getFd(), &wfds))
  346. server.processSocketWriteEvent(*i);
  347. }
  348. if (desktop.isRunning() && sched.goodTimeToPoll()) {
  349. sched.newPass();
  350. desktop.poll();
  351. }
  352. }
  353. } catch (rdr::Exception &e) {
  354. vlog.error("%s", e.str());
  355. return 1;
  356. }
  357. TXWindow::handleXEvents(dpy);
  358. // Run listener destructors; remove UNIX sockets etc
  359. for (std::list<SocketListener*>::iterator i = listeners.begin();
  360. i != listeners.end();
  361. i++) {
  362. delete *i;
  363. }
  364. vlog.info("Terminated");
  365. return 0;
  366. }