aboutsummaryrefslogtreecommitdiffstats
path: root/win/winvnc/VNCServerWin32.cxx
blob: 79769e93cd787ea2434839d5397ba497fc1005cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/* Copyright (C) 2002-2005 RealVNC Ltd.  All Rights Reserved.
 * 
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 * USA.
 */

// -=- WinVNC Version 4.0 Main Routine

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <winvnc/VNCServerWin32.h>
#include <winvnc/resource.h>
#include <winvnc/ListConnInfo.h>
#include <winvnc/STrayIcon.h>

#include <os/Mutex.h>

#include <rfb_win32/ComputerName.h>
#include <rfb_win32/CurrentUser.h>
#include <rfb_win32/Service.h>

#include <rfb/Hostname.h>
#include <rfb/LogWriter.h>

using namespace rfb;
using namespace win32;
using namespace winvnc;
using namespace network;

static LogWriter vlog("VNCServerWin32");


const TCHAR* winvnc::VNCServerWin32::RegConfigPath = _T("Software\\TigerVNC\\WinVNC4");


static IntParameter port_number("PortNumber",
  "TCP/IP port on which the server will accept connections", 5900);
static StringParameter hosts("Hosts",
  "Filter describing which hosts are allowed access to this server", "+");
static BoolParameter localHost("LocalHost",
  "Only accept connections from via the local loop-back network interface", false);
static BoolParameter queryOnlyIfLoggedOn("QueryOnlyIfLoggedOn",
  "Only prompt for a local user to accept incoming connections if there is a user logged on", false);
static BoolParameter showTrayIcon("ShowTrayIcon",
  "Show the configuration applet in the system tray icon", true);


VNCServerWin32::VNCServerWin32()
  : command(NoCommand),
    commandEvent(CreateEvent(0, TRUE, FALSE, 0)),
    sessionEvent(isServiceProcess() ?
      CreateEvent(0, FALSE, FALSE, "Global\\SessionEventTigerVNC") : 0),
    vncServer(CStr(ComputerName().buf), &desktop),
    thread_id(-1), runServer(false), isDesktopStarted(false),
    config(&sockMgr), rfbSock(&sockMgr), trayIcon(0),
    queryConnectDialog(0)
{
  commandLock = new os::Mutex;
  commandSig = new os::Condition(commandLock);

  runLock = new os::Mutex;

  // Initialise the desktop
  desktop.setStatusLocation(&isDesktopStarted);
  desktop.setQueryConnectionHandler(this);

  // Register the desktop's event to be handled
  sockMgr.addEvent(desktop.getUpdateEvent(), &desktop);
  sockMgr.addEvent(desktop.getTerminateEvent(), this);

  // Register the queued command event to be handled
  sockMgr.addEvent(commandEvent, this);
  if (sessionEvent)
    sockMgr.addEvent(sessionEvent, this);
}

VNCServerWin32::~VNCServerWin32() {
  delete trayIcon;

  // Stop the SDisplay from updating our state
  desktop.setStatusLocation(0);

  // Join the Accept/Reject dialog thread
  if (queryConnectDialog) {
    queryConnectDialog->wait();
    delete queryConnectDialog;
  }

  delete runLock;

  delete commandSig;
  delete commandLock;
}


void VNCServerWin32::processAddressChange() {
  if (!trayIcon)
    return;

  // Tool-tip prefix depends on server mode
  const TCHAR* prefix = _T("VNC Server (User):");
  if (isServiceProcess())
    prefix = _T("VNC Server (Service):");

  // Fetch the list of addresses
  std::list<char*> addrs;
  if (rfbSock.isListening())
    TcpListener::getMyAddresses(&addrs);
  else
    addrs.push_front(strDup("Not accepting connections"));

  // Allocate space for the new tip
  std::list<char*>::iterator i, next_i;
  int length = _tcslen(prefix)+1;
  for (i=addrs.begin(); i!= addrs.end(); i++)
    length += strlen(*i) + 1;

  // Build the new tip
  TCharArray toolTip(length);
  _tcscpy(toolTip.buf, prefix);
  for (i=addrs.begin(); i!= addrs.end(); i=next_i) {
    next_i = i; next_i ++;
    TCharArray addr(*i);    // Assumes ownership of string
    _tcscat(toolTip.buf, addr.buf);
    if (next_i != addrs.end())
      _tcscat(toolTip.buf, _T(","));
  }
  
  // Pass the new tip to the tray icon
  vlog.info("Refreshing tray icon");
  trayIcon->setToolTip(toolTip.buf);
}

void VNCServerWin32::regConfigChanged() {
  // -=- Make sure we're listening on the right ports.
  rfbSock.setServer(&vncServer);
  rfbSock.setPort(port_number, localHost);

  // -=- Update the TCP address filter for both ports, if open.
  CharArray pattern(hosts.getData());
  rfbSock.setFilter(pattern.buf);

  // -=- Update the tray icon tooltip text with IP addresses
  processAddressChange();
}


int VNCServerWin32::run() {
  {
    os::AutoMutex a(runLock);
    thread_id = GetCurrentThreadId();
    runServer = true;
  }

  // - Create the tray icon (if possible)
  if (showTrayIcon)
	  trayIcon = new STrayIconThread(*this, IDI_ICON, IDI_CONNECTED,
                                 IDI_ICON_DISABLE, IDI_CONNECTED_DISABLE,
                                 IDR_TRAY);

  // - Register for notification of configuration changes
  config.setCallback(this);
  if (isServiceProcess())
    config.setKey(HKEY_LOCAL_MACHINE, RegConfigPath);
  else
    config.setKey(HKEY_CURRENT_USER, RegConfigPath);

  // - Set the address-changed handler for the RFB socket
  rfbSock.setAddressChangeNotifier(this);

  DWORD result = 0;
  try {
    vlog.debug("Entering message loop");

    // - Run the server until we're told to quit
    MSG msg;
    int result = 0;
    while (runServer) {
      result = sockMgr.getMessage(&msg, NULL, 0, 0);
      if (result < 0)
        throw rdr::SystemException("getMessage", GetLastError());
      if (!isServiceProcess() && (result == 0))
        break;
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }

    vlog.debug("Server exited cleanly");
  } catch (rdr::SystemException &s) {
    vlog.error("%s", s.str());
    result = s.err;
  } catch (rdr::Exception &e) {
    vlog.error("%s", e.str());
  }

  {
    os::AutoMutex a(runLock);
    runServer = false;
    thread_id = (DWORD)-1;
  }

  return result;
}

void VNCServerWin32::stop() {
  os::AutoMutex a(runLock);
  runServer = false;
  if (thread_id != (DWORD)-1)
    PostThreadMessage(thread_id, WM_QUIT, 0, 0);
}


bool VNCServerWin32::disconnectClients(const char* reason) {
  return queueCommand(DisconnectClients, reason, 0);
}

bool VNCServerWin32::addNewClient(const char* client) {
  TcpSocket* sock = 0;
  try {
    CharArray hostname;
    int port;
    getHostAndPort(client, &hostname.buf, &port, 5500);
    vlog.error("port=%d", port);
    sock = new TcpSocket(hostname.buf, port);
    if (queueCommand(AddClient, sock, 0))
      return true;
    delete sock;
  } catch (...) {
    delete sock;
  }
  return false;
}

bool VNCServerWin32::getClientsInfo(ListConnInfo* LCInfo) {
  return queueCommand(GetClientsInfo, LCInfo, 0);
}

bool VNCServerWin32::setClientsStatus(ListConnInfo* LCInfo) {
  return queueCommand(SetClientsStatus, LCInfo, 0);
}

void VNCServerWin32::queryConnection(network::Socket* sock,
                                     const char* userName)
{
  if (queryOnlyIfLoggedOn && CurrentUserToken().noUserLoggedOn()) {
    vncServer.approveConnection(sock, true, NULL);
    return;
  }
  if (queryConnectDialog) {
    vncServer.approveConnection(sock, false, "Another connection is currently being queried.");
    return;
  }
  queryConnectDialog = new QueryConnectDialog(sock, userName, this);
  queryConnectDialog->startDialog();
}

void VNCServerWin32::queryConnectionComplete() {
  queueCommand(QueryConnectionComplete, 0, 0, false);
}


bool VNCServerWin32::queueCommand(Command cmd, const void* data, int len, bool wait) {
  os::AutoMutex a(commandLock);
  while (command != NoCommand)
    commandSig->wait();
  command = cmd;
  commandData = data;
  commandDataLen = len;
  SetEvent(commandEvent);
  if (wait) {
    while (command != NoCommand)
      commandSig->wait();
    commandSig->signal();
  }
  return true;
}

void VNCServerWin32::processEvent(HANDLE event_) {
  ResetEvent(event_);

  if (event_ == commandEvent.h) {
    // If there is no command queued then return immediately
    {
      os::AutoMutex a(commandLock);
      if (command == NoCommand)
        return;
    }

    // Perform the required command
    switch (command) {

    case DisconnectClients:
      // Disconnect all currently active VNC Viewers
      vncServer.closeClients((const char*)commandData);
      break;

    case AddClient:
      // Make a reverse connection to a VNC Viewer
      sockMgr.addSocket((network::Socket*)commandData, &vncServer);
      break;
  case GetClientsInfo:
    getConnInfo((ListConnInfo*)commandData);
    break;
  case SetClientsStatus:
    setConnStatus((ListConnInfo*)commandData);
    break;

    case QueryConnectionComplete:
      // The Accept/Reject dialog has completed
      // Get the result, then clean it up
      vncServer.approveConnection(queryConnectDialog->getSock(),
                                  queryConnectDialog->isAccepted(),
                                  "Connection rejected by user");
      queryConnectDialog->wait();
      delete queryConnectDialog;
      queryConnectDialog = 0;
      break;

    default:
      vlog.error("unknown command %d queued", command);
    };

    // Clear the command and signal completion
    {
      os::AutoMutex a(commandLock);
      command = NoCommand;
      commandSig->signal();
    }
  } else if ((event_ == sessionEvent.h) ||
             (event_ == desktop.getTerminateEvent())) {
    stop();
  }
}

void VNCServerWin32::getConnInfo(ListConnInfo * listConn)
{
  std::list<network::Socket*> sockets;
  std::list<network::Socket*>::iterator i;

  listConn->Clear();
  listConn->setDisable(sockMgr.getDisable(&vncServer));

  vncServer.getSockets(&sockets);

  for (i = sockets.begin(); i != sockets.end(); i++) {
    rfb::SConnection* conn;
    int status;

    conn = vncServer.getConnection(*i);
    if (!conn)
      continue;

    if (!conn->authenticated())
      status = 3;
    else if (conn->accessCheck(rfb::SConnection::AccessPtrEvents |
                               rfb::SConnection::AccessKeyEvents |
                               rfb::SConnection::AccessView))
      status = 0;
    else if (conn->accessCheck(rfb::SConnection::AccessView))
      status = 1;
    else
      status = 2;

    listConn->addInfo((void*)(*i), (*i)->getPeerAddress(), status);
  }
}

void VNCServerWin32::setConnStatus(ListConnInfo* listConn)
{
  sockMgr.setDisable(&vncServer, listConn->getDisable());

  if (listConn->Empty())
    return;

  for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
    network::Socket* sock;
    rfb::SConnection* conn;
    int status;

    sock = (network::Socket*)listConn->iGetConn();

    conn = vncServer.getConnection(sock);
    if (!conn)
      continue;

    status = listConn->iGetStatus();
    if (status == 3) {
      conn->close(0);
    } else {
      rfb::SConnection::AccessRights ar;

      ar = rfb::SConnection::AccessDefault;

      switch (status) {
      case 0:
        ar |= rfb::SConnection::AccessPtrEvents |
              rfb::SConnection::AccessKeyEvents |
              rfb::SConnection::AccessView;
        break;
      case 1:
        ar |= rfb::SConnection::AccessView;
        ar &= ~(rfb::SConnection::AccessPtrEvents |
                rfb::SConnection::AccessKeyEvents);
        break;
      case 2:
        ar &= ~(rfb::SConnection::AccessPtrEvents |
                rfb::SConnection::AccessKeyEvents |
                rfb::SConnection::AccessView);
        break;
      }
      conn->setAccessRights(ar);
      conn->framebufferUpdateRequest(vncServer.getPixelBuffer()->getRect(), false);
    }
  }
}