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