blob: f799de3a52b11d598f980322ff47450cb3744d0c [file] [log] [blame]
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +00001/* Copyright (C) 2002-2004 RealVNC Ltd. All Rights Reserved.
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +00002 * Copyright (C) 2004-2005 Constantin Kaplinsky. All Rights Reserved.
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +00003 *
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 */
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000019
20// FIXME: Check cases when screen width/height is not a multiply of 32.
21// e.g. 800x600.
22
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000023#include <strings.h>
24#include <sys/time.h>
25#include <sys/types.h>
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000026#include <sys/stat.h>
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000027#include <unistd.h>
28#include <errno.h>
29#include <rfb/Logger_stdio.h>
30#include <rfb/LogWriter.h>
31#include <rfb/VNCServerST.h>
32#include <rfb/Configuration.h>
33#include <rfb/SSecurityFactoryStandard.h>
34
35#include <network/TcpSocket.h>
36
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000037#include <signal.h>
38#include <X11/X.h>
39#include <X11/Xlib.h>
40#include <X11/Xutil.h>
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000041#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000042#include <X11/extensions/XTest.h>
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000043#endif
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000044
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +000045#include <x0vncserver/Image.h>
46#include <x0vncserver/PollingManager.h>
47#include <x0vncserver/CPUMonitor.h>
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000048
49using namespace rfb;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000050using namespace network;
51
52LogWriter vlog("main");
53
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +000054IntParameter pollingCycle("PollingCycle", "Milliseconds per one polling "
55 "cycle; actual interval may be dynamically "
56 "adjusted to satisfy MaxProcessorUsage setting", 50);
57IntParameter maxProcessorUsage("MaxProcessorUsage", "Maximum percentage of "
58 "CPU time to be consumed", 35);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000059BoolParameter useShm("UseSHM", "Use MIT-SHM extension if available", true);
60BoolParameter useOverlay("OverlayMode", "Use overlay mode under "
61 "IRIX or Solaris", true);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000062StringParameter displayname("display", "The X display", "");
63IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",5900);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000064StringParameter hostsFile("HostsFile", "File with IP access control rules", "");
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000065VncAuthPasswdFileParameter vncAuthPasswdFile;
66
67static void CleanupSignalHandler(int sig)
68{
69 // CleanupSignalHandler allows C++ object cleanup to happen because it calls
70 // exit() rather than the default which is to abort.
71 fprintf(stderr,"CleanupSignalHandler called\n");
72 exit(1);
73}
74
75
76class XDesktop : public SDesktop, public rfb::ColourMap
77{
78public:
79 XDesktop(Display* dpy_)
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000080 : dpy(dpy_), pb(0), server(0), oldButtonMask(0), haveXtest(false),
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +000081 maxButtons(0)
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000082 {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000083#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000084 int xtestEventBase;
85 int xtestErrorBase;
86 int major, minor;
87
88 if (XTestQueryExtension(dpy, &xtestEventBase,
89 &xtestErrorBase, &major, &minor)) {
90 XTestGrabControl(dpy, True);
91 vlog.info("XTest extension present - version %d.%d",major,minor);
92 haveXtest = true;
93 } else {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000094#endif
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000095 vlog.info("XTest extension not present");
96 vlog.info("unable to inject events or display while server is grabbed");
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000097#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000098 }
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000099#endif
100
101 // Determine actual number of buttons of the X pointer device.
102 unsigned char btnMap[8];
103 int numButtons = XGetPointerMapping(dpy, btnMap, 8);
104 maxButtons = (numButtons > 8) ? 8 : numButtons;
105 vlog.info("Enabling %d button%s of X pointer device",
106 maxButtons, (maxButtons != 1) ? "s" : "");
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000107
108 int dpyWidth = DisplayWidth(dpy, DefaultScreen(dpy));
109 int dpyHeight = DisplayHeight(dpy, DefaultScreen(dpy));
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000110
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000111 ImageFactory factory((bool)useShm, (bool)useOverlay);
112 image = factory.newImage(dpy, dpyWidth, dpyHeight);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000113 image->get(DefaultRootWindow(dpy));
114
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000115 pollmgr = new PollingManager(dpy, image, &factory);
116
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000117 pf.bpp = image->xim->bits_per_pixel;
118 pf.depth = image->xim->depth;
119 pf.bigEndian = (image->xim->byte_order == MSBFirst);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000120 pf.trueColour = image->isTrueColor();
121 pf.redShift = ffs(image->xim->red_mask) - 1;
122 pf.greenShift = ffs(image->xim->green_mask) - 1;
123 pf.blueShift = ffs(image->xim->blue_mask) - 1;
124 pf.redMax = image->xim->red_mask >> pf.redShift;
125 pf.greenMax = image->xim->green_mask >> pf.greenShift;
126 pf.blueMax = image->xim->blue_mask >> pf.blueShift;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000127
128 pb = new FullFramePixelBuffer(pf, dpyWidth, dpyHeight,
129 (rdr::U8*)image->xim->data, this);
130 }
131 virtual ~XDesktop() {
132 delete pb;
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000133 delete pollmgr;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000134 }
135
136 void setVNCServer(VNCServer* s) {
137 server = s;
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000138 pollmgr->setVNCServer(s);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000139 server->setPixelBuffer(pb);
140 }
141
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000142 inline void poll() {
143 pollmgr->poll();
144 }
145
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000146 // -=- SDesktop interface
147
148 virtual void pointerEvent(const Point& pos, rdr::U8 buttonMask) {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000149#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000150 if (!haveXtest) return;
151 XTestFakeMotionEvent(dpy, DefaultScreen(dpy), pos.x, pos.y, CurrentTime);
152 if (buttonMask != oldButtonMask) {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000153 for (int i = 0; i < maxButtons; i++) {
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000154 if ((buttonMask ^ oldButtonMask) & (1<<i)) {
155 if (buttonMask & (1<<i)) {
156 XTestFakeButtonEvent(dpy, i+1, True, CurrentTime);
157 } else {
158 XTestFakeButtonEvent(dpy, i+1, False, CurrentTime);
159 }
160 }
161 }
162 }
163 oldButtonMask = buttonMask;
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000164#endif
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000165 }
166
167 virtual void keyEvent(rdr::U32 key, bool down) {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000168#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000169 if (!haveXtest) return;
170 int keycode = XKeysymToKeycode(dpy, key);
171 if (keycode)
172 XTestFakeKeyEvent(dpy, keycode, down, CurrentTime);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000173#endif
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000174 }
175
176 virtual void clientCutText(const char* str, int len) {
177 }
178
179 virtual Point getFbSize() {
180 return Point(pb->width(), pb->height());
181 }
182
183 // rfb::ColourMap callbacks
184 virtual void lookup(int index, int* r, int* g, int* b) {
185 XColor xc;
186 xc.pixel = index;
187 if (index < DisplayCells(dpy,DefaultScreen(dpy))) {
188 XQueryColor(dpy, DefaultColormap(dpy,DefaultScreen(dpy)), &xc);
189 } else {
190 xc.red = xc.green = xc.blue = 0;
191 }
192 *r = xc.red;
193 *g = xc.green;
194 *b = xc.blue;
195 }
196
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000197protected:
198 Display* dpy;
199 PixelFormat pf;
200 PixelBuffer* pb;
201 VNCServer* server;
202 Image* image;
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000203 PollingManager* pollmgr;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000204 int oldButtonMask;
205 bool haveXtest;
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000206 int maxButtons;
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000207};
208
209
210class FileTcpFilter : public TcpFilter
211{
212
213public:
214
215 FileTcpFilter(const char *fname)
216 : TcpFilter("-"), fileName(NULL), lastModTime(0)
217 {
218 if (fname != NULL)
219 fileName = strdup((char *)fname);
220 }
221
222 virtual ~FileTcpFilter()
223 {
224 if (fileName != NULL)
225 free(fileName);
226 }
227
228 virtual bool verifyConnection(Socket* s)
229 {
230 if (!reloadRules()) {
231 vlog.error("Could not read IP filtering rules: rejecting all clients");
232 filter.clear();
233 filter.push_back(parsePattern("-"));
234 return false;
235 }
236
237 return TcpFilter::verifyConnection(s);
238 }
239
240protected:
241
242 bool reloadRules()
243 {
244 if (fileName == NULL)
245 return true;
246
247 struct stat st;
248 if (stat(fileName, &st) != 0)
249 return false;
250
251 if (st.st_mtime != lastModTime) {
252 // Actually reload only if the file was modified
253 FILE *fp = fopen(fileName, "r");
254 if (fp == NULL)
255 return false;
256
257 // Remove all the rules from the parent class
258 filter.clear();
259
260 // Parse the file contents adding rules to the parent class
261 char buf[32];
262 while (readLine(buf, 32, fp)) {
263 if (buf[0] && strchr("+-?", buf[0])) {
264 filter.push_back(parsePattern(buf));
265 }
266 }
267
268 fclose(fp);
269 lastModTime = st.st_mtime;
270 }
271 return true;
272 }
273
274protected:
275
276 char *fileName;
277 time_t lastModTime;
278
279private:
280
281 //
282 // NOTE: we silently truncate long lines in this function.
283 //
284
285 bool readLine(char *buf, int bufSize, FILE *fp)
286 {
287 if (fp == NULL || buf == NULL || bufSize == 0)
288 return false;
289
290 if (fgets(buf, bufSize, fp) == NULL)
291 return false;
292
293 char *ptr = strchr(buf, '\n');
294 if (ptr != NULL) {
295 *ptr = '\0'; // remove newline at the end
296 } else {
297 if (!feof(fp)) {
298 int c;
299 do { // skip the rest of a long line
300 c = getc(fp);
301 } while (c != '\n' && c != EOF);
302 }
303 }
304 return true;
305 }
306
307};
308
309
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000310char* programName;
311
312static void usage()
313{
314 fprintf(stderr, "\nusage: %s [<parameters>]\n", programName);
315 fprintf(stderr,"\n"
316 "Parameters can be turned on with -<param> or off with -<param>=0\n"
317 "Parameters which take a value can be specified as "
318 "-<param> <value>\n"
319 "Other valid forms are <param>=<value> -<param>=<value> "
320 "--<param>=<value>\n"
321 "Parameter names are case-insensitive. The parameters are:\n\n");
322 Configuration::listParams(79, 14);
323 exit(1);
324}
325
326int main(int argc, char** argv)
327{
328 initStdIOLoggers();
329 LogWriter::setLogParams("*:stderr:30");
330
331 programName = argv[0];
332 Display* dpy;
333
334 for (int i = 1; i < argc; i++) {
335 if (Configuration::setParam(argv[i]))
336 continue;
337
338 if (argv[i][0] == '-') {
339 if (i+1 < argc) {
340 if (Configuration::setParam(&argv[i][1], argv[i+1])) {
341 i++;
342 continue;
343 }
344 }
345 usage();
346 }
347
348 usage();
349 }
350
351 CharArray dpyStr(displayname.getData());
352 if (!(dpy = XOpenDisplay(dpyStr.buf[0] ? dpyStr.buf : 0))) {
353 fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
354 programName, XDisplayName(displayname.getData()));
355 exit(1);
356 }
357
358 signal(SIGHUP, CleanupSignalHandler);
359 signal(SIGINT, CleanupSignalHandler);
360 signal(SIGTERM, CleanupSignalHandler);
361
362 try {
363 XDesktop desktop(dpy);
364 VNCServerST server("x0vncserver", &desktop);
365 desktop.setVNCServer(&server);
366
367 TcpSocket::initTcpSockets();
368 TcpListener listener((int)rfbport);
369 vlog.info("Listening on port %d", (int)rfbport);
370
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000371 FileTcpFilter fileTcpFilter(hostsFile.getData());
372 if (strlen(hostsFile.getData()) != 0)
373 listener.setFilter(&fileTcpFilter);
374
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +0000375 CPUMonitor cpumon((int)maxProcessorUsage, 1000);
376 int dynPollingCycle = (int)pollingCycle;
377
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000378 struct timeval timeSaved, timeNow;
379 struct timezone tz;
380 gettimeofday(&timeSaved, &tz);
381 timeSaved.tv_sec -= 60;
382
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000383 while (true) {
384 fd_set rfds;
385 struct timeval tv;
386
387 tv.tv_sec = 0;
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +0000388 tv.tv_usec = dynPollingCycle * 1000;
389 if (tv.tv_usec > 500000) {
390 tv.tv_usec = 500000;
391 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000392
393 FD_ZERO(&rfds);
394 FD_SET(listener.getFd(), &rfds);
395
396 std::list<Socket*> sockets;
397 server.getSockets(&sockets);
398 std::list<Socket*>::iterator i;
399 for (i = sockets.begin(); i != sockets.end(); i++) {
400 FD_SET((*i)->getFd(), &rfds);
401 }
402
403 int n = select(FD_SETSIZE, &rfds, 0, 0, &tv);
Constantin Kaplinsky659e9002005-09-09 08:32:02 +0000404 if (n < 0) {
405 if (errno == EINTR) {
406 vlog.debug("interrupted select() system call");
407 continue;
408 } else {
409 throw rdr::SystemException("select", errno);
410 }
411 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000412
413 if (FD_ISSET(listener.getFd(), &rfds)) {
414 Socket* sock = listener.accept();
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000415 if (sock) {
416 server.addClient(sock);
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +0000417 cpumon.update(); // count time from now
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000418 } else {
419 vlog.status("Client connection rejected");
420 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000421 }
422
423 server.getSockets(&sockets);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000424
425 // Nothing more to do if there are no client connections.
426 if (sockets.empty())
427 continue;
428
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000429 for (i = sockets.begin(); i != sockets.end(); i++) {
430 if (FD_ISSET((*i)->getFd(), &rfds)) {
431 server.processSocketEvent(*i);
432 }
433 }
434
435 server.checkTimeouts();
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000436
437 if (gettimeofday(&timeNow, &tz) == 0) {
438 int diff = (int)((timeNow.tv_usec - timeSaved.tv_usec + 500) / 1000 +
439 (timeNow.tv_sec - timeSaved.tv_sec) * 1000);
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +0000440 if (diff >= dynPollingCycle) {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000441 timeSaved = timeNow;
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +0000442 int coeff = cpumon.check();
443 if (coeff < 90 || coeff > 110) {
444 // Adjust polling cycle to satisfy MaxProcessorUsage setting
445 dynPollingCycle = (dynPollingCycle * 100 + coeff/2) / coeff;
446 if (dynPollingCycle < (int)pollingCycle) {
447 dynPollingCycle = (int)pollingCycle;
448 } else if (dynPollingCycle > (int)pollingCycle * 32) {
449 dynPollingCycle = (int)pollingCycle * 32;
450 }
451 // DEBUG:
452 // if (dynPollingCycle != old) {
453 // fprintf(stderr, "[%dms]\t", dynPollingCycle);
454 // }
455 }
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000456 desktop.poll();
457 }
458 } else {
459 // Something strange has happened -- gettimeofday(2) failed.
460 // Poll after each select(), as in the original VNC4 code.
461 desktop.poll();
462 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000463 }
464
465 } catch (rdr::Exception &e) {
466 vlog.error(e.str());
467 };
468
469 return 0;
470}