Beispiel #1
0
void QPubNub::publish(const QString& channel, const QJsonValue& value) {
  if (m_publishKey.isEmpty()) {
    emit error("No publish key set", 0);
    return ;
  }

  QByteArray message;
#ifdef Q_PUBNUB_CRYPT
  if (!m_cipherKey.isEmpty()) {
    QPubNubCrypt crypt(m_cipherKey);
    int errorCode = 0;
    message = crypt.encrypt(value, errorCode);
    if (errorCode != 0) {
      char errorString[1024+1];
      ERR_error_string_n(errorCode, errorString, 1024);
      emit error(errorString, errorCode);
      return;
    }
  } else {
#endif // Q_PUBNUB_CRYPT
    message = toByteArray(value);
#ifdef Q_PUBNUB_CRYPT
  }
#endif

  QNetworkReply * reply = sendRequest(publishUrl("\""+message+"\"", channel));
  // This can't be connected using the new syntax, cause the signal and error property have the same name "error"
  connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
  connect(reply, &QNetworkReply::finished, this, &QPubNub::publishFinished);
}
CompleteMessageWidget::CompleteMessageWidget(QWidget *parent, QSettings *settings, Plugins::PluginManager *pluginManager,
        Imap::Mailbox::FavoriteTagsModel *m_favoriteTags)
    : QWidget(parent)
    , FindBarMixin(this), settings(settings)
{
    setWindowIcon(UiUtils::loadIcon(QStringLiteral("mail-mark-read")));
    messageView = new MessageView(this, settings, pluginManager, m_favoriteTags);
    area = new QScrollArea();
    area->setWidget(messageView);
    area->setWidgetResizable(true);
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(area);
    animator = new QPropertyAnimation(area->verticalScrollBar(), "value", this);
    animator->setDuration(250); // the default, maybe play with values
    animator->setEasingCurve(QEasingCurve::InOutCubic); // InOutQuad?

    layout->addWidget(m_findBar);
    connect(messageView, &MessageView::searchRequestedBy,
            this, [this](EmbeddedWebView *w) {
        searchRequestedBy(w);
    });
    // because the FindBarMixin is not a QObject, we have to use lambda above, otherwise a cast
    // from FindBarMixin * to QObject * fails

    auto geometry = settings->value(Common::SettingsNames::completeMessageWidgetGeometry);
    if (geometry.isValid()) {
        restoreGeometry(geometry.toByteArray());
    } else {
        resize(800, 600);
    }
}
bool Qca2ByteArrayChecksumAlgorithm::calculateChecksum( QString* result,
                                                        const Okteta::AbstractByteArrayModel* model, const Okteta::AddressRange& range ) const
{
    QCA::Hash hash( mType );

    // TODO: find a way without needing to copy, perhaps by smart iterator which can return spans of original data
    // TODO: see if buffer size could be a value which matches the algorithm and qca2

    char buffer[CalculatedByteCountSignalLimit];
    int bufferLength = CalculatedByteCountSignalLimit;
    Okteta::Address nextBlockEnd = range.start() + CalculatedByteCountSignalLimit;
    for( Okteta::Address i = range.start(); i<=range.end(); i+=CalculatedByteCountSignalLimit )
    {
        if( range.end() < i+CalculatedByteCountSignalLimit )
            bufferLength = range.end() - i + 1;
        model->copyTo( reinterpret_cast<Okteta::Byte*>(buffer), i, bufferLength );
        hash.update( buffer, bufferLength );

        if( i >= nextBlockEnd )
        {
            nextBlockEnd += CalculatedByteCountSignalLimit;
            emit calculatedBytes( range.localIndex(i)+1 );
        }
    }

    const QByteArray hashResult = hash.final().toByteArray();

    *result = QCA::arrayToHex( hashResult );
    return true;
}
Beispiel #4
0
// public
bool IPAddressV4::inSubnetWithMask(const IPAddressV4& subnet,
                                   const ByteArray4 cidrMask) const {
  const ByteArray4 mask = detail::Bytes::mask(toByteArray(), cidrMask);
  const ByteArray4 subMask = detail::Bytes::mask(subnet.toByteArray(),
                                                 cidrMask);
  return (mask == subMask);
}
Beispiel #5
0
void ItemEncryptedScriptable::copyEncryptedItems()
{
    const auto dataValueList = call("selectedItemsData").toList();
    QString text;
    for (const auto &dataValue : dataValueList) {
        if ( !text.isEmpty() )
            text.append('\n');

        const auto data = dataValue.toMap();
        const auto itemTextValue = data.value(mimeText);
        if ( itemTextValue.isValid() ) {
            text.append( getTextData(itemTextValue.toByteArray()) );
        } else {
            const auto encryptedBytes = data.value(mimeEncryptedData).toByteArray();
            if ( !encryptedBytes.isEmpty() ) {
                const auto itemData = decrypt(encryptedBytes);
                if (itemData.isEmpty())
                    return;
                const auto dataMap = call("unpack", QVariantList() << itemData).toMap();
                text.append( getTextData(dataMap) );
            }
        }
    }

    const auto args = QVariantList()
            << mimeText << text
            << mimeHidden << "1";
    call("copy", args);
    call("copySelection", args);
}
Beispiel #6
0
/* Gets registered as metamethod automatically by WSLUA_REGISTER_CLASS/META */
static int ByteArray__gc(lua_State* L) {
    ByteArray ba = toByteArray(L,1);

    if (!ba) return 0;

    g_byte_array_free(ba,TRUE);
    return 0;
}
QVector<QVariant> MasterSlaveCommunicator::master_command_loop(int taskIndex, QVector<QVariant> inputVector)
{
    // prepare an output vector of the appropriate size
    int numitems = inputVector.size();
    QVector<QVariant> outputVector(numitems);

    // prepare a vector to remember the index of most recent item handed out to each slave
    QVector<int> itemForSlave(size());

    // the index of the next item to be handed out
    int numsent = 0;

    // hand out an item to each slave (unless there are less items than slaves)
    for (int slave=1; slave<size() && numsent<numitems; slave++,numsent++)
    {
        QByteArray buffer = toByteArray(_bufsize, inputVector[numsent]);

        ProcessManager::sendByteBuffer(buffer, slave, taskIndex);

        itemForSlave[slave] = numsent;
    }

    // receive results, handing out more items until all have been handed out
    QByteArray resultbuffer(_bufsize, 0);
    for (int i=0; i<numitems; i++)
    {
        // receive a message from any slave
        int slave;
        ProcessManager::receiveByteBuffer(resultbuffer, slave);

        // put the result in the output vector
        outputVector[itemForSlave[slave]] = toVariant(resultbuffer);

        // if more items are available, hand one to this slave
        if (numsent<numitems)
        {
            QByteArray buffer = toByteArray(_bufsize, inputVector[numsent]);

            ProcessManager::sendByteBuffer(buffer, slave, taskIndex);

            itemForSlave[slave] = numsent;
            numsent++;
        }
    }
    return outputVector;
}
Beispiel #8
0
	/**
	* Processes the first message of the Zero Knowledge protocol:
	*  "COMPUTE the first message a in sigma, using (x,w) as input
	*	SEND a to V".
	* @param input
	*/
	void processFirstMsg(shared_ptr<SigmaProverInput>  input) {
		// compute the first message by the underlying proverComputation.
		auto a = sProver->computeFirstMsg(input);
		auto msg = a->toByteArray();
		int len = a->getSerializedSize();
		// send the first message.
		sendMsgToVerifier(msg.get(), len);
	}
QString ConnectionError::description() const
{
    switch (m_code) {
    case InvalidAuthKey:
        return QStringLiteral("Invalid auth key");
    default:
        return QStringLiteral("Unknown error bytes: %1").arg(QString::fromLatin1(toByteArray().toHex()));
    }
}
Beispiel #10
0
 CMessageBuffer *clone()
 {
     // copies data (otherwise use transferFrom)
     CMessageBuffer *ret = new CMessageBuffer();
     ret->tag = tag;
     ret->sender = sender;
     ret->replytag = replytag;
     ret->append(length(),toByteArray());
     return ret;
 }
Beispiel #11
0
QVariant QDBusDemarshaller::toVariantInternal()
{
    switch (q_dbus_message_iter_get_arg_type(&iterator)) {
    case DBUS_TYPE_BYTE:
        return qVariantFromValue(toByte());
    case DBUS_TYPE_INT16:
	return qVariantFromValue(toShort());
    case DBUS_TYPE_UINT16:
	return qVariantFromValue(toUShort());
    case DBUS_TYPE_INT32:
        return toInt();
    case DBUS_TYPE_UINT32:
        return toUInt();
    case DBUS_TYPE_DOUBLE:
        return toDouble();
    case DBUS_TYPE_BOOLEAN:
        return toBool();
    case DBUS_TYPE_INT64:
        return toLongLong();
    case DBUS_TYPE_UINT64:
        return toULongLong();
    case DBUS_TYPE_STRING:
        return toString();
    case DBUS_TYPE_OBJECT_PATH:
        return qVariantFromValue(toObjectPath());
    case DBUS_TYPE_SIGNATURE:
        return qVariantFromValue(toSignature());
    case DBUS_TYPE_VARIANT:
        return qVariantFromValue(toVariant());

    case DBUS_TYPE_ARRAY:
        switch (q_dbus_message_iter_get_element_type(&iterator)) {
        case DBUS_TYPE_BYTE:
            // QByteArray
            return toByteArray();
        case DBUS_TYPE_STRING:
            return toStringList();
        case DBUS_TYPE_DICT_ENTRY:
            return qVariantFromValue(duplicate());

        default:
            return qVariantFromValue(duplicate());
        }

    case DBUS_TYPE_STRUCT:
        return qVariantFromValue(duplicate());

    default:
        qWarning("QDBusDemarshaller: Found unknown D-Bus type %d '%c'",
                 q_dbus_message_iter_get_arg_type(&iterator),
                 q_dbus_message_iter_get_arg_type(&iterator));
        return QVariant();
        break;
    };
}
Beispiel #12
0
void Chunk::load(const NBT &nbt) {
  renderedAt = -1;  // impossible.
  renderedFlags = 0;  // no flags
  memset(this->biomes, 127, 256);  // init to unknown biome
  for (int i = 0; i < 16; i++)
    this->sections[i] = NULL;
  highest = 0;

  auto level = nbt.at("Level");
  chunkX = level->at("xPos")->toInt();
  chunkZ = level->at("zPos")->toInt();

  auto biomes = level->at("Biomes");
  memcpy(this->biomes, biomes->toByteArray(), biomes->length());
  auto sections = level->at("Sections");
  int numSections = sections->length();
  for (int i = 0; i < numSections; i++) {
    auto section = sections->at(i);
    auto cs = new ChunkSection();
    auto raw = section->at("Blocks")->toByteArray();
    for (int i = 0; i < 4096; i++)
      cs->blocks[i] = raw[i];
    if (section->has("Add")) {
      raw = section->at("Add")->toByteArray();
      for (int i = 0; i < 2048; i++) {
        cs->blocks[i * 2] |= (raw[i] & 0xf) << 8;
        cs->blocks[i * 2 + 1] |= (raw[i] & 0xf0) << 4;
      }
    }
    memcpy(cs->data, section->at("Data")->toByteArray(), 2048);
    memcpy(cs->light, section->at("BlockLight")->toByteArray(), 2048);
    int idx = section->at("Y")->toInt();
    this->sections[idx] = cs;
  }
  loaded = true;


  auto entitylist = level->at("Entities");
  int numEntities = entitylist->length();
  for (int i = 0; i < numEntities; ++i) {
    auto e = Entity::TryParse(entitylist->at(i));
    if (e)
      entities.insertMulti(e->type(), e);
  }

  for (int i = 15; i >= 0; i--) {  // check for the highest block in this chunk
    if (this->sections[i]) {
      for (int j = 4095; j >= 0; j--) {
        if (this->sections[i]->blocks[j]) {
          highest = i * 16 + (j >> 8);
          return;
        }
      }
    }
  }
Beispiel #13
0
TBTDevAddr QBtAddress::convertToSymbianBtDevAddr()
{
	const TUint8* memPtr = (const TUint8*)toByteArray().constData();
		
	TPtrC8 devAddrPtr8;
	devAddrPtr8.Set(memPtr, 6);

	const TBTDevAddr devAddress = TBTDevAddr(devAddrPtr8);
	
	return devAddress;
}
Beispiel #14
0
QByteArray Authentication::saltHashPassword(const std::string &password, const QByteArray &salt) const
{
    QCA::Hash shaHash("sha1");

    shaHash.update(password.c_str(), password.size());
    for (int i = 0; i < SALT_ITERATIONS; i++) {
        shaHash.update(salt);
    }

    return shaHash.final().toByteArray();
}
Beispiel #15
0
 StringBuffer &getDetails(StringBuffer &buf)
 {
     StringBuffer ep;
     StringBuffer data;
     unsigned n=(length()<16)?length():16;
     for (unsigned i=0;i<n;i++) {
         if (i!=0) 
             data.append(", ");
         data.append((unsigned)(byte)toByteArray()[i]);
     }
     return buf.appendf("CMessageBuffer(%8X) tag=%d, sender=%s, replytag=%d, size== %d, data head = %s", (int)(long)toByteArray(), (int)tag, sender.getUrlStr(ep).str(), (int)replytag, length(), data.str());
 }
Beispiel #16
0
bool EciesHelper::Decrypt(const ByteArray &chiper, ByteArray &plain)
{
	assert (valid_);
	try { 
		DER der(chiper);
		ECIES decrypt = der.toECIES();
		OCTETSTR temp = decrypt.decrypt(*sk_);	
		plain = toByteArray(temp);
		return true;
	} catch (borzoiException e) { 
		//e.debug_print ();
		return false;
	}
}
Beispiel #17
0
bool ItemEncryptedScriptable::isEncrypted()
{
    const auto args = currentArguments();
    for (const auto &arg : args) {
        bool ok;
        const int row = arg.toInt(&ok);
        if (ok) {
            const auto result = call("read", QVariantList() << "?" << row);
            if ( result.toByteArray().contains(mimeEncryptedData) )
                return true;
        }
    }

    return false;
}
Beispiel #18
0
void MasterSlaveCommunicator::slave_obey_loop()
{
    QByteArray inbuffer(_bufsize, 0);
    while (true)
    {
        // receive the next message from the master
        int tag;
        ProcessManager::receiveByteBuffer(inbuffer, master(), tag);

        // if the message tag specifies a non-existing task, terminate the obey loop
        if (tag < 0 || tag >= _tasks.size()) break;

        // perform the requested task, deserializing and serializing QVariant from/to buffer
        QByteArray outbuffer = toByteArray(_bufsize, _tasks[tag]->perform(toVariant(inbuffer)));

        // send the result back to the master
        ProcessManager::sendByteBuffer(outbuffer, master(), tag);
    }
}
Beispiel #19
0
QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
    QCA::Initializer init;
    QByteArray temp = cipherText;

    // do padding ourselves
    if (direction) {
        while ((temp.length() % 8) != 0)
            temp.append('\0');
    }
    else {
        // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
        if ((temp.length() % 12) != 0)
            return cipherText;

        temp = b64ToByte(temp);
        while ((temp.length() % 8) != 0)
            temp.append('\0');
    }

    QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
    QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
    QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
    temp2 += cipher.final().toByteArray();

    if (!cipher.ok())
        return cipherText;

    if (direction) {
        // Sanity check
        if ((temp2.length() % 8) != 0)
            return cipherText;

        temp2 = byteToB64(temp2);
    }

    return temp2;
}
Beispiel #20
0
// THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
{
    QCA::Initializer init;
    QByteArray temp = cipherText;
    if (direction) {
        // make sure cipherText is an interval of 8 bits. We do this before so that we
        // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
        while ((temp.length() % 8) != 0)
            temp.append('\0');

        QCA::InitializationVector iv(8);
        temp.prepend(iv.toByteArray());  // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
    }
    else {
        temp = QByteArray::fromBase64(temp);
        // supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
        // en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
        while ((temp.length() % 8) != 0)
            temp.append('\0');
    }

    QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
    QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
    QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
    temp2 += cipher.final().toByteArray();

    if (!cipher.ok())
        return cipherText;

    if (direction)  // send in base64
        temp2 = temp2.toBase64();
    else  // cut off the 8bits of IV
        temp2 = temp2.remove(0, 8);

    return temp2;
}
// here we use DataTime instead of QT's built-in time conversion
// since the latter does not properly handle fractions of seconds
// in the ISO8601 specification.
QString Soprano::LiteralValue::toString() const
{
    if ( d ) {
        if ( !d->stringCacheValid ) {
            if( isInt() )
                d->stringCache = QString::number( toInt() );
            else if( isInt64() )
                d->stringCache = QString::number( toInt64() );
            else if( isUnsignedInt() )
                d->stringCache = QString::number( toUnsignedInt() );
            else if( isUnsignedInt64() )
                d->stringCache = QString::number( toUnsignedInt64() );
            else if( isBool() )
                d->stringCache = ( toBool() ? QString("true") : QString("false" ) );
            else if( isDouble() ) // FIXME: decide on a proper double encoding or check if there is one in xml schema
                d->stringCache = QString::number( toDouble(), 'e', 10 );
            else if( isDate() )
                d->stringCache = DateTime::toString( toDate() );
            else if( isTime() )
                d->stringCache = DateTime::toString( toTime() );
            else if( isDateTime() )
                d->stringCache = DateTime::toString( toDateTime() );
            else if ( isByteArray() )
                d->stringCache = QString::fromAscii( toByteArray().toBase64() );
            else
                d->stringCache = d->value.toString();

            d->stringCacheValid = true;
        }

        return d->stringCache;
    }
    else {
        return QString();
    }
}
Beispiel #22
0
std::string RedisValue::toString() const
{
    const std::vector<char> &buf = toByteArray();
    return std::string(buf.begin(), buf.end());
}
Beispiel #23
0
QByteArray HttpInfo::toReplyByteArray() const
{
    return httpVersion() + " " + QByteArray::number(error()) + " " + errorString().toUtf8() + "\r\n" + toByteArray();
}
void net_server_serverClass::sendTo(string data,int index)
{
    sendTo(toByteArray(data),index);
}
Beispiel #25
0
 /// Convert object (rend, obj, cam) to bytearray
 qlib::LScrSp<qlib::LByteArray> toByteArray(const qlib::LScrSp<qlib::LScrObjBase> &pSObj)
 {
   return toByteArray(pSObj, LString());
 }
void net_server_serverClass::sendToAllClient(string data)
{
    sendToAllClient(toByteArray(data));
}
Beispiel #27
0
qint64 FilePrototype::write(const QScriptValue &value)
{
    return thisFile()->write(toByteArray(value));
}
void net_server_serverClass::sendToAllClientExcept(string data,int exceptIndex)
{
    sendToAllClientExcept(toByteArray(data),exceptIndex);
}
Beispiel #29
0
QByteArray AclValue::toByteArray() const
{
  return toByteArray(m_mask);
}
Beispiel #30
0
QByteArray HttpInfo::toRequestByteArray() const
{
    return method() + " " + m_url.path().toUtf8() + " " + httpVersion() + "\r\n" + toByteArray();
}