blob: 8489290a1f6c105163c5a1e09b9ee5e56eb5bb05 [file] [log] [blame]
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Constantin Kaplinsky2c019832008-05-30 11:02:04 +00002 * Copyright (C) 2004-2008 Constantin Kaplinsky. All Rights Reserved.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +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 */
19
20// FIXME: Check cases when screen width/height is not a multiply of 32.
21// e.g. 800x600.
22
23#include <strings.h>
24#include <sys/types.h>
25#include <sys/stat.h>
26#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#include <rfb/Timer.h>
34#include <network/TcpSocket.h>
35#include <tx/TXWindow.h>
36
Constantin Kaplinskya3b60c42006-06-02 04:07:49 +000037#include <vncconfig/QueryConnectDialog.h>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000038
39#include <signal.h>
40#include <X11/X.h>
41#include <X11/Xlib.h>
42#include <X11/Xutil.h>
43#ifdef HAVE_XTEST
44#include <X11/extensions/XTest.h>
45#endif
46
47#include <x0vncserver/Geometry.h>
48#include <x0vncserver/Image.h>
Constantin Kaplinsky614c7b52007-12-26 18:17:09 +000049#include <x0vncserver/XPixelBuffer.h>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000050#include <x0vncserver/PollingManager.h>
51#include <x0vncserver/PollingScheduler.h>
52
53// XXX Lynx/OS 2.3: protos for select(), bzero()
54#ifdef Lynx
55#include <sys/proto.h>
56#endif
57
Constantin Kaplinskyb9632702006-12-01 10:54:55 +000058extern char buildtime[];
59
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000060using namespace rfb;
61using namespace network;
62
63static LogWriter vlog("Main");
64
65IntParameter pollingCycle("PollingCycle", "Milliseconds per one polling "
66 "cycle; actual interval may be dynamically "
67 "adjusted to satisfy MaxProcessorUsage setting", 30);
68IntParameter maxProcessorUsage("MaxProcessorUsage", "Maximum percentage of "
69 "CPU time to be consumed", 35);
70BoolParameter useShm("UseSHM", "Use MIT-SHM extension if available", true);
71BoolParameter useOverlay("OverlayMode", "Use overlay mode under "
72 "IRIX or Solaris", true);
73StringParameter displayname("display", "The X display", "");
74IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",5900);
75IntParameter queryConnectTimeout("QueryConnectTimeout",
76 "Number of seconds to show the Accept Connection dialog before "
77 "rejecting the connection",
78 10);
79StringParameter hostsFile("HostsFile", "File with IP access control rules", "");
80
81//
82// Allow the main loop terminate itself gracefully on receiving a signal.
83//
84
85static bool caughtSignal = false;
86
87static void CleanupSignalHandler(int sig)
88{
89 caughtSignal = true;
90}
91
92
93class QueryConnHandler : public VNCServerST::QueryConnectionHandler,
94 public QueryResultCallback {
95public:
96 QueryConnHandler(Display* dpy, VNCServerST* vs)
97 : display(dpy), server(vs), queryConnectDialog(0), queryConnectSock(0) {}
98 ~QueryConnHandler() { delete queryConnectDialog; }
99
100 // -=- VNCServerST::QueryConnectionHandler interface
101 virtual VNCServerST::queryResult queryConnection(network::Socket* sock,
102 const char* userName,
103 char** reason) {
104 if (queryConnectSock) {
105 *reason = strDup("Another connection is currently being queried.");
106 return VNCServerST::REJECT;
107 }
108 if (!userName) userName = "(anonymous)";
109 queryConnectSock = sock;
110 CharArray address(sock->getPeerAddress());
111 delete queryConnectDialog;
112 queryConnectDialog = new QueryConnectDialog(display, address.buf,
113 userName, queryConnectTimeout,
114 this);
115 queryConnectDialog->map();
116 return VNCServerST::PENDING;
117 }
118
119 // -=- QueryResultCallback interface
120 virtual void queryApproved() {
121 server->approveConnection(queryConnectSock, true, 0);
122 queryConnectSock = 0;
123 }
124 virtual void queryRejected() {
125 server->approveConnection(queryConnectSock, false,
126 "Connection rejected by local user");
127 queryConnectSock = 0;
128 }
129private:
130 Display* display;
131 VNCServerST* server;
132 QueryConnectDialog* queryConnectDialog;
133 network::Socket* queryConnectSock;
134};
135
136
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000137class XDesktop : public SDesktop, public ColourMap
138{
139public:
140 XDesktop(Display* dpy_, Geometry *geometry_)
141 : dpy(dpy_), geometry(geometry_), pb(0), server(0), image(0), pollmgr(0),
142 oldButtonMask(0), haveXtest(false), maxButtons(0), running(false)
143 {
144#ifdef HAVE_XTEST
145 int xtestEventBase;
146 int xtestErrorBase;
147 int major, minor;
148
149 if (XTestQueryExtension(dpy, &xtestEventBase,
150 &xtestErrorBase, &major, &minor)) {
151 XTestGrabControl(dpy, True);
152 vlog.info("XTest extension present - version %d.%d",major,minor);
153 haveXtest = true;
154 } else {
155#endif
156 vlog.info("XTest extension not present");
157 vlog.info("Unable to inject events or display while server is grabbed");
158#ifdef HAVE_XTEST
159 }
160#endif
161
162 }
163 virtual ~XDesktop() {
164 stop();
165 }
166
167 // -=- SDesktop interface
168
169 virtual void start(VNCServer* vs) {
170
171 // Determine actual number of buttons of the X pointer device.
172 unsigned char btnMap[8];
173 int numButtons = XGetPointerMapping(dpy, btnMap, 8);
174 maxButtons = (numButtons > 8) ? 8 : numButtons;
175 vlog.info("Enabling %d button%s of X pointer device",
176 maxButtons, (maxButtons != 1) ? "s" : "");
177
178 // Create an image for maintaining framebuffer data.
179 ImageFactory factory((bool)useShm, (bool)useOverlay);
180 image = factory.newImage(dpy, geometry->width(), geometry->height());
181 vlog.info("Allocated %s", image->classDesc());
182
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000183 pf.bpp = image->xim->bits_per_pixel;
184 pf.depth = image->xim->depth;
185 pf.bigEndian = (image->xim->byte_order == MSBFirst);
186 pf.trueColour = image->isTrueColor();
187 pf.redShift = ffs(image->xim->red_mask) - 1;
188 pf.greenShift = ffs(image->xim->green_mask) - 1;
189 pf.blueShift = ffs(image->xim->blue_mask) - 1;
190 pf.redMax = image->xim->red_mask >> pf.redShift;
191 pf.greenMax = image->xim->green_mask >> pf.greenShift;
192 pf.blueMax = image->xim->blue_mask >> pf.blueShift;
193
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000194 // Provide pixel buffer to the server object.
Constantin Kaplinsky936c3692007-12-27 08:42:53 +0000195 pb = new XPixelBuffer(dpy, image,
196 geometry->offsetLeft(), geometry->offsetTop(),
197 pf, this);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000198 server = vs;
199 server->setPixelBuffer(pb);
200
Constantin Kaplinsky2c019832008-05-30 11:02:04 +0000201 // Create polling manager object for detection of pixel changes.
202 pollmgr = new PollingManager(dpy, pb, &factory,
203 geometry->offsetLeft(),
204 geometry->offsetTop());
205 pollmgr->setVNCServer(vs);
206
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000207 running = true;
208 }
209
210 virtual void stop() {
211 running = false;
212
213 delete pb;
214 delete pollmgr;
215 delete image;
216
217 pb = 0;
218 pollmgr = 0;
219 image = 0;
220 }
221
222 inline bool isRunning() {
223 return running;
224 }
225
226 inline void poll() {
227 if (pollmgr)
228 pollmgr->poll();
229 }
230
231 virtual void pointerEvent(const Point& pos, int buttonMask) {
232 pollmgr->setPointerPos(pos);
233#ifdef HAVE_XTEST
234 if (!haveXtest) return;
235 XTestFakeMotionEvent(dpy, DefaultScreen(dpy),
236 geometry->offsetLeft() + pos.x,
237 geometry->offsetTop() + pos.y,
238 CurrentTime);
239 if (buttonMask != oldButtonMask) {
240 for (int i = 0; i < maxButtons; i++) {
241 if ((buttonMask ^ oldButtonMask) & (1<<i)) {
242 if (buttonMask & (1<<i)) {
243 XTestFakeButtonEvent(dpy, i+1, True, CurrentTime);
244 } else {
245 XTestFakeButtonEvent(dpy, i+1, False, CurrentTime);
246 }
247 }
248 }
249 }
250 oldButtonMask = buttonMask;
251#endif
252 }
253
254 virtual void keyEvent(rdr::U32 key, bool down) {
255#ifdef HAVE_XTEST
256 if (!haveXtest) return;
257 int keycode = XKeysymToKeycode(dpy, key);
258 if (keycode)
259 XTestFakeKeyEvent(dpy, keycode, down, CurrentTime);
260#endif
261 }
262
263 virtual void clientCutText(const char* str, int len) {
264 }
265
266 virtual Point getFbSize() {
267 return Point(pb->width(), pb->height());
268 }
269
270 // -=- ColourMap callbacks
271 virtual void lookup(int index, int* r, int* g, int* b) {
272 XColor xc;
273 xc.pixel = index;
274 if (index < DisplayCells(dpy,DefaultScreen(dpy))) {
275 XQueryColor(dpy, DefaultColormap(dpy,DefaultScreen(dpy)), &xc);
276 } else {
277 xc.red = xc.green = xc.blue = 0;
278 }
279 *r = xc.red;
280 *g = xc.green;
281 *b = xc.blue;
282 }
283
284protected:
285 Display* dpy;
286 Geometry* geometry;
287 PixelFormat pf;
Constantin Kaplinsky2c019832008-05-30 11:02:04 +0000288 XPixelBuffer* pb;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000289 VNCServer* server;
290 Image* image;
291 PollingManager* pollmgr;
292 int oldButtonMask;
293 bool haveXtest;
294 int maxButtons;
295 bool running;
296};
297
298
299class FileTcpFilter : public TcpFilter
300{
301
302public:
303
304 FileTcpFilter(const char *fname)
305 : TcpFilter("-"), fileName(NULL), lastModTime(0)
306 {
307 if (fname != NULL)
308 fileName = strdup((char *)fname);
309 }
310
311 virtual ~FileTcpFilter()
312 {
313 if (fileName != NULL)
314 free(fileName);
315 }
316
317 virtual bool verifyConnection(Socket* s)
318 {
319 if (!reloadRules()) {
320 vlog.error("Could not read IP filtering rules: rejecting all clients");
321 filter.clear();
322 filter.push_back(parsePattern("-"));
323 return false;
324 }
325
326 return TcpFilter::verifyConnection(s);
327 }
328
329protected:
330
331 bool reloadRules()
332 {
333 if (fileName == NULL)
334 return true;
335
336 struct stat st;
337 if (stat(fileName, &st) != 0)
338 return false;
339
340 if (st.st_mtime != lastModTime) {
341 // Actually reload only if the file was modified
342 FILE *fp = fopen(fileName, "r");
343 if (fp == NULL)
344 return false;
345
346 // Remove all the rules from the parent class
347 filter.clear();
348
349 // Parse the file contents adding rules to the parent class
350 char buf[32];
351 while (readLine(buf, 32, fp)) {
352 if (buf[0] && strchr("+-?", buf[0])) {
353 filter.push_back(parsePattern(buf));
354 }
355 }
356
357 fclose(fp);
358 lastModTime = st.st_mtime;
359 }
360 return true;
361 }
362
363protected:
364
365 char *fileName;
366 time_t lastModTime;
367
368private:
369
370 //
371 // NOTE: we silently truncate long lines in this function.
372 //
373
374 bool readLine(char *buf, int bufSize, FILE *fp)
375 {
376 if (fp == NULL || buf == NULL || bufSize == 0)
377 return false;
378
379 if (fgets(buf, bufSize, fp) == NULL)
380 return false;
381
382 char *ptr = strchr(buf, '\n');
383 if (ptr != NULL) {
384 *ptr = '\0'; // remove newline at the end
385 } else {
386 if (!feof(fp)) {
387 int c;
388 do { // skip the rest of a long line
389 c = getc(fp);
390 } while (c != '\n' && c != EOF);
391 }
392 }
393 return true;
394 }
395
396};
397
398char* programName;
399
400static void usage()
401{
Constantin Kaplinskyb9632702006-12-01 10:54:55 +0000402 fprintf(stderr, "TightVNC Server version %s, built %s\n\n",
403 VERSION, buildtime);
Constantin Kaplinskyf4986f42006-06-02 10:49:03 +0000404 fprintf(stderr, "Usage: %s [<parameters>]\n", programName);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000405 fprintf(stderr,"\n"
406 "Parameters can be turned on with -<param> or off with -<param>=0\n"
407 "Parameters which take a value can be specified as "
408 "-<param> <value>\n"
409 "Other valid forms are <param>=<value> -<param>=<value> "
410 "--<param>=<value>\n"
411 "Parameter names are case-insensitive. The parameters are:\n\n");
412 Configuration::listParams(79, 14);
413 exit(1);
414}
415
416int main(int argc, char** argv)
417{
418 initStdIOLoggers();
419 LogWriter::setLogParams("*:stderr:30");
420
421 programName = argv[0];
422 Display* dpy;
423
424 for (int i = 1; i < argc; i++) {
425 if (Configuration::setParam(argv[i]))
426 continue;
427
428 if (argv[i][0] == '-') {
429 if (i+1 < argc) {
430 if (Configuration::setParam(&argv[i][1], argv[i+1])) {
431 i++;
432 continue;
433 }
434 }
435 usage();
436 }
437
438 usage();
439 }
440
441 CharArray dpyStr(displayname.getData());
442 if (!(dpy = XOpenDisplay(dpyStr.buf[0] ? dpyStr.buf : 0))) {
443 fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
444 programName, XDisplayName(displayname.getData()));
445 exit(1);
446 }
447
448 signal(SIGHUP, CleanupSignalHandler);
449 signal(SIGINT, CleanupSignalHandler);
450 signal(SIGTERM, CleanupSignalHandler);
451
452 try {
453 TXWindow::init(dpy,"x0vncserver");
454 Geometry geo(DisplayWidth(dpy, DefaultScreen(dpy)),
455 DisplayHeight(dpy, DefaultScreen(dpy)));
456 XDesktop desktop(dpy, &geo);
Constantin Kaplinsky82328312008-04-24 08:44:24 +0000457
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000458 VNCServerST server("x0vncserver", &desktop);
459 QueryConnHandler qcHandler(dpy, &server);
460 server.setQueryConnectionHandler(&qcHandler);
Constantin Kaplinsky82328312008-04-24 08:44:24 +0000461 server.enableVideoSelection(true);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000462
463 TcpListener listener((int)rfbport);
464 vlog.info("Listening on port %d", (int)rfbport);
465
466 FileTcpFilter fileTcpFilter(hostsFile.getData());
467 if (strlen(hostsFile.getData()) != 0)
468 listener.setFilter(&fileTcpFilter);
469
470 PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
471
472 while (!caughtSignal) {
473 struct timeval tv;
474 fd_set rfds;
475 std::list<Socket*> sockets;
476 std::list<Socket*>::iterator i;
477
478 // Process any incoming X events
479 TXWindow::handleXEvents(dpy);
480
481 FD_ZERO(&rfds);
482 FD_SET(listener.getFd(), &rfds);
483 server.getSockets(&sockets);
484 int clients_connected = 0;
485 for (i = sockets.begin(); i != sockets.end(); i++) {
486 if ((*i)->isShutdown()) {
487 server.removeSocket(*i);
488 delete (*i);
489 } else {
490 FD_SET((*i)->getFd(), &rfds);
491 clients_connected++;
492 }
493 }
494
Constantin Kaplinsky813dbb42006-12-05 08:03:18 +0000495 if (!clients_connected)
496 sched.reset();
497
498 if (sched.isRunning()) {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000499 int wait_ms = sched.millisRemaining();
500 if (wait_ms > 500) {
501 wait_ms = 500;
502 }
503 tv.tv_usec = wait_ms * 1000;
504#ifdef DEBUG
505 // fprintf(stderr, "[%d]\t", wait_ms);
506#endif
507 } else {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000508 tv.tv_usec = 100000;
509 }
510 tv.tv_sec = 0;
511
512 // Do the wait...
513 sched.sleepStarted();
514 int n = select(FD_SETSIZE, &rfds, 0, 0, &tv);
515 sched.sleepFinished();
516
517 if (n < 0) {
518 if (errno == EINTR) {
519 vlog.debug("Interrupted select() system call");
520 continue;
521 } else {
522 throw rdr::SystemException("select", errno);
523 }
524 }
525
526 // Accept new VNC connections
527 if (FD_ISSET(listener.getFd(), &rfds)) {
528 Socket* sock = listener.accept();
529 if (sock) {
530 server.addSocket(sock);
531 } else {
532 vlog.status("Client connection rejected");
533 }
534 }
535
536 Timer::checkTimeouts();
537 server.checkTimeouts();
538
539 // Client list could have been changed.
540 server.getSockets(&sockets);
541
542 // Nothing more to do if there are no client connections.
543 if (sockets.empty())
544 continue;
545
546 // Process events on existing VNC connections
547 for (i = sockets.begin(); i != sockets.end(); i++) {
548 if (FD_ISSET((*i)->getFd(), &rfds))
549 server.processSocketEvent(*i);
550 }
551
552 if (desktop.isRunning() && sched.goodTimeToPoll()) {
553 sched.newPass();
554 desktop.poll();
555 }
556 }
557
558 } catch (rdr::Exception &e) {
559 vlog.error(e.str());
560 return 1;
561 }
562
563 vlog.info("Terminated");
564 return 0;
565}