Example #1
0
void WinDxgiDevice::getAdapter(IDXGIAdapter **dxgiAdapter) {
  HRESULT hr = m_dxgiDevice->GetAdapter(dxgiAdapter);
  if (FAILED(hr)) {
    StringStorage errMess;
    errMess.format(_T("Can't get default Adapter for IDXGIDevice (%ld)"), (long)hr);
    throw Exception(errMess.getString());
  }
}
void AdministrationConfigDialog::apply()
{
  StringStorage logLevelStringStorage;
  m_logLevel.getText(&logLevelStringStorage);

  int logLevel = 0;

  StringParser::parseInt(logLevelStringStorage.getString(), &logLevel);

  m_config->setLogLevel(logLevel);

  bool alwaysShared = false;
  bool neverShared = false;
  bool disconnectClients = false;

  if (m_shared[0].isChecked()) {
    alwaysShared = true;
    neverShared = false;
    disconnectClients = false;
  } else if (m_shared[1].isChecked()) {
    alwaysShared = false;
    neverShared = true;
    disconnectClients = false;
  } else if (m_shared[2].isChecked()) {
    alwaysShared = false;
    neverShared = true;
    disconnectClients = true;
  } else if (m_shared[3].isChecked()) {
    alwaysShared = false;
    neverShared = false;
    disconnectClients = false;
  } else if (m_shared[4].isChecked()) {
    alwaysShared = false;
    neverShared = false;
    disconnectClients = true;
  }

  m_config->useControlAuth(m_useControlAuth.isChecked());

  if (m_cpControl->hasPassword()) {
    m_config->setControlPassword((const unsigned char *)m_cpControl->getCryptedPassword());
  } else {
    m_config->deleteControlPassword();
  }

  if (m_disconnectAction[0].isChecked()) {
    m_config->setDisconnectAction(ServerConfig::DA_DO_NOTHING);
  } else if (m_disconnectAction[1].isChecked()) {
    m_config->setDisconnectAction(ServerConfig::DA_LOCK_WORKSTATION);
  } else if (m_disconnectAction[2].isChecked()) {
    m_config->setDisconnectAction(ServerConfig::DA_LOGOUT_WORKSTATION);
  }

  m_config->setAlwaysShared(alwaysShared);
  m_config->setNeverShared(neverShared);
  m_config->disconnectExistingClients(disconnectClients);
  m_config->saveLogToAllUsersPath(m_logForAllUsers.isChecked());
}
Example #3
0
void AnonymousPipe::assignHandlesFor(HANDLE hTargetProc, bool neededToClose,
                                     bool keepCloseRight)
{
  HANDLE hSrcProc = GetCurrentProcess();
  HANDLE hWrite = 0, hRead = 0;
  if (DuplicateHandle(hSrcProc, m_hWrite, hTargetProc, &hWrite, 0, FALSE,
                      DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == 0) {
    StringStorage errText;
    Environment::getErrStr(_T("Cannot dupplicate write")
                           _T(" handle for the anonymous pipe"),
                           &errText);
    throw Exception(errText.getString());
  }
  m_hWrite = hWrite;
  if (DuplicateHandle(hSrcProc, m_hRead, hTargetProc, &hRead, 0, FALSE,
                      DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == 0) {
    StringStorage errText;
    Environment::getErrStr(_T("Cannot dupplicate read")
                           _T(" handle for the anonymous pipe"),
                           &errText);
    throw Exception(errText.getString());
  }
  m_hRead = hRead;
  // Try keep of the close rights.
  if (keepCloseRight) {
    if (DuplicateHandle(hTargetProc, m_hWrite, 0, 0, 0, FALSE,
                        DUPLICATE_CLOSE_SOURCE) == 0) {
      StringStorage errText;
      Environment::getErrStr(_T("Cannot keep the right to close of the write")
                             _T(" handle of the anonymous pipe"),
                             &errText);
      throw Exception(errText.getString());
    }
    if (DuplicateHandle(hTargetProc, m_hRead, 0, 0, 0, FALSE,
                        DUPLICATE_CLOSE_SOURCE) == 0) {
      StringStorage errText;
      Environment::getErrStr(_T("Cannot keep the right to close of the read")
                             _T(" handle of the anonymous pipe"),
                             &errText);
      throw Exception(errText.getString());
    }
    // Now the current process can close the handles.
  }
  m_neededToClose = neededToClose;
}
bool EditPortMappingDialog::isUserDataValid()
{
  StringStorage rectStringStorage;
  StringStorage portStringStorage;

  m_geometryTextBox.getText(&rectStringStorage);
  m_portTextBox.getText(&portStringStorage);

  if (!PortMappingRect::tryParse(rectStringStorage.getString())) {
    MessageBox(m_ctrlThis.getWindow(),
               StringTable::getString(IDS_INVALID_PORT_MAPPING_STRING),
               StringTable::getString(IDS_CAPTION_BAD_INPUT),
               MB_OK | MB_ICONWARNING);
    m_geometryTextBox.setFocus();
    return false;
  }

  int port;

  StringParser::parseInt(portStringStorage.getString(), &port);

  if ((port < 1) || (port > 65535)) {
    MessageBox(m_ctrlThis.getWindow(),
               StringTable::getString(IDS_PORT_RANGE_ERROR),
               StringTable::getString(IDS_CAPTION_BAD_INPUT),
               MB_OK | MB_ICONWARNING);
    m_portTextBox.setFocus();
    return false;
  }

  PortMappingContainer *extraPorts = Configurator::getInstance()->getServerConfig()->getPortMappingContainer();

  size_t index = extraPorts->findByPort(port);

  if ((index != (size_t)-1) && (extraPorts->at(index) != m_mapping)) {
    MessageBox(m_ctrlThis.getWindow(),
               StringTable::getString(IDS_PORT_ALREADY_IN_USE),
               StringTable::getString(IDS_CAPTION_BAD_INPUT),
               MB_OK | MB_ICONWARNING);
    m_portTextBox.setFocus();
    return false;
  }

  return true;
}
void FileTransferReplyBuffer::onFileListReply()
{
  UINT8 compressionLevel = 0;
  UINT32 compressedSize = 0;
  UINT32 uncompressedSize = 0;

  UINT8 *buffer = NULL;

  {
    omni_mutex_lock l(*m_readMutex);

    compressionLevel = m_dataInputStream->readUInt8();
    compressedSize = m_dataInputStream->readUInt32();
    uncompressedSize = m_dataInputStream->readUInt32();

    buffer = readCompressedDataBlock(compressedSize,
                                     uncompressedSize,
                                     compressionLevel);
  }

  ByteArrayInputStream memoryInputStream((char *)buffer, uncompressedSize);
  DataInputStream filesInfoReader(&memoryInputStream);

  if (m_filesInfo != NULL) {
    delete[] m_filesInfo;
  }

  try {
    m_filesInfoCount = filesInfoReader.readUInt32();
    m_filesInfo = new FileInfo[m_filesInfoCount];

    for (UINT32 i = 0; i < m_filesInfoCount; i++) {
      FileInfo *fileInfo = &m_filesInfo[i];

      fileInfo->setSize(filesInfoReader.readUInt64());
      fileInfo->setLastModified(filesInfoReader.readUInt64());
      fileInfo->setFlags(filesInfoReader.readUInt16());

      StringStorage t;
      filesInfoReader.readUTF8(&t);

      fileInfo->setFileName(t.getString());
    } 
  } catch (IOException &ioEx) {

    delete[] buffer;

    throw ioEx;
  } 

  Log::info(_T("Recieved file list reply: \n")
            _T("\t files count = %d\n")
            _T("\t use compression = %d\n"),
            m_filesInfoCount, compressionLevel);

  delete[] buffer;
}
Example #6
0
bool File::renameTo(File *dest)
{
  StringStorage destPathName;
  dest->getPath(&destPathName);
  if (MoveFile(m_pathName.getString(), destPathName.getString()) == 0) {
    return false;
  }
  return true;
}
BOOL ConfirmDialog::onInitDialog()
{
  setControlById(m_text, IDC_CONFIRM_TEXT);

  StringStorage text;
  text.format(_T("管理员%s需要控制您的电脑,确定?"), m_tvnServerApplication->getUser().getString());
  m_text.setText(text.getString());
  return TRUE;
}
int QueryConnectionApplication::execute(const TCHAR *peerAddr, bool acceptByDefault, DWORD timeOutSec)
{

  StringStorage curModulePath;
  StringStorage command;

  Environment::getCurrentModulePath(&curModulePath);

  command.format(_T("%s %s %s %s %s %s %d"),
                 curModulePath.getString(),
                 QueryConnectionCommandLine::QUERY_CONNECTION,
                 QueryConnectionCommandLine::PEER_ADDR,
                 peerAddr,
                 acceptByDefault ? QueryConnectionCommandLine::ACCEPT : _T(""),
                 QueryConnectionCommandLine::TIMEOUT,
                 timeOutSec);

  Process *process = 0;

  int defaultRetCode = acceptByDefault ? 0 : 1;
  int retCode = defaultRetCode;

  if (Configurator::getInstance()->getServiceFlag()) {
    process = new CurrentConsoleProcess(command.getString());
  } else {
    process = new Process(command.getString());
  }

  try {
    process->start();
    process->waitForExit();
    retCode = process->getExitCode();
  } catch (Exception &ex) {
    Log::error(ex.getMessage());
  }

  delete process;

  if (retCode != 0 && retCode != 1) {
    retCode = defaultRetCode;
  }

  return retCode;
}
void RemoteViewerCore::handshake()
{
  char serverProtocol[13];
  serverProtocol[12] = 0;
  m_input->readFully(serverProtocol, 12);

  m_major = strtol(&serverProtocol[4], 0, 10);
  m_minor = strtol(&serverProtocol[8], 0, 10);
  m_isTight = false;

  m_logWriter.info(_T("Server sent protocol version: %s"), getProtocolString().getString());
  if (!isRfbProtocolString(serverProtocol) || 
      m_major < 3 ||
      (m_major == 3 && m_minor < 3)) {
    StringStorage error;
    AnsiStringStorage protocolAnsi(serverProtocol);
    StringStorage protocol;
    protocolAnsi.toStringStorage(&protocol);
    error.format(_T("Unsupported protocol: %s"), protocol.getString());
    m_logWriter.error(_T("%s"), error.getString());
    throw Exception(error.getString());
  }

  // if version is 4.0 or later, then set version 3.8.
  if (m_major > 3) {
    m_major = 3;
    m_minor = 8;
  } else { // else set version from list 3.3, 3.7, 3.8.
    // select minor version:
    if (m_minor < 7) {
      m_minor = 3;
    }
    if (m_minor >= 8) {
     m_minor = 8;
    }
  }

  m_logWriter.info(_T("Send to server protocol version: %s"), getProtocolString().getString());

  AnsiStringStorage clientProtocolAnsi;
  clientProtocolAnsi.fromStringStorage(&getProtocolString());
  m_output->writeFully(clientProtocolAnsi.getString(), 12);
  m_output->flush();
}
bool VncViewerConfigDialog::testNum(TextBox *tb, const TCHAR *tbName)
{
  StringStorage text;
  tb->getText(&text);

  if (StringParser::tryParseInt(text.getString())) {
    return true;
  }

  StringStorage message;
  message.format(_T("Value in field '%s' must be numeric"), tbName);

  MessageBox(m_ctrlThis.getWindow(), message.getString(),
             _T("VNCViewer general config"), MB_OK | MB_ICONWARNING);

  tb->setFocus();

  return false;
}
Example #11
0
void WinFilePath::setString(const TCHAR *string)
{
  StringStorage str(string);
  if (!str.isEmpty()) {
    if (str.findLast('/') == 0) {
      m_parentPathIsRoot = true;
    }
    str.replaceChar(_T('/'), _T('\\'));
    if (str.beginsWith(_T('\\'))) {
      str.remove(0, 1);
    }
    if (str.endsWith(_T('\\'))) {
      str.truncate(1);
    }
  }
  // desktop replacement
//TCHAR path[MAX_PATH + 1];

	StringStorage specFolder;
	str.getSubstring(&specFolder,0,8);

	if(specFolder.isEqualTo(_T("[Desktop]"))){
		StringStorage tmp;
		str.getSubstring(&tmp,9,str.getLength());
		Environment::getSpecialFolderPath(Environment::USERDESKTOP_DATA_SPECIAL_FOLDER, &specFolder);
		str.setString(specFolder.getString());
		str.appendString(tmp.getString());
  }
	
	str.getSubstring(&specFolder,0,5);

	if(specFolder.isEqualTo(_T("[Docs]"))){
		StringStorage tmp;
		str.getSubstring(&tmp,6,str.getLength());
		Environment::getSpecialFolderPath(Environment::USERDOCS_DATA_SPECIAL_FOLDER, &specFolder);
		str.setString(specFolder.getString());
		str.appendString(tmp.getString());
	}



  StringStorage::setString(str.getString());
}
void DesktopServerProto::checkDimension(const Dimension *dim)
{
  StringStorage errMess;
  if (abs(dim->width)  > 64000 ||
      abs(dim->height) > 64000) {
    errMess.format(_T("Wrong dimension (%dx%d)"), dim->width,
                                                  dim->height);
    throw Exception(errMess.getString());
  }
}
ConnectionConfigSM::ConnectionConfigSM(const TCHAR registryPath[],
                                       const TCHAR entryName[])
: RegistrySettingsManager()
{
  StringStorage keyName;
  keyName.format(_T("%s\\History\\%s"),
                 registryPath,
                 entryName);
  setRegistryKey(Registry::getCurrentUserKey(), keyName.getString());
}
void ConfigDialog::updateCaption()
{
  StringStorage caption;

  caption.format(StringTable::getString(IDS_SERVER_CONFIG_CAPTION_FORMAT),
                 StringTable::getString(m_isConfiguringService ? IDS_SERVICE : IDS_SERVER),
                 m_reloadConfigCommand == 0 ? StringTable::getString(IDS_OFFLINE_MODE) : _T(""));

  m_ctrlThis.setText(caption.getString());
}
Example #15
0
void DownloadOperation::notifyFailedToDownload(const TCHAR *errorDescription)
{
  StringStorage message;

  message.format(_T("Error: failed to download '%s' (%s)"),
                 m_pathToSourceFile.getString(),
                 errorDescription);

  notifyError(message.getString());
}
WinDxgiDevice::WinDxgiDevice(WinD3D11Device *winD3D11Device)
: m_dxgiDevice(0)
{
  HRESULT hr = winD3D11Device->deviceQueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&m_dxgiDevice));
  if (FAILED(hr)) {
    StringStorage errMess;
    errMess.format(_T("Can't QueryInterface for IDXGIDevice (%l)"), (long)hr);
    throw Exception(errMess.getString());
  }
}
void ControlApplication::checkServicePasswords()
{
  Configurator::getInstance()->setServiceFlag(true);
  Configurator::getInstance()->load();
  ServerConfig *config = Configurator::getInstance()->getServerConfig();

  bool askToChangeRfbAuth = !config->isUsingAuthentication() || !config->hasPrimaryPassword();
  bool askToChangeAdmAuth = !config->isControlAuthEnabled() || !config->hasControlPassword();
  SetPasswordsDialog dialog(askToChangeRfbAuth, askToChangeAdmAuth);
  if (dialog.showModal() == IDOK) {
    UINT8 cryptedPass[8];
    bool useRfbAuth = dialog.getUseRfbPass();
    bool dontUseRfbAuth = dialog.getRfbPassForClear();
    // Note: The state !useRfbAuth && !dontUseRfbAuth is valid and means "do not change
    // the auth settings".
    if (useRfbAuth) {
      StringStorage pass;
      dialog.getRfbPass(&pass);
      getCryptedPassword(cryptedPass, pass.getString());
      config->setPrimaryPassword(cryptedPass);
      config->useAuthentication(true);
    } else if (dontUseRfbAuth) {
      config->deletePrimaryPassword();
      config->deleteReadOnlyPassword();
      config->useAuthentication(false);
    }
    bool useAdmAuth = dialog.getUseAdmPass();
    bool dontUseAdmAuth = dialog.getAdmPassForClear();
    if (useAdmAuth) {
      StringStorage pass;
      dialog.getAdmPass(&pass);
      getCryptedPassword(cryptedPass, pass.getString());
      config->setControlPassword(cryptedPass);
      config->useControlAuth(true);
    } else if (dontUseAdmAuth) {
      config->deleteControlPassword();
      config->useControlAuth(false);
    }
    Configurator::getInstance()->save();
    reloadConfig();
  }
}
void RfbInitializer::doVncAuth()
{
  UINT8 challenge[16];
  srand((unsigned)time(0));
  for (int i = 0; i < sizeof(challenge); i++) {
    challenge[i] = rand() & 0xff;
  }

  m_output->writeFully(challenge, sizeof(challenge));
  UINT8 response[16];
  m_input->readFully(response, sizeof(response));
  // Checking for a ban after auth.
  checkForBan();

  // Comparing the challenge with the response.
  ServerConfig *srvConf = Configurator::getInstance()->getServerConfig();
  bool hasPrim = srvConf->hasPrimaryPassword();

  if (!hasPrim) {
    throw AuthException(_T("Server is not configured properly"));
  }

  if (hasPrim) {
    UINT8 primPass[8];
    srvConf->getPrimaryPassword(primPass);
    VncPassCrypt passCrypt;
    passCrypt.setPlain(primPass);
    if (passCrypt.challengeAndResponseIsValid(challenge, response)) {
      return;
    }
  }

  // At this time we are sure that the client was typed an incorectly password.
  m_extAuthListener->onAuthFailed(m_client);

  StringStorage clientAddressStorage;
  m_client->getPeerHost(&clientAddressStorage);
  StringStorage errMess;
  errMess.format(_T("Authentication failed from %s"), clientAddressStorage.getString());

  throw AuthException(errMess.getString());
}
bool RemoteViewerCore::receiveFbUpdateRectangle()
{
  Rect rect;
  rect.left = m_input->readUInt16();
  rect.top = m_input->readUInt16();
  rect.setWidth(m_input->readUInt16());
  rect.setHeight(m_input->readUInt16());

  int encodingType = m_input->readInt32();

  m_logWriter.debug(_T("Rectangle: (%d, %d), (%d, %d). Type is %d"), 
                    rect.left, rect.top, rect.right, rect.bottom, encodingType);

  if (encodingType == PseudoEncDefs::LAST_RECT)
    return true;
  if (!Decoder::isPseudo(encodingType)) {
    if (!m_frameBuffer.getDimension().getRect().intersection(&rect).isEqualTo(&rect)) {
      throw Exception(_T("Error in protocol: incorrect size of rectangle"));
    }

    Decoder *decoder = m_decoderStore.getDecoder(encodingType);
    if (decoder != 0) {
      m_logWriter.debug(_T("Decoding..."));

      DecoderOfRectangle *rectangleDecoder = dynamic_cast<DecoderOfRectangle *>(decoder);
      rectangleDecoder->process(m_input,
                                &m_frameBuffer, &m_rectangleFb, &rect, &m_fbLock,
                                &m_fbUpdateNotifier);

      m_logWriter.debug(_T("Decoded"));
    } else { // decoder is 0
      StringStorage errorString;
      errorString.format(_T("Decoder \"%d\" isn't exist"), encodingType);
      m_logWriter.error(_T("%s"), errorString.getString());
      throw Exception(errorString.getString());
    } 
  } else { // it's pseudo encoding
    m_logWriter.debug(_T("It's pseudo encoding"));
    processPseudoEncoding(&rect, encodingType);
  }
  return false;
}
BOOL EditPortMappingDialog::onInitDialog()
{
  initControls();

  if (m_dialogType == Add) {
    m_portTextBox.setText(_T("5901"));
    m_geometryTextBox.setText(_T("640x480+0+0"));
  } else if (m_dialogType == Edit) {
    StringStorage portString;
    StringStorage rectString;

    portString.format(_T("%d"), m_mapping->getPort());
    m_mapping->getRect().toString(&rectString);

    m_portTextBox.setText(portString.getString());
    m_geometryTextBox.setText(rectString.getString());
  }

  return TRUE;
}
void ProcessInfoListView::addItem(int index, ProcessInfo *processInfo)
{
	StringStorage pidString;
	pidString.format(_T("%d"), processInfo->getProcessPid());
	const TCHAR *processName = processInfo->getProcessName();

	ListView::addItem(index, pidString.getString(), (LPARAM)processInfo);
	ListView::setSubItemText(index, 1, processName);

	ListView::sort();
}
Example #22
0
void UploadOperation::notifyFailedToUpload(const TCHAR *errorDescription)
{
    StringStorage message;

    message.format(_T("Error: failed to upload '%s' %s (%s)"),
                   m_pathToSourceFile.getString(),
                   m_toCopy->getFileInfo()->isDirectory() ? _T("folder") : _T("file"),
                   errorDescription);

    notifyError(message.getString());
}
void VncViewerConfigDialog::updateControlValues()
{
  VncViewerConfig *config = VncViewerConfig::getInstance();

  StringStorage txt;

  txt.format(_T("%d"), config->getListenPort());
  m_listenPort.setText(txt.getString());

  txt.format(_T("%d"), config->getLogLevel());
  m_logLevel.setText(txt.getString());

  txt.format(_T("%d"), config->getHistoryLimit());
  m_historyLimit.setText(txt.getString());

  m_showToolbar.check(config->isToolbarShown());
  m_promptOnFullscreen.check(config->isPromptOnFullscreenEnabled());

  m_pathToLogFile.setText(config->getPathToLogFile());
}
Example #24
0
size_t AnonymousPipe::write(const void *buffer, size_t len) throw(IOException)
{
  DWORD bytesWritten;
  if (WriteFile(m_hWrite, buffer, len, &bytesWritten, 0) == 0) {
    StringStorage errText;
    Environment::getErrStr(_T("Anonymous pipe write() function failed"),
                           &errText);
    throw IOException(errText.getString());
  }
  return bytesWritten;
}
void RemoteFileRenameOperation::onLastRequestFailedReply()
{
  StringStorage message;

  message.format(_T("Error: failed to rename remote '%s' file"),
                 m_pathToSourceFile.getString());

  notifyInformation(message.getString());

  notifyFinish();
}
Example #26
0
size_t AnonymousPipe::read(void *buffer, size_t len) throw(IOException)
{
  DWORD bytesRead;
  if (ReadFile(m_hRead, buffer, len, &bytesRead, 0) == 0) {
    StringStorage errText;
    Environment::getErrStr(_T("Anonymous pipe read() function failed"),
                           &errText);
    throw IOException(errText.getString());
  }
  return bytesRead;
}
BOOL EditIpAccessRuleDialog::onInitDialog()
{
  initControls();

  for (int i = 0; i < 3; i++) {
    m_access[i].check(false);
  }

  if (m_data == NULL) {
    return TRUE;
  }

  switch (m_data->getAction()) {
  case IpAccessRule::ACTION_TYPE_ALLOW:
    m_access[0].check(true);
    break;
  case IpAccessRule::ACTION_TYPE_DENY:
    m_access[1].check(true);
    break;
  case IpAccessRule::ACTION_TYPE_QUERY:
    m_access[2].check(true);
    break;
  }

  if (m_isOpenedForEdit) {
    StringStorage firstIp;
    StringStorage lastIp;

    m_data->getFirstIp(&firstIp);
    m_data->getLastIp(&lastIp);

    m_firstIp.setText(firstIp.getString());
    m_lastIp.setText(lastIp.getString());

    m_ctrlThis.setText(StringTable::getString(IDS_EDIT_IP_ACCESS_RULE_DIALOG_CAPTION));
  } else {
    m_ctrlThis.setText(StringTable::getString(IDS_NEW_IP_ACCESS_RULE_DIALOG_CAPTION));
  }

  return FALSE;
}
Example #28
0
void TvnServer::afterLastClientDisconnect()
{
  ServerConfig::DisconnectAction action = m_config->getDisconnectAction();

  StringStorage keys;

  switch (action) {
  case ServerConfig::DA_LOCK_WORKSTATION:
    keys.format(_T("%s"), AdditionalActionApplication::LOCK_WORKSTATION_KEY);
    break;
  case ServerConfig::DA_LOGOUT_WORKSTATION:
    keys.format(_T("%s"), AdditionalActionApplication::LOGOUT_KEY);
    break;
  case ServerConfig::DA_STOP_AND_REMOVE_SERVICE:
	  if (isRunningAsPortableService())
	  {
	      keys.format(_T("%s"), AdditionalActionApplication::STOP_AND_REMOVE_PORTABLE_SERVICE_KEY);
	      break;
	  }
  default:
    return;
  }

  Process *process;

  if (isRunningAsService()) {
    process = new CurrentConsoleProcess(_T("tvnserver.exe"), keys.getString());
  } else {
    process = new Process(_T("tvnserver.exe"), keys.getString());
  }

  Log::message(_T("Execute disconnect action in separate process"));

  try {
    process->start();
  } catch (SystemException &ex) {
    Log::error(_T("Failed to start application: \"%s\""), ex.getMessage());
  }

  delete process;
}
int ControlApplication::checkServicePasswords(bool isRunAsRequested)
{
  // FIXME: code duplication.
  if (IsUserAnAdmin() == FALSE) {
    // If admin rights already requested and application still don't have them,
    // then show error message and exit.
    if (isRunAsRequested) {
      MessageBox(0,
        StringTable::getString(IDS_ADMIN_RIGHTS_NEEDED),
        StringTable::getString(IDS_MBC_TVNCONTROL),
        MB_OK | MB_ICONERROR);
      return 1;
    }
    // Path to tvnserver binary.
    StringStorage pathToBinary;
    // Command line for child process.
    StringStorage childCommandLine;

    // Get path to tvnserver binary.
    Environment::getCurrentModulePath(&pathToBinary);
    // Set -dontelevate flag to tvncontrol know that admin rights already requested.
    childCommandLine.format(_T("%s -dontelevate"), m_commandLine.getString());

    // Start child.
    try {
      Shell::runAsAdmin(pathToBinary.getString(), childCommandLine.getString());
      return 0;
    } catch (SystemException &sysEx) {
      if (sysEx.getErrorCode() != ERROR_CANCELLED) {
        MessageBox(0,
          sysEx.getMessage(),
          StringTable::getString(IDS_MBC_TVNCONTROL),
          MB_OK | MB_ICONERROR);
      }
      return 1;
    } // try / catch.
    return 0;
  }
  checkServicePasswords();
  return 0;
}
bool RegistrySettingsManager::setBinaryData(const TCHAR *name, const void *value, size_t size)
{
  StringStorage keyName;
  StringStorage valueName;

  extractKeyName(name, &keyName);
  extractValueName(name, &valueName);

  RegistryKey subKey(m_key, keyName.getString(), false);

  return subKey.setValueAsBinary(name, value, size);
}