Exemplo n.º 1
0
/**
 * SendResendRequest:
 * Request RAOP client to resend missed RTP packets
 */
void MythRAOPConnection::SendResendRequest(uint64_t timestamp,
                                           uint16_t expected, uint16_t got)
{
    if (!m_clientControlSocket)
        return;

    int16_t missed = (got < expected) ?
                (int16_t)(((int32_t)got + UINT16_MAX + 1) - expected) :
                got - expected;

    LOG(VB_GENERAL, LOG_INFO, LOC +
        QString("Missed %1 packet(s): expected %2 got %3 ts:%4")
        .arg(missed).arg(expected).arg(got).arg(timestamp));

    char req[8];
    req[0] = 0x80;
    req[1] = RANGE_RESEND | 0x80;
    *(uint16_t *)(req + 2) = qToBigEndian(m_seqNum++);
    *(uint16_t *)(req + 4) = qToBigEndian(expected);   // missed seqnum
    *(uint16_t *)(req + 6) = qToBigEndian(missed);     // count

    if (m_clientControlSocket->writeDatagram(req, sizeof(req),
                                             m_peerAddress, m_clientControlPort)
        == sizeof(req))
    {
        for (uint16_t count = 0; count < missed; count++)
        {
            LOG(VB_GENERAL, LOG_INFO, LOC + QString("Sent resend for %1")
                .arg(expected + count));
            m_resends.insert(expected + count, timestamp);
        }
    }
    else
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to send resend request.");
}
Exemplo n.º 2
0
void RpcConnection::writeHeader(char* header, quint16 type, quint16 method, 
                                quint32 length)
{
    *((quint16*)(header+0)) = qToBigEndian(type);
    *((quint16*)(header+2)) = qToBigEndian(method);
    *((quint32*)(header+4)) = qToBigEndian(length);
}
Exemplo n.º 3
0
/**
 * SendTimeRequest:
 * Send a time request to the RAOP client.
 */
void MythRAOPConnection::SendTimeRequest(void)
{
    if (!m_clientControlSocket) // should never happen
        return;

    timeval t;
    gettimeofday(&t, NULL);

    char req[32];
    req[0] = 0x80;
    req[1] = TIMING_REQUEST | 0x80;
    // this is always 0x00 0x07 according to http://blog.technologeek.org/airtunes-v2
    // no other value works
    req[2] = 0x00;
    req[3] = 0x07;
    *(uint32_t *)(req + 4)  = (uint32_t)0;
    *(uint64_t *)(req + 8)  = (uint64_t)0;
    *(uint64_t *)(req + 16) = (uint64_t)0;
    *(uint32_t *)(req + 24) = qToBigEndian((uint32_t)t.tv_sec);
    *(uint32_t *)(req + 28) = qToBigEndian((uint32_t)t.tv_usec);

    if (m_clientTimingSocket->writeDatagram(req, sizeof(req), m_peerAddress, m_clientTimingPort) != sizeof(req))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to send resend time request.");
        return;
    }
    LOG(VB_GENERAL, LOG_DEBUG, LOC +
        QString("Requesting master time (Local %1.%2)")
        .arg(t.tv_sec).arg(t.tv_usec));
}
Exemplo n.º 4
0
QByteArray SettingsFrame::dump(StreamContext& context) const
{
    if (context.identifier != 0) {
        qWarning() << "SETTINGS Frame identifier must be 0";
    }

    QByteArray payload;

    if (!ack_) {
        payload.resize(settings_.size() * 8);
        uchar* payloadPtr = reinterpret_cast<uchar*>(payload.data());

        for(SettingsType key: settings_.keys()) {
            quint32 value = settings_[key];
            qToBigEndian(static_cast<quint32>(key), payloadPtr);
            payloadPtr += sizeof(quint32);
            qToBigEndian(value, payloadPtr);
            payloadPtr += sizeof(quint32);
        }
    }

    uchar flags = 0;
    if (ack_) flags |= SETTINGS_FLAG_ACK;

    BasicFrame frame;
    frame.setType(FRAME_SETTINGS);
    frame.setFlags(flags);
    frame.setPayload(payload);
    frame.setIdentifier(0);
    return frame.dump();
}
Exemplo n.º 5
0
void CryptFileDevice::initCtr(CtrState *state, const unsigned char *iv)
{
    qint64 position = pos();

    state->num = position % AES_BLOCK_SIZE;

    memset(state->ecount, 0, 16);

    /* Initialise counter in 'ivec' */
    qint64 count = position / AES_BLOCK_SIZE;
    if (state->num > 0)
        count++;

    qint64 newCount = count;
    if (newCount > 0)
        newCount = qToBigEndian(count);

    memcpy(state->ivec + 8, &newCount, 8);

    /* Copy IV into 'ivec' */
    memcpy(state->ivec, iv, 8);

    if (count > 0)
    {
        count = qToBigEndian(count - 1);
        unsigned char * prevIvec = new unsigned char[16];
        memcpy(prevIvec, state->ivec, 8);

        memcpy(prevIvec + 8, &count, 8);

        AES_encrypt(prevIvec, state->ecount, &m_aesKey);
    }
}
Exemplo n.º 6
0
void TimeSync::getNTPTime()
{
    QUdpSocket sock;
    sock.connectToHost("0.pool.ntp.org",123);
    if(!sock.waitForConnected(1000))return;
    QByteArray data(48,char(0)); *(reinterpret_cast<qint32 *>(&data.data()[0]))=4194959577;
    if(sock.write(data)<0||!sock.waitForReadyRead(3000)||sock.bytesAvailable()!=48)return;
    data=sock.readAll();
    quint32 seconds=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[40])));
    quint32 fraction=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[44])));
    quint32 newTime=QDateTime::fromMSecsSinceEpoch(seconds*1000ll+fraction*1000ll/0x100000000ll-2208988800000ll).toTime_t();

    if(newTime<1451606400 || newTime>4000000000){
        QThread::msleep(500);
        emit startSync();
        return;
    }
    qint32 tempTimeShift=qint64(newTime)-qint64(QDateTime::currentDateTime().toTime_t());

    if(timeShift!=0)tempTimeShift=qint32((qint64(timeShift)+qint64(tempTimeShift))/2);

    if(tempTimeShift>3600 || tempTimeShift<-3600){
        static bool showMessage=true;
        if(showMessage)emit warningMessage(julyTr("TIME_SYNC_ERROR","Your clock is not set. Please close the Qt Bitcoin Trader and set the clock. Changing time at Qt Bitcoin Trader enabled can cause errors and damage the keys."));
        showMessage=false;
    }
    else
        timeShift.fetchAndStoreOrdered(tempTimeShift);

    getNTPTimeRetryCount++;
    if(getNTPTimeRetryCount<3)emit startSync();
}
Exemplo n.º 7
0
int MovePointer::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	qToBigEndian(m_x, ptr); ptr += 4;
	qToBigEndian(m_y, ptr); ptr += 4;

	return ptr-data;
}
Exemplo n.º 8
0
int PenMove::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = contextId();
	foreach(const PenPoint &p, _points) {
		qToBigEndian(p.x, ptr); ptr += 4;
		qToBigEndian(p.y, ptr); ptr += 4;
		qToBigEndian(p.p, ptr); ptr += 2;
	}
Exemplo n.º 9
0
int PenMove::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = _ctx;
	foreach(const PenPoint &p, _points) {
		qToBigEndian(p.x, ptr); ptr += 2;
		qToBigEndian(p.y, ptr); ptr += 2;
		*(ptr++) = p.p;
	}
Exemplo n.º 10
0
void LedGridControllerUT::setPixel()
{
    MyMock::expectOneCallAndReturnInt(QString("open_fbdev"), 1);
    LedGridController *controller = LedGridController::getInstance();
    controller->setPixel(0,0, QColor(0x80,0x0,0xFF));
    QCOMPARE(controller->frameBuffer[0], qToBigEndian((quint16)0x781F));
    controller->setPixel(3,4, QColor(0xFF,0xFF,0xFF));
    QCOMPARE(controller->frameBuffer[(4*8)+3], qToBigEndian((quint16)0xFFFF));
}
Exemplo n.º 11
0
int CanvasResize::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = contextId();
	qToBigEndian(_top, ptr); ptr += 2;
	qToBigEndian(_right, ptr); ptr += 2;
	qToBigEndian(_bottom, ptr); ptr += 2;
	qToBigEndian(_left, ptr); ptr += 2;
	return ptr - data;
}
Exemplo n.º 12
0
int MovePointer::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = contextId();
	qToBigEndian(_x, ptr); ptr += 4;
	qToBigEndian(_y, ptr); ptr += 4;
	*(ptr++) = _persistence;

	return ptr-data;
}
Exemplo n.º 13
0
int PenMove::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	for(const PenPoint &p : _points) {
		qToBigEndian(p.x, ptr); ptr += 4;
		qToBigEndian(p.y, ptr); ptr += 4;
		qToBigEndian(p.p, ptr); ptr += 2;
	}
	return ptr - data;
}
Exemplo n.º 14
0
int AnnotationReshape::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = contextId();
	*(ptr++) = _id;
	qToBigEndian(_x, ptr); ptr += 4;
	qToBigEndian(_y, ptr); ptr += 4;
	qToBigEndian(_w, ptr); ptr += 2;
	qToBigEndian(_h, ptr); ptr += 2;
	return ptr - data;
}
Exemplo n.º 15
0
void SatelliteSingleSend::connected()
{
   SATELLITE_PKGINFO_HEADER_TYPE   header( SATELLITE_PKGINFO_MAGIC_VALUE );
   header <<= 32;
   header |= mMessage.size();
   header = qToBigEndian( header );
   SATELLITE_PKGINFO_CHECKSUM_TYPE checksum( qChecksum( mMessage.constData(), mMessage.size() ) );
   checksum = qToBigEndian( checksum );
   mpServerConnection->write( (char*)(&header), SATELLITE_PKGINFO_HEADER_SIZE );
   mpServerConnection->write( mMessage );
   mpServerConnection->write( (char*)(&checksum), SATELLITE_PKGINFO_CHECKSUM_SIZE );
   mpServerConnection->flush();
   mpServerConnection->disconnectFromHost();
}
Exemplo n.º 16
0
void ClientSocket::sendDeleteKeyCommand(const QString &trackName, int row)
{
	if (!connected() ||
	    clientTracks.count(trackName) == 0)
		return;

	quint32 track = qToBigEndian((quint32)clientTracks[trackName]);
	row = qToBigEndian((quint32)row);

	unsigned char cmd = DELETE_KEY;
	send((char *)&cmd, 1, false);
	send((char *)&track, sizeof(int), false);
	send((char *)&row,   sizeof(int), true);
}
Exemplo n.º 17
0
TinySVCMDNS::TinySVCMDNS() {
  // Get all network interfaces
  QList<QNetworkInterface> network_interfaces =
      QNetworkInterface::allInterfaces();
  for (QNetworkInterface network_interface : network_interfaces) {
    // Only use up and non loopback interfaces
    if (network_interface.flags().testFlag(network_interface.IsUp) &&
        !network_interface.flags().testFlag(network_interface.IsLoopBack)) {
      uint32_t ipv4 = 0;
      QString ipv6;

      qLog(Debug) << "Interface" << network_interface.humanReadableName();

      // Now check all network addresses for this device
      QList<QNetworkAddressEntry> network_address_entries =
          network_interface.addressEntries();

      for (QNetworkAddressEntry network_address_entry :
           network_address_entries) {
        QHostAddress host_address = network_address_entry.ip();
        if (host_address.protocol() == QAbstractSocket::IPv4Protocol) {
          ipv4 = qToBigEndian(host_address.toIPv4Address());
          qLog(Debug) << "  ipv4:" << host_address.toString();
        } else if (host_address.protocol() == QAbstractSocket::IPv6Protocol) {
          ipv6 = host_address.toString();
          qLog(Debug) << "  ipv6:" << host_address.toString();
        }
      }

      // Now start the service
      CreateMdnsd(ipv4, ipv6);
    }
  }
}
Exemplo n.º 18
0
/*
 * DnsServiceRegistrar::add
 *
 * Registers a new service.
 *
 * Parameters:
 *	- type: service type
 *	- port: port number of the registered service
 *	- name: service name (optional)
 *
 * Return value: reference of the DNS service if registration was successful, NULL otherwise
 */
DNSServiceRef DnsServiceRegistrar::add(const QString& type, quint16 port, const QString& name)
{
    /* Deal with name default value */
    char *nameStr;
    if (name == "") {
        nameStr = NULL;
    } else {
        nameStr = name.toUtf8().data();
    }

    /* Create and register the new service ref. */
    DNSServiceRef ref;
     DNSServiceErrorType err = DNSServiceRegister(&ref, 0, 0, nameStr, type.toUtf8().data(), NULL,
                                                                 NULL, qToBigEndian(port), 0, NULL, registerCallback, this);
    if (err != kDNSServiceErr_NoError) {
        Model::logger().addEntry(Logger::Error, QString("Error while registering service (error code = %1)").arg(err));
        return NULL;
    }

    /* Create the QSocketNotifier */
    int sockFd = DNSServiceRefSockFD(ref);
    RefNotifier *pNotif = new RefNotifier(ref, sockFd, QSocketNotifier::Read, this);
    connect(pNotif, SIGNAL(activated(int)), this, SLOT(onNotifierActivated()));

    return ref;
}
Exemplo n.º 19
0
bool LwIPTcpServer::listen(const QHostAddress &address, quint16 port) {
	Q_D(LwIPTcpServer);

	if(d->conn == 0) {
		d->conn = LwIPDispatcher::createConn(NETCONN_TCP, this);

		if(d->conn == 0) {
			return false;
		}

		struct ip_addr addr;

		addr.addr = qToBigEndian(address.toIPv4Address());

		if(netconn_bind(d->conn, &addr, port) != ERR_OK)
			goto failure;

		if(netconn_listen(d->conn) != ERR_OK)
			goto failure;

		d->serverAddress = address;
		d->serverPort = port;

		return true;
	} else
		return false;

failure:
	LwIPDispatcher::disposeConn(d->conn);

	d->conn = 0;
	return false;

}
Exemplo n.º 20
0
int UserAttr::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = contextId();
	qToBigEndian(_attrs, ptr); ptr += 2;
	return ptr-data;
}
Exemplo n.º 21
0
static QByteArray deriveKeyPbkdf2(QCryptographicHash::Algorithm algorithm,
                                  const QByteArray &data, const QByteArray &salt,
                                  int iterations, quint64 dkLen)
{
    QByteArray key;
    quint32 currentIteration = 1;
    QMessageAuthenticationCode hmac(algorithm, data);
    QByteArray index(4, Qt::Uninitialized);
    while (quint64(key.length()) < dkLen) {
        hmac.addData(salt);
        qToBigEndian(currentIteration, reinterpret_cast<uchar*>(index.data()));
        hmac.addData(index);
        QByteArray u = hmac.result();
        hmac.reset();
        QByteArray tkey = u;
        for (int iter = 1; iter < iterations; iter++) {
            hmac.addData(u);
            u = hmac.result();
            hmac.reset();
            std::transform(tkey.cbegin(), tkey.cend(), u.cbegin(), tkey.begin(),
                           std::bit_xor<char>());
        }
        key += tkey;
        currentIteration++;
    }
    return key.left(dkLen);
}
Exemplo n.º 22
0
int SessionConf::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	*(ptr++) = _maxusers;
	qToBigEndian(_attrs, ptr); ptr += 2;
	return ptr-data;
}
Exemplo n.º 23
0
void Core::bootstrapDht()
{
    const Settings& s = Settings::getInstance();
    QList<Settings::DhtServer> dhtServerList = s.getDhtServerList();

    int listSize = dhtServerList.size();
    static int j = qrand() % listSize, n=0;

    // We couldn't connect after trying 6 different nodes, let's try something else
    if (n>3)
    {
        qDebug() << "Core: We're having trouble connecting to the DHT, slowing down";
        bootstrapTimer->setInterval(TOX_BOOTSTRAP_INTERVAL*(n-1));
    }
    else
        qDebug() << "Core: Connecting to the DHT ...";

    int i=0;
    while (i < (2 - (n>3)))
    {
        const Settings::DhtServer& dhtServer = dhtServerList[j % listSize];
        if (tox_bootstrap_from_address(tox, dhtServer.address.toLatin1().data(),
            qToBigEndian(dhtServer.port), CUserId(dhtServer.userId).data()) == 1)
            qDebug() << QString("Core: Bootstraping from ")+dhtServer.name+QString(", addr ")+dhtServer.address.toLatin1().data()
                        +QString(", port ")+QString().setNum(dhtServer.port);
        else
            qDebug() << "Core: Error bootstraping from "+dhtServer.name;

        tox_do(tox);
        j++;
        i++;
        n++;
    }
}
Exemplo n.º 24
0
static inline T castWithEndian(T src)
{
    if(Socket_Handler::endian() == QSysInfo::BigEndian)
        return qToBigEndian(src);
    else
        return qToLittleEndian(src);
}
Exemplo n.º 25
0
bool Writer::writeHeader()
{
	Q_ASSERT(m_file->isOpen());

	// Format identification
	const char *MAGIC = "DPREC";
	m_file->write(MAGIC, 6);

	// Metadata block
	QJsonObject metadata;
	QJsonObject version;
	version["major"] = DRAWPILE_PROTO_MAJOR_VERSION;
	version["minor"] = DRAWPILE_PROTO_MINOR_VERSION;
	version["str"] = DRAWPILE_VERSION;
	metadata["version"] = version;

	// Write metadata
	QByteArray metadatabuf = QJsonDocument(metadata).toJson(QJsonDocument::Compact);

	uchar lenbuf[2];
	qToBigEndian(quint16(metadatabuf.length()), lenbuf);
	m_file->write((const char*)lenbuf, 2);

	m_file->write(metadatabuf);

	return true;
}
Exemplo n.º 26
0
void SonicPiTCPOSCServer::readMessage()
{
    while(socket->bytesAvailable() > 0){
        if (blockSize == 0) {
            if (socket->bytesAvailable() < (int)sizeof(quint32)){
                return;
            }

            socket->read((char *)&blockSize, sizeof(quint32));
            blockSize = qToBigEndian(blockSize);
        }

        if (socket->bytesAvailable() < blockSize){
            return;
        }

        buffer.resize(blockSize);
        int bytesRead = socket->read(&buffer[0], blockSize);

        if(bytesRead < 0 || (uint32_t)bytesRead != blockSize) {
            std::cerr << "[GUI] - Error: read: " << bytesRead << " Expected:" << blockSize << "\n";
            blockSize = 0;
            return;
        }
        std::vector<char> tmp(buffer);
        tmp.swap(buffer);
        handler->oscMessage(buffer);
        blockSize = 0;
        std::vector<char>().swap(buffer);
    }
}
Exemplo n.º 27
0
QByteArray AbstractSshPacket::generateMac(const SshAbstractCryptoFacility &crypt,
    quint32 seqNr) const
{
    const quint32 seqNrBe = qToBigEndian(seqNr);
    QByteArray data(reinterpret_cast<const char *>(&seqNrBe), sizeof seqNrBe);
    data += QByteArray(m_data.constData(), length() + 4);
    return crypt.generateMac(data, data.size());
}
Exemplo n.º 28
0
int LaserTrail::serializePayload(uchar *data) const
{
	uchar *ptr = data;
	qToBigEndian(m_color, ptr); ptr += 4;
	*(ptr++) = m_persistence;

	return ptr-data;
}
Exemplo n.º 29
0
/*!
   Retrieves the sfnt table named \a tagName from the underlying physical font, or an empty
   byte array if no such table was found. The returned font table's byte order is Big Endian, like
   the sfnt format specifies. The \a tagName must be four characters long and should be formatted
   in the default endianness of the current platform.
*/
QByteArray QRawFont::fontTable(const char *tagName) const
{
    if (!d->isValid())
        return QByteArray();

    const quint32 *tagId = reinterpret_cast<const quint32 *>(tagName);
    return d->fontEngine->getSfntTable(qToBigEndian(*tagId));
}
Exemplo n.º 30
0
std::string Common::packAddress(const QHostAddress &addr,
                                const uint16_t &port)
{
    std::string addrBin;
    char typeChar;
    std::string portNs(2, '\0');
    qToBigEndian(port, reinterpret_cast<uchar*>(&portNs[0]));
    if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
        uint32_t ipv4Address = qToBigEndian(addr.toIPv4Address());
        typeChar = static_cast<char>(Address::IPV4);
        addrBin = std::string(reinterpret_cast<char*>(&ipv4Address), 4);
    } else {
        typeChar = static_cast<char>(Address::IPV6);
        Q_IPV6ADDR ipv6Address = addr.toIPv6Address();
        addrBin = std::string(reinterpret_cast<char*>(ipv6Address.c), 16);
    }
    return typeChar + addrBin + portNs;
}