blob: 30e54162019c00a9c56b914e340e28ad9e4769dc [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>
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000024#include <sys/types.h>
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000025#include <sys/stat.h>
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000026#include <unistd.h>
27#include <errno.h>
28#include <rfb/Logger_stdio.h>
29#include <rfb/LogWriter.h>
30#include <rfb/VNCServerST.h>
31#include <rfb/Configuration.h>
32#include <rfb/SSecurityFactoryStandard.h>
33
34#include <network/TcpSocket.h>
35
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000036#include <signal.h>
37#include <X11/X.h>
38#include <X11/Xlib.h>
39#include <X11/Xutil.h>
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000040#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000041#include <X11/extensions/XTest.h>
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000042#endif
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000043
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +000044#include <x0vncserver/Image.h>
45#include <x0vncserver/PollingManager.h>
Constantin Kaplinsky0cbad332006-02-16 14:51:11 +000046#include <x0vncserver/PollingScheduler.h>
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000047
48using namespace rfb;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000049using namespace network;
50
51LogWriter vlog("main");
52
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +000053IntParameter pollingCycle("PollingCycle", "Milliseconds per one polling "
54 "cycle; actual interval may be dynamically "
Constantin Kaplinskyef7ac9b2006-02-10 12:26:54 +000055 "adjusted to satisfy MaxProcessorUsage setting", 30);
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +000056IntParameter maxProcessorUsage("MaxProcessorUsage", "Maximum percentage of "
57 "CPU time to be consumed", 35);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000058BoolParameter useShm("UseSHM", "Use MIT-SHM extension if available", true);
59BoolParameter useOverlay("OverlayMode", "Use overlay mode under "
60 "IRIX or Solaris", true);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000061StringParameter displayname("display", "The X display", "");
62IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",5900);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000063StringParameter hostsFile("HostsFile", "File with IP access control rules", "");
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000064VncAuthPasswdFileParameter vncAuthPasswdFile;
65
66static void CleanupSignalHandler(int sig)
67{
68 // CleanupSignalHandler allows C++ object cleanup to happen because it calls
69 // exit() rather than the default which is to abort.
70 fprintf(stderr,"CleanupSignalHandler called\n");
71 exit(1);
72}
73
74
75class XDesktop : public SDesktop, public rfb::ColourMap
76{
77public:
78 XDesktop(Display* dpy_)
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000079 : dpy(dpy_), pb(0), server(0), oldButtonMask(0), haveXtest(false),
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +000080 maxButtons(0)
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000081 {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000082#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000083 int xtestEventBase;
84 int xtestErrorBase;
85 int major, minor;
86
87 if (XTestQueryExtension(dpy, &xtestEventBase,
88 &xtestErrorBase, &major, &minor)) {
89 XTestGrabControl(dpy, True);
90 vlog.info("XTest extension present - version %d.%d",major,minor);
91 haveXtest = true;
92 } else {
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000093#endif
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000094 vlog.info("XTest extension not present");
95 vlog.info("unable to inject events or display while server is grabbed");
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000096#ifdef HAVE_XTEST
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +000097 }
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +000098#endif
99
100 // Determine actual number of buttons of the X pointer device.
101 unsigned char btnMap[8];
102 int numButtons = XGetPointerMapping(dpy, btnMap, 8);
103 maxButtons = (numButtons > 8) ? 8 : numButtons;
104 vlog.info("Enabling %d button%s of X pointer device",
105 maxButtons, (maxButtons != 1) ? "s" : "");
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000106
107 int dpyWidth = DisplayWidth(dpy, DefaultScreen(dpy));
108 int dpyHeight = DisplayHeight(dpy, DefaultScreen(dpy));
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000109
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000110 ImageFactory factory((bool)useShm, (bool)useOverlay);
111 image = factory.newImage(dpy, dpyWidth, dpyHeight);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000112 image->get(DefaultRootWindow(dpy));
113
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000114 pollmgr = new PollingManager(dpy, image, &factory);
115
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000116 pf.bpp = image->xim->bits_per_pixel;
117 pf.depth = image->xim->depth;
118 pf.bigEndian = (image->xim->byte_order == MSBFirst);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000119 pf.trueColour = image->isTrueColor();
120 pf.redShift = ffs(image->xim->red_mask) - 1;
121 pf.greenShift = ffs(image->xim->green_mask) - 1;
122 pf.blueShift = ffs(image->xim->blue_mask) - 1;
123 pf.redMax = image->xim->red_mask >> pf.redShift;
124 pf.greenMax = image->xim->green_mask >> pf.greenShift;
125 pf.blueMax = image->xim->blue_mask >> pf.blueShift;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000126
127 pb = new FullFramePixelBuffer(pf, dpyWidth, dpyHeight,
128 (rdr::U8*)image->xim->data, this);
129 }
130 virtual ~XDesktop() {
131 delete pb;
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000132 delete pollmgr;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000133 }
134
135 void setVNCServer(VNCServer* s) {
136 server = s;
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000137 pollmgr->setVNCServer(s);
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000138 server->setPixelBuffer(pb);
139 }
140
Constantin Kaplinskyaf1891c2005-09-29 06:18:28 +0000141 inline void poll() {
142 pollmgr->poll();
143 }
144
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000145 // -=- SDesktop interface
146
147 virtual void pointerEvent(const Point& pos, rdr::U8 buttonMask) {
Constantin Kaplinskyce676c62006-02-08 13:36:58 +0000148 pollmgr->setPointerPos(pos);
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 Kaplinskye179b5a2006-02-17 09:30:21 +0000375 PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
Constantin Kaplinsky602f34d2005-09-14 16:11:41 +0000376
Constantin Kaplinsky3f56fa72006-02-16 11:50:25 +0000377 fd_set rfds;
378 struct timeval tv;
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000379
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000380 while (true) {
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000381
382 FD_ZERO(&rfds);
383 FD_SET(listener.getFd(), &rfds);
384
385 std::list<Socket*> sockets;
386 server.getSockets(&sockets);
387 std::list<Socket*>::iterator i;
Constantin Kaplinsky3f56fa72006-02-16 11:50:25 +0000388 int clients_connected = 0;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000389 for (i = sockets.begin(); i != sockets.end(); i++) {
390 FD_SET((*i)->getFd(), &rfds);
Constantin Kaplinsky3f56fa72006-02-16 11:50:25 +0000391 clients_connected++;
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000392 }
393
Constantin Kaplinsky3f56fa72006-02-16 11:50:25 +0000394 if (clients_connected) {
Constantin Kaplinsky0cbad332006-02-16 14:51:11 +0000395 int wait_ms = sched.millisRemaining();
396 if (wait_ms > 500) {
Constantin Kaplinsky3f56fa72006-02-16 11:50:25 +0000397 wait_ms = 500;
398 }
399 tv.tv_usec = wait_ms * 1000;
400#ifdef DEBUG
401 fprintf(stderr, "[%d]\t", wait_ms);
402#endif
403 } else {
Constantin Kaplinsky0cbad332006-02-16 14:51:11 +0000404 sched.reset();
405 tv.tv_usec = 100000;
Constantin Kaplinsky3f56fa72006-02-16 11:50:25 +0000406 }
407 tv.tv_sec = 0;
408
Constantin Kaplinskye179b5a2006-02-17 09:30:21 +0000409 sched.sleepStarted();
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000410 int n = select(FD_SETSIZE, &rfds, 0, 0, &tv);
Constantin Kaplinskye179b5a2006-02-17 09:30:21 +0000411 sched.sleepFinished();
412
Constantin Kaplinsky659e9002005-09-09 08:32:02 +0000413 if (n < 0) {
414 if (errno == EINTR) {
415 vlog.debug("interrupted select() system call");
416 continue;
417 } else {
418 throw rdr::SystemException("select", errno);
419 }
420 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000421
422 if (FD_ISSET(listener.getFd(), &rfds)) {
423 Socket* sock = listener.accept();
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000424 if (sock) {
425 server.addClient(sock);
426 } else {
427 vlog.status("Client connection rejected");
428 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000429 }
430
431 server.getSockets(&sockets);
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000432
433 // Nothing more to do if there are no client connections.
434 if (sockets.empty())
435 continue;
436
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000437 for (i = sockets.begin(); i != sockets.end(); i++) {
438 if (FD_ISSET((*i)->getFd(), &rfds)) {
439 server.processSocketEvent(*i);
440 }
441 }
442
443 server.checkTimeouts();
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000444
Constantin Kaplinskye47123e2006-02-16 16:44:50 +0000445 if (sched.goodTimeToPoll()) {
Constantin Kaplinsky0cbad332006-02-16 14:51:11 +0000446 sched.newPass();
Constantin Kaplinskyd31fd312005-09-08 19:29:02 +0000447 desktop.poll();
448 }
Constantin Kaplinsky47ed8d32004-10-08 09:43:57 +0000449 }
450
451 } catch (rdr::Exception &e) {
452 vlog.error(e.str());
453 };
454
455 return 0;
456}