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