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