Пример #1
0
UIntN LpmConfigurationReaderV1::readControlValue(void)
{
    string key = "ControlValue";
    UIntN controlValue = getPolicyServices().platformConfigurationData->readConfigurationUInt32(
        root() + keyPath() + key);
    return controlValue;
}
Пример #2
0
UInt32 LpmConfigurationReaderV0::readGfxTargetFrequency()
{
    string key = "GfxTargetFrequency";
    UInt32 gfxTargetFrequency;
    try
    {
        gfxTargetFrequency =
            getPolicyServices().platformConfigurationData->readConfigurationUInt32(
            root() + keyPath() + key);
    }
    catch(dptf_exception& e)
    {
        string msg = e.what();

        m_policyServices.messageLogging->writeMessageError(PolicyMessage(FLF,
            "Error in reading GfxTargetFrequency, default 100Mhz. msg - " + msg,
            Constants::Invalid));

        //
        // if not found, we default to 100 mhz,
        // which will be the lowest graphics p-state (since we round up)
        //
        gfxTargetFrequency = 100;
    }

    return gfxTargetFrequency;
}
Пример #3
0
UInt32 LpmConfigurationReaderV0::readCpuPercentageActiveLogicalProcessors()
{
    string key = "CpuPercentageActiveLogicalProcessors";
    UInt32 cpuPercentageActiveLogicalProcessors;
    try
    {
        cpuPercentageActiveLogicalProcessors =
            getPolicyServices().platformConfigurationData->readConfigurationUInt32(
                root() + keyPath() + key);
    }
    catch(dptf_exception& e)
    {
        string msg = e.what();

        m_policyServices.messageLogging->writeMessageDebug(PolicyMessage(FLF,
            "No CpuPercentageActiveLogicalProcessors - defaulting to 1%. msg - " + msg,
            Constants::Invalid));

        // Default to 1% (translates to 1 core).
        cpuPercentageActiveLogicalProcessors = 1;
    }

    if (cpuPercentageActiveLogicalProcessors < 1)
    {
        cpuPercentageActiveLogicalProcessors = 1;
    }
    else if (cpuPercentageActiveLogicalProcessors > 100)
    {
        cpuPercentageActiveLogicalProcessors = 100;
    }

    return cpuPercentageActiveLogicalProcessors;
}
Пример #4
0
// static
KeyPath
KeyPath::DeserializeFromString(const nsAString& aString)
{
    KeyPath keyPath(0);

    if (!aString.IsEmpty() && aString.First() == ',') {
        keyPath.SetType(ARRAY);

        // We use a comma in the beginning to indicate that it's an array of
        // key paths. This is to be able to tell a string-keypath from an
        // array-keypath which contains only one item.
        nsCharSeparatedTokenizerTemplate<IgnoreWhitespace> tokenizer(aString, ',');
        tokenizer.nextToken();
        while (tokenizer.hasMoreTokens()) {
            keyPath.mStrings.AppendElement(tokenizer.nextToken());
        }

        return keyPath;
    }

    keyPath.SetType(STRING);
    keyPath.mStrings.AppendElement(aString);

    return keyPath;
}
Пример #5
0
Bool LpmConfigurationReaderV0::readCpuUseTStateThrottling()
{
    string key = "CpuUseTStateThrottling";
    Bool cpuUseTStateThrottling;
    try
    {
        UIntN valueInt =
            getPolicyServices().platformConfigurationData->readConfigurationUInt32(
            root() + keyPath() + key);
        if (valueInt)
        {
            cpuUseTStateThrottling = true;
        }
        else
        {
            cpuUseTStateThrottling = false;
        }
    }
    catch(dptf_exception& e)
    {
        string msg = e.what();
        m_policyServices.messageLogging->writeMessageDebug(PolicyMessage(FLF,
            "No CpuUseTStateThrottling - defaulting to false. msg - " + msg,
            Constants::Invalid));
        cpuUseTStateThrottling = false;
    }

    if ((cpuUseTStateThrottling != true) && (cpuUseTStateThrottling != false))
    {
        cpuUseTStateThrottling = false;
    }

    return cpuUseTStateThrottling;
}
Пример #6
0
CoreControlOffliningMode::Type LpmConfigurationReaderV0::readCpuOffliningMode()
{
    string key = "CpuOffLiningMode";
    CoreControlOffliningMode::Type cpuOffliningMode;
    try
    {
        UIntN valueInt = getPolicyServices().platformConfigurationData->readConfigurationUInt32(
            root() + keyPath() + key);
        if (valueInt > CoreControlOffliningMode::Core)
        {
            m_policyServices.messageLogging->writeMessageError(PolicyMessage(FLF,
            "Invalid CoreControlOffliningMode returned (" + to_string(valueInt) + ")" +
                " - defaulting to core", Constants::Invalid));
            cpuOffliningMode = CoreControlOffliningMode::Core;
        }
        else
        {
            cpuOffliningMode = (CoreControlOffliningMode::Type)valueInt;
        }
    }
    catch(dptf_exception& e)
    {
        string msg = e.what();
        m_policyServices.messageLogging->writeMessageDebug(PolicyMessage(FLF,
            "No CoreControlOffliningMode returned - defaulting to core. msg - " + msg,
            Constants::Invalid));
        cpuOffliningMode = CoreControlOffliningMode::Core;
    }

    return cpuOffliningMode;
}
Пример #7
0
// static
nsresult
KeyPath::Parse(JSContext* aCx, const JS::Value& aValue, KeyPath* aKeyPath)
{
  KeyPath keyPath(0);

  aKeyPath->SetType(NONEXISTENT);

  // See if this is a JS array.
  if (!JSVAL_IS_PRIMITIVE(aValue) &&
      JS_IsArrayObject(aCx, JSVAL_TO_OBJECT(aValue))) {

    JSObject* obj = JSVAL_TO_OBJECT(aValue);

    uint32_t length;
    if (!JS_GetArrayLength(aCx, obj, &length)) {
      return NS_ERROR_FAILURE;
    }

    if (!length) {
      return NS_ERROR_FAILURE;
    }

    keyPath.SetType(ARRAY);

    for (uint32_t index = 0; index < length; index++) {
      jsval val;
      JSString* jsstr;
      nsDependentJSString str;
      if (!JS_GetElement(aCx, obj, index, &val) ||
          !(jsstr = JS_ValueToString(aCx, val)) ||
          !str.init(aCx, jsstr)) {
        return NS_ERROR_FAILURE;
      }

      if (!keyPath.AppendStringWithValidation(aCx, str)) {
        return NS_ERROR_FAILURE;
      }
    }
  }
  // Otherwise convert it to a string.
  else if (!JSVAL_IS_NULL(aValue) && !JSVAL_IS_VOID(aValue)) {
    JSString* jsstr;
    nsDependentJSString str;
    if (!(jsstr = JS_ValueToString(aCx, aValue)) ||
        !str.init(aCx, jsstr)) {
      return NS_ERROR_FAILURE;
    }

    keyPath.SetType(STRING);

    if (!keyPath.AppendStringWithValidation(aCx, str)) {
      return NS_ERROR_FAILURE;
    }
  }

  *aKeyPath = keyPath;
  return NS_OK;
}
Пример #8
0
// static
nsresult
KeyPath::Parse(JSContext* aCx, const JS::Value& aValue_, KeyPath* aKeyPath)
{
    JS::Rooted<JS::Value> aValue(aCx, aValue_);
    KeyPath keyPath(0);

    aKeyPath->SetType(NONEXISTENT);

    // See if this is a JS array.
    if (JS_IsArrayObject(aCx, aValue)) {

        JS::Rooted<JSObject*> obj(aCx, aValue.toObjectOrNull());

        uint32_t length;
        if (!JS_GetArrayLength(aCx, obj, &length)) {
            return NS_ERROR_FAILURE;
        }

        if (!length) {
            return NS_ERROR_FAILURE;
        }

        keyPath.SetType(ARRAY);

        for (uint32_t index = 0; index < length; index++) {
            JS::Rooted<JS::Value> val(aCx);
            JSString* jsstr;
            nsAutoJSString str;
            if (!JS_GetElement(aCx, obj, index, &val) ||
                    !(jsstr = JS::ToString(aCx, val)) ||
                    !str.init(aCx, jsstr)) {
                return NS_ERROR_FAILURE;
            }

            if (!keyPath.AppendStringWithValidation(aCx, str)) {
                return NS_ERROR_FAILURE;
            }
        }
    }
    // Otherwise convert it to a string.
    else if (!aValue.isNull() && !aValue.isUndefined()) {
        JSString* jsstr;
        nsAutoJSString str;
        if (!(jsstr = JS::ToString(aCx, aValue)) ||
                !str.init(aCx, jsstr)) {
            return NS_ERROR_FAILURE;
        }

        keyPath.SetType(STRING);

        if (!keyPath.AppendStringWithValidation(aCx, str)) {
            return NS_ERROR_FAILURE;
        }
    }

    *aKeyPath = keyPath;
    return NS_OK;
}
Пример #9
0
DomainType::Type LpmConfigurationReaderV1::readDomainType(void)
{
    string key = "DomainType";
    UIntN valueInt = getPolicyServices().platformConfigurationData->readConfigurationUInt32(
        root() + keyPath() + key);
    // Convert from esif/acpi type to dptf type.
    esif_domain_type esifDomainType = static_cast<esif_domain_type>(valueInt);
    return(EsifDomainTypeToDptfDomainType(esifDomainType));
}
Пример #10
0
// static
nsresult KeyPath::Parse(const nsAString& aString, KeyPath* aKeyPath) {
  KeyPath keyPath(0);
  keyPath.SetType(STRING);

  if (!keyPath.AppendStringWithValidation(aString)) {
    return NS_ERROR_FAILURE;
  }

  *aKeyPath = keyPath;
  return NS_OK;
}
Пример #11
0
ControlKnobType::Type LpmConfigurationReaderV1::readControlKnob(void)
{
    string key = "ControlKnob";
    UIntN valueInt = getPolicyServices().platformConfigurationData->readConfigurationUInt32(
        root() + keyPath() + key);
    if (validControlKnob(valueInt) == false)
    {
        throw dptf_exception("Invalid control knob returned");
    }
    return(ControlKnobType::Type(valueInt));
}
Пример #12
0
// static
nsresult KeyPath::Parse(const Sequence<nsString>& aStrings, KeyPath* aKeyPath) {
  KeyPath keyPath(0);
  keyPath.SetType(ARRAY);

  for (uint32_t i = 0; i < aStrings.Length(); ++i) {
    if (!keyPath.AppendStringWithValidation(aStrings[i])) {
      return NS_ERROR_FAILURE;
    }
  }

  *aKeyPath = keyPath;
  return NS_OK;
}
Пример #13
0
std::string LpmConfigurationReaderV1::readTargetDeviceAcpiScope(void)
{
    string key = "TargetDeviceObjectId";
    string target = getPolicyServices().platformConfigurationData->readConfigurationString(
        root() + keyPath() + key);
    if (target.empty())
    {
        throw dptf_exception("Empty ACPI scope string returned");
    }

    string normalizedTarget = BinaryParse::normalizeAcpiScope(target);
    return normalizedTarget;
}
Пример #14
0
void
BackEndFile::doDeleteKey(const Name& keyName)
{
  boost::filesystem::path keyPath(m_impl->toFileName(keyName));

  if (boost::filesystem::exists(keyPath)) {
    try {
      boost::filesystem::remove(keyPath);
    }
    catch (const boost::filesystem::filesystem_error&) {
      BOOST_THROW_EXCEPTION(Error("Cannot delete key"));
    }
  }
}
Пример #15
0
void QWinSettingsPrivate::remove(const QString &uKey)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    // try to delete value bar in key foo
    LONG res;
    HKEY handle = openKey(writeHandle(), registryPermissions, keyPath(rKey));
    if (handle != 0) {
        res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()));
        RegCloseKey(handle);
    }

    // try to delete key foo/bar and all subkeys
    handle = openKey(writeHandle(), registryPermissions, rKey);
    if (handle != 0) {
        deleteChildGroups(handle);

        if (rKey.isEmpty()) {
            QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);

            for (int i = 0; i < childKeys.size(); ++i) {
                QString group = childKeys.at(i);

                LONG res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(group.utf16()));
                if (res != ERROR_SUCCESS) {
                    qWarning("QSettings: RegDeleteValue failed on subkey \"%s\": %s",
                              group.toLatin1().data(), errorCodeToString(res).toLatin1().data());
                }
            }
        } else {
#if defined(Q_OS_WINCE)
            // For WinCE always Close the handle first.
            RegCloseKey(handle);
#endif
            res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(rKey.utf16()));

            if (res != ERROR_SUCCESS) {
                qWarning("QSettings: RegDeleteKey failed on key \"%s\": %s",
                            rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
            }
        }
        RegCloseKey(handle);
    }
}
Пример #16
0
vector<string> LpmConfigurationReaderV1::readAppNames(UInt32 entryIndex)
{
    string indexAsString = getIndexAsString(entryIndex);
    string path = "AppSpecificLpm" + indexAsString + "/";
    setKeyPath(path);

    string key = "ExecutableNames";
    string execNames = getPolicyServices().platformConfigurationData->readConfigurationString(
        root() + keyPath() + key);
    if (execNames.empty())
    {
        throw dptf_exception("Empty execNames string returned");
    }

    // Parse the string, it contains app names each separated by space.
    vector<string> appNames = tokenize(execNames, ' ');
    return appNames;
}
Пример #17
0
vector<LpmEntry> LpmConfigurationReaderV1::readLpmEntries(void)
{
    vector<LpmEntry> lpmEntries;

    string target;
    DomainType::Type domainType;
    ControlKnobType::Type controlKnob;
    UInt32 controlValue;

    UIntN lpmEntryIndex;
    string inputKeyPath = keyPath();
    try
    {
        for (lpmEntryIndex = 0; ; lpmEntryIndex++)
        {
            setLpmEntryKeyPath(inputKeyPath, lpmEntryIndex);

            target = readTargetDeviceAcpiScope();
            domainType = readDomainType();
            controlKnob = readControlKnob();
            controlValue = readControlValue();
            
            lpmEntries.push_back(LpmEntry(target, domainType, controlKnob, controlValue));
            if (lpmEntryIndex >= LpmEntriesIndexLimit::MaxLpmEntryIndex)
            {
                throw dptf_exception("LPM entries exceeded max value");
            }
        }
    }
    catch (dptf_exception& e)
    {
        string msg = e.what();
        postInfoMessage(PolicyMessage(FLF,
            "Error msg (" + msg + "). Last lpmEntryIndex = " + to_string(lpmEntryIndex),
            Constants::Invalid));
        return lpmEntries;
    }

    return (lpmEntries);
}
Пример #18
0
vector<AppSpecificEntry> LpmConfigurationReaderV1::readAppSpecificEntries(void)
{
    vector<AppSpecificEntry> appSpecificEntries;

    //
    // Since this configuration does not have the numAppSpecificEntries we loop through
    // till we fail to read. We handle it in the catch block.
    //
    UIntN appIndex;
    try
    {
        for (appIndex = 0; ; appIndex++)
        {
            vector<string> appNames = readAppNames(appIndex);

            string key = "LPMSet";
            UIntN lpmSetIndex = getPolicyServices().platformConfigurationData->readConfigurationUInt32(
                root() + keyPath() + key);

            appSpecificEntries.push_back(AppSpecificEntry(appNames, lpmSetIndex));

            if (appIndex >= LpmEntriesIndexLimit::MaxAppEntryIndex)
            {
                throw dptf_exception("App Entries exceeded max value");
            }
        }
    }
    catch (dptf_exception& e)
    {
        string msg = e.what();
        postInfoMessage(PolicyMessage(FLF,
            "Error msg (" + msg + "). Last appIndex = " + to_string(appIndex),
            Constants::Invalid));
        return appSpecificEntries;
    }

    return appSpecificEntries;

}
Пример #19
0
// static
nsresult KeyPath::Parse(const Nullable<OwningStringOrStringSequence>& aValue,
                        KeyPath* aKeyPath) {
  KeyPath keyPath(0);

  aKeyPath->SetType(NONEXISTENT);

  if (aValue.IsNull()) {
    *aKeyPath = keyPath;
    return NS_OK;
  }

  if (aValue.Value().IsString()) {
    return Parse(aValue.Value().GetAsString(), aKeyPath);
  }

  MOZ_ASSERT(aValue.Value().IsStringSequence());

  const Sequence<nsString>& seq = aValue.Value().GetAsStringSequence();
  if (seq.Length() == 0) {
    return NS_ERROR_FAILURE;
  }
  return Parse(seq, aKeyPath);
}
Пример #20
0
vector<string> LpmConfigurationReaderV0::readAppNames(UInt32 entryIndex)
{
    string key = "AppName";
    vector<string> appNames;
    string indexAsString = getIndexAsString(entryIndex);

    setKeyPath("AppSpecificMode" + indexAsString + "/");
    try
    {
        // TODO: Error check for appname?
        string appName = getPolicyServices().platformConfigurationData->readConfigurationString(
            root() + keyPath() + key);
        appNames.push_back(appName);
    }
    catch (dptf_exception& e)
    {
        string msg = e.what();
        m_policyServices.messageLogging->writeMessageDebug(PolicyMessage(FLF,
            "Error msg (" + msg + "). Error in reading AppName", Constants::Invalid));
    }

    return appNames;
}
Пример #21
0
UInt32 LpmConfigurationReaderV0::readCpuTargetFrequency()
{
    string key = "CpuTargetFrequency";
    UInt32 cpuTargetFrequency;
    try
    {
        cpuTargetFrequency =
          getPolicyServices().platformConfigurationData->readConfigurationUInt32(
              root() + keyPath() + key);
    }
    catch(dptf_exception& e)
    {
        string msg = e.what();

        m_policyServices.messageLogging->writeMessageDebug(PolicyMessage(FLF,
        "No CpuTargetFrequency - defaulting to 800Mhz. msg - " + msg,
        Constants::Invalid));

        // if not found, we default to 800 mhz (MFM or LFM)
        cpuTargetFrequency = 800;
    }

    return cpuTargetFrequency;
}
Пример #22
0
UInt32 LpmConfigurationReaderV0::readPackagePowerLimit()
{
    // TODO: Check regarding PL -> string/uint? Do we need to sku check like 7.0?
    UInt32 packagePowerLimit;
    string key = "PackagePowerLimit";

    try
    {
        string valueString = getPolicyServices().platformConfigurationData->readConfigurationString(
            root() + keyPath() + key);
        packagePowerLimit = extractPowerLimit(valueString);
    }
    catch (dptf_exception& e)
    {
        string msg = e.what();

        m_policyServices.messageLogging->writeMessageError(PolicyMessage(FLF,
            "Error in reading PackagePowerLimit, default 10000000. msg - " + msg,
            Constants::Invalid));
        packagePowerLimit = 10000000; // Max valid power
    }

    return packagePowerLimit;
}
Пример #23
0
bool QWinSettingsPrivate::readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const
{
    QString rSubkeyName = keyName(rSubKey);
    QString rSubkeyPath = keyPath(rSubKey);

    // open a handle on the subkey
    HKEY handle = openKey(parentHandle, KEY_READ, rSubkeyPath);
    if (handle == 0)
        return false;

    // get the size and type of the value
    DWORD dataType;
    DWORD dataSize;
    LONG res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, &dataType, 0, &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return false;
    }

    // get the value
    QByteArray data(dataSize, 0);
    res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, 0,
                           reinterpret_cast<unsigned char*>(data.data()), &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return false;
    }

    switch (dataType) {
        case REG_EXPAND_SZ:
        case REG_SZ: {
            QString s;
            if (dataSize) {
                s = QString::fromWCharArray(((const wchar_t *)data.constData()));
            }
            if (value != 0)
                *value = stringToVariant(s);
            break;
        }

        case REG_MULTI_SZ: {
            QStringList l;
            if (dataSize) {
                int i = 0;
                for (;;) {
                    QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i);
                    i += s.length() + 1;

                    if (s.isEmpty())
                        break;
                    l.append(s);
                }
            }
            if (value != 0)
                *value = stringListToVariantList(l);
            break;
        }

        case REG_NONE:
        case REG_BINARY: {
            QString s;
            if (dataSize) {
                s = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2);
            }
            if (value != 0)
                *value = stringToVariant(s);
            break;
        }

        case REG_DWORD_BIG_ENDIAN:
        case REG_DWORD: {
            Q_ASSERT(data.size() == sizeof(int));
            int i;
            memcpy((char*)&i, data.constData(), sizeof(int));
            if (value != 0)
                *value = i;
            break;
        }

        case REG_QWORD: {
            Q_ASSERT(data.size() == sizeof(qint64));
            qint64 i;
            memcpy((char*)&i, data.constData(), sizeof(qint64));
            if (value != 0)
                *value = i;
            break;
        }

        default:
            qWarning("QSettings: Unknown data %d type in Windows registry", static_cast<int>(dataType));
            if (value != 0)
                *value = QVariant();
            break;
    }

    RegCloseKey(handle);
    return true;
}
Пример #24
0
int cond::KeyManager::execute(){

  if( hasOptionValue("dump_template") ) {
    if( hasOptionValue("textFile") ) {
      std::string textFile = getOptionValue<std::string>("textFile");
      std::ofstream outFile ( textFile.c_str() );
      if (outFile.is_open()){
	outFile <<DecodingKey::templateFile()<<std::endl;
	outFile.close();
      } else {
	std::cout <<"ERROR: file \""<<textFile<<"\" cannot be open."<<std::endl;
	outFile.close();
	return 1;
      }
    } else {
      std::cout <<DecodingKey::templateFile()<<std::endl;
    }
    return 0;    
  }

  if( hasOptionValue("create") ) {
    std::string textFile = getOptionValue<std::string>("textFile");
    size_t keySize = Auth::COND_AUTHENTICATION_KEY_SIZE;
    DecodingKey key;
    key.init( DecodingKey::FILE_NAME, Auth::COND_KEY, false );
    key.createFromInputFile( textFile, keySize );
    if( hasDebug() ) key.list( std::cout );
    key.flush();
    return 0;
  }

  if( !hasOptionValue("dump") && !hasOptionValue("read")) {
    return 0;
  }

  std::string path = getOptionValue<std::string>("keyPath");
  boost::filesystem::path keyPath( path );
  boost::filesystem::path keyFile( DecodingKey::FILE_PATH );
  keyPath /= keyFile;
  std::string keyFileName = keyPath.string();
  if(!boost::filesystem::exists( keyFileName )){
    std::cout <<"ERROR: specified key file \""<<keyFileName<<"\" does not exist."<<std::endl;
    return 1;
  }

  if( hasOptionValue("dump") ) {
    std::string textFile = getOptionValue<std::string>("textFile");
    std::ofstream outFile ( textFile.c_str() );
    if (outFile.is_open()){
      DecodingKey key;
      key.init( keyFileName, Auth::COND_KEY );
      key.list( outFile );
      outFile.close();
      return 0;
    } else {
      std::cout <<"ERROR: file \""<<textFile<<"\" cannot be open."<<std::endl;
      outFile.close();
      return 1;
    }
  }

  if( hasOptionValue("read") ) {
    DecodingKey key;
    key.init( keyFileName, Auth::COND_KEY );
    key.list( std::cout );
    return 0;
  }

  return 1;
}
Пример #25
0
QList<KeyData> QCrmlParser::parseKey(quint32 repoUid)
{
    QList<KeyData> rv;
    QStringList mandatoryAttributes;
    mandatoryAttributes << QLatin1String("int");
    if (!checkMandatoryAttributes(mandatoryAttributes))
        return rv;

    QXmlStreamAttributes attribs = attributes();
    QString keyIntStr = attribs.value(QLatin1String("int")).toString();
    bool ok =false;
    quint32 keyInt = uidStringToUInt32(keyIntStr, &ok);
    if (!ok) {
        setError(ParseError,QObject::tr("key element has invalid int attribute on line %1").
                arg(QString::number(lineNumber())));
        return rv;
    }

    if (attribs.value(QLatin1String("ref")).isNull()) {
        //no ref attribute so this must be
        //a bitmask key
        while (!atEnd()) {
            readNext();
            if (QXmlStreamReader::error() != QXmlStreamReader::NoError) {
                 setError(ParseError, QXmlStreamReader::errorString());
                 rv.clear();
                 return rv;
            }
            if (isEndElement())
                break;

            if (isStartElement()) {
                if (name() == "bit") {
                    rv.append(parseBit(repoUid, keyInt));
                } else {
                    parseUnknownElement();
                }
            }
        }
    } else {
        QString keyRef = attribs.value(QLatin1String("ref")).toString();
        if (keyRef.isEmpty()) {
            setError(ParseError, QObject::tr("ref attribute of key element is empty on line %1")
                    .arg(QString::number(lineNumber())));
            rv.clear();
            return rv;
        }

        while (!atEnd()) {
            readNext();
            if (QXmlStreamReader::error() != QXmlStreamReader::NoError) {
                setError(ParseError, QXmlStreamReader::errorString());
                rv.clear();
                return rv;
            }
            if (isEndElement() && name() == "key") {
                break;
            }

            if (isStartElement()) {
                if (name() == "key" || name() == "keyRange") {
                    setError(ParseError, QObject::tr("key and/or keyRange element has "
                                "been nested in a key element on line %1").arg(QString::number(lineNumber())));
                    rv.clear();
                    return rv;
                } else {
                    parseUnknownElement();
                }
            }
        }

        QString keyPath(keyRef);
        if (!keyPath.startsWith(QLatin1Char('/')))
            keyPath.prepend(QLatin1Char('/'));
        quint64 uid = repoUid;
        uid = uid << 32;
        uid += keyInt;
        rv.append(KeyData(keyPath, uid,m_target));
    }
    return rv;
}
Пример #26
0
QString qt_readRegistryKey(HKEY parentHandle, const QString &rSubkey, unsigned long options)
{
    QString result;

#ifdef Q_OS_WIN32
    QString rSubkeyName = keyName(rSubkey);
    QString rSubkeyPath = keyPath(rSubkey);

    HKEY handle = 0;
    LONG res = RegOpenKeyEx(parentHandle, (wchar_t*)rSubkeyPath.utf16(), 0,
                            KEY_READ | options, &handle);

    if (res != ERROR_SUCCESS)
        return QString();

    // get the size and type of the value
    DWORD dataType;
    DWORD dataSize;
    res = RegQueryValueEx(handle, (wchar_t*)rSubkeyName.utf16(), 0, &dataType, 0, &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return QString();
    }

    // get the value
    QByteArray data(dataSize, 0);
    res = RegQueryValueEx(handle, (wchar_t*)rSubkeyName.utf16(), 0, 0,
                          reinterpret_cast<unsigned char*>(data.data()), &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return QString();
    }

    switch (dataType) {
        case REG_EXPAND_SZ:
        case REG_SZ: {
            result = QString::fromWCharArray(((const wchar_t *)data.constData()));
            break;
        }

        case REG_MULTI_SZ: {
            QStringList l;
            int i = 0;
            for (;;) {
                QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i);
                i += s.length() + 1;

                if (s.isEmpty())
                    break;
                l.append(s);
            }
            result = l.join(QLatin1String(", "));
            break;
        }

        case REG_NONE:
        case REG_BINARY: {
            result = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2);
            break;
        }

        case REG_DWORD_BIG_ENDIAN:
        case REG_DWORD: {
            Q_ASSERT(data.size() == sizeof(int));
            int i;
            memcpy((char*)&i, data.constData(), sizeof(int));
            result = QString::number(i);
            break;
        }

        default:
            qWarning("QSettings: unknown data %u type in windows registry", quint32(dataType));
            break;
    }

    RegCloseKey(handle);
#else
    Q_UNUSED(parentHandle);
    Q_UNUSED(rSubkey)
    Q_UNUSED(options);
#endif

    return result;
}
Пример #27
0
//funzione principale
unsigned initAesCuda(std::string myKeyFile, unsigned char myKeyBuffer[], const unsigned int myKeyBitsSize, std::string myInputFile, char inputArray[], const unsigned inputArraySize){
	
	path inputPath(myInputFile.c_str());
	path keyPath(myKeyFile.c_str());
	
	if ( !exists(keyPath) )
		throw std::string("file "+keyPath.string()+" doesn't exist");

	if ( !exists(inputPath) )
		throw std::string("file "+inputPath.string()+" doesn't exist");
	
	if ( myKeyBitsSize!=256 && myKeyBitsSize!=128)
		throw std::string("cannot use a key dimension different from 256 or 128");

	if ( !myKeyBuffer )
		throw std::string("key array not allocated");

	if ( !inputArray )
		throw std::string("input array not allocated");

	boost::intmax_t inputFileSize	= getFileSize(inputPath);
	boost::intmax_t keyFileSize		= getFileSize(keyPath);

	if ( keyFileSize==0 ) 
		throw std::string("cannot use an empty input file");

	if ( inputFileSize==0 ) 
		throw std::string("cannot use an empty key file");

	if ( inputFileSize > inputArraySize - 1 && MODE) 
		throw std::string("cannot encrypt a file bigger than 34.603.007 bytes");

	if ( inputFileSize > inputArraySize && !MODE) 
		throw std::string("cannot decrypt a file bigger than 33MB");

	//legge l'input
	readFromFileNotForm(inputPath, inputArray, inputFileSize);
	
	std::vector<unsigned> keyArray(myKeyBitsSize/8);
	
	unsigned ekSize = (myKeyBitsSize != 256) ? 176 : 240;

	std::vector<unsigned> expKeyArray(ekSize);
	std::vector<unsigned> invExpKeyArray(ekSize);
	
	//legge la chiave
	readFromFileForm(keyPath, keyArray);

	std::cout << "\n###############################################################\n\n";
	std::cout << "AES - CUDA by Svetlin Manavski)\n\n";
	std::cout << "AES " << myKeyBitsSize << " is running...." << std::endl << std::endl;
	std::cout << "Input file size: " << inputFileSize << " Bytes" << std::endl << std::endl;
	std::cout << "Key: ";
	for (unsigned cnt=0; cnt<keyArray.size(); ++cnt)
		std::cout << std::hex << keyArray[cnt];

	if (MODE){
		//ENCRYPTION MODE

		//PADDING MANAGEMENT FOLLOWING THE PKCS STANDARD
		unsigned mod16 = inputFileSize % 16;
		unsigned div16 = inputFileSize / 16;

		unsigned padElem;
		if ( mod16 != 0 )
			padElem =  16 - mod16;
		else 
			padElem =  16;

		for (unsigned cnt = 0; cnt < padElem; ++cnt)
				inputArray[div16*16 + mod16 + cnt] = padElem;

		inputFileSize = inputFileSize + padElem;
		
		//IN THE ENCRYPTION MODE I NEED THE EXPANDED KEY
		expFunc(keyArray, expKeyArray);
		for (unsigned cnt=0; cnt<expKeyArray.size(); ++cnt){
			unsigned val = expKeyArray[cnt];
			unsigned char *pc = reinterpret_cast<unsigned char *>(&val);
			myKeyBuffer[cnt] = *(pc);
		}
	} else {
		//DECRYPTION MODE 

		//IN THE ENCRYPTION MODE I NEED THE INVERSE EXPANDED KEY
		expFunc(keyArray, expKeyArray);
		invExpFunc(expKeyArray, invExpKeyArray);
		for (unsigned cnt=0; cnt<invExpKeyArray.size(); ++cnt){
			unsigned val = invExpKeyArray[cnt];
			unsigned char *pc = reinterpret_cast<unsigned char *>(&val);
			myKeyBuffer[cnt] = *(pc);
		}
	}
	std::cout << std::endl;

	return inputFileSize;
}
Пример #28
0
void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey));
    if (handle == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    DWORD type;
    QByteArray regValueBuff;

    // Determine the type
    switch (value.type()) {
        case QVariant::List:
        case QVariant::StringList: {
            // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
            // native registry string list type. Otherwise we use REG_BINARY.
            type = REG_MULTI_SZ;
            QStringList l = variantListToStringList(value.toList());
            QStringList::const_iterator it = l.constBegin();
            for (; it != l.constEnd(); ++it) {
                if ((*it).length() == 0 || stringContainsNullChar(*it)) {
                    type = REG_BINARY;
                    break;
                }
            }

            if (type == REG_BINARY) {
                QString s = variantToString(value);
                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
            } else {
                QStringList::const_iterator it = l.constBegin();
                for (; it != l.constEnd(); ++it) {
                    const QString &s = *it;
                    regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
                }
                regValueBuff.append((char)0);
                regValueBuff.append((char)0);
            }
            break;
        }

        case QVariant::Int:
        case QVariant::UInt: {
            type = REG_DWORD;
            qint32 i = value.toInt();
            regValueBuff = QByteArray((const char*)&i, sizeof(qint32));
            break;
        }

        case QVariant::LongLong:
        case QVariant::ULongLong: {
            type = REG_QWORD;
            qint64 i = value.toLongLong();
            regValueBuff = QByteArray((const char*)&i, sizeof(qint64));
            break;
        }

        case QVariant::ByteArray:
            // fallthrough intended

        default: {
            // If the string does not contain '\0', we can use REG_SZ, the native registry
            // string type. Otherwise we use REG_BINARY.
            QString s = variantToString(value);
            type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ;
            if (type == REG_BINARY) {
                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
            } else {
                regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
            }
            break;
        }
    }

    // set the value
    LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type,
                             reinterpret_cast<const unsigned char*>(regValueBuff.constData()),
                             regValueBuff.size());

    if (res == ERROR_SUCCESS) {
        deleteWriteHandleOnExit = false;
    } else {
        qWarning("QSettings: failed to set subkey \"%s\": %s",
                rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
        setStatus(QSettings::AccessError);
    }

    RegCloseKey(handle);
}
Пример #29
0
already_AddRefed<IDBObjectStore>
IDBDatabase::CreateObjectStore(
                            const nsAString& aName,
                            const IDBObjectStoreParameters& aOptionalParameters,
                            ErrorResult& aRv)
{
  AssertIsOnOwningThread();

  IDBTransaction* transaction = IDBTransaction::GetCurrent();
  if (!transaction ||
      transaction->Database() != this ||
      transaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
    return nullptr;
  }

  if (!transaction->IsOpen()) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
    return nullptr;
  }

  KeyPath keyPath(0);
  if (NS_FAILED(KeyPath::Parse(aOptionalParameters.mKeyPath, &keyPath))) {
    aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
    return nullptr;
  }

  nsTArray<ObjectStoreSpec>& objectStores = mSpec->objectStores();
  for (uint32_t count = objectStores.Length(), index = 0;
       index < count;
       index++) {
    if (aName == objectStores[index].metadata().name()) {
      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR);
      return nullptr;
    }
  }

  if (!keyPath.IsAllowedForObjectStore(aOptionalParameters.mAutoIncrement)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
    return nullptr;
  }

  const ObjectStoreSpec* oldSpecElements =
    objectStores.IsEmpty() ? nullptr : objectStores.Elements();

  ObjectStoreSpec* newSpec = objectStores.AppendElement();
  newSpec->metadata() =
    ObjectStoreMetadata(transaction->NextObjectStoreId(), nsString(aName),
                        keyPath, aOptionalParameters.mAutoIncrement);

  if (oldSpecElements &&
      oldSpecElements != objectStores.Elements()) {
    MOZ_ASSERT(objectStores.Length() > 1);

    // Array got moved, update the spec pointers for all live objectStores and
    // indexes.
    RefreshSpec(/* aMayDelete */ false);
  }

  RefPtr<IDBObjectStore> objectStore =
    transaction->CreateObjectStore(*newSpec);
  MOZ_ASSERT(objectStore);

  // Don't do this in the macro because we always need to increment the serial
  // number to keep in sync with the parent.
  const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();

  IDB_LOG_MARK("IndexedDB %s: Child  Transaction[%lld] Request[%llu]: "
                 "database(%s).transaction(%s).createObjectStore(%s)",
               "IndexedDB %s: C T[%lld] R[%llu]: "
                 "IDBDatabase.createObjectStore()",
               IDB_LOG_ID_STRING(),
               transaction->LoggingSerialNumber(),
               requestSerialNumber,
               IDB_LOG_STRINGIFY(this),
               IDB_LOG_STRINGIFY(transaction),
               IDB_LOG_STRINGIFY(objectStore));

  return objectStore.forget();
}
Пример #30
0
/// Microsoft helper function for getting the contents of a registry key
void queryKey(const std::string& hive,
              const std::string& key,
              QueryData& results) {
  if (kRegistryHives.count(hive) != 1) {
    return;
  }

  HKEY hRegistryHandle;
  auto ret = RegOpenKeyEx(kRegistryHives.at(hive),
                          TEXT(key.c_str()),
                          0,
                          KEY_READ,
                          &hRegistryHandle);

  if (ret != ERROR_SUCCESS) {
    return;
  }

  const DWORD maxKeyLength = 255;
  const DWORD maxValueName = 16383;
  TCHAR achClass[MAX_PATH] = TEXT("");
  DWORD cchClassName = MAX_PATH;
  DWORD cSubKeys = 0;
  DWORD cbMaxSubKey;
  DWORD cchMaxClass;
  DWORD cValues;
  DWORD cchMaxValueName;
  DWORD cbMaxValueData;
  DWORD cbSecurityDescriptor;
  DWORD retCode;
  FILETIME ftLastWriteTime;
  retCode = RegQueryInfoKey(hRegistryHandle,
                            achClass,
                            &cchClassName,
                            nullptr,
                            &cSubKeys,
                            &cbMaxSubKey,
                            &cchMaxClass,
                            &cValues,
                            &cchMaxValueName,
                            &cbMaxValueData,
                            &cbSecurityDescriptor,
                            &ftLastWriteTime);

  TCHAR achKey[maxKeyLength];
  DWORD cbName;

  // Process registry subkeys
  if (cSubKeys > 0) {
    for (DWORD i = 0; i < cSubKeys; i++) {
      cbName = maxKeyLength;
      retCode = RegEnumKeyEx(hRegistryHandle,
                             i,
                             achKey,
                             &cbName,
                             nullptr,
                             nullptr,
                             nullptr,
                             &ftLastWriteTime);
      if (retCode != ERROR_SUCCESS) {
        continue;
      }
      Row r;
      fs::path keyPath(key);
      r["hive"] = hive;
      r["key"] = keyPath.string();
      r["subkey"] = (keyPath / achKey).string();
      r["name"] = "(Default)";
      r["type"] = "REG_SZ";
      r["data"] = "(value not set)";
      r["mtime"] = std::to_string(filetimeToUnixtime(ftLastWriteTime));
      results.push_back(r);
    }
  }

  if (cValues <= 0) {
    return;
  }

  BYTE* bpDataBuff = new BYTE[cbMaxValueData];
  DWORD cchValue = maxKeyLength;
  TCHAR achValue[maxValueName];

  // Process registry values
  for (size_t i = 0, retCode = ERROR_SUCCESS; i < cValues; i++) {
    size_t cnt = 0;
    ZeroMemory(bpDataBuff, cbMaxValueData);
    cchValue = maxValueName;
    achValue[0] = '\0';

    retCode = RegEnumValue(hRegistryHandle,
                           static_cast<DWORD>(i),
                           achValue,
                           &cchValue,
                           nullptr,
                           nullptr,
                           nullptr,
                           nullptr);

    if (retCode != ERROR_SUCCESS) {
      continue;
    }

    DWORD lpData = cbMaxValueData;
    DWORD lpType;
    retCode = RegQueryValueEx(
        hRegistryHandle, achValue, 0, &lpType, bpDataBuff, &lpData);

    if (retCode != ERROR_SUCCESS) {
      continue;
    }

    Row r;
    fs::path keyPath(key);
    r["hive"] = hive;
    r["key"] = keyPath.string();
    r["subkey"] = keyPath.string();
    r["name"] = achValue;
    if (kRegistryTypes.count(lpType) > 0) {
      r["type"] = kRegistryTypes.at(lpType);
    } else {
      r["type"] = "UNKNOWN";
    }
    r["mtime"] = std::to_string(filetimeToUnixtime(ftLastWriteTime));

    bpDataBuff[cbMaxValueData - 1] = 0x00;

    /// REG_LINK is a Unicode string, which in Windows is wchar_t
    char* regLinkStr = nullptr;
    if (lpType == REG_LINK) {
      regLinkStr = new char[cbMaxValueData];
      const size_t newSize = cbMaxValueData;
      size_t convertedChars = 0;
      wcstombs_s(&convertedChars,
                 regLinkStr,
                 newSize,
                 (wchar_t*)bpDataBuff,
                 _TRUNCATE);
    }

    BYTE* bpDataBuffTmp = bpDataBuff;
    std::vector<std::string> multiSzStrs;
    std::vector<char> regBinary;
    std::string data;

    switch (lpType) {
    case REG_FULL_RESOURCE_DESCRIPTOR:
    case REG_RESOURCE_LIST:
    case REG_BINARY:
      for (unsigned int i = 0; i < cbMaxValueData; i++) {
        regBinary.push_back((char)bpDataBuff[i]);
      }
      boost::algorithm::hex(
          regBinary.begin(), regBinary.end(), std::back_inserter(data));
      r["data"] = data;
      break;
    case REG_DWORD:
      r["data"] = std::to_string(*((int*)bpDataBuff));
      break;
    case REG_DWORD_BIG_ENDIAN:
      r["data"] = std::to_string(_byteswap_ulong(*((int*)bpDataBuff)));
      break;
    case REG_EXPAND_SZ:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    case REG_LINK:
      r["data"] = std::string(regLinkStr);
      break;
    case REG_MULTI_SZ:
      while (*bpDataBuffTmp != 0x00) {
        std::string s((char*)bpDataBuffTmp);
        bpDataBuffTmp += s.size() + 1;
        multiSzStrs.push_back(s);
      }
      r["data"] = boost::algorithm::join(multiSzStrs, ",");
      break;
    case REG_NONE:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    case REG_QWORD:
      r["data"] = std::to_string(*((unsigned long long*)bpDataBuff));
      break;
    case REG_SZ:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    default:
      r["data"] = "";
      break;
    }
    results.push_back(r);
    if (regLinkStr != nullptr) {
      delete (regLinkStr);
    }
  }
  delete (bpDataBuff);
  RegCloseKey(hRegistryHandle);
};