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