blob: edaf1a8cf3a0050f603515f85ffcd7df6c71c1b0 [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());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000205 running = true;
206 }
207
208 virtual void stop() {
209 running = false;
210
211 delete pb;
212 delete pollmgr;
213 delete image;
214
215 pb = 0;
216 pollmgr = 0;
217 image = 0;
218 }
219
220 inline bool isRunning() {
221 return running;
222 }
223
224 inline void poll() {
225 if (pollmgr)
Constantin Kaplinsky54cfef32008-06-03 07:04:17 +0000226 pollmgr->poll(server);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000227 }
228
229 virtual void pointerEvent(const Point& pos, int buttonMask) {
230 pollmgr->setPointerPos(pos);
231#ifdef HAVE_XTEST
232 if (!haveXtest) return;
233 XTestFakeMotionEvent(dpy, DefaultScreen(dpy),
234 geometry->offsetLeft() + pos.x,
235 geometry->offsetTop() + pos.y,
236 CurrentTime);
237 if (buttonMask != oldButtonMask) {
238 for (int i = 0; i < maxButtons; i++) {
239 if ((buttonMask ^ oldButtonMask) & (1<<i)) {
240 if (buttonMask & (1<<i)) {
241 XTestFakeButtonEvent(dpy, i+1, True, CurrentTime);
242 } else {
243 XTestFakeButtonEvent(dpy, i+1, False, CurrentTime);
244 }
245 }
246 }
247 }
248 oldButtonMask = buttonMask;
249#endif
250 }
251
252 virtual void keyEvent(rdr::U32 key, bool down) {
253#ifdef HAVE_XTEST
254 if (!haveXtest) return;
255 int keycode = XKeysymToKeycode(dpy, key);
256 if (keycode)
257 XTestFakeKeyEvent(dpy, keycode, down, CurrentTime);
258#endif
259 }
260
261 virtual void clientCutText(const char* str, int len) {
262 }
263
264 virtual Point getFbSize() {
265 return Point(pb->width(), pb->height());
266 }
267
268 // -=- ColourMap callbacks
269 virtual void lookup(int index, int* r, int* g, int* b) {
270 XColor xc;
271 xc.pixel = index;
272 if (index < DisplayCells(dpy,DefaultScreen(dpy))) {
273 XQueryColor(dpy, DefaultColormap(dpy,DefaultScreen(dpy)), &xc);
274 } else {
275 xc.red = xc.green = xc.blue = 0;
276 }
277 *r = xc.red;
278 *g = xc.green;
279 *b = xc.blue;
280 }
281
282protected:
283 Display* dpy;
284 Geometry* geometry;
285 PixelFormat pf;
Constantin Kaplinsky2c019832008-05-30 11:02:04 +0000286 XPixelBuffer* pb;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000287 VNCServer* server;
288 Image* image;
289 PollingManager* pollmgr;
290 int oldButtonMask;
291 bool haveXtest;
292 int maxButtons;
293 bool running;
294};
295
296
297class FileTcpFilter : public TcpFilter
298{
299
300public:
301
302 FileTcpFilter(const char *fname)
303 : TcpFilter("-"), fileName(NULL), lastModTime(0)
304 {
305 if (fname != NULL)
306 fileName = strdup((char *)fname);
307 }
308
309 virtual ~FileTcpFilter()
310 {
311 if (fileName != NULL)
312 free(fileName);
313 }
314
315 virtual bool verifyConnection(Socket* s)
316 {
317 if (!reloadRules()) {
318 vlog.error("Could not read IP filtering rules: rejecting all clients");
319 filter.clear();
320 filter.push_back(parsePattern("-"));
321 return false;
322 }
323
324 return TcpFilter::verifyConnection(s);
325 }
326
327protected:
328
329 bool reloadRules()
330 {
331 if (fileName == NULL)
332 return true;
333
334 struct stat st;
335 if (stat(fileName, &st) != 0)
336 return false;
337
338 if (st.st_mtime != lastModTime) {
339 // Actually reload only if the file was modified
340 FILE *fp = fopen(fileName, "r");
341 if (fp == NULL)
342 return false;
343
344 // Remove all the rules from the parent class
345 filter.clear();
346
347 // Parse the file contents adding rules to the parent class
348 char buf[32];
349 while (readLine(buf, 32, fp)) {
350 if (buf[0] && strchr("+-?", buf[0])) {
351 filter.push_back(parsePattern(buf));
352 }
353 }
354
355 fclose(fp);
356 lastModTime = st.st_mtime;
357 }
358 return true;
359 }
360
361protected:
362
363 char *fileName;
364 time_t lastModTime;
365
366private:
367
368 //
369 // NOTE: we silently truncate long lines in this function.
370 //
371
372 bool readLine(char *buf, int bufSize, FILE *fp)
373 {
374 if (fp == NULL || buf == NULL || bufSize == 0)
375 return false;
376
377 if (fgets(buf, bufSize, fp) == NULL)
378 return false;
379
380 char *ptr = strchr(buf, '\n');
381 if (ptr != NULL) {
382 *ptr = '\0'; // remove newline at the end
383 } else {
384 if (!feof(fp)) {
385 int c;
386 do { // skip the rest of a long line
387 c = getc(fp);
388 } while (c != '\n' && c != EOF);
389 }
390 }
391 return true;
392 }
393
394};
395
396char* programName;
397
398static void usage()
399{
Constantin Kaplinskyb9632702006-12-01 10:54:55 +0000400 fprintf(stderr, "TightVNC Server version %s, built %s\n\n",
401 VERSION, buildtime);
Constantin Kaplinskyf4986f42006-06-02 10:49:03 +0000402 fprintf(stderr, "Usage: %s [<parameters>]\n", programName);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000403 fprintf(stderr,"\n"
404 "Parameters can be turned on with -<param> or off with -<param>=0\n"
405 "Parameters which take a value can be specified as "
406 "-<param> <value>\n"
407 "Other valid forms are <param>=<value> -<param>=<value> "
408 "--<param>=<value>\n"
409 "Parameter names are case-insensitive. The parameters are:\n\n");
410 Configuration::listParams(79, 14);
411 exit(1);
412}
413
414int main(int argc, char** argv)
415{
416 initStdIOLoggers();
417 LogWriter::setLogParams("*:stderr:30");
418
419 programName = argv[0];
420 Display* dpy;
421
422 for (int i = 1; i < argc; i++) {
423 if (Configuration::setParam(argv[i]))
424 continue;
425
426 if (argv[i][0] == '-') {
427 if (i+1 < argc) {
428 if (Configuration::setParam(&argv[i][1], argv[i+1])) {
429 i++;
430 continue;
431 }
432 }
433 usage();
434 }
435
436 usage();
437 }
438
439 CharArray dpyStr(displayname.getData());
440 if (!(dpy = XOpenDisplay(dpyStr.buf[0] ? dpyStr.buf : 0))) {
441 fprintf(stderr,"%s: unable to open display \"%s\"\r\n",
442 programName, XDisplayName(displayname.getData()));
443 exit(1);
444 }
445
446 signal(SIGHUP, CleanupSignalHandler);
447 signal(SIGINT, CleanupSignalHandler);
448 signal(SIGTERM, CleanupSignalHandler);
449
450 try {
451 TXWindow::init(dpy,"x0vncserver");
452 Geometry geo(DisplayWidth(dpy, DefaultScreen(dpy)),
453 DisplayHeight(dpy, DefaultScreen(dpy)));
454 XDesktop desktop(dpy, &geo);
Constantin Kaplinsky82328312008-04-24 08:44:24 +0000455
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000456 VNCServerST server("x0vncserver", &desktop);
457 QueryConnHandler qcHandler(dpy, &server);
458 server.setQueryConnectionHandler(&qcHandler);
Constantin Kaplinsky82328312008-04-24 08:44:24 +0000459 server.enableVideoSelection(true);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000460
461 TcpListener listener((int)rfbport);
462 vlog.info("Listening on port %d", (int)rfbport);
463
464 FileTcpFilter fileTcpFilter(hostsFile.getData());
465 if (strlen(hostsFile.getData()) != 0)
466 listener.setFilter(&fileTcpFilter);
467
468 PollingScheduler sched((int)pollingCycle, (int)maxProcessorUsage);
469
470 while (!caughtSignal) {
471 struct timeval tv;
472 fd_set rfds;
473 std::list<Socket*> sockets;
474 std::list<Socket*>::iterator i;
475
476 // Process any incoming X events
477 TXWindow::handleXEvents(dpy);
478
479 FD_ZERO(&rfds);
480 FD_SET(listener.getFd(), &rfds);
481 server.getSockets(&sockets);
482 int clients_connected = 0;
483 for (i = sockets.begin(); i != sockets.end(); i++) {
484 if ((*i)->isShutdown()) {
485 server.removeSocket(*i);
486 delete (*i);
487 } else {
488 FD_SET((*i)->getFd(), &rfds);
489 clients_connected++;
490 }
491 }
492
Constantin Kaplinsky813dbb42006-12-05 08:03:18 +0000493 if (!clients_connected)
494 sched.reset();
495
496 if (sched.isRunning()) {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000497 int wait_ms = sched.millisRemaining();
498 if (wait_ms > 500) {
499 wait_ms = 500;
500 }
501 tv.tv_usec = wait_ms * 1000;
502#ifdef DEBUG
503 // fprintf(stderr, "[%d]\t", wait_ms);
504#endif
505 } else {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000506 tv.tv_usec = 100000;
507 }
508 tv.tv_sec = 0;
509
510 // Do the wait...
511 sched.sleepStarted();
512 int n = select(FD_SETSIZE, &rfds, 0, 0, &tv);
513 sched.sleepFinished();
514
515 if (n < 0) {
516 if (errno == EINTR) {
517 vlog.debug("Interrupted select() system call");
518 continue;
519 } else {
520 throw rdr::SystemException("select", errno);
521 }
522 }
523
524 // Accept new VNC connections
525 if (FD_ISSET(listener.getFd(), &rfds)) {
526 Socket* sock = listener.accept();
527 if (sock) {
528 server.addSocket(sock);
529 } else {
530 vlog.status("Client connection rejected");
531 }
532 }
533
534 Timer::checkTimeouts();
535 server.checkTimeouts();
536
537 // Client list could have been changed.
538 server.getSockets(&sockets);
539
540 // Nothing more to do if there are no client connections.
541 if (sockets.empty())
542 continue;
543
544 // Process events on existing VNC connections
545 for (i = sockets.begin(); i != sockets.end(); i++) {
546 if (FD_ISSET((*i)->getFd(), &rfds))
547 server.processSocketEvent(*i);
548 }
549
550 if (desktop.isRunning() && sched.goodTimeToPoll()) {
551 sched.newPass();
552 desktop.poll();
553 }
554 }
555
556 } catch (rdr::Exception &e) {
557 vlog.error(e.str());
558 return 1;
559 }
560
561 vlog.info("Terminated");
562 return 0;
563}