Exemple #1
0
//  EndReport writes a "End Report" record and closes the report file.
void CReport::EndReport()
{
  WriteLine();
  stringT cs_title;
  LoadAString(cs_title, IDSC_END_REPORT1);
  WriteLine(cs_title);
  LoadAString(cs_title, IDSC_END_REPORT2);
  WriteLine(cs_title);

  m_osxs.flush();
}
Exemple #2
0
bool CXMLprefs::Store()
{
  bool retval = false;
  bool alreadyLocked = m_bIsLocked;
  pugi::xml_node decl;

  if (!alreadyLocked) {
    stringT locker;
    if (!Lock(locker)) {
      LoadAString(m_Reason, IDSC_XMLLOCK_CFG_FAILED);
      m_Reason += _T("\n  "); m_Reason += locker;
      return false;
    }
  }

  // Although technically possible, it doesn't make sense
  // to create a toplevel document here, since we'd then
  // be saving an empty document.
  ASSERT(m_pXMLDoc != NULL);
  if (m_pXMLDoc == NULL) {
    LoadAString(m_Reason, IDSC_XMLCREATE_CFG_FAILED);
    retval = false;
    goto exit;
  }

  decl = m_pXMLDoc->prepend_child(pugi::node_declaration);
  if (decl == NULL)
    goto exit;

  decl.append_attribute(_T("version")) = _T("1.0");
  decl.append_attribute(_T("encoding")) = _T("utf-8");
  decl.append_attribute(_T("standalone")) = _T("yes");

  retval = m_pXMLDoc->save_file(m_csConfigFile.c_str(), _T("  "),
                         pugi::format_default | pugi::format_write_bom,
                         pugi::encoding_utf8);

exit:
  // If we locked it, we should unlock it...
  if (!alreadyLocked)
    Unlock();
  
  // If OK - delete any error message
  if (retval)
    m_Reason.clear();

  return retval;
}
void CSafeCombinationEntry::ProcessPhrase()
{
  int status = m_core.CheckPasskey(tostringx(m_filename), m_password);
  wxString errmess;
  switch (status) {
  case PWScore::SUCCESS:
    m_core.SetReadOnly(m_readOnly);
    m_core.SetCurFile(tostringx(m_filename));
    wxGetApp().recentDatabases().AddFileToHistory(m_filename);
    EndModal(wxID_OK);
    return;
  case PWScore::CANT_OPEN_FILE:
    { stringT str;
      LoadAString(str, IDSC_FILE_UNREADABLE);
      errmess = str.c_str();
    }
    break;
  case PWScore::WRONG_PASSWORD:
  default:
    if (m_tries >= 2) {
      errmess = _("Three strikes - yer out!");
    } else {
      m_tries++;
      errmess = _("Incorrect passkey, not a PasswordSafe database, or a corrupt database. (Backup database has same name as original, ending with '~')");
    }
    break;
  } // switch (status)
    // here iff CheckPasskey failed.
  wxMessageDialog err(this, errmess,
                      _("Error"), wxOK | wxICON_EXCLAMATION);
  err.ShowModal();
  wxTextCtrl *txt = (wxTextCtrl *)FindWindow(ID_COMBINATION);
  txt->SetSelection(-1,-1);
  txt->SetFocus();
}
Exemple #4
0
int WINAPI MessageBoxR(_In_ HANDLE hHeap, _In_opt_ HINSTANCE hInstance, _In_ HWND hWnd, _In_ UINT uText, _In_ UINT uCaption, _In_ UINT uType)
{
	LPTSTR lpszText, lpszCaption;
	int msgBoxID;

	msgBoxID = 0;

	if (LoadAString(hHeap, hInstance, uText, &lpszText, NULL)) {
		if (LoadAString(hHeap, hInstance, uCaption, &lpszCaption, NULL)) {
			msgBoxID = MessageBox(hWnd, lpszText, lpszCaption, uType);
			HeapSafeFree(hHeap, 0, (LPVOID) lpszCaption);
		}
		HeapSafeFree(hHeap, 0, (LPVOID) lpszText);
	}

	return msgBoxID;
}
Exemple #5
0
static stringT ErrorMessages()
{
  stringT cs_text;

  switch (errno) {
  case EACCES:
    LoadAString(cs_text, IDSC_FILEREADONLY);
    break;
  case EEXIST:
    LoadAString(cs_text, IDSC_FILEEXISTS);
    break;
  case EINVAL:
    LoadAString(cs_text, IDSC_INVALIDFLAG);
    break;
  case EMFILE:
    LoadAString(cs_text, IDSC_NOMOREHANDLES);
    break;
  case ENOENT:
    LoadAString(cs_text, IDSC_FILEPATHNOTFOUND);
    break;
  case EIO: // synthesized upon fwrite failure
    LoadAString(cs_text, IDSC_FILEWRITEERROR);
    break;
  case EFBIG:
    LoadAString(cs_text, IDSC_FILE_TOO_BIG);
    break;
  default:
    break;
  }
  return cs_text;
}
Exemple #6
0
bool CXMLprefs::Load()
{
  // Already loaded?
  if (m_pXMLDoc != NULL)
    return true;

  bool alreadyLocked = m_bIsLocked;
  if (!alreadyLocked) {
    stringT locker;
    if (!Lock(locker)) {
      LoadAString(m_Reason, IDSC_XMLLOCK_CFG_FAILED);
      m_Reason += _T("\n"); m_Reason += locker;
      // Show filename for troubleshooting
      m_Reason += _T("\n"); m_Reason += m_csConfigFile;
      return false;
    }
  }

  if (!CreateXML(true)) {
    LoadAString(m_Reason, IDSC_XMLCREATE_CFG_FAILED);
    return false;
  }

  pugi::xml_parse_result result = m_pXMLDoc->load_file(m_csConfigFile.c_str());

  if (!result) {
    // An XML load error occurred so display the reason
    // Note: "result.description()" returns char* even in Unicode builds.
    stringT sErrorDesc;
    sErrorDesc = pugi::as_wide(result.description());
    Format(m_Reason, IDSC_XMLFILEERROR,
           sErrorDesc.c_str(), m_csConfigFile.c_str(), result.offset);
    delete m_pXMLDoc;
    m_pXMLDoc = NULL;
    return false;
  } // load failed

  // If we locked it, we should unlock it...
  if (!alreadyLocked)
    Unlock();
  
  // If OK - delete any error message
  m_Reason.clear();
  return true;
}
Exemple #7
0
BOOL WINAPI SetDlgItemTextR(_In_ HANDLE hHeap, _In_opt_ HINSTANCE hInstance, _In_ HWND hDlg, _In_ int nIDDlgItem, _In_ UINT uText)
{
	LPTSTR lpszText;
	BOOL res;

	if (LoadAString(hHeap, hInstance, uText, &lpszText, NULL)) {
		res = SetDlgItemText(hDlg, nIDDlgItem, lpszText);
		HeapSafeFree(hHeap, 0, (LPVOID) lpszText);
	} else {
		res = SetDlgItemText(hDlg, nIDDlgItem, TEXT(""));
	}

	return res;
}
Exemple #8
0
static StringX ReMergeNotes(const CItemData &item)
{
  StringX notes = item.GetNotes();
  const StringX url(item.GetURL());
  if (!url.empty()) {
    notes += _T("\r\n"); notes += url;
  }
  const StringX at(item.GetAutoType());
  if (!at.empty()) {
    stringT cs_autotype;
    LoadAString(cs_autotype, IDSC_AUTOTYPE);
    notes += _T("\r\n");
    notes += cs_autotype.c_str();
    notes += at;
  }
  return notes;
}
Exemple #9
0
/*
  It writes a header record and a "Start Report" record.
*/
void CReport::StartReport(LPCTSTR tcAction, const stringT &csDataBase)
{
  m_osxs.str(_T(""));

  m_tcAction = tcAction;
  m_csDataBase = csDataBase;

  stringT cs_title, sTimeStamp;
  PWSUtil::GetTimeStamp(sTimeStamp);
  Format(cs_title, IDSC_REPORT_TITLE1, tcAction, sTimeStamp.c_str());
  WriteLine();
  WriteLine(cs_title);
  Format(cs_title, IDSC_REPORT_TITLE2, csDataBase.c_str());
  WriteLine(cs_title);
  WriteLine();
  LoadAString(cs_title, IDSC_START_REPORT);
  WriteLine(cs_title);
  WriteLine();
}
HRESULT STDMETHODCALLTYPE MFileSAX2ErrorHandler::error(struct ISAXLocator * pLocator,
                                                       const wchar_t * pwchErrorMessage,
                                                       HRESULT hrErrorCode )
{
  TCHAR szErrorMessage[MAX_PATH * 2] = {0};
  TCHAR szFormatString[MAX_PATH * 2] = {0};
  int iLineNumber, iCharacter;

#ifdef _UNICODE
#if (_MSC_VER >= 1400)
  _tcscpy_s(szErrorMessage, MAX_PATH * 2, pwchErrorMessage);
#else
  _tcscpy(szErrorMessage, pwchErrorMessage);
#endif
#else
#if (_MSC_VER >= 1400)
  size_t num_converted;
  wcstombs_s(&num_converted, szErrorMessage, MAX_PATH * 2, pwchErrorMessage, MAX_PATH);
#else
  wcstombs(szErrorMessage, pwchErrorMessage, MAX_PATH);
#endif
#endif
  pLocator->getLineNumber(&iLineNumber);
  pLocator->getColumnNumber(&iCharacter);

  stringT cs_format;
  LoadAString(cs_format, IDSC_MSXMLSAXGENERROR);

#if (_MSC_VER >= 1400)
  _stprintf_s(szFormatString, MAX_PATH * 2, cs_format.c_str(),
              hrErrorCode, iLineNumber, iCharacter, szErrorMessage);
#else
  _stprintf(szFormatString, cs_format.c_str(),
            hrErrorCode, iLineNumber, iCharacter, szErrorMessage);
#endif

  m_strValidationResult += szFormatString;

  bErrorsFound = TRUE;

  return S_OK;
}
Exemple #11
0
template<class T> void Format(T &s, int fmt, ...)
{
  va_list args;

  va_start(args, fmt);
  T fmt_str;
  LoadAString(fmt_str, fmt);

  ConvertFormatSpecs(fmt_str);

  int len = GetStringBufSize(fmt_str.c_str(), args);
  va_end(args);//after using args we should reset list
  va_start(args, fmt);

  TCHAR *buffer = new TCHAR[len];

  _vstprintf_s(buffer, len, fmt_str.c_str(), args);
  s = buffer;
  delete[] buffer;
  va_end(args);
}
Exemple #12
0
static void ExtractAutoTypeCmd(StringX &notesStr, StringX &autotypeStr)
{
  StringX instr(notesStr);
  stringT cs_autotype;
  LoadAString(cs_autotype, IDSC_AUTOTYPE);
  StringX::size_type left = instr.find(cs_autotype.c_str(), 0);
  if (left == StringX::npos) {
    autotypeStr = _T("");
  } else {
    StringX tmp(notesStr);
    tmp = tmp.substr(left+9); // throw out everything left of "autotype:"
    instr = instr.substr(0, left);
    StringX::size_type right = tmp.find_first_of(_T("\r\n"));
    if (right != StringX::npos) {
      instr += tmp.substr(right);
      tmp = tmp.substr(0, right);
    }
    autotypeStr = tmp;
    notesStr = instr;
  }
}
Exemple #13
0
HRESULT STDMETHODCALLTYPE MFilterSAX2ErrorHandler::error(struct ISAXLocator * pLocator,
                                                         const wchar_t * pwchErrorMessage,
                                                         HRESULT hrErrorCode )
{
  TCHAR szErrorMessage[MAX_PATH*2] = {0};
  TCHAR szFormatString[MAX_PATH*2] = {0};
  int iLineNumber, iCharacter;

  _tcscpy_s(szErrorMessage, MAX_PATH * 2, pwchErrorMessage);
  pLocator->getLineNumber(&iLineNumber);
  pLocator->getColumnNumber(&iCharacter);

  stringT cs_format;
  LoadAString(cs_format, IDSC_MSXMLSAXGENERROR);

  _stprintf_s(szFormatString, MAX_PATH * 2, cs_format.c_str(),
              hrErrorCode, iLineNumber, iCharacter, szErrorMessage);

  m_strValidationResult += szFormatString;

  bErrorsFound = TRUE;

  return S_OK;
}
Exemple #14
0
// ---------------------------------------------------------------------------
bool MFileXMLProcessor::Process(const bool &bvalidation, const stringT &ImportedPrefix,
                                const stringT &strXMLFileName, const stringT &strXSDFileName,
                                const bool &bImportPSWDsOnly)
{
  HRESULT hr, hr0, hr60;
  bool b_ok = false;
  bool b_into_empty;
  stringT cs_validation;
  LoadAString(cs_validation, IDSC_XMLVALIDATION);
  stringT cs_import;
  LoadAString(cs_import, IDSC_XMLIMPORT);

  m_strXMLErrors = _T("");
  m_bValidation = bvalidation;  // Validate or Import

  //  Create SAXReader object
  ISAXXMLReader *pSAX2Reader = nullptr;
  //  Get ready for XSD schema validation
  IXMLDOMSchemaCollection2 *pSchemaCache = nullptr;

  if (m_bValidation) { //XMLValidate
    hr60 = CoCreateInstance(__uuidof(SAXXMLReader60), nullptr, CLSCTX_ALL,
                            __uuidof(ISAXXMLReader), (void **)&pSAX2Reader);
    if (FAILED(hr60)) {
      LoadAString(m_strXMLErrors, IDSC_NOMSXMLREADER);
      goto exit;
    }
  } else {  // XMLImport
    b_into_empty = m_pXMLcore->GetNumEntries() == 0;
    hr0 = CoCreateInstance(__uuidof(SAXXMLReader60), nullptr, CLSCTX_ALL,
                           __uuidof(ISAXXMLReader), (void **)&pSAX2Reader);
  }

  //  Create ContentHandlerImpl object
  MFileSAX2ContentHandler *pCH = new MFileSAX2ContentHandler();
  pCH->SetVariables(m_bValidation ? nullptr : m_pXMLcore, m_bValidation, 
                    ImportedPrefix, m_delimiter, bImportPSWDsOnly,
                    m_bValidation ? nullptr : m_pPossible_Aliases, 
                    m_bValidation ? nullptr : m_pPossible_Shortcuts,
                    m_pmulticmds, m_prpt);

  //  Create ErrorHandlerImpl object
  MFileSAX2ErrorHandler *pEH = new MFileSAX2ErrorHandler();

  //  Set Content Handler
  hr = pSAX2Reader->putContentHandler(pCH);

  //  Set Error Handler
  hr = pSAX2Reader->putErrorHandler(pEH);

  hr = CoCreateInstance(__uuidof(XMLSchemaCache60), nullptr, CLSCTX_ALL,
                        __uuidof(IXMLDOMSchemaCollection2), (void **)&pSchemaCache);

  if (!FAILED(hr)) {  // Create SchemaCache
    //  Initialize the SchemaCache object with the XSD filename
    CComVariant cvXSDFileName = strXSDFileName.c_str();
    hr = pSchemaCache->add(L"", cvXSDFileName);

    //  Set the SAXReader/Schema Cache features and properties
    {
      /* Documentation is unclear as to what is in which release.
      Try them all - if they don't get set, the world will not end!
      Common Error codes:
      S_OK          Operation successful         0x00000000
      E_NOTIMPL     Not implemented              0x80004001
      E_NOINTERFACE No such interface supported  0x80004002
      E_ABORT       Operation aborted            0x80004004
      E_FAIL        Unspecified failure          0x80004005
      E_INVALIDARG Invalid argument              0x80070057
      Normally not supported on a back level MSXMLn.DLL
      */

      // Want all validation errors
      hr = pSAX2Reader->putFeature(L"exhaustive-errors", VARIANT_TRUE);
      // Don't allow user to override validation by using DTDs
      hr = pSAX2Reader->putFeature(L"prohibit-dtd", VARIANT_TRUE);
      // Don't allow user to override validation by using DTDs (2 features)
      hr = pSAX2Reader->putFeature(L"http://xml.org/sax/features/external-general-entities",
                                   VARIANT_FALSE);
      hr = pSAX2Reader->putFeature(L"http://xml.org/sax/features/external-parameter-entities",
                                   VARIANT_FALSE);
      // Want to validate XML file
      hr = pSAX2Reader->putFeature(L"schema-validation", VARIANT_TRUE);
      // Ignore any schema specified in the XML file
      hr = pSAX2Reader->putFeature(L"use-schema-location", VARIANT_FALSE);
      // Ignore any schema in the XML file
      hr = pSAX2Reader->putFeature(L"use-inline-schema", VARIANT_FALSE);
      // Only use the XSD in PWSafe's installation directory!
      hr = pSAX2Reader->putProperty(L"schemas", _variant_t(pSchemaCache));
    }

    //  Let's begin the parsing now
    wchar_t wcURL[MAX_PATH] = {0};
    _tcscpy_s(wcURL, MAX_PATH, strXMLFileName.c_str());
    hr = pSAX2Reader->parseURL(wcURL);

    if (!FAILED(hr)) {  // Check for parsing errors
      if (pEH->bErrorsFound == TRUE) {
        m_strXMLErrors = pEH->m_strValidationResult;
      } else {
        if (m_bValidation) {
          m_numEntriesValidated = pCH->m_numEntries;
          m_delimiter = pCH->m_delimiter;
        } else {
          // Now add entries
          pCH->AddXMLEntries();

          // Get numbers (may have been modified by AddXMLEntries
          m_numEntriesImported = pCH->m_numEntries;
          m_numEntriesSkipped = pCH->getNumSkipped();
          m_numEntriesRenamed = pCH->getNumRenamed();
          m_numEntriesPWHErrors = pCH->getNumPWHErrors();
          m_numNoPolicies = pCH->getNumNoPolicies();
          m_numRenamedPolicies = pCH->getNumRenamedPolicies();
          m_numShortcutsRemoved = pCH->getNumShortcutsRemoved();
          m_numEmptyGroupsImported = pCH->getNumEmptyGroupsImported();

          // Get lists
          m_strXMLErrors = pCH->getXMLErrors();
          m_strSkippedList = pCH->getSkippedList();
          m_strPWHErrorList = pCH->getPWHErrorList();
          m_strRenameList = pCH->getRenameList();

          if (b_into_empty) {
            pCH->AddDBPreferences();
          }
        }

        b_ok = true;
      }
    } else {
      if (pEH->bErrorsFound == TRUE) {
        m_strXMLErrors = pEH->m_strValidationResult;
      } else {
        Format(m_strXMLErrors, IDSC_MSXMLPARSEERROR, hr,
               m_bValidation ? cs_validation.c_str() : cs_import.c_str());
      }
    }  // End Check for parsing errors

  } else {
    Format(m_strXMLErrors, IDSC_MSXMLBADCREATESCHEMA, hr,
           m_bValidation ? cs_validation.c_str() : cs_import.c_str());
  }  // End Create Schema Cache

exit:
  if (pSchemaCache != nullptr)
    pSchemaCache->Release();

  if (pSAX2Reader != nullptr)
    pSAX2Reader->Release();

  return b_ok;
}
Exemple #15
0
bool PWSfile::Decrypt(const stringT &fn, const StringX &passwd, stringT &errmess)
{
  size_t len;
  unsigned char* buf = NULL;
  bool status = true;
  unsigned char salt[SaltLength];
  unsigned char ipthing[8];
  unsigned char randstuff[StuffSize];
  unsigned char randhash[SHA1::HASHLEN];
  unsigned char temphash[SHA1::HASHLEN];

  FILE *in = pws_os::FOpen(fn, _T("rb"));
  if (in == NULL) {
    status = false;
    goto exit;
  }

#ifdef KEEP_FILE_MODE_BWD_COMPAT
  uint32 i32;
  fread(&i32, 1, sizeof(uint32), in); // XXX portability issue
  len = i32;
#else
  fread(randstuff, 1, 8, in);
  randstuff[8] = randstuff[9] = TCHAR('\0'); // ugly bug workaround
  fread(randhash, 1, sizeof(randhash), in);

  GenRandhash(passwd, randstuff, temphash);
  if (memcmp(reinterpret_cast<char *>(randhash), reinterpret_cast<char *>(temphash), SHA1::HASHLEN) != 0) {
    fclose(in);
    LoadAString(errmess, IDSC_BADPASSWORD);
    return false;
  }
#endif // KEEP_FILE_MODE_BWD_COMPAT

  { // decryption in a block, since we use goto
    fread(salt,    1, SaltLength, in);
    fread(ipthing, 1, 8,          in);

    unsigned char dummyType;
    unsigned char *pwd = NULL;
    size_t passlen = 0;
    long file_len = pws_os::fileLength(in);
    ConvertString(passwd, pwd, passlen);
    Fish *fish = BlowFish::MakeBlowFish(pwd, reinterpret_cast<int &>(passlen), salt, SaltLength);
    trashMemory(pwd, passlen);
#ifdef UNICODE
    delete[] pwd; // gross - ConvertString allocates only if UNICODE.
#endif
    if (_readcbc(in, buf, len,dummyType, fish, ipthing, 0, file_len) == 0) {
      delete fish;
      delete[] buf; // if not yet allocated, delete[] NULL, which is OK
      return false;
    }
    delete fish;
    fclose(in);
  } // decrypt

  { // write decrypted data
    size_t suffix_len = CIPHERTEXT_SUFFIX.length();
    size_t filepath_len = fn.length();

    stringT out_fn = fn;
    out_fn = out_fn.substr(0,filepath_len - suffix_len);

    FILE *out = pws_os::FOpen(out_fn, _T("wb"));
    if (out != NULL) {
      size_t fret = fwrite(buf, 1, len, out);
      if (fret != len) {
        int save_errno = errno;
        fclose(out);
        errno = save_errno;
        goto exit;
      }
      if (fclose(out) != 0) {
        status = false;
        goto exit;
      }
    } else { // open failed
      status = false;
      goto exit;
    }
  } // write decrypted
 exit:
  if (!status)
    errmess = ErrorMessages();
  delete[] buf; // allocated by _readcbc
  return status;
}
// ---------------------------------------------------------------------------
bool XFileXMLProcessor::Process(const bool &bvalidation, const stringT &ImportedPrefix,
                                const stringT &strXMLFileName, const stringT &strXSDFileName,
                                const bool &bImportPSWDsOnly)
{
  USES_XMLCH_STR

  bool bErrorOccurred = false;
  bool b_into_empty = false;
  stringT cs_validation;
  LoadAString(cs_validation, IDSC_XMLVALIDATION);
  stringT cs_import;
  LoadAString(cs_import, IDSC_XMLIMPORT);
  stringT strResultText(_T(""));
  m_bValidation = bvalidation;  // Validate or Import

  XSecMemMgr sec_mm;

  // Initialize the XML4C2 system
  try
  {
    XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, &sec_mm);
  }
  catch (const XMLException& toCatch)
  {
    strResultText = stringT(_X2ST(toCatch.getMessage()));
    return false;
  }

  const XMLCh* xmlfilename = _W2X(strXMLFileName.c_str());
  const XMLCh* schemafilename = _W2X(strXSDFileName.c_str());

  //  Create a SAX2 parser object.
  SAX2XMLReader* pSAX2Parser = XMLReaderFactory::createXMLReader(&sec_mm);

  // Set non-default features
  pSAX2Parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);
  pSAX2Parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
  pSAX2Parser->setFeature(XMLUni::fgXercesDynamic, false);
  pSAX2Parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
  pSAX2Parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
  pSAX2Parser->setFeature(XMLUni::fgXercesSkipDTDValidation, true);

  // Set properties
  pSAX2Parser->setProperty(XMLUni::fgXercesScannerName,
                           const_cast<void*>(reinterpret_cast<const void*>(XMLUni::fgSGXMLScanner)));
  pSAX2Parser->setInputBufferSize(4096);

  // Set schema file name (also via property)
  pSAX2Parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation,
                           const_cast<void*>(reinterpret_cast<const void*>(schemafilename)));

  // Create SAX handler object and install it on the pSAX2Parser, as the
  // document and error pSAX2Handler.
  XFileSAX2Handlers * pSAX2Handler = new XFileSAX2Handlers;
  pSAX2Parser->setContentHandler(pSAX2Handler);
  pSAX2Parser->setErrorHandler(pSAX2Handler);

  pSAX2Handler->SetVariables(m_bValidation ? NULL : m_pXMLcore, m_bValidation,
                             ImportedPrefix, m_delimiter, bImportPSWDsOnly,
                             m_bValidation ? NULL : m_pPossible_Aliases,
                             m_bValidation ? NULL : m_pPossible_Shortcuts,
                             m_pmulticmds, m_prpt);
  if (!m_bValidation) {
    b_into_empty = m_pXMLcore->GetNumEntries() == 0;
  }

  try {
    // Let's begin the parsing now
    pSAX2Parser->parse(xmlfilename);
  }
  catch (const OutOfMemoryException&) {
    LoadAString(strResultText, IDCS_XERCESOUTOFMEMORY);
    bErrorOccurred = true;
  }
  catch (const XMLException& e) {
    strResultText = stringT(_X2ST(e.getMessage()));
    bErrorOccurred = true;
  }

  catch (...) {
    LoadAString(strResultText, IDCS_XERCESEXCEPTION);
    bErrorOccurred = true;
  }

  if (pSAX2Handler->getIfErrors() || bErrorOccurred) {
    bErrorOccurred = true;
    strResultText = pSAX2Handler->getValidationResult();
    Format(m_strXMLErrors, IDSC_XERCESPARSEERROR,
           m_bValidation ? cs_validation.c_str() : cs_import.c_str(),
           strResultText.c_str());
  } else {
    if (m_bValidation) {
      m_strXMLErrors = pSAX2Handler->getValidationResult();
      m_numEntriesValidated = pSAX2Handler->getNumEntries();
      m_delimiter = pSAX2Handler->getDelimiter();
    } else {
      pSAX2Handler->AddXMLEntries();

      // Get numbers (may have been modified by AddXMLEntries
      m_numEntriesImported = pSAX2Handler->getNumEntries();
      m_numEntriesSkipped = pSAX2Handler->getNumSkipped();
      m_numEntriesRenamed = pSAX2Handler->getNumRenamed();
      m_numEntriesPWHErrors = pSAX2Handler->getNumPWHErrors();
      m_numNoPolicies = pSAX2Handler->getNumNoPolicies();
      m_numRenamedPolicies = pSAX2Handler->getNumRenamedPolicies();
      m_numShortcutsRemoved = pSAX2Handler->getNumShortcutsRemoved();

      // Get lists
      m_strXMLErrors = pSAX2Handler->getXMLErrors();
      m_strSkippedList = pSAX2Handler->getSkippedList();
      m_strPWHErrorList = pSAX2Handler->getPWHErrorList();
      m_strRenameList = pSAX2Handler->getRenameList();


      if (b_into_empty) {
        pSAX2Handler->AddDBPreferences();
      }
    }
  }

  //  Delete the pSAX2Parser itself.  Must be done prior to calling Terminate, below.
  delete pSAX2Parser;
  delete pSAX2Handler;

  USES_XMLCH_STR_END

  // And call the termination method
  XMLPlatformUtils::Terminate();

  return !bErrorOccurred;
}
Exemple #17
0
//-----------------------------------------------------------------
// Internal functions
//-----------------------------------------------------------------
static UINT ParseRunCommand(const StringX &sxInputString,
                            std::vector<st_RunCommandTokens> &v_rctokens,
                            bool &bDoAutoType, StringX &sxAutoType,
                            stringT &serrmsg, StringX::size_type &st_column)
{
  // tokenize into separate elements
  std::vector<st_RunCommandTokens>::iterator rc_iter;
  std::vector<size_t> v_pos;
  StringX::iterator str_Iter;
  st_RunCommandTokens st_rctoken;
  size_t st_num_quotes(0);

  UINT uierr(0);
  int var_index(0);

  const stringT alphanum =
    _T("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

  if (sxInputString.empty()) {
  // String is empty!
    uierr = IDSC_EXS_INPUTEMPTY;
    goto exit;
  }

  for (StringX::size_type l = 0; l < sxInputString.length(); l++) {
    if (sxInputString[l] == _T('"'))
      st_num_quotes++;
  }

  if (st_num_quotes % 2 != 0) {
    st_column = sxInputString.find(_T('"'));
    // Unmatched quotes
    uierr = IDSC_EXS_UNMATCHEDQUOTES;
    goto exit;
  }

  // tokenize into separate elements using $ as the field separator
  for (StringX::size_type st_startpos = 0;
       st_startpos < sxInputString.size();
       /* st_startpos advanced in body */) {
    StringX::size_type st_next = sxInputString.find(_T('$'), st_startpos);
    if (st_next == StringX::npos)
      st_next = sxInputString.size();
    if (st_next > 0) {
      st_rctoken.sxname = sxInputString.substr(st_startpos, st_next - st_startpos);
      st_rctoken.sxindex = _T("");
      st_rctoken.index = 0;
      st_rctoken.is_variable  = st_startpos == 0 ? false : true;
      st_rctoken.has_brackets = false;
      v_rctokens.push_back(st_rctoken);
      v_pos.push_back(st_startpos);
    }
    st_startpos = st_next + 1; // too complex for for statement
  } // tokenization for loop

  // Check if escaped - ending character of previous token == '\'
  // Make sure this '\' is not escaped itself!
  for (size_t st_idx = v_rctokens.size() - 1; st_idx > 0 ; st_idx--) {
    st_RunCommandTokens &st_rctokens = v_rctokens[st_idx - 1];
    StringX::size_type name_len = st_rctokens.sxname.length();
    if (name_len == 0 || (name_len >= 2 &&
            st_rctokens.sxname.substr(name_len - 2, 2).compare(_T("\\\\")) == 0))
      continue;

    if (st_rctokens.sxname.substr(name_len - 1, 1).compare(_T("\\")) == 0) {
      st_rctokens.sxname = st_rctokens.sxname.substr(0, name_len - 1) + 
                         _T("$") + v_rctokens[st_idx].sxname;
      v_rctokens.erase(v_rctokens.begin() + st_idx);
    }
  }

  // Check if variable enclosed in curly brackets
  for (size_t st_idx = 0; st_idx < v_rctokens.size(); st_idx++) {
    if (v_rctokens[st_idx].sxname.length() == 0)
      continue;

    str_Iter = v_rctokens[st_idx].sxname.begin();
    // Does it start with a curly bracket?
    if (*str_Iter == _T('{')) {
      v_rctokens[st_idx].has_brackets = true;
      StringX sxvar, sxnonvar, sxindex(_T(""));
      // Yes - Find end curly bracket
      StringX::size_type st_end_cb = v_rctokens[st_idx].sxname.find(_T('}'));
      if (st_end_cb == StringX::npos) {
        st_column = v_pos[st_idx] + v_rctokens[st_idx].sxname.length();
        // Missing end curly bracket
        uierr = IDSC_EXS_MISSINGCURLYBKT;
        goto exit;
      }
      // Now see if there is an Index here
      StringX::size_type st_start_sb = v_rctokens[st_idx].sxname.find(_T('['));
      if (st_start_sb != StringX::npos) {
        // Yes  - find end square bracket
        if (st_start_sb > st_end_cb) {
          // Square backet after end of variable
          sxvar = v_rctokens[st_idx].sxname.substr(1, st_end_cb - 1);
          sxnonvar = v_rctokens[st_idx].sxname.substr(st_end_cb + 1);
          v_rctokens[st_idx].sxname = sxvar;
          if (sxnonvar.length() > 0) {
            st_rctoken.sxname = sxnonvar;
            st_rctoken.sxindex = _T("");
            st_rctoken.index = 0;
            st_rctoken.is_variable = false;
            st_rctoken.has_brackets = false;
            v_rctokens.insert(v_rctokens.begin() + st_idx + 1, st_rctoken);
            v_pos.insert(v_pos.begin() + st_idx + 1, v_pos[st_idx] + st_end_cb);
          }
          continue;
        }
        StringX::size_type st_end_sb = v_rctokens[st_idx].sxname.find(_T(']'), st_start_sb);
        if (st_end_sb == StringX::npos) {
          st_column = v_pos[st_idx] + 1;
          // Missing end square bracket
          uierr = IDSC_EXS_MISSINGSQUAREBKT;
          goto exit;
        }
        // The end-curly backet must immediately follow the end-square bracket
        if (st_end_cb != st_end_sb + 1) {
          st_column = v_pos[st_idx] + st_end_sb + 1;
          // Characters between ']' and ')'
          uierr = IDSC_EXS_INVALIDBRACKETS;
          goto exit;
        }
        sxindex = v_rctokens[st_idx].sxname.substr(st_start_sb + 1, st_end_sb - st_start_sb - 1);
        v_rctokens[st_idx].sxindex = sxindex;
        // Now check index
        uierr = ProcessIndex(sxindex, var_index, st_column);
        if (uierr > 0) {
          st_column += v_pos[st_idx];
          goto exit;
        }

        v_rctokens[st_idx].index = var_index;
        sxvar = v_rctokens[st_idx].sxname.substr(1, st_start_sb - 1);
        sxnonvar = v_rctokens[st_idx].sxname.substr(st_end_cb + 1);
      } else {
        // No square bracket
        // Split current token into 'variable' and 'non-variable' parts
        sxvar = v_rctokens[st_idx].sxname.substr(1, st_end_cb - 1);
        sxnonvar = v_rctokens[st_idx].sxname.substr(st_end_cb + 1);
      }
      v_rctokens[st_idx].sxname = sxvar;
      if (sxnonvar.length() > 0) {
        st_rctoken.sxname = sxnonvar;
        st_rctoken.sxindex = _T("");
        st_rctoken.index = 0;
        st_rctoken.is_variable = false;
        st_rctoken.has_brackets = false;
        v_rctokens.insert(v_rctokens.begin() + st_idx + 1, st_rctoken);
        v_pos.insert(v_pos.begin() + st_idx + 1, v_pos[st_idx] + st_end_cb);
      }
    }
  }

  // Now use rules of variables to get the real variable
  for (size_t st_idx = 0; st_idx < v_rctokens.size(); st_idx++) {
    if (!v_rctokens[st_idx].is_variable)
      continue;

    if (v_rctokens[st_idx].sxname.length() == 0) {
      st_column = v_pos[st_idx];
      // Variable name is empty
      uierr = IDSC_EXS_VARNAMEEMPTY;
      goto exit;
    }

    str_Iter = v_rctokens[st_idx].sxname.begin();
    if (!isalpha(*str_Iter)) {
      st_column = v_pos[st_idx];
      // First character of variable is not alphabetic
      uierr = IDSC_EXS_FIRSTNOTALPHA;
      goto exit;
    }
    StringX::size_type st_next = v_rctokens[st_idx].sxname.find_first_not_of(alphanum.c_str());
    if (st_next != StringX::npos) {
      // Split current token into 'variable' and 'non-variable' parts
      StringX sxvar = v_rctokens[st_idx].sxname.substr(0, st_next);
      StringX sxnonvar = v_rctokens[st_idx].sxname.substr(st_next);
      v_rctokens[st_idx].sxname = sxvar;
      // Before saving non-variable part - check if it is an Index e.g. var[i]
      if (sxnonvar.c_str()[0] == _T('[')) {
        // Find ending square bracket
        StringX::size_type st_end_sb = sxnonvar.find(_T(']'));
        if (st_end_sb == StringX::npos) {
          st_column = v_pos[st_idx] + sxvar.length() + 2;
          // Missing end square bracket
          uierr = IDSC_EXS_MISSINGSQUAREBKT;
          goto exit;
        }
        StringX sxindex = sxnonvar.substr(1, st_end_sb - 1);
        v_rctokens[st_idx].sxindex = sxindex;
        // Now check index
        uierr = ProcessIndex(sxindex, var_index, st_column);
        if (uierr > 0) {
          st_column += v_pos[st_idx] + sxvar.length();
          goto exit;
        }

        v_rctokens[st_idx].index = var_index;
        sxnonvar = sxnonvar.substr(st_end_sb + 1);
      } else {
        // Not a square bracket
        if (v_rctokens[st_idx].has_brackets) {
          st_column = v_pos[st_idx] + st_next + 1;
          // Variable must be alphanumeric
          uierr = IDSC_EXS_VARNAMEINVALID;
          goto exit;
        }
      }
      if (!sxnonvar.empty()) {
        st_rctoken.sxname = sxnonvar;
        st_rctoken.sxindex = _T("");
        st_rctoken.index = 0;
        st_rctoken.is_variable = false;
        st_rctoken.has_brackets = false;
        v_rctokens.insert(v_rctokens.begin() + st_idx + 1, st_rctoken);
        v_pos.insert(v_pos.begin() + st_idx + 1, v_pos[st_idx] + st_next);
      }
    }
  }

  // Special Autotype processing
  bDoAutoType = false;
  sxAutoType = _T("");
  for (size_t st_idx = 0; st_idx < v_rctokens.size(); st_idx++) {
    if (!v_rctokens[st_idx].is_variable)
      continue;

    // Is it a autotype variable?
    if (v_rctokens[st_idx].sxname == _T("a") ||
        v_rctokens[st_idx].sxname == _T("autotype")) {
      bDoAutoType = true;
      // Is the next token text and starts with '('?
      if (st_idx + 1 < v_rctokens.size() &&
          !v_rctokens[st_idx + 1].is_variable &&
          v_rctokens[st_idx + 1].sxname.c_str()[0] == _T('(')) {
        // Find ending round bracket
        StringX sx_autotype = v_rctokens[st_idx + 1].sxname;
        StringX::size_type st_end_rb = sx_autotype.find(_T(')'));
        if (st_end_rb == StringX::npos) {
          st_column = v_pos[st_idx + 1] + sx_autotype.length() + 2;
          // Missing end round bracket
          uierr = IDSC_EXS_MISSINGROUNDBKT;
          goto exit;
        }
        sxAutoType = sx_autotype.substr(1, st_end_rb - 1);
        v_rctokens[st_idx + 1].sxname = sx_autotype.substr(st_end_rb + 1);
        // Check if anything left in this text - none -> delete
        if (v_rctokens[st_idx + 1].sxname.length() == 0)
          v_rctokens.erase(v_rctokens.begin() + st_idx + 1);
        // Now delete Autotype variable
        v_rctokens.erase(v_rctokens.begin() + st_idx);
        break;
      }
    }
  }

exit:
  if (uierr != 0)
    LoadAString(serrmsg, uierr);
  else
    serrmsg = _T("");

  if (uierr > 0) {
    v_rctokens.clear();
  }
  v_pos.clear();
  return uierr;
}
bool MFilterXMLProcessor::Process(const bool &bvalidation,
                                  const StringX &strXMLData,
                                  const stringT &strXMLFileName,
                                  const stringT &strXSDFileName)
{
  HRESULT hr, hr0, hr60;
  bool b_ok(false);
  stringT cs_validation;
  LoadAString(cs_validation, IDSC_XMLVALIDATION);
  stringT cs_import;
  LoadAString(cs_import, IDSC_XMLIMPORT);

  m_strXMLErrors = _T("");
  m_bValidation = bvalidation;  // Validate or Import

  //  Create SAXReader object
  ISAXXMLReader *pSAX2Reader = nullptr;
  //  Get ready for XSD schema validation
  IXMLDOMSchemaCollection2 *pSchemaCache = nullptr;

  if (m_bValidation) { //XMLValidate
    hr60 = CoCreateInstance(__uuidof(SAXXMLReader60), nullptr, CLSCTX_ALL,
                            __uuidof(ISAXXMLReader), (void **)&pSAX2Reader);
    if (FAILED(hr60)) {
      LoadAString(m_strXMLErrors, IDSC_NOMSXMLREADER);
      goto exit;
    }
  } else {  // XMLImport
    hr0 = CoCreateInstance(__uuidof(SAXXMLReader60), nullptr, CLSCTX_ALL,
                           __uuidof(ISAXXMLReader), (void **)&pSAX2Reader);

  }

  //  Create ContentHandlerImpl object
  MFilterSAX2ContentHandler *pCH = new MFilterSAX2ContentHandler;
  //  Create ErrorHandlerImpl object
  MFilterSAX2ErrorHandler *pEH = new MFilterSAX2ErrorHandler;

  pCH->SetVariables(m_pAsker, &m_MapXMLFilters, m_FPool, m_bValidation);

  //  Set Content Handler
  hr = pSAX2Reader->putContentHandler(pCH);

  //  Set Error Handler
  hr = pSAX2Reader->putErrorHandler(pEH);

  hr = CoCreateInstance(__uuidof(XMLSchemaCache60), nullptr, CLSCTX_ALL,
                        __uuidof(IXMLDOMSchemaCollection2), (void **)&pSchemaCache);

  if (!FAILED(hr)) {  // Create SchemaCache
    //  Initialize the SchemaCache object with the XSD filename
    CComVariant cvXSDFileName = strXSDFileName.c_str();
    hr = pSchemaCache->add(L"", cvXSDFileName);
    if (hr != S_OK) {
      LoadAString(m_strXMLErrors, IDSC_INVALID_SCHEMA);
      goto exit;
    }
    hr = pSchemaCache->validate();
    if (hr != S_OK) {
      LoadAString(m_strXMLErrors, IDSC_INVALID_SCHEMA);
      goto exit;
    }

    // Check that we can get the Schema version
    BSTR bst_schema, bst_schema_version;
    bst_schema = L"";
    ISchema *pischema;
    hr = pSchemaCache->getSchema(bst_schema, &pischema);
    if (hr != S_OK) {
      LoadAString(m_strXMLErrors, IDSC_MISSING_SCHEMA_VER);
      goto exit;
    }
    hr = pischema->get_version(&bst_schema_version);
    if (hr != S_OK) {
      LoadAString(m_strXMLErrors, IDSC_INVALID_SCHEMA_VER);
      goto exit;
    }

    pCH->SetSchemaVersion(&bst_schema_version);

    //  Set the SAXReader/Schema Cache features and properties
    {
      /* Documentation is unclear as to what is in which release.
      Try them all - if they don't get set, the world will not end!
      Common Error codes:
      S_OK          Operation successful         0x00000000
      E_NOTIMPL     Not implemented              0x80004001
      E_NOINTERFACE No such interface supported  0x80004002
      E_ABORT       Operation aborted            0x80004004
      E_FAIL        Unspecified failure          0x80004005
      E_INVALIDARG Invalid argument              0x80070057
      Normally not supported on a back level MSXMLn.DLL
      */

      // Want all validation errors
      hr = pSAX2Reader->putFeature(L"exhaustive-errors", VARIANT_TRUE);
      // Don't allow user to override validation by using DTDs
      hr = pSAX2Reader->putFeature(L"prohibit-dtd", VARIANT_TRUE);
      // Don't allow user to override validation by using DTDs (2 features)
      hr = pSAX2Reader->putFeature(L"http://xml.org/sax/features/external-general-entities",
                                   VARIANT_FALSE);
      hr = pSAX2Reader->putFeature(L"http://xml.org/sax/features/external-parameter-entities",
                                   VARIANT_FALSE);
      // Want to validate XML file
      hr = pSAX2Reader->putFeature(L"schema-validation", VARIANT_TRUE);
      // Ignore any schema specified in the XML file
      hr = pSAX2Reader->putFeature(L"use-schema-location", VARIANT_FALSE);
      // Ignore any schema in the XML file
      hr = pSAX2Reader->putFeature(L"use-inline-schema", VARIANT_FALSE);
      // Only use the XSD in PWSafe's installation directory!
      hr = pSAX2Reader->putProperty(L"schemas", _variant_t(pSchemaCache));
    }

    //  Let's begin the parsing now
    if (!strXMLFileName.empty()) {
      wchar_t wcURL[MAX_PATH]={0};
      _tcscpy_s(wcURL, MAX_PATH, strXMLFileName.c_str());
      hr = pSAX2Reader->parseURL(wcURL);
    } else {
      CComVariant cvXMLData = strXMLData.c_str();
      hr = pSAX2Reader->parse(cvXMLData);
    }

    if (!FAILED(hr)) {  // Check for parsing errors
      if (pEH->bErrorsFound == TRUE) {
        m_strXMLErrors = pEH->m_strValidationResult;
      } else {
        b_ok = true;
      }
    } else {
      if (pEH->bErrorsFound == TRUE) {
        m_strXMLErrors = pEH->m_strValidationResult;
      } else {
        Format(m_strXMLErrors, IDSC_MSXMLPARSEERROR, hr,
               m_bValidation ? cs_validation.c_str() : cs_import.c_str());
      }
    }  // End Check for parsing errors

  } else {
    Format(m_strXMLErrors, IDSC_MSXMLBADCREATESCHEMA, hr,
           m_bValidation ? cs_validation.c_str() : cs_import.c_str());
  }  // End Create Schema Cache

exit:
  if (pSchemaCache != nullptr)
    pSchemaCache->Release();

  if (pSAX2Reader != nullptr)
    pSAX2Reader->Release();

  return b_ok;
}
Exemple #19
0
//  ---------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE MFilterSAX2ContentHandler::startElement(
  /* [in] */ const wchar_t __RPC_FAR *pwchNamespaceUri,
  /* [in] */ int cchNamespaceUri,
  /* [in] */ const wchar_t __RPC_FAR *pwchLocalName,
  /* [in] */ int cchLocalName,
  /* [in] */ const wchar_t __RPC_FAR *pwchRawName,
  /* [in] */ int cchRawName,
  /* [in] */ ISAXAttributes __RPC_FAR *pAttributes)
{
  TCHAR szCurElement[MAX_PATH + 1] = {0};

  _tcsncpy_s(szCurElement, MAX_PATH + 1, pwchRawName, cchRawName);

  if (m_bValidation && _tcscmp(szCurElement, _T("filters")) == 0) {
    int iAttribs = 0;
    if (m_pSchema_Version == NULL) {
      LoadAString(m_strXMLErrors, IDSC_MISSING_SCHEMA_VER);
      return E_FAIL;
    }

    m_iSchemaVersion = _wtoi(*m_pSchema_Version);
    if (m_iSchemaVersion <= 0) {
      LoadAString(m_strXMLErrors, IDSC_INVALID_SCHEMA_VER);
      return E_FAIL;
    }

    pAttributes->getLength(&iAttribs);
    for (int i = 0; i < iAttribs; i++) {
      TCHAR szQName[MAX_PATH + 1] = {0};
      TCHAR szValue[MAX_PATH + 1] = {0};
      const wchar_t *QName, *Value;
      int QName_length, Value_length;

      pAttributes->getQName(i, &QName, &QName_length);
      pAttributes->getValue(i, &Value, &Value_length);
      _tcsncpy_s(szQName, MAX_PATH + 1, QName, QName_length);
      _tcsncpy_s(szValue, MAX_PATH + 1, Value, Value_length);
      if (QName_length == 7 && memcmp(szQName, _T("version"), 7 * sizeof(TCHAR)) == 0) {
        m_iXMLVersion = _ttoi(szValue);
      }
    }
  }

  if (m_bValidation || _tcscmp(szCurElement, _T("filters")) == 0)
    return S_OK;

  bool bfilter = (_tcscmp(szCurElement, _T("filter")) == 0);
  bool bfilter_entry = (_tcscmp(szCurElement, _T("filter_entry")) == 0);

  if (bfilter) {
    cur_filter = new st_filters;
  }

  if (bfilter_entry) {
    cur_filterentry = new st_FilterRow;
    cur_filterentry->Empty();
    cur_filterentry->bFilterActive = true;
    m_bEntryBeingProcessed = true;
  }

  if (bfilter || bfilter_entry) {
    // Process the attributes we need.
    int iAttribs = 0;
    pAttributes->getLength(&iAttribs);
    for (int i = 0; i < iAttribs; i++) {
      TCHAR szQName[MAX_PATH + 1] = {0};
      TCHAR szValue[MAX_PATH + 1] = {0};
      const wchar_t *QName, *Value;
      int QName_length, Value_length;

      pAttributes->getQName(i, &QName, &QName_length);
      pAttributes->getValue(i, &Value, &Value_length);
      _tcsncpy_s(szQName, MAX_PATH + 1, QName, QName_length);
      _tcsncpy_s(szValue, MAX_PATH + 1, Value, Value_length);

      if (bfilter && QName_length == 10 && memcmp(szQName, _T("filtername"), 10 * sizeof(TCHAR)) == 0)
        cur_filter->fname = szValue;

      if (bfilter_entry && QName_length == 6 && memcmp(szQName, _T("active"), 6 * sizeof(TCHAR)) == 0) {
        if (Value_length == 2 && memcmp(szValue, _T("no"), 2 * sizeof(TCHAR)) == 0)
          cur_filterentry->bFilterActive = false;
      }
    }
  }

  m_sxElemContent = _T("");

  return S_OK;
}
Exemple #20
0
BOOL COptionsSystem::OnInitDialog() 
{
  COptions_PropertyPage::OnInitDialog();

  PWSprefs *prefs = PWSprefs::GetInstance();
  if (!m_bShowConfigFile) {
    GetDlgItem(IDC_STATIC_CONFIGFILE)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_STATIC_RWSTATUS)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_CONFIGFILE)->ShowWindow(SW_HIDE);
  } else {
    PWSprefs::ConfigOption configoption;
    std::wstring wsCF = prefs->GetConfigFile(configoption);
    std::wstring wsCO(L"");
    switch (configoption) {
      case PWSprefs::CF_NONE:
        LoadAString(wsCF, IDS_NONE);
        break;
      case PWSprefs::CF_REGISTRY:
        LoadAString(wsCF, IDS_REGISTRY);
        break;
      case PWSprefs::CF_FILE_RO:
        LoadAString(wsCO, IDS_READ_ONLY);
        break;
      case PWSprefs::CF_FILE_RW:
      case PWSprefs::CF_FILE_RW_NEW:
        LoadAString(wsCO, IDS_READ_WRITE);
        break;
      default:
        ASSERT(0);
    }
    GetDlgItem(IDC_CONFIGFILE)->SetWindowText(wsCF.c_str());
    GetDlgItem(IDC_STATIC_RWSTATUS)->SetWindowText(wsCO.c_str());
  }

  bool bofferdeleteregistry = prefs->OfferDeleteRegistry();

  bool boffermigrate2appdata = OfferConfigMigration();

  if (!bofferdeleteregistry) {
    GetDlgItem(IDC_REGDEL)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);
  }

  if (!boffermigrate2appdata) {
    GetDlgItem(IDC_MIGRATETOAPPDATA)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);
  }

  if (!bofferdeleteregistry && !boffermigrate2appdata) {
    GetDlgItem(IDC_CONFIG_GRP)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_HIDE);
  } else {
    GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_SHOW);
  }

  GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);

  CSpinButtonCtrl *pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_RESPIN);

  pspin->SetBuddy(GetDlgItem(IDC_MAXREITEMS));
  pspin->SetRange(0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);
  pspin->SetBase(10);
  pspin->SetPos(m_MaxREItems);

  pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_MRUSPIN);

  pspin->SetBuddy(GetDlgItem(IDC_MAXMRUITEMS));
  pspin->SetRange(0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);
  pspin->SetBase(10);
  pspin->SetPos(m_MaxMRUItems);

  OnUseSystemTray();

  InitToolTip(TTS_BALLOON | TTS_NOPREFIX, 2);
  AddTool(IDC_REGDEL,           IDS_REGDEL);
  AddTool(IDC_MIGRATETOAPPDATA, IDS_MIGRATETOAPPDATA);
  ActivateToolTip();

  return TRUE;  // return TRUE unless you set the focus to a control
  // EXCEPTION: OCX Property Pages should return FALSE
}
Exemple #21
0
BOOL COptionsSystem::OnInitDialog() 
{
  COptions_PropertyPage::OnInitDialog();

  PWSprefs *prefs = PWSprefs::GetInstance();

  PWSprefs::ConfigOption configoption;
  StringX sx_CF = prefs->GetConfigFile(configoption).c_str();
  std::wstring  wsCO(L"");
  switch (configoption) {
    case PWSprefs::CF_NONE:
      LoadAString(sx_CF, IDS_NONE);
      break;
    case PWSprefs::CF_REGISTRY:
      LoadAString(sx_CF, IDS_REGISTRY);
      break;
    case PWSprefs::CF_FILE_RO:
      LoadAString(wsCO, IDS_READ_ONLY);
      break;
    case PWSprefs::CF_FILE_RW:
    case PWSprefs::CF_FILE_RW_NEW:
      LoadAString(wsCO, IDS_READ_WRITE);
      break;
    default:
      ASSERT(0);
  }

  CString cs_text;

  // R/W status
  GetDlgItem(IDC_STATIC_RWSTATUS)->SetWindowText(wsCO.c_str());

  // Config file name & location
  cs_text = PWSUtil::NormalizeTTT(sx_CF, 60).c_str();
  GetDlgItem(IDC_CONFIGFILE)->SetWindowText(cs_text);

  // Effective host & user used in config file
  if (configoption == PWSprefs::CF_FILE_RO || 
      configoption == PWSprefs::CF_FILE_RW ||
      configoption == PWSprefs::CF_FILE_RW_NEW) {
    stringT hn = SysInfo::GetInstance()->GetEffectiveHost();
    PWSprefs::XMLify(charT('H'), hn);
    stringT un = SysInfo::GetInstance()->GetEffectiveUser();
    PWSprefs::XMLify(charT('u'), un);

    cs_text.Format(IDS_HOSTUSER, static_cast<LPCWSTR>(hn.c_str()), static_cast<LPCWSTR>(un.c_str()));
    GetDlgItem(IDC_STATIC_HOSTUSER)->SetWindowText(cs_text);
  }

  bool bofferdeleteregistry = prefs->OfferDeleteRegistry();

  bool boffermigrate2appdata = OfferConfigMigration();

  if (!bofferdeleteregistry) {
    GetDlgItem(IDC_REGDEL)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);
  }

  if (!boffermigrate2appdata) {
    GetDlgItem(IDC_MIGRATETOAPPDATA)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);
  }

  if (!bofferdeleteregistry && !boffermigrate2appdata) {
    GetDlgItem(IDC_CONFIG_GRP)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_HIDE);
  } else {
    GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_SHOW);
  }

  GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);

  CSpinButtonCtrl *pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_RESPIN);
  pspin->SetBuddy(GetDlgItem(IDC_MAXREITEMS));
  pspin->SetRange(M_prefminREItems(), M_prefmaxREItems());
  pspin->SetBase(10);
  pspin->SetPos(m_MaxREItems);

  pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_MRUSPIN);
  pspin->SetBuddy(GetDlgItem(IDC_MAXMRUITEMS));
  pspin->SetRange(M_prefminMRU(), M_prefmaxMRU());
  pspin->SetBase(10);
  pspin->SetPos(m_MaxMRUItems);

  OnUseSystemTray();

  if (InitToolTip(TTS_BALLOON | TTS_NOPREFIX, 0)) {
    m_Help1.Init(IDB_QUESTIONMARK);
    m_Help2.Init(IDB_QUESTIONMARK);

    // Note naming convention: string IDS_xxx corresponds to control IDC_xxx_HELP
    AddTool(IDC_REGDELHELP, IDS_REGDEL);
    AddTool(IDC_MIGRATETOAPPDATAHELP, IDS_MIGRATETOAPPDATA);
    ActivateToolTip();
  } else {
    m_Help1.EnableWindow(FALSE);
    m_Help1.ShowWindow(SW_HIDE);
    m_Help2.EnableWindow(FALSE);
    m_Help2.ShowWindow(SW_HIDE);
  }

  if (!bofferdeleteregistry) {
    m_Help1.EnableWindow(FALSE);
    m_Help1.ShowWindow(SW_HIDE);
  }

  if (!boffermigrate2appdata) {
    m_Help2.EnableWindow(FALSE);
    m_Help2.ShowWindow(SW_HIDE);
  }

  return TRUE;  // return TRUE unless you set the focus to a control
}
bool XFilterXMLProcessor::Process(const bool &bvalidation,
                                  const StringX &strXMLData,
                                  const stringT &strXMLFileName,
                                  const stringT &strXSDFileName)
{
  USES_XMLCH_STR
  
  bool bErrorOccurred = false;
  stringT cs_validation;
  LoadAString(cs_validation, IDSC_XMLVALIDATION);
  stringT cs_import;
  LoadAString(cs_import, IDSC_XMLIMPORT);
  stringT strResultText(_T(""));
  m_bValidation = bvalidation;  // Validate or Import

  XSecMemMgr sec_mm;

  // Initialize the XML4C2 system
  try
  {
    XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, &sec_mm);
  }
  catch (const XMLException& toCatch)
  {
#ifdef UNICODE
    m_strXMLErrors = stringT(_X2ST(toCatch.getMessage()));
#else
    char *szData = XMLString::transcode(toCatch.getMessage());
    strResultText = stringT(szData);
    XMLString::release(&szData);
#endif
    return false;
  }

  //  Create a SAX2 parser object.
  SAX2XMLReader* pSAX2Parser = XMLReaderFactory::createXMLReader(&sec_mm);

  // Set non-default features
  pSAX2Parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);
  pSAX2Parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
  pSAX2Parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
  pSAX2Parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
  pSAX2Parser->setFeature(XMLUni::fgXercesSkipDTDValidation, true);

  // Set properties
  pSAX2Parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation,
                      (void *)strXSDFileName.c_str());
  pSAX2Parser->setProperty(XMLUni::fgXercesScannerName,
                      (void *)XMLUni::fgSGXMLScanner);
  pSAX2Parser->setInputBufferSize(4096);

  // Create SAX handler object and install it on the pSAX2Parser, as the
  // document and error pSAX2Handler.
  XFilterSAX2Handlers * pSAX2Handler = new XFilterSAX2Handlers;
  pSAX2Parser->setContentHandler(pSAX2Handler);
  pSAX2Parser->setErrorHandler(pSAX2Handler);

  // Workaround/bypass until Xerces supports retrieving version from the
  // <xs:schema ...> statement!
  // Set 'dummy' schema version to arbitrary value > 1
  pSAX2Handler->SetSchemaVersion(99);

  pSAX2Handler->SetVariables(m_pAsker, &m_MapFilters, m_FPool, m_bValidation);

  try
  {
    // Let's begin the parsing now
    if (!strXMLFileName.empty()) {
      pSAX2Parser->parse(_W2X(strXMLFileName.c_str()));
    } else {
      const char *szID = "database_filters";
#ifdef UNICODE
      const char *buffer = XMLString::transcode(_W2X(strXMLData.c_str()));
#else
      const char *buffer = strXMLData.c_str();
#endif
      MemBufInputSource* memBufIS = new MemBufInputSource(
                    (const XMLByte*)buffer,
                    strXMLData.length(),
                    szID, false);
      pSAX2Parser->parse(*memBufIS);
      delete memBufIS;
#ifdef UNICODE
      XMLString::release((char **)&buffer);
#endif
    }
  }
  catch (const OutOfMemoryException&)
  {
    LoadAString(strResultText, IDCS_XERCESOUTOFMEMORY);
    bErrorOccurred = true;
  }
  catch (const XMLException& e)
  {
#ifdef UNICODE
    strResultText = stringT(_X2ST(e.getMessage()));
#else
    char *szData = XMLString::transcode(e.getMessage());
    strResultText = stringT(szData);
    XMLString::release(&szData);
#endif
    bErrorOccurred = true;
  }

  catch (...)
  {
    LoadAString(strResultText, IDCS_XERCESEXCEPTION);
    bErrorOccurred = true;
  }

  if (pSAX2Handler->getIfErrors() || bErrorOccurred) {
    bErrorOccurred = true;
    strResultText = pSAX2Handler->getValidationResult();
    Format(m_strXMLErrors, IDSC_XERCESPARSEERROR, 
           m_bValidation ? cs_validation.c_str() : cs_import.c_str(), 
           strResultText.c_str());
  } else {
    m_strXMLErrors = strResultText;
  }

  //  Delete the pSAX2Parser itself.  Must be done prior to calling Terminate, below.
  delete pSAX2Parser;
  delete pSAX2Handler;

  USES_XMLCH_STR_END

  // And call the termination method
  XMLPlatformUtils::Terminate();

  return !bErrorOccurred;
}
bool XFilterXMLProcessor::Process(const bool &bvalidation,
                                  const StringX &strXMLData,
                                  const stringT &strXMLFileName,
                                  const stringT &strXSDFileName)
{
  USES_XMLCH_STR

  bool bErrorOccurred = false;
  stringT cs_validation;
  LoadAString(cs_validation, IDSC_XMLVALIDATION);
  stringT cs_import;
  LoadAString(cs_import, IDSC_XMLIMPORT);
  stringT strResultText(_T(""));
  m_bValidation = bvalidation;  // Validate or Import

  XSecMemMgr sec_mm;

  // Initialize the XML4C2 system
  try
  {
    XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, &sec_mm);
  }
  catch (const XMLException& toCatch)
  {
    m_strXMLErrors = stringT(_X2ST(toCatch.getMessage()));
    return false;
  }

  //  Create a SAX2 parser object.
  SAX2XMLReader* pSAX2Parser = XMLReaderFactory::createXMLReader(&sec_mm);

  // Set non-default features
  pSAX2Parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);
  pSAX2Parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
  pSAX2Parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
  pSAX2Parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
  pSAX2Parser->setFeature(XMLUni::fgXercesSkipDTDValidation, true);

  // Set properties
  // we need const_cast here, because _W2X return const wchar_t* when
  // WCHAR_INCOMPATIBLE_XMLCH isn't set
  pSAX2Parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation,
                      const_cast<XMLCh*>(_W2X(strXSDFileName.c_str())));
  pSAX2Parser->setProperty(XMLUni::fgXercesScannerName,
                      const_cast<XMLCh*>(XMLUni::fgSGXMLScanner));
  pSAX2Parser->setInputBufferSize(4096);

  // Create SAX handler object and install it on the pSAX2Parser, as the
  // document and error pSAX2Handler.
  XFilterSAX2Handlers * pSAX2Handler = new XFilterSAX2Handlers;
  pSAX2Parser->setContentHandler(pSAX2Handler);
  pSAX2Parser->setErrorHandler(pSAX2Handler);

  // Workaround/bypass until Xerces supports retrieving version from the
  // <xs:schema ...> statement!
  // Set 'dummy' schema version to arbitrary value > 1
  pSAX2Handler->SetSchemaVersion(99);

  pSAX2Handler->SetVariables(m_pAsker, &m_MapFilters, m_FPool, m_bValidation);

  // instantiate converter out of if/else to be sure that string will be valid
  // till the end of pSAX2Parser, that may capture pointer to string from MemBufInputSource
  CUTF8Conv conv;
  try
  {
    // Let's begin the parsing now
    if (!strXMLFileName.empty()) {
      pSAX2Parser->parse(_W2X(strXMLFileName.c_str()));
    } else {
      const char *szID = "database_filters";
      // Xerces use encoding from XML (we have set it to utf-8), but transcode() on Windows convert to one-byte cpXXXX,
      // so we need to manually convert from wchar to UTF-8
      const unsigned char* buffer=nullptr;
      size_t len;
      if (!conv.ToUTF8(strXMLData, buffer, len)) {
        throw std::runtime_error("Can't convert data to UTF-8");
      }
      //2nd parameter must be number of bytes, so we use a length for char* representation
      MemBufInputSource* memBufIS = new MemBufInputSource(
                    reinterpret_cast<const XMLByte *>(buffer),
                    strlen(reinterpret_cast<const char*>(buffer)),
                    szID, false);
      pSAX2Parser->parse(*memBufIS);
      delete memBufIS;
    }
  }
  catch (const OutOfMemoryException&)
  {
    LoadAString(strResultText, IDCS_XERCESOUTOFMEMORY);
    bErrorOccurred = true;
  }
  catch (const XMLException& e)
  {
    strResultText = stringT(_X2ST(e.getMessage()));
    bErrorOccurred = true;
  }

  catch (...)
  {
    LoadAString(strResultText, IDCS_XERCESEXCEPTION);
    bErrorOccurred = true;
  }

  if (pSAX2Handler->getIfErrors() || bErrorOccurred) {
    bErrorOccurred = true;
    if (pSAX2Handler->getIfErrors())
      strResultText = pSAX2Handler->getValidationResult();
    Format(m_strXMLErrors, IDSC_XERCESPARSEERROR,
           m_bValidation ? cs_validation.c_str() : cs_import.c_str(),
           strResultText.c_str());
  } else {
    m_strXMLErrors = strResultText;
  }

  //  Delete the pSAX2Parser itself.  Must be done prior to calling Terminate, below.
  delete pSAX2Parser;
  delete pSAX2Handler;

  USES_XMLCH_STR_END

  // And call the termination method
  XMLPlatformUtils::Terminate();

  return !bErrorOccurred;
}
Exemple #24
0
bool PWSfile::Decrypt(const stringT &fn, const StringX &passwd, stringT &errmess)
{
  ulong64 file_len;
  size_t len;
  unsigned char* buf = nullptr;
  bool status = true;
  unsigned char salt[SaltLength];
  unsigned char ipthing[8];
  unsigned char randstuff[StuffSize];
  unsigned char randhash[SHA1::HASHLEN];
  unsigned char temphash[SHA1::HASHLEN];

  FILE *in = pws_os::FOpen(fn, _T("rb"));
  if (in == nullptr) {
    status = false;
    goto exit;
  }

  file_len = pws_os::fileLength(in);

  if (file_len < (8 + sizeof(randhash) + 8 + SaltLength)) {
    fclose(in);
    LoadAString(errmess, IDSC_FILE_TOO_SHORT);
    return false;
  }

  fread(randstuff, 1, 8, in);
  randstuff[8] = randstuff[9] = TCHAR('\0'); // ugly bug workaround
  fread(randhash, 1, sizeof(randhash), in);

  GenRandhash(passwd, randstuff, temphash);
  if (memcmp(reinterpret_cast<char *>(randhash), reinterpret_cast<char *>(temphash), SHA1::HASHLEN) != 0) {
    fclose(in);
    LoadAString(errmess, IDSC_BADPASSWORD);
    return false;
  }

  { // decryption in a block, since we use goto
    fread(salt,    1, SaltLength, in);
    fread(ipthing, 1, 8,          in);

    unsigned char dummyType;
    unsigned char *pwd = nullptr;
    size_t passlen = 0;
    ConvertPasskey(passwd, pwd, passlen);
    Fish *fish = BlowFish::MakeBlowFish(pwd, reinterpret_cast<unsigned int &>(passlen), salt, SaltLength);
    trashMemory(pwd, passlen);
    delete[] pwd; // gross - ConvertPasskey allocates.
    if (_readcbc(in, buf, len,dummyType, fish, ipthing, 0, file_len) == 0) {
      delete fish;
      delete[] buf; // if not yet allocated, delete[] nullptr, which is OK
      return false;
    }
    delete fish;
    fclose(in);
  } // decrypt

  { // write decrypted data
    size_t suffix_len = CIPHERTEXT_SUFFIX.length();
    size_t filepath_len = fn.length();

    stringT out_fn = fn;
    out_fn = out_fn.substr(0,filepath_len - suffix_len);

    FILE *out = pws_os::FOpen(out_fn, _T("wb"));
    if (out != nullptr) {
      size_t fret = fwrite(buf, 1, len, out);
      if (fret != len) {
        int save_errno = errno;
        fclose(out);
        errno = save_errno;
        goto exit;
      }
      if (fclose(out) != 0) {
        status = false;
        goto exit;
      }
    } else { // open failed
      status = false;
      goto exit;
    }
  } // write decrypted
 exit:
  if (!status)
    errmess = ErrorMessages();
  delete[] buf; // allocated by _readcbc
  return status;
}
Exemple #25
0
void CompareDlg::OnGridCellRightClick(wxGridEvent& evt)
{
  wxGrid* grid = wxDynamicCast(evt.GetEventObject(), wxGrid);
  if (!grid) {
    evt.Skip();
    return;
  }
  ComparisonData* cd = reinterpret_cast<ComparisonData*>(grid->GetClientData());
  wxCHECK_RET(cd, wxT("ClientData object not found in grid"));

  ContextMenuData menuContext;
  menuContext.cdata = cd;

  if (!menuContext.cdata->grid->IsInSelection(evt.GetRow(), evt.GetCol())) {
    menuContext.cdata->grid->SelectRow(evt.GetRow(), false);
  }

  if (menuContext.cdata == m_conflicts) {
    menuContext.cdata->grid->SelectRow(evt.GetRow()%2 == 0? evt.GetRow()+1: evt.GetRow()-1, true);
  }

  menuContext.cdata->grid->SetGridCursor(evt.GetRow(), evt.GetCol());

  menuContext.selectedRows = menuContext.cdata->grid->GetSelectedRows();
  menuContext.selectedItems = menuContext.selectedRows;
  size_t selectionCount = menuContext.selectedRows.GetCount();
  if (menuContext.cdata == m_conflicts) {
    selectionCount /= 2;
    wxCHECK_RET(menuContext.selectedItems.GetCount()%2 ==0, wxT("Conflicts grid should always select an even numer of items"));
    //Our alogo requires the indexes to be in order, and sometimes these are actually unsorted
    menuContext.selectedItems.Sort(pless);
    for( size_t idx = 1; idx <= selectionCount; ++idx) {
      wxCHECK_RET(menuContext.selectedItems[idx]%2 != 0, wxT("Selection indexes not in expected order"));
      wxLogDebug( wxString() << wxT("Removing index ") << menuContext.selectedItems.Item(idx) << wxT(" from selection at index ") << idx << wxT('\n'));
      menuContext.selectedItems.RemoveAt(idx, 1);
    }
    for( size_t idx = 0; idx < selectionCount; ++idx) {
      wxLogDebug(wxString() << wxT("Found index ") << menuContext.selectedItems.Item(idx) << wxT(" from selection at ") << idx << wxT('\n'));
      wxCHECK_RET(menuContext.selectedItems[idx]%2 == 0, wxT("Conflicts grid selection should only have even indexes after normalization"));
      menuContext.selectedItems[idx] /= 2;
    }
  }

  stringT itemStr;
  LoadAString(itemStr, selectionCount > 1? IDSC_ENTRIES: IDSC_ENTRY);

  wxString selCountStr(wxT(" "));
  if (selectionCount > 1)
    selCountStr << selectionCount << wxT(" ");

  wxMenu itemEditMenu;

  wxString strSyncSelectedItemsMenu;
  if (selectionCount == 1)
    strSyncSelectedItemsMenu << _("Synchronize this item...");
  else
    strSyncSelectedItemsMenu << _("Synchronize") << selCountStr << _("selected ") << towxstring(itemStr) << _("...");
  itemEditMenu.Append(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB, strSyncSelectedItemsMenu);

  itemEditMenu.Append(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB, _("Synchronize all items..."));

  wxString strCopyItemsMenu;
  strCopyItemsMenu << _("Copy") << selCountStr << _("selected ") << towxstring(itemStr) << _(" to current db");
  itemEditMenu.Append(ID_COPY_ITEMS_TO_CURRENT_DB, strCopyItemsMenu);

  wxString strDeleteItemsMenu;
  strDeleteItemsMenu << _("Delete") << selCountStr << _("selected ") << towxstring(itemStr) << _(" from current db");
  itemEditMenu.Append(ID_DELETE_ITEMS_FROM_CURRENT_DB, strDeleteItemsMenu);

  if (selectionCount == 1) {
    itemEditMenu.AppendSeparator();

    itemEditMenu.Append(ID_EDIT_IN_CURRENT_DB,   _("&Edit entry in current db"));
    itemEditMenu.Append(ID_VIEW_IN_COMPARISON_DB,   _("&View entry in comparison db"));
  }

  if (menuContext.cdata == m_conflicts) {
    wxString strCopyFieldMenu;
    ComparisonGridTable* table = wxDynamicCast(menuContext.cdata->grid->GetTable(), ComparisonGridTable);
    menuContext.field = table->ColumnToField(evt.GetCol());
    if (selectionCount > 1)
      strCopyFieldMenu << _("&Copy ") << selectionCount << _(" selected ") <<
        towxstring(CItemData::FieldName(menuContext.field))
                       << _(" fields to current db");
    else
      strCopyFieldMenu << _("&Copy this ") << towxstring(CItemData::FieldName(menuContext.field)) << _(" to current db");

    itemEditMenu.Insert(0, ID_COPY_FIELD_TO_CURRENT_DB, strCopyFieldMenu);

    itemEditMenu.InsertSeparator(1);
    itemEditMenu.Delete(ID_COPY_ITEMS_TO_CURRENT_DB);
  }
  else if (menuContext.cdata == m_current) {
    itemEditMenu.Delete(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_COPY_ITEMS_TO_CURRENT_DB);
    if (selectionCount == 1)
      itemEditMenu.Delete(ID_VIEW_IN_COMPARISON_DB);
  }
  else if (menuContext.cdata == m_comparison) {
    itemEditMenu.Delete(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_DELETE_ITEMS_FROM_CURRENT_DB);
    if (selectionCount == 1)
      itemEditMenu.Delete(ID_EDIT_IN_CURRENT_DB);
  }
  else if (menuContext.cdata == m_identical) {
    itemEditMenu.Delete(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_COPY_ITEMS_TO_CURRENT_DB);
  }

  // Make the menuContext object available to the handlers
  EventDataInjector<wxCommandEvent> inject(&itemEditMenu, &menuContext, wxEVT_COMMAND_MENU_SELECTED);

  menuContext.cdata->grid->PopupMenu(&itemEditMenu);
}
Exemple #26
0
//  -----------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE MFilterSAX2ContentHandler::endElement (
  const wchar_t * pwchNamespaceUri,
  int cchNamespaceUri,
  const wchar_t * pwchLocalName,
  int cchLocalName,
  const wchar_t * pwchQName,
  int cchQName)
{
  TCHAR szCurElement[MAX_PATH + 1] = {0};

  _tcsncpy_s(szCurElement, MAX_PATH + 1, pwchQName, cchQName);

  if (m_bValidation && _tcscmp(szCurElement, _T("filters")) == 0) {
    // Check that the XML file version is present and that
    // a. it is less than or equal to the Filter schema version
    // b. it is less than or equal to the version supported by this PWS
    if (m_iXMLVersion < 0) {
      LoadAString(m_strXMLErrors, IDSC_MISSING_XML_VER);
      return E_FAIL;
    }
    if (m_iXMLVersion > m_iSchemaVersion) {
      Format(m_strXMLErrors,
             IDSC_INVALID_XML_VER1, m_iXMLVersion, m_iSchemaVersion);
      return E_FAIL;
    }
    if (m_iXMLVersion > PWS_XML_FILTER_VERSION) {
      Format(m_strXMLErrors,
             IDSC_INVALID_XML_VER2, m_iXMLVersion, PWS_XML_FILTER_VERSION);
      return E_FAIL;
    }
  }

  if (m_bValidation) {
    return S_OK;
  }

  if (_tcscmp(szCurElement, _T("filter")) == 0) {
    INT_PTR rc = IDYES;
    st_Filterkey fk;
    fk.fpool = m_FPool;
    fk.cs_filtername = cur_filter->fname;
    if (m_MapFilters->find(fk) != m_MapFilters->end()) {
      stringT question;
      Format(question, IDSC_FILTEREXISTS, cur_filter->fname.c_str());
      if (m_pAsker == NULL || !(*m_pAsker)(question)) {
        m_MapFilters->erase(fk);
      }
    }
    if (rc == IDYES) {
      m_MapFilters->insert(PWSFilters::Pair(fk, *cur_filter));
    }
    delete cur_filter;
    return S_OK;
  }

  else if (_tcscmp(szCurElement, _T("filter_entry")) == 0) {
    if (cur_filterentry->mtype  == PWSMatch::MT_DATE &&
        cur_filterentry->rule   != PWSMatch::MR_PRESENT &&
        cur_filterentry->rule   != PWSMatch::MR_NOTPRESENT &&
        cur_filterentry->fdate1 == (time_t)0 &&
        cur_filterentry->fdate2 == (time_t)0)
      cur_filterentry->fdatetype = 1; // Relative Date
    if (m_type == DFTYPE_MAIN) {
      cur_filter->num_Mactive++;
      cur_filter->vMfldata.push_back(*cur_filterentry);
    } else if (m_type == DFTYPE_PWHISTORY) {
      cur_filter->num_Hactive++;
      cur_filter->vHfldata.push_back(*cur_filterentry);
    } else if (m_type == DFTYPE_PWPOLICY) {
      cur_filter->num_Pactive++;
      cur_filter->vPfldata.push_back(*cur_filterentry);
    }
    delete cur_filterentry;
  }

  else if (_tcscmp(szCurElement, _T("grouptitle")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_GROUPTITLE;
  }

  else if (_tcscmp(szCurElement, _T("group")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_GROUP;
  }

  else if (_tcscmp(szCurElement, _T("title")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_TITLE;
  }

  else if (_tcscmp(szCurElement, _T("user")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_USER;
  }

  else if (_tcscmp(szCurElement, _T("password")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_PASSWORD;
    cur_filterentry->ftype = FT_PASSWORD;
  }

  else if (_tcscmp(szCurElement, _T("notes")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_NOTES;
  }

  else if (_tcscmp(szCurElement, _T("url")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_URL;
  }

  else if (_tcscmp(szCurElement, _T("autotype")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_AUTOTYPE;
  }

  else if (_tcscmp(szCurElement, _T("runcommand")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_RUNCMD;
  }

  else if (_tcscmp(szCurElement, _T("DCA")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_DCA;
    cur_filterentry->ftype = FT_DCA;
  }

  else if (_tcscmp(szCurElement, _T("ShiftDCA")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_SHIFTDCA;
    cur_filterentry->ftype = FT_SHIFTDCA;
  }

  else if (_tcscmp(szCurElement, _T("email")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_EMAIL;
  }

  else if (_tcscmp(szCurElement, _T("protected")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = FT_PROTECTED;
  }

  else if (_tcscmp(szCurElement, _T("kbshortcut")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = FT_KBSHORTCUT;
  }

  else if (_tcscmp(szCurElement, _T("symbols")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_SYMBOLS;
    cur_filterentry->fstring = PWSUtil::DeDupString(cur_filterentry->fstring);
  }

  else if (_tcscmp(szCurElement, _T("policy_name")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_STRING;
    cur_filterentry->ftype = FT_POLICYNAME;
  }

  else if (_tcscmp(szCurElement, _T("create_time")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_DATE;
    cur_filterentry->ftype = FT_CTIME;
  }

  else if (_tcscmp(szCurElement, _T("password_modified_time")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_DATE;
    cur_filterentry->ftype = FT_PMTIME;
  }

  else if (_tcscmp(szCurElement, _T("last_access_time")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_DATE;
    cur_filterentry->ftype = FT_ATIME;
  }

  else if (_tcscmp(szCurElement, _T("expiry_time")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_DATE;
    cur_filterentry->ftype = FT_XTIME;
  }

  else if (_tcscmp(szCurElement, _T("record_modified_time")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_DATE;
    cur_filterentry->ftype = FT_RMTIME;
  }

  else if (_tcscmp(szCurElement, _T("password_expiry_interval")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = FT_XTIME_INT;
  }

  else if (_tcscmp(szCurElement, _T("password_length")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = FT_PASSWORDLEN;
  }

  else if (_tcscmp(szCurElement, _T("entrytype")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_ENTRYTYPE;
    cur_filterentry->ftype = FT_ENTRYTYPE;
  }

  else if (_tcscmp(szCurElement, _T("entrystatus")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_ENTRYSTATUS;
    cur_filterentry->ftype = FT_ENTRYSTATUS;
  }

  else if (_tcscmp(szCurElement, _T("entrysize")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_ENTRYSIZE;
    cur_filterentry->ftype = FT_ENTRYSIZE;
  }

  else if (_tcscmp(szCurElement, _T("unknownfields")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->ftype = FT_UNKNOWNFIELDS;
  }

  else if (_tcscmp(szCurElement, _T("password_history")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_PWHIST;
    cur_filterentry->ftype = FT_PWHIST;
  }

  else if (_tcscmp(szCurElement, _T("history_present")) == 0) {
    m_type = DFTYPE_PWHISTORY;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = HT_PRESENT;
  }

  else if (_tcscmp(szCurElement, _T("history_active")) == 0) {
    m_type = DFTYPE_PWHISTORY;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = HT_ACTIVE;
  }

  else if (_tcscmp(szCurElement, _T("history_number")) == 0) {
    m_type = DFTYPE_PWHISTORY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = HT_NUM;
  }

  else if (_tcscmp(szCurElement, _T("history_maximum")) == 0) {
    m_type = DFTYPE_PWHISTORY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = HT_MAX;
  }

  else if (_tcscmp(szCurElement, _T("history_changedate")) == 0) {
    m_type = DFTYPE_PWHISTORY;
    cur_filterentry->mtype = PWSMatch::MT_DATE;
    cur_filterentry->ftype = HT_CHANGEDATE;
  }

  else if (_tcscmp(szCurElement, _T("history_passwords")) == 0) {
    m_type = DFTYPE_PWHISTORY;
    cur_filterentry->mtype = PWSMatch::MT_PASSWORD;
    cur_filterentry->ftype = HT_PASSWORDS;
  }

  else if (_tcscmp(szCurElement, _T("password_policy")) == 0) {
    m_type = DFTYPE_MAIN;
    cur_filterentry->mtype = PWSMatch::MT_POLICY;
    cur_filterentry->ftype = FT_POLICY;
  }

  else if (_tcscmp(szCurElement, _T("policy_present")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = PT_PRESENT;
  }

  else if (_tcscmp(szCurElement, _T("policy_length")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = PT_LENGTH;
  }

  else if (_tcscmp(szCurElement, _T("policy_number_lowercase")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = PT_LOWERCASE;
  }

  else if (_tcscmp(szCurElement, _T("policy_number_uppercase")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = PT_UPPERCASE;
  }

  else if (_tcscmp(szCurElement, _T("policy_number_digits")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = PT_DIGITS;
  }

  else if (_tcscmp(szCurElement, _T("policy_number_symbols")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_INTEGER;
    cur_filterentry->ftype = PT_SYMBOLS;
  }

  else if (_tcscmp(szCurElement, _T("policy_easyvision")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = PT_EASYVISION;
  }

  else if (_tcscmp(szCurElement, _T("policy_pronounceable")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = PT_PRONOUNCEABLE;
  }

  else if (_tcscmp(szCurElement, _T("policy_hexadecimal")) == 0) {
    m_type = DFTYPE_PWPOLICY;
    cur_filterentry->mtype = PWSMatch::MT_BOOL;
    cur_filterentry->ftype = PT_HEXADECIMAL;
  }

  else if (_tcscmp(szCurElement, _T("rule")) == 0) {
    ToUpper(m_sxElemContent);
    cur_filterentry->rule = PWSMatch::GetRule(m_sxElemContent);
  }

  else if (_tcscmp(szCurElement, _T("logic")) == 0) {
    if (m_sxElemContent == _T("or"))
      cur_filterentry->ltype = LC_OR;
    else
      cur_filterentry->ltype = LC_AND;
  }

  else if (_tcscmp(szCurElement, _T("string")) == 0) {
    cur_filterentry->fstring = m_sxElemContent;
  }

  else if (_tcscmp(szCurElement, _T("case")) == 0) {
    cur_filterentry->fcase = _ttoi(m_sxElemContent.c_str()) != 0;
  }

  else if (_tcscmp(szCurElement, _T("warn")) == 0) {
    cur_filterentry->fnum1 = _ttoi(m_sxElemContent.c_str());
  }

  else if (_tcscmp(szCurElement, _T("num1")) == 0) {
    cur_filterentry->fnum1 = _ttoi(m_sxElemContent.c_str());
  }

  else if (_tcscmp(szCurElement, _T("num2")) == 0) {
    cur_filterentry->fnum2 = _ttoi(m_sxElemContent.c_str());
  }

  else if (_tcscmp(szCurElement, _T("unit")) == 0) {
    cur_filterentry->funit = _ttoi(m_sxElemContent.c_str());
  }

  else if (_tcscmp(szCurElement, _T("date1")) == 0) {
    time_t t(0);
    if (VerifyXMLDateString(m_sxElemContent.c_str(), t) &&
        (t != (time_t)-1))
      cur_filterentry->fdate1 = t;
    else
      cur_filterentry->fdate1 = (time_t)0;
  }

  else if (_tcscmp(szCurElement, _T("date2")) == 0) {
    time_t t(0);
    if (VerifyXMLDateString(m_sxElemContent.c_str(), t) &&
        (t != (time_t)-1))
      cur_filterentry->fdate2 = t;
    else
      cur_filterentry->fdate1 = (time_t)0;
  }

  else if (_tcscmp(szCurElement, _T("dca")) == 0) {
    cur_filterentry->fdca = (short)_ttoi(m_sxElemContent.c_str());
  }

  else if (_tcscmp(szCurElement, _T("shiftdca")) == 0) {
    cur_filterentry->fdca = (short)_ttoi(m_sxElemContent.c_str());
  }

  else if (_tcscmp(szCurElement, _T("type")) == 0) {
    if (m_sxElemContent == _T("normal"))
      cur_filterentry->etype = CItemData::ET_NORMAL;
    else if (m_sxElemContent == _T("alias"))
      cur_filterentry->etype = CItemData::ET_ALIAS;
    else if (m_sxElemContent == _T("shortcut"))
      cur_filterentry->etype = CItemData::ET_SHORTCUT;
    else if (m_sxElemContent == _T("aliasbase"))
      cur_filterentry->etype = CItemData::ET_ALIASBASE;
    else if (m_sxElemContent == _T("shortcutbase"))
      cur_filterentry->etype = CItemData::ET_SHORTCUTBASE;
    else
      cur_filterentry->etype = CItemData::ET_INVALID;
  }

  else if (_tcscmp(szCurElement, _T("status")) == 0) {
    if (m_sxElemContent == _T("clean"))
      cur_filterentry->estatus = CItemData::ES_CLEAN;
    else if (m_sxElemContent == _T("added"))
      cur_filterentry->estatus = CItemData::ES_ADDED;
    else if (m_sxElemContent == _T("modified"))
      cur_filterentry->estatus = CItemData::ES_MODIFIED;
    else
      cur_filterentry->estatus = CItemData::ES_INVALID;
  } else if (!(_tcscmp(szCurElement, _T("test")) == 0 ||
               _tcscmp(szCurElement, _T("filters")) == 0))
    ASSERT(0);

  return S_OK;
}