Beispiel #1
0
bool Nicookie::safariFindCookie(QIODevice &device)
{
    qint64 begin_pos = device.pos();

    readUint32LE(device); // cookie_size not use
    readUint32LE(device); // unknown
    readUint32LE(device); // flags not use
    readUint32LE(device);  // unknown
    quint32 url_offset = readUint32LE(device);
    quint32 name_offset = readUint32LE(device);
    quint32 path_offset = readUint32LE(device);
    quint32 value_offset = readUint32LE(device);

    // check url
    device.seek(begin_pos + url_offset);
    if (!checkSameStr(device, Nicookie::COOKIE_HOST)) return false;

    // check name
    device.seek(begin_pos + name_offset);
    if (!checkSameStr(device, Nicookie::COOKIE_NAME)) return false;

    // check path
    device.seek(begin_pos + path_offset);
    if (!checkSameStr(device, Nicookie::COOKIE_PATH)) return false;

    device.seek(begin_pos + value_offset);
    QString str = readStr(device);
    if (str.isEmpty()) {
        setError(Nicookie::NotFoundDataError);
        return false;
    } else {
        this->userSession = str;
        return true;
    }
}
Beispiel #2
0
void seekFile(QIODevice &device, qint64 offset)
{
    if (!device.seek(offset))
    {
        throw std::runtime_error("Unable to seek file");
    }
}
Beispiel #3
0
bool Nicookie::safariFindPage(QIODevice &device)
{
    qint64 begin_pos = device.pos();

    // Page Header
    quint32 page_header = readUint32BE(device);
    if (page_header != 0x00000100) {
        setError(Nicookie::InvalidDataFormtaError);
        return false;
    }

    // No. of cookies
    quint32 cookie_num = readUint32LE(device);
    if (cookie_num == 0) {
        // エラーじゃ無い?
        return false;
    }

    // Cookie N offset
    QList<quint32> cookie_offset_list;
    for (quint32 i = 0; i < cookie_num; i++) {
        cookie_offset_list.append(readUint32LE(device));
    }

    // Cookie N
    for (auto &cookie_offset: cookie_offset_list) {
        device.seek(begin_pos + cookie_offset);
        if (safariFindCookie(device)) return true;
    }

    return false;
}
Beispiel #4
0
bool CharArchive::openAnimBoneCount()
{
    if (!isOpen()) {
        qWarning() << "CharArchive::openAnimBoneCount" << "archive not opened";
        return false;
    }

    _animBoneCount.clear();

    LgpIterator it = _io.iterator();
    while(it.hasNext()) {
        it.next();
        const QString &fileName = it.fileName();
        if(fileName.endsWith(".a", Qt::CaseInsensitive)) {
            QCoreApplication::processEvents();
            QIODevice *aFile = it.file();
            if(aFile && aFile->open(QIODevice::ReadOnly)) {
                quint32 boneCount;
                if(!aFile->seek(8) ||
                        aFile->read((char *)&boneCount, 4) != 4) {
                    qWarning() << "CharArchive::openAnimBoneCount" << "animation error" << fileName;
                    continue;
                }
                _animBoneCount.insert(boneCount, fileName.left(fileName.size()-2).toUpper());
            } else {
                return false;
            }
        }
    }

    return true;
}
bool QIODeviceProto::seek(qint64 pos)
{
  QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject());
  if (item)
    return item->seek(pos);
  return false;
}
Beispiel #6
0
toff_t okular_tiffSeekProc( thandle_t handle, toff_t offset, int whence )
{
    QIODevice * device = static_cast< QIODevice * >( handle );
    switch ( whence )
    {
        case SEEK_SET:
            device->seek( offset );
            break;
        case SEEK_CUR:
            device->seek( device->pos() + offset );
            break;
        case SEEK_END:
            device->seek( device->size() + offset );
            break;
    }

    return device->pos();
}
sf_count_t nSndfileStream_vio_seek(sf_count_t offset, int whence, void * userData)
{
    QIODevice * device = ((QIODevice*)userData);
    switch(whence)
    {
    case SEEK_SET:
        device->seek(offset);
        return 0;

    case SEEK_CUR:
        device->seek(device->pos()+offset);
        return 0;

    case SEEK_END:
        device->seek(device->size()-offset);
        return 0;
    }

    return -1;
}
Beispiel #8
0
bool WavHeader::writeDataLength(QIODevice &device, qint64 dataLength)
{
    bool result = false;
    if (!device.isSequential()) {
        device.seek(40);
        unsigned char dataLengthLE[4];
        qToLittleEndian<quint32>(quint32(dataLength), dataLengthLE);
        result = (device.write(reinterpret_cast<const char *>(dataLengthLE), 4) == 4);
    }
    return result;
}
Beispiel #9
0
voidpf ZCALLBACK qiodevice_open_file_func (
   voidpf opaque,
   voidpf file,
   int mode)
{
    QIODevice_descriptor *d = reinterpret_cast<QIODevice_descriptor*>(opaque);
    QIODevice *iodevice = reinterpret_cast<QIODevice*>(file);
    QIODevice::OpenMode desiredMode;
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        desiredMode = QIODevice::ReadOnly;
    else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        desiredMode = QIODevice::ReadWrite;
    else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        desiredMode = QIODevice::WriteOnly;
    if (iodevice->isOpen()) {
        if ((iodevice->openMode() & desiredMode) == desiredMode) {
            if (desiredMode != QIODevice::WriteOnly
                    && iodevice->isSequential()) {
                // We can use sequential devices only for writing.
                delete d;
                return NULL;
            } else {
                if ((desiredMode & QIODevice::WriteOnly) != 0) {
                    // open for writing, need to seek existing device
                    if (!iodevice->isSequential()) {
                        iodevice->seek(0);
                    } else {
                        d->pos = iodevice->pos();
                    }
                }
            }
            return iodevice;
        } else {
            delete d;
            return NULL;
        }
    }
    iodevice->open(desiredMode);
    if (iodevice->isOpen()) {
        if (desiredMode != QIODevice::WriteOnly && iodevice->isSequential()) {
            // We can use sequential devices only for writing.
            iodevice->close();
            delete d;
            return NULL;
        } else {
            return iodevice;
        }
    } else {
        delete d;
        return NULL;
    }
}
Beispiel #10
0
/* callback function for libisofs */
static int readf(char *buf, unsigned int start, unsigned int len, void *udata)
{
    KISOFUNC;

    QIODevice* dev = (static_cast<KIso*>(udata))->device();

    if (dev->seek((qint64)start << (qint64)11)) {
        if ((dev->read(buf, len << 11u)) != -1) return (len);
    }
    //qDebug() << "KIso::ReadRequest failed start: " << start << " len: " << len << endl;

    return -1;
}
Beispiel #11
0
//--------------------------------------------------------------------
void tst_QIODevice::peek()
{
    QBuffer buffer;
    QFile::remove("peektestfile");
    QFile file("peektestfile");

    for (int i = 0; i < 2; ++i) {
        QIODevice *device = i ? (QIODevice *)&file : (QIODevice *)&buffer;

        device->open(QBuffer::ReadWrite);
        device->write("ZXCV");

        device->seek(0);
        QCOMPARE(device->peek(4), QByteArray("ZXCV"));
        QCOMPARE(device->pos(), qint64(0));
        device->write("ABCDE");
        device->seek(3);
        QCOMPARE(device->peek(1), QByteArray("D"));
        QCOMPARE(device->peek(5), QByteArray("DE"));
        device->seek(0);
        QCOMPARE(device->read(4), QByteArray("ABCD"));
        QCOMPARE(device->pos(), qint64(4));

        device->seek(0);
        device->write("ZXCV");
        device->seek(0);
        char buf[5];
        buf[4] = 0;
        device->peek(buf, 4);
        QCOMPARE(static_cast<const char *>(buf), "ZXCV");
        QCOMPARE(device->pos(), qint64(0));
        device->read(buf, 4);
        QCOMPARE(static_cast<const char *>(buf), "ZXCV");
        QCOMPARE(device->pos(), qint64(4));
    }
    QFile::remove("peektestfile");
}
static int64_t SeekFunc(void *opaque, int64_t offset, int whence)
{
    QIODevice *io = (QIODevice*)opaque;

    if (whence == AVSEEK_SIZE)
    {
        return io->size();
    }
    else if (whence == SEEK_SET)
    {
        if (offset <= io->size())
            return io->seek(offset);
        else
            return -1;
    }
    else if (whence == SEEK_END)
    {
        int64_t newPos = io->size() + offset;
        if (newPos >= 0 && newPos <= io->size())
            return io->seek(newPos);
        else
            return -1;
    }
    else if (whence == SEEK_CUR)
    {
        int64_t newPos = io->pos() + offset;
        if (newPos >= 0 && newPos < io->size())
            return io->seek(newPos);
        else
            return -1;
    }
    else
        return -1;

     return -1;
}
Beispiel #13
0
/*!
    Only Size option is supported
*/
QVariant QWbmpHandler::option(ImageOption option) const
{
    if (option == QImageIOHandler::Size) {
        QIODevice *device = QImageIOHandler::device();
        if (device->isSequential())
            return QVariant();

        // Save old position
        qint64 oldPos = device->pos();

        WBMPHeader hdr;
        if (readWBMPHeader(device, &hdr)) {
            device->seek(oldPos);
            return QSize(hdr.width, hdr.height);
        }

        device->seek(oldPos);

    } else if (option == QImageIOHandler::ImageFormat) {
        return QVariant(QImage::Format_Mono);
    }

    return QVariant();
}
Beispiel #14
0
bool WavHeader::read(QIODevice &device)
{
    bool result = true;

    if (!device.isSequential())
        result = device.seek(0);
    // else, assume that current position is the start of the header

    if (result) {
        CombinedHeader header;
        result = (device.read(reinterpret_cast<char *>(&header), HeaderLength) == HeaderLength);
        if (result) {
            if ((memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0
                || memcmp(&header.riff.descriptor.id, "RIFX", 4) == 0)
                && memcmp(&header.riff.type, "WAVE", 4) == 0
                && memcmp(&header.wave.descriptor.id, "fmt ", 4) == 0
                && header.wave.audioFormat == 1 // PCM
            ) {
                if (memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0)
                    m_format.setByteOrder(QAudioFormat::LittleEndian);
                else
                    m_format.setByteOrder(QAudioFormat::BigEndian);

                m_format.setChannels(qFromLittleEndian<quint16>(header.wave.numChannels));
                m_format.setCodec("audio/pcm");
                m_format.setFrequency(qFromLittleEndian<quint32>(header.wave.sampleRate));
                m_format.setSampleSize(qFromLittleEndian<quint16>(header.wave.bitsPerSample));

                switch(header.wave.bitsPerSample) {
                case 8:
                    m_format.setSampleType(QAudioFormat::UnSignedInt);
                    break;
                case 16:
                    m_format.setSampleType(QAudioFormat::SignedInt);
                    break;
                default:
                    result = false;
                }

                m_dataLength = device.size() - HeaderLength;
            } else {
                result = false;
            }
        }
    }

    return result;
}
Beispiel #15
0
bool ExternalFile::readItem( QDataStream& in, ItemData& itemData, DatFormat *datFormat, TibiaModule *tibiaModule, qint32 index, quint32& address, QString& error )
{
    QIODevice *device = in.device();
    if( !device )
        return false;

    quint8 type = 0;
    in >> type;

    if( type != ITEM_TYPE_ITEM && type != ITEM_TYPE_OUTFIT && type != ITEM_TYPE_EFFECT && type != ITEM_TYPE_PROJECTILE ) {
        error = QObject::tr( "Unknown Item type" );
        return false;
    }

    ItemData d_itemData;
    if( datFormat ) {
        if( !ItemFile::loadItem( datFormat, in, d_itemData, error ) )
            return false;
    }

    d_itemData.parent = ITEM_PARENT_EXTERNAL;
    d_itemData.type = type;

    address = 0;

    if( !device->atEnd() ) {
        quint32 spriteCount = 0, now = 0, offset = 0;
        in >> spriteCount;
        address = device->pos();
        now = device->pos();
        for( quint32 i = 0; i < spriteCount; i++ ) {
            device->seek( now );
            in >> offset;
            if ( offset == 0x00000000 || offset > device->size() ) { // Direct to an image that doesnt exist or out of boundaries
                now += sizeof( quint32 );
                continue;
            }

            QMutex mutex;
            mutex.lock();
            SharedResource *resource = &g_resourceHandler.addResource(RESOURCE_TYPE_SPRITE, index, i, tibiaModule);
            d_itemData.setSpriteResource(i, *resource);
            mutex.unlock();
            now += sizeof( quint32 );
        }
    }
Beispiel #16
0
int64_t khopper::ffmpeg::seek( void * opaque, int64_t offset, int whence ) {
	QIODevice * device = static_cast< QIODevice * >( opaque );
	switch( whence ) {
	case SEEK_CUR:
		offset += device->pos();
		break;
	case SEEK_END:
		offset = device->size();
		break;
	case AVSEEK_SIZE:
		return device->size();
	default:
		;
	}
	device->seek( offset );
	return device->pos();
}
Dynamic::ReplacementBias::ReplacementBias( const QString &n, QXmlStreamReader *reader )
    : m_name( n )
{
    // -- read the original bias data as one block
    quint64 start = reader->characterOffset();
    reader->skipCurrentElement();
    quint64 end = reader->characterOffset();

    QIODevice *device = reader->device();
    if( device->isSequential() )
    {
        warning() << "Cannot read xml for bias"<<n<<"from sequential device.";
        return;
    }
    device->seek( start );
    m_html = device->read( end - start );

    debug() << "replacement bias for"<<n<<"is"<<m_html;

    connect( BiasFactory::instance(), SIGNAL(changed()), this, SLOT(factoryChanged()) );
}
Beispiel #18
0
/*! Read and parse the header block from the given input device stream. 
    The stream must be random access, binary and positioned to 0.

	 \retval true the header was read successfully.
	 \retval false the header failed to read for some reason.
 */
bool BlockHeader::Read(
	QIODevice& fIn	//! Input stream (binary, random access).
							 )
{
	ASSERT(fIn.isSequential()==false);
	ASSERT(fIn.isReadable()==true);
	ASSERT(fIn.isTextModeEnabled()==false);
	ASSERT(fIn.pos() == 0);
	ASSERT(sizeof(float) == 4);
	
	QDataStream in(&fIn);
	// Check the magic number
	quint32 uiMagic;
	in >> uiMagic;
	// OK, try to read the rest of the header.
	if(uiMagic == MAGIC_NUMBER) {
		in >> m_uiVersion;
		in >> m_iJulianDay;
		
		in >> m_fOriginLon;
		in >> m_fOriginLat;
		in >> m_fArcLon;
		in >> m_fArcLat;
		
		in >> m_uiRasterPos;
		in >> m_uiVectorPos;
		
		// The next 24 bytes are reserved. 
		// They should be zero, but we do not read them, just skip them.
		// Some additional checks are fast and harmless.
		if(   m_uiVersion >= 1 
		   && m_iJulianDay > 2454110 // 9.Jan.2007
			&& m_fArcLon >= 1.0f
			&& m_fArcLat >= 1.0f
			&& fIn.size() >= MBH_HEADER_SIZE
		  ) {
			fIn.seek(MBH_HEADER_SIZE); // position the file pointer to the 64-th byte.
			return true;
		}
	}
Beispiel #19
0
bool MimePart::writeData(QIODevice *device)
{
    Q_D(MimePart);

    /* === Content === */
    QIODevice *input = d->contentDevice;
    if (!input->isOpen()) {
        if (!input->open(QIODevice::ReadOnly)) {
            return false;
        }
    } else if (!input->seek(0)) {
        return false;
    }

    switch (d->contentEncoding) {
    case MimePart::_7Bit:
    case MimePart::_8Bit:
        if (!d->writeRaw(input, device)) {
            return false;
        }
        break;
    case MimePart::Base64:
        if (!d->writeBase64(input, device)) {
            return false;
        }
        break;
    case MimePart::QuotedPrintable:
        if (!d->writeQuotedPrintable(input, device)) {
            return false;
        }
        break;
    }

    if (device->write("\r\n", 2) != 2) {
        return false;
    }

    return true;
}
Beispiel #20
0
voidpf ZCALLBACK qiodevice_open_file_func (
   voidpf /*opaque UNUSED*/,
   voidpf file,
   int mode)
{
    QIODevice *iodevice = reinterpret_cast<QIODevice*>(file);
    QIODevice::OpenMode desiredMode;
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        desiredMode = QIODevice::ReadOnly;
    else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        desiredMode = QIODevice::ReadWrite;
    else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        desiredMode = QIODevice::WriteOnly;
    if (iodevice->isOpen()) {
        if ((iodevice->openMode() & desiredMode) == desiredMode) {
            if (iodevice->isSequential()) {
                return NULL;
            } else {
                if ((desiredMode & QIODevice::WriteOnly) != 0) {
                    // open for writing, need to seek existing device
                    iodevice->seek(0);
                }
            }
            return iodevice;
        } else {
            return NULL;
        }
    }
    iodevice->open(desiredMode);
    if (iodevice->isOpen()) {
        if (iodevice->isSequential()) {
            iodevice->close();
            return NULL;
        } else {
            return iodevice;
        }
    } else
        return NULL;
}
Beispiel #21
0
static
void CALLBACK_CALL_TYPE iod_read_fn(png_structp png_ptr, png_bytep data, png_size_t length)
{
    QPngHandlerPrivate *d = (QPngHandlerPrivate *)png_get_io_ptr(png_ptr);
    QIODevice *in = d->q->device();

    if (d->state == QPngHandlerPrivate::ReadingEnd && !in->isSequential() && (in->size() - in->pos()) < 4 && length == 4) {
        // Workaround for certain malformed PNGs that lack the final crc bytes
        uchar endcrc[4] = { 0xae, 0x42, 0x60, 0x82 };
        qMemCopy(data, endcrc, 4);
        in->seek(in->size());
        return;
    }

    while (length) {
        int nr = in->read((char*)data, length);
        if (nr <= 0) {
            png_error(png_ptr, "Read Error");
            return;
        }
        length -= nr;
    }
}
Beispiel #22
0
bool Nicookie::safariFindFile(QIODevice &device) {
    // Signature
    QByteArray headr_signature("cook", 4);
    if (headr_signature != device.read(4)) {
        setError(Nicookie::InvalidDataFormtaError);
        return false;
    }

    // No. of pages
    quint32 page_num = readUint32BE(device);
    if (page_num == 0) {
        setError(Nicookie::NotFoundDataError);
        return false;
    }

    // Page N Size
    QList<quint32> page_size_list;
    for (quint32 i = 0; i < page_num; ++i) {
        page_size_list.append(readUint32BE(device));
    }
    if (device.atEnd()) {
        setError(Nicookie::InvalidDataFormtaError);
        return false;
    }

    // Page N
    for (auto &page_size: page_size_list) {
        qint64 pos = device.pos();
        if (safariFindPage(device)) return true;
        device.seek(pos + page_size);
    }

    if (!hasError()) {
        setError(Nicookie::NotFoundDataError);
    }
    return false;
}
Beispiel #23
0
int ZCALLBACK qiodevice64_seek_file_func (
   voidpf /*opaque UNUSED*/,
   voidpf stream,
   ZPOS64_T offset,
   int origin)
{
    QIODevice *iodevice = reinterpret_cast<QIODevice*>(stream);
    if (iodevice->isSequential()) {
        if (origin == ZLIB_FILEFUNC_SEEK_END
                && offset == 0) {
            // sequential devices are always at end (needed in mdAppend)
            return 0;
        } else {
            qWarning("qiodevice_seek_file_func() called for sequential device");
            return -1;
        }
    }
    qint64 qiodevice_seek_result=0;
    int ret;
    switch (origin)
    {
    case ZLIB_FILEFUNC_SEEK_CUR :
        qiodevice_seek_result = ((QIODevice*)stream)->pos() + offset;
        break;
    case ZLIB_FILEFUNC_SEEK_END :
        qiodevice_seek_result = ((QIODevice*)stream)->size() - offset;
        break;
    case ZLIB_FILEFUNC_SEEK_SET :
        qiodevice_seek_result = offset;
        break;
    default:
        return -1;
    }
    ret = !iodevice->seek(qiodevice_seek_result);
    return ret;
}
Beispiel #24
0
bool Record::open()
{
    QIODevice *device = new QFile(m_fileName);
    if (!device->open(QFile::ReadOnly))
        return false;

    char header;
    device->getChar(&header);
    if (header == '\0') {
        m_format = CompressedText;
        QByteArray content = device->readAll();
        delete device;

        QByteArray *data = new QByteArray(qUncompress(content));
        device = new QBuffer(data);
        device->open(QFile::ReadOnly);
    } else {
        m_format = PlainText;
        device->ungetChar(header);
        device->seek(0);
    }

    m_commands.clear();
    while (!device->atEnd()) {
        QByteArray line = device->readLine();
        int split = line.indexOf(' ');

        Command command;
        command.elapsed = line.left(split).toInt();
        command.data = line.mid(split + 1);

        m_commands << command;
    }

    return true;
}
Beispiel #25
0
void tst_QIODevice::peekAndRead()
{
    QByteArray originalData;
    for (int i=0; i<1000; i++)
        originalData += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    QBuffer buffer;
    QFile::remove("peektestfile");
    QFile file("peektestfile");

    for (int i = 0; i < 2; ++i) {
        QByteArray readData;
        QIODevice *device = i ? (QIODevice *)&file : (QIODevice *)&buffer;
        device->open(QBuffer::ReadWrite);
        device->write(originalData);
        device->seek(0);
        while (!device->atEnd()) {
            char peekIn[26];
            device->peek(peekIn, 26);
            readData += device->read(26);
        }
        QCOMPARE(readData, originalData);
    }
    QFile::remove("peektestfile");
}
Beispiel #26
0
bool KTar::openArchive( QIODevice::OpenMode mode ) {

    if ( !(mode & QIODevice::ReadOnly) )
        return true;

    if ( !d->fillTempFile( fileName() ) )
        return false;

    // We'll use the permission and user/group of d->rootDir
    // for any directory we emulate (see findOrCreate)
    //struct stat buf;
    //stat( fileName(), &buf );

    d->dirList.clear();
    QIODevice* dev = device();

    if ( !dev )
        return false;

    // read dir information
    char buffer[ 0x200 ];
    bool ende = false;
    do
    {
        QString name;
        QString symlink;

        // Read header
        qint64 n = d->readHeader( buffer, name, symlink );
        if (n < 0) return false;
        if (n == 0x200)
        {
            bool isdir = false;

            if ( name.endsWith( QLatin1Char( '/' ) ) )
            {
                isdir = true;
                name.truncate( name.length() - 1 );
            }

            QByteArray prefix = QByteArray(buffer + 0x159, 155);
            if (prefix[0] != '\0') {
                name = (QString::fromLatin1(prefix.constData()) + QLatin1Char('/') +  name);
            }

            int pos = name.lastIndexOf( QLatin1Char('/') );
            QString nm = ( pos == -1 ) ? name : name.mid( pos + 1 );

            // read access
            buffer[ 0x6b ] = 0;
            char *dummy;
            const char* p = buffer + 0x64;
            while( *p == ' ' ) ++p;
            int access = (int)strtol( p, &dummy, 8 );

            // read user and group
            QString user = QString::fromLocal8Bit( buffer + 0x109 );
            QString group = QString::fromLocal8Bit( buffer + 0x129 );

            // read time
            buffer[ 0x93 ] = 0;
            p = buffer + 0x88;
            while( *p == ' ' ) ++p;
            uint time = (int)strtol( p, &dummy, 8 );

            // read type flag
            char typeflag = buffer[ 0x9c ];
            // '0' for files, '1' hard link, '2' symlink, '5' for directory
            // (and 'L' for longlink fileNames, 'K' for longlink symlink targets)
            // 'D' for GNU tar extension DUMPDIR, 'x' for Extended header referring
            // to the next file in the archive and 'g' for Global extended header

            if ( typeflag == '5' )
                isdir = true;

            bool isDumpDir = false;
            if ( typeflag == 'D' )
            {
                isdir = false;
                isDumpDir = true;
            }
            //qDebug() << nm << "isdir=" << isdir << "pos=" << dev->pos() << "typeflag=" << typeflag << " islink=" << ( typeflag == '1' || typeflag == '2' );

            if (typeflag == 'x' || typeflag == 'g') { // pax extended header, or pax global extended header
                // Skip it for now. TODO: implement reading of extended header, as per http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html
                (void)dev->read( buffer, 0x200 );
                continue;
            }

            if (isdir)
                access |= S_IFDIR; // f*cking broken tar files

            KArchiveEntry* e;
            if ( isdir )
            {
                //qDebug() << "directory" << nm;
                e = new KArchiveDirectory( this, nm, access, KArchivePrivate::time_tToDateTime(time), user, group, symlink );
            }
            else
            {
                // read size
                QByteArray sizeBuffer( buffer + 0x7c, 12 );
                qint64 size = sizeBuffer.trimmed().toLongLong( 0, 8 /*octal*/ );
                //qDebug() << "sizeBuffer='" << sizeBuffer << "' -> size=" << size;

                // for isDumpDir we will skip the additional info about that dirs contents
                if ( isDumpDir )
                {
                    //qDebug() << nm << "isDumpDir";
                    e = new KArchiveDirectory( this, nm, access, KArchivePrivate::time_tToDateTime(time), user, group, symlink );
                }
                else
                {

                    // Let's hack around hard links. Our classes don't support that, so make them symlinks
                    if ( typeflag == '1' )
                    {
                        //qDebug() << "Hard link, setting size to 0 instead of" << size;
                        size = 0; // no contents
                    }

                    //qDebug() << "file" << nm << "size=" << size;
                    e = new KArchiveFile( this, nm, access, KArchivePrivate::time_tToDateTime(time), user, group, symlink,
                                          dev->pos(), size );
                }

                // Skip contents + align bytes
                qint64 rest = size % 0x200;
                qint64 skip = size + (rest ? 0x200 - rest : 0);
                //qDebug() << "pos()=" << dev->pos() << "rest=" << rest << "skipping" << skip;
                if (! dev->seek( dev->pos() + skip ) ) {
                    //qWarning() << "skipping" << skip << "failed";
                }
            }

            if ( pos == -1 )
            {
                if (nm == QLatin1String(".")) { // special case
                    Q_ASSERT( isdir );
                    if (isdir) {
                        setRootDir( static_cast<KArchiveDirectory *>( e ) );
                    }
                } else {
                    rootDir()->addEntry( e );
                }
            }
            else
            {
                // In some tar files we can find dir/./file => call cleanPath
                QString path = QDir::cleanPath( name.left( pos ) );
                // Ensure container directory exists, create otherwise
                KArchiveDirectory * d = findOrCreate( path );
                d->addEntry( e );
            }
        }
        else
        {
            //qDebug("Terminating. Read %d bytes, first one is %d", n, buffer[0]);
            d->tarEnd = dev->pos() - n; // Remember end of archive
            ende = true;
        }
    } while( !ende );
    return true;
}
/**
 * Verifies contents of specified archive against test fileset
 * @param archive archive
 */
static void testFileData(KArchive *archive)
{
    const KArchiveDirectory *dir = archive->directory();

    const KArchiveFile *f = dir->file(QStringLiteral("z/test3"));
    QByteArray arr(f->data());
    QCOMPARE(arr.size(), 13);
    QCOMPARE(arr, QByteArray("Noch so einer"));

    // Now test using createDevice()
    QIODevice *dev = f->createDevice();
    QByteArray contents = dev->readAll();
    QCOMPARE(contents, arr);
    delete dev;

    dev = f->createDevice();
    contents = dev->read(5); // test reading in two chunks
    QCOMPARE(contents.size(), 5);
    contents += dev->read(50);
    QCOMPARE(contents.size(), 13);
    QCOMPARE(QString::fromLatin1(contents.constData()), QString::fromLatin1(arr.constData()));
    delete dev;

    // test read/seek/peek work fine
    f = dir->file(QStringLiteral("test1"));
    dev = f->createDevice();
    contents = dev->peek(4);
    QCOMPARE(contents, QByteArray("Hall"));
    contents = dev->peek(2);
    QCOMPARE(contents, QByteArray("Ha"));
    dev->seek(2);
    contents = dev->peek(2);
    QCOMPARE(contents, QByteArray("ll"));
    dev->seek(0);
    contents = dev->read(2);
    QCOMPARE(contents, QByteArray("Ha"));
    contents = dev->peek(2);
    QCOMPARE(contents, QByteArray("ll"));
    dev->seek(1);
    contents = dev->read(1);
    QCOMPARE(contents, QByteArray("a"));
    dev->seek(4);
    contents = dev->read(1);
    QCOMPARE(contents, QByteArray("o"));

    const KArchiveEntry *e = dir->entry(QStringLiteral("mediumfile"));
    QVERIFY(e && e->isFile());
    f = (KArchiveFile *)e;
    QCOMPARE(f->data().size(), SIZE1);

    f = dir->file(QStringLiteral("hugefile"));
    QCOMPARE(f->data().size(), 20000);

    e = dir->entry(QStringLiteral("aaaemptydir"));
    QVERIFY(e && e->isDirectory());
    QVERIFY(!dir->file("aaaemptydir"));

    e = dir->entry(QStringLiteral("my/dir/test3"));
    QVERIFY(e && e->isFile());
    f = (KArchiveFile *)e;
    dev = f->createDevice();
    QByteArray firstLine = dev->readLine();
    QCOMPARE(QString::fromLatin1(firstLine.constData()), QString::fromLatin1("I do not speak German\n"));
    QByteArray secondLine = dev->read(100);
    QCOMPARE(QString::fromLatin1(secondLine.constData()), QString::fromLatin1("David."));
    delete dev;
#ifndef Q_OS_WIN
    e = dir->entry(QStringLiteral("z/test3_symlink"));
    QVERIFY(e);
    QVERIFY(e->isFile());
    QCOMPARE(e->symLinkTarget(), QString("test3"));
#endif

    // Test "./" prefix for KOffice (xlink:href="./ObjectReplacements/Object 1")
    e = dir->entry(QStringLiteral("./hugefile"));
    QVERIFY(e && e->isFile());
    e = dir->entry(QStringLiteral("./my/dir/test3"));
    QVERIFY(e && e->isFile());

    // Test directory entries
    e = dir->entry(QStringLiteral("my"));
    QVERIFY(e && e->isDirectory());
    e = dir->entry(QStringLiteral("my/"));
    QVERIFY(e && e->isDirectory());
    e = dir->entry(QStringLiteral("./my/"));
    QVERIFY(e && e->isDirectory());
}
Beispiel #28
0
bool EPSHandler::read(QImage *image)
{
    kDebug(399) << "kimgio EPS: starting...";

    FILE * ghostfd;
    int x1, y1, x2, y2;
    //QTime dt;
    //dt.start();

    QString cmdBuf;
    QString tmp;

    QIODevice* io = device();
    quint32 ps_offset, ps_size;

    // find start of PostScript code
    if ( !seekToCodeStart(io, ps_offset, ps_size) )
        return false;

    // find bounding box
    if ( !bbox (io, &x1, &y1, &x2, &y2)) {
        kError(399) << "kimgio EPS: no bounding box found!" << endl;
        return false;
    }

    QTemporaryFile tmpFile;
    if( !tmpFile.open() ) {
        kError(399) << "kimgio EPS: no temp file!" << endl;
        return false;
    }

    // x1, y1 -> translation
    // x2, y2 -> new size

    x2 -= x1;
    y2 -= y1;
    //kDebug(399) << "origin point: " << x1 << "," << y1 << "  size:" << x2 << "," << y2;
    double xScale = 1.0;
    double yScale = 1.0;
    int wantedWidth = x2;
    int wantedHeight = y2;

    // create GS command line

    cmdBuf = "gs -sOutputFile=";
    cmdBuf += tmpFile.fileName();
    cmdBuf += " -q -g";
    tmp.setNum( wantedWidth );
    cmdBuf += tmp;
    tmp.setNum( wantedHeight );
    cmdBuf += 'x';
    cmdBuf += tmp;
    cmdBuf += " -dSAFER -dPARANOIDSAFER -dNOPAUSE -sDEVICE=ppm -c "
              "0 0 moveto "
              "1000 0 lineto "
              "1000 1000 lineto "
              "0 1000 lineto "
              "1 1 254 255 div setrgbcolor fill "
              "0 0 0 setrgbcolor - -c showpage quit";

    // run ghostview

    ghostfd = popen (QFile::encodeName(cmdBuf), "w");

    if ( ghostfd == 0 ) {
        kError(399) << "kimgio EPS: no GhostScript?" << endl;
        return false;
    }

    fprintf (ghostfd, "\n%d %d translate\n", -qRound(x1*xScale), -qRound(y1*yScale));

    // write image to gs

    io->reset(); // Go back to start of file to give all the file to GhostScript
    if (ps_offset>0L) // We have an offset
        io->seek(ps_offset);
    QByteArray buffer ( io->readAll() );

    // If we have no MS-DOS EPS file or if the size seems wrong, then choose the buffer size
    if (ps_size<=0 || ps_size>(unsigned int)buffer.size())
        ps_size=buffer.size();

    fwrite(buffer.data(), sizeof(char), ps_size, ghostfd);
    buffer.resize(0);

    pclose ( ghostfd );

    // load image
    if( image->load (tmpFile.fileName()) ) {
        kDebug(399) << "kimgio EPS: success!";
        //kDebug(399) << "Loading EPS took " << (float)(dt.elapsed()) / 1000 << " seconds";
        return true;
    }

    kError(399) << "kimgio EPS: no image!" << endl;
    return false;
}
Beispiel #29
0
//--------------------------------------------------------------------
void tst_QIODevice::unget()
{
#if defined(Q_OS_WINCE) && defined(WINCE_EMULATOR_TEST)
    QSKIP("Networking tests in a WinCE emulator are unstable", SkipAll);
#endif
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    buffer.write("ZXCV");
    buffer.seek(0);
    QCOMPARE(buffer.read(4), QByteArray("ZXCV"));
    QCOMPARE(buffer.pos(), qint64(4));

    buffer.ungetChar('a');
    buffer.ungetChar('b');
    buffer.ungetChar('c');
    buffer.ungetChar('d');

    QCOMPARE(buffer.pos(), qint64(0));

    char buf[6];
    QCOMPARE(buffer.readLine(buf, 5), qint64(4));
    QCOMPARE(buffer.pos(), qint64(4));
    QCOMPARE(static_cast<const char*>(buf), "dcba");

    buffer.ungetChar('a');
    buffer.ungetChar('b');
    buffer.ungetChar('c');
    buffer.ungetChar('d');

    QCOMPARE(buffer.pos(), qint64(0));

    for (int i = 0; i < 5; ++i) {
        buf[0] = '@';
        buf[1] = '@';
        QTest::ignoreMessage(QtWarningMsg,
                             "QIODevice::readLine: Called with maxSize < 2");
        QCOMPARE(buffer.readLine(buf, 1), qint64(-1));
        QCOMPARE(buffer.readLine(buf, 2), qint64(i < 4 ? 1 : -1));
        switch (i) {
        case 0:
            QCOMPARE(buf[0], 'd');
            break;
        case 1:
            QCOMPARE(buf[0], 'c');
            break;
        case 2:
            QCOMPARE(buf[0], 'b');
            break;
        case 3:
            QCOMPARE(buf[0], 'a');
            break;
        case 4:
            QCOMPARE(buf[0], '\0');
            break;
        }
        QCOMPARE(buf[1], i < 4 ? '\0' : '@');
    }

    buffer.ungetChar('\n');
    QCOMPARE(buffer.readLine(), QByteArray("\n"));

    buffer.seek(1);
    buffer.readLine(buf, 3);
    QCOMPARE(static_cast<const char*>(buf), "XC");

    buffer.seek(4);
    buffer.ungetChar('Q');
    QCOMPARE(buffer.readLine(buf, 3), qint64(1));

    for (int i = 0; i < 2; ++i) {
        QTcpSocket socket;
        QIODevice *dev;
        QByteArray result;
        const char *lineResult;
        if (i == 0) {
            dev = &buffer;
            result = QByteArray("ZXCV");
            lineResult = "ZXCV";
        } else {
            socket.connectToHost(QtNetworkSettings::serverName(), 80);
            socket.write("GET / HTTP/1.0\r\n\r\n");
            QVERIFY(socket.waitForReadyRead());
            dev = &socket;
            result = QByteArray("HTTP");
            lineResult = "Date";
        }
        char ch, ch2;
        dev->seek(0);
        dev->getChar(&ch);
        dev->ungetChar(ch);
        QCOMPARE(dev->peek(4), result);
        dev->getChar(&ch);
        dev->getChar(&ch2);
        dev->ungetChar(ch2);
        dev->ungetChar(ch);
        QCOMPARE(dev->read(1), result.left(1));
        QCOMPARE(dev->read(3), result.right(3));

        if (i == 0)
            dev->seek(0);
        else
            dev->readLine();
        dev->getChar(&ch);
        dev->ungetChar(ch);
        dev->readLine(buf, 5);
        QCOMPARE(static_cast<const char*>(buf), lineResult);

        if (i == 1)
            socket.close();
    }
}
Beispiel #30
0
void RpcConnection::sendRpcReply(PbRpcController *controller)
{
    google::protobuf::Message *response = controller->response();
    QIODevice *blob;
    char msgBuf[PB_HDR_SIZE];
    char* const msg = &msgBuf[0];
    int len;

    if (controller->Failed())
    {
        QByteArray err = controller->ErrorString().toUtf8();

        qWarning("rpc failed (%s)", qPrintable(controller->ErrorString()));
        len = err.size();
        writeHeader(msg, PB_MSG_TYPE_ERROR, pendingMethodId, len);
        clientSock->write(msg, PB_HDR_SIZE);
        clientSock->write(err.constData(), len);

        goto _exit;
    }

    blob = controller->binaryBlob();
    if (blob)
    {
        len = blob->size();
        qDebug("is binary blob of len %d", len);

        writeHeader(msg, PB_MSG_TYPE_BINBLOB, pendingMethodId, len);
        clientSock->write(msg, PB_HDR_SIZE);

        blob->seek(0);
        while (!blob->atEnd())
        {    
            int l;

            len = blob->read(msg, sizeof(msgBuf));
            l = clientSock->write(msg, len);
            Q_ASSERT(l == len);
            Q_UNUSED(l);
        }

        goto _exit;
    }

    if (!response->IsInitialized())
    {
        qWarning("response missing required fields!! <----");
        qDebug("response = \n%s"
               "missing = \n%s---->",
                response->DebugString().c_str(),
                response->InitializationErrorString().c_str());
        qFatal("exiting");
        goto _exit;
    }

    len = response->ByteSize();
    writeHeader(msg, PB_MSG_TYPE_RESPONSE, pendingMethodId, len);

    // Avoid printing stats since it happens once every couple of seconds
    if (pendingMethodId != 13)
    {
        qDebug("Server(%s): sending %d bytes to client <----",
            __FUNCTION__, len + PB_HDR_SIZE);
        BUFDUMP(msg, 8);
        qDebug("method = %d\nreq = \n%s---->", 
            pendingMethodId, response->DebugString().c_str());
    }

    clientSock->write(msg, PB_HDR_SIZE);
    response->SerializeToZeroCopyStream(outStream);
    outStream->Flush();

    if (pendingMethodId == 15) {
        isCompatCheckDone = true;
        isNotifEnabled = controller->NotifEnabled();
    }

_exit:
    if (controller->Disconnect())
        clientSock->disconnectFromHost();

    delete controller;
    isPending = false;
}