Esempio n. 1
0
//***************************************************************************
Kwave::RIFFParser::RIFFParser(QIODevice &device,
                              const QStringList &main_chunks,
                              const QStringList &known_subchunks)
    :m_dev(device),
     m_root(0, "", "", toUint32(device.size()), 0, toUint32(device.size())),
     m_main_chunk_names(main_chunks), m_sub_chunk_names(known_subchunks),
     m_endianness(Kwave::UnknownEndian), m_cancel(false)
{
    m_root.setType(Kwave::RIFFChunk::Root);
}
/*!
    \reimp
 */
void QxtXmlFileLoggerEngine::initLoggerEngine()
{
    QxtAbstractFileLoggerEngine::initLoggerEngine();

    // Mkay, we have an open file.  We need to check that it's all valid.
    // at the end of this block of code, we either can't log, or the carat is ready for writing.
    /*
    <?xml version="1.0" encoding="UTF-8"?>
    <log>
        <entry type="Error" time="sometime">
            <message>What's going on?</message>
            <message?Hi there</message>
        </entry>
    </log>
    */
    QIODevice* file = device();
    Q_ASSERT(file);
    if (file->size() == 0)
    {
        file->write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        file->write("<log>\n");
        file->write("</log>");
    }
    else
    {
        QByteArray data = file->read(64);
        if (!data.startsWith(QByteArray("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<log>")))
        {
            QFile* ptr_fileTarget = static_cast<QFile*>(file);
            qxtLog->warning(QString(" is not a valid XML log file.").prepend(ptr_fileTarget->fileName()));
            killLoggerEngine();
            return;
        }
    }
}
qint64 QIODeviceProto::size() const
{
  QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject());
  if (item)
    return item->size();
  return 0;
}
Esempio n. 4
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();
}
Esempio n. 5
0
/*!
    Read the unformatted contents of the file associated with a QContent into \a data.

    If \a data is not empty the contents will be overridden.

    Returns true if data could be read from the file and false otherwise.
 */
bool QContent::load(QByteArray &data) const
{
    QIODevice *dev = open();
    if (!dev)
        return false;

    if (dev->size() > 0)
        data = dev->readAll();
    dev->close();
    delete dev;

    return true;
}
Esempio n. 6
0
Tellico::Data::CollPtr AMCImporter::collection() {
  if(m_coll) {
    return m_coll;
  }

  if(!fileRef().open()) {
    return Data::CollPtr();
  }

  QIODevice* f = fileRef().file();
  m_ds.setDevice(f);
  // AMC is always little-endian? can't confirm
  m_ds.setByteOrder(QDataStream::LittleEndian);
  emit signalTotalSteps(this, f->size());

  const uint l = AMC_FILE_ID.length();
  QVector<char> buffer(l+1);
  m_ds.readRawData(buffer.data(), l);
  QString version = QString::fromLocal8Bit(buffer.data(), l);
  QRegExp versionRx(QLatin1String(".+AMC_(\\d+)\\.(\\d+).+"));
  if(versionRx.indexIn(version) == -1) {
    myDebug() << "no file id match";
    return Data::CollPtr();
  }

  m_coll = new Data::VideoCollection(true);

  m_majVersion = versionRx.cap(1).toInt();
  m_minVersion = versionRx.cap(2).toInt();
//  myDebug() << m_majVersion << "-" << m_minVersion;

  readString(); // name
  readString(); // email
  if(m_majVersion <= 3 && m_minVersion < 5) {
    readString(); // icq
  }
  readString(); // webpage
  readString(); // description

  const bool showProgress = options() & ImportProgress;

  while(!m_cancelled && !m_failed && !f->atEnd()) {
    readEntry();
    if(showProgress) {
      emit signalProgress(this, f->pos());
      qApp->processEvents();
    }
  }

  return m_coll;
}
Esempio n. 7
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;
    }
}
Esempio n. 8
0
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;
}
Esempio n. 9
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;
}
Esempio n. 10
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 );
        }
    }
Esempio n. 11
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();
}
Esempio n. 12
0
bool KDSoapServerSocket::handleFileDownload(KDSoapServerObjectInterface *serverObjectInterface, const QString &path)
{
    QByteArray contentType;
    QIODevice* device = serverObjectInterface->processFileRequest(path, contentType);
    if (!device) {
        const QByteArray notFound = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
        write(notFound);
        return true;
    }
    if (!device->open(QIODevice::ReadOnly)) {
        const QByteArray forbidden = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n";
        write(forbidden);
        delete device;
        return true; // handled!
    }
    const QByteArray response = httpResponseHeaders(false, contentType, device->size());
    if (m_doDebug) {
        qDebug() << "KDSoapServerSocket: file download response" << response;
    }
    qint64 written = write(response);
    Q_ASSERT(written == response.size()); // Please report a bug if you hit this.
    Q_UNUSED(written);

    char block[4096];
    qint64 totalRead = 0;
    while (!device->atEnd()) {
        const qint64 in = device->read(block, sizeof(block));
        if (in <= 0)
            break;
        totalRead += in;
        if(in != write(block, in)) {
            //error = true;
            break;
        }
    }
    //if (totalRead != device->size()) {
    //    // Unable to read from the source.
    //    error = true;
    //}

    delete device;
    // TODO log the file request, if logging is enabled?
    return true;
}
Esempio n. 13
0
/*
    A simple web page that can be used to test us: http://www.procata.com/cachetest/
 */
bool QNetworkAccessHttpBackend::sendCacheContents(const QNetworkCacheMetaData &metaData)
{
    setCachingEnabled(false);
    if (!metaData.isValid())
        return false;

    QAbstractNetworkCache *nc = networkCache();
    Q_ASSERT(nc);
    QIODevice *contents = nc->data(url());
    if (!contents) {
#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
        qDebug() << "Can not send cache, the contents are 0" << url();
#endif
        return false;
    }
    contents->setParent(this);

    QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
    int status = attributes.value(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (status < 100)
        status = 200;           // fake it

    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, status);
    setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));
    setAttribute(QNetworkRequest::SourceIsFromCacheAttribute, true);

    QNetworkCacheMetaData::RawHeaderList rawHeaders = metaData.rawHeaders();
    QNetworkCacheMetaData::RawHeaderList::ConstIterator it = rawHeaders.constBegin(),
                                                       end = rawHeaders.constEnd();
    for ( ; it != end; ++it)
        setRawHeader(it->first, it->second);

    checkForRedirect(status);

    writeDownstreamData(contents);
#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
    qDebug() << "Successfully sent cache:" << url() << contents->size() << "bytes";
#endif
    if (httpReply)
        disconnect(httpReply, SIGNAL(finished()), this, SLOT(replyFinished()));
    return true;
}
Esempio n. 14
0
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;
}
Esempio n. 15
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;
		}
	}
Esempio n. 16
0
ConversionStatus GettextImportPlugin::load(const QString& filename, const QString&)
{
   kdDebug( KBABEL ) << k_funcinfo << endl;
   
   if ( filename.isEmpty() ) {
      kdDebug(KBABEL) << "fatal error: empty filename to open" << endl;
      return NO_FILE;
   }

   QFileInfo info(filename);

   if(!info.exists() || info.isDir())
      return NO_FILE;

   if(!info.isReadable())
      return NO_PERMISSIONS;

   QFile file(filename);

   if ( !file.open( IO_ReadOnly ) )
      return NO_PERMISSIONS;
   
   uint oldPercent = 0;
   emit signalResetProgressBar(i18n("loading file"),100);

   QByteArray ba = file.readAll();
   file.close();

   // find codec for file
   bool hadCodec;
   QTextCodec* codec=codecForArray( ba, &hadCodec );
   
   bool recoveredErrorInHeader = false;
   
   QTextStream stream(ba,IO_ReadOnly);

   if(codec)
      stream.setCodec(codec);
   else
   {
      kdWarning() << "No encoding declared or found, using UTF-8" << endl;
      stream.setEncoding( QTextStream::UnicodeUTF8 );
#ifdef __GNUC__
# warning Default UTF-8 encoding needs to be improved
#endif
      // Templates define CHARSET, so if e make it a recoverable error, the template is not loadable anymore, as for templates recoverable errors are disqualifying.
      //recoveredErrorInHeader = true;
   }
   
   QIODevice *dev = stream.device();
   int fileSize = dev->size();

   // if somethings goes wrong with the parsing, we don't have deleted the old contents
   CatalogItem tempHeader;
   QStringList tempObsolete;


   kdDebug(KBABEL) << "start parsing..." << endl;

   // first read header
   const ConversionStatus status = readHeader(stream);


   if ( status == RECOVERED_PARSE_ERROR )
   {
      kdDebug( KBABEL ) << "Recovered error in header entry" << endl;
      recoveredErrorInHeader = true;
   }
   else if ( status != OK )
   {
      emit signalClearProgressBar();

      kdDebug( KBABEL ) << "Parse error in header entry" << endl;
      return status;
   }
   
   kdDebug() << "HEADER MSGID: " << _msgid << endl;
   kdDebug() << "HEADER MSGSTR: " << _msgstr << endl;
   if ( !_msgid.isEmpty() && !_msgid.first().isEmpty() )
   {
      // The header must have an empty msgid
      kdWarning(KBABEL) << "Header entry has non-empty msgid. Creating a temporary header! " << _msgid << endl;
      tempHeader.setMsgid( QStringList() );
      QStringList tmp;
      tmp.append(
         "Content-Type: text/plain; charset=UTF-8\\n" // Unknown charset
         "Content-Transfer-Encoding: 8bit\\n"
         "Mime-Version: 1.0" );
      tempHeader.setMsgstr( tmp );
      // We keep the comment of the first entry, as it might really be a header comment (at least partially)
      const QString comment( "# Header entry was created by KBabel!\n#\n" + _comment );
      tempHeader.setComment( comment );
      recoveredErrorInHeader = true;
   }
   else
   {
      tempHeader.setMsgid( _msgid );
      tempHeader.setMsgstr( _msgstr );
      tempHeader.setComment( _comment );
   }
   if(tempHeader.isFuzzy())
   {
      tempHeader.removeFuzzy();
   }

   // check if header seems to indicate docbook content generated by xml2pot
   const bool docbookContent = (tempHeader.msgstr().find("application/x-xml2pot") != tempHeader.msgstr().end());

   // now parse the rest of the file
   uint counter=0;
   QValueList<uint> errorIndex;
   bool recoveredError=false;
   bool docbookFile=false;

   while( !stream.eof() )
   {
      kapp->processEvents(10);
      if( isStopped() )
      {
         return STOPPED;
      }

      const ConversionStatus success=readEntry(stream);

      if(success==OK)
      {
         if( _obsolete )
         {
               tempObsolete.append(_comment);
         }
         else
         {
               CatalogItem tempCatItem;
               tempCatItem.setMsgctxt( _msgctxt );
               tempCatItem.setMsgid( _msgid );
               tempCatItem.setMsgstr( _msgstr );
               tempCatItem.setComment( _comment );
               tempCatItem.setGettextPluralForm( _gettextPluralForm );
               
               // add new entry to the list of entries
               appendCatalogItem(tempCatItem);
               // check if first comment seems to indicate a docbook source file
               if(counter==0)
                  docbookFile = ( tempCatItem.comment().find(".docbook") != -1 );
         }
      }
      else if(success==RECOVERED_PARSE_ERROR)
      {
         kdDebug( KBABEL ) << "Recovered parse error in entry: " << counter << endl;
         recoveredError=true;
         errorIndex.append(counter);
         
         CatalogItem tempCatItem;
         tempCatItem.setMsgctxt( _msgctxt );
         tempCatItem.setMsgid( _msgid );
         tempCatItem.setMsgstr( _msgstr );
         tempCatItem.setComment( _comment );
         tempCatItem.setGettextPluralForm( _gettextPluralForm );

         // add new entry to the list of entries
         appendCatalogItem(tempCatItem);
      }
      else if ( success == PARSE_ERROR )
      {
         kdDebug( KBABEL ) << "Parse error in entry: " << counter << endl;
         return PARSE_ERROR;
      }
      else
      {
         kdWarning( KBABEL ) << "Unknown success status, assumig parse error " << success << endl;
         return PARSE_ERROR;
      }
      counter++;

      const uint newPercent = (100*dev->at())/fileSize;
      if(newPercent > oldPercent)
      {
         oldPercent = newPercent;
         emit signalProgress(oldPercent);
      }
   }


   // to be sure it is set to 100, if someone don't connect to
   // signalClearProgressBar()
   emit signalProgress(100);

   emit signalClearProgressBar();


   // ### TODO: can we check that there is no useful entry?
   if ( !counter )
   {
      // Empty file? (Otherwise, there would be a try of getting an entry and the count would be 1 !)
      kdDebug( KBABEL ) << k_funcinfo << " Empty file?" << endl;
      return PARSE_ERROR;
   }

   kdDebug(KBABEL) << k_funcinfo << " ready" << endl;

   // We have succesfully loaded the file (perhaps with recovered errors)
   
   setGeneratedFromDocbook(docbookContent || docbookFile);

   setHeader(tempHeader);
   setCatalogExtraData(tempObsolete);
   setErrorIndex(errorIndex);

   if(hadCodec)
      setFileCodec(codec);
   else
      setFileCodec(0);
   
   setMimeTypes( "application/x-gettext" );

   if ( recoveredErrorInHeader )
   {
      kdDebug( KBABEL ) << k_funcinfo << " Returning: header error" << endl;
      return RECOVERED_HEADER_ERROR;
   }
   else if ( recoveredError )
   {
      kdDebug( KBABEL ) << k_funcinfo << " Returning: recovered parse error" << endl;
      return RECOVERED_PARSE_ERROR;
   }
   else
   {
      kdDebug( KBABEL ) << k_funcinfo << " Returning: OK! :-)" << endl;
      return OK;
   }
}
Esempio n. 17
0
sf_count_t nSndfileStream_vio_filelen(void * userData)
{
    QIODevice * device = ((QIODevice*)userData);
    sf_count_t size = device->size();
    return size;
}
Esempio n. 18
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;
}
Esempio n. 19
0
int main(int argc, char **argv)
{
    QCoreApplication application(argc, argv);
    QCoreApplication::setOrganizationDomain(QLatin1String("sites.google.com/site/zeromusparadoxe01"));
    QCoreApplication::setApplicationName(QLatin1String("zBrowser"));

    QStringList args = application.arguments();
    args.takeFirst();
    if (args.isEmpty()) {
        QTextStream stream(stdout);
        stream << "zbrowser-cacheinfo is a tool for viewing and extracting information out of zBrowser cache files." << endl;
        stream << "zbrowser-cacheinfo [-o cachefile] [file | url]" << endl;
        return 0;
    }

    NetworkDiskCache diskCache;
    QString location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation)
            + QLatin1String("/browser/");
    diskCache.setCacheDirectory(location);

    QNetworkCacheMetaData metaData;
    QString last = args.takeLast();
    if (QFile::exists(last)) {
        qDebug() << "Reading in from a file and not a URL.";
        metaData = diskCache._fileMetaData(last);
    } else {
        qDebug() << "Reading in from a URL and not a file.";
        metaData = diskCache.metaData(last);
    }

    if (!args.isEmpty()
        && args.count() >= 1
        && args.first() == QLatin1String("-o")) {
        QUrl url = metaData.url();
        QIODevice *device = diskCache.data(url);
        if (!device) {
            qDebug() << "Error: data for URL is 0!";
            return 1;
        }
        QString fileName;
        if (args.count() == 2) {
            fileName = args.last();
        } else {
            QFileInfo info(url.path());
            fileName = info.fileName();
            if (fileName.isEmpty()) {
                qDebug() << "URL file name is empty, please specify an output file, I wont guess.";
                return 1;
            }
            if (QFile::exists(fileName)) {
                qDebug() << "File already exists, not overwriting, please specify an output file.";
                return 1;
            }
        }
        qDebug() << "Saved cache file to:" << fileName;
        QFile file(fileName);
        if (!file.open(QFile::ReadWrite))
            qDebug() << "Unable to open the output file for writing.";
        else
            file.write(device->readAll());
        delete device;
    }

    QTextStream stream(stdout);
    stream << "URL: " << metaData.url().toString() << endl;
    stream << "Expiration Date: " << metaData.expirationDate().toString() << endl;
    stream << "Last Modified Date: " << metaData.lastModified().toString() << endl;
    stream << "Save to disk: " << metaData.saveToDisk() << endl;
    stream << "Headers:" << endl;
    foreach (const QNetworkCacheMetaData::RawHeader &header, metaData.rawHeaders())
        stream << "\t" << header.first << ": " << header.second << endl;
    QIODevice *device = diskCache.data(metaData.url());
    if (device) {
        stream << "Data Size: " << device->size() << endl;
        stream << "First line: " << device->readLine(100);
    } else {
        stream << "No data? Either the file is corrupt or there is an error." << endl;
    }

    delete device;
    return 0;
}
Esempio n. 20
0
// Read pre atlas header from file, return NULL if invalid
//
boost::shared_ptr< tChPreAtlasHdr > tAt5PreAtlas::ExtPreAtlasHdr(QIODevice& Qd) 
{
    // Since we don't know the version number at this time,
    //  we need to get tChPreAtlasHdr using version 1.
    //  From there, we'll read the version and then re-read the entire
    //  header again using the proper version number.


    // First get as version 1 then get as defined in PreAtlasHdr
    //
    tChPreAtlasHdr preAtlasV1( tAt5AtlasVersion( 1, 0 ) );           

    // 1st test to see if enough data in i/o to read header, return NULL if not
    //
    if ( Qd.size() < preAtlasV1.DataSize() )
    {
        tAt5Exception except;
        except.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO, "Insufficient amount of data in I/O" ) );
        throw except; 
    }

    // Now open stream and read pre_atlas1
    //
    tAt5Stream strm; 
    try
    {
        strm.InsStrm( Qd, 0, 0, 0, preAtlasV1.DataSize() );
        strm >> preAtlasV1;
    }
    catch( tAt5Exception Excpt )
    {
        Excpt.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO ) );
        throw Excpt;
    }

    // Verify preamble for correct signiture, return NULL if not
    //
    if ( ( preAtlasV1.SigChar0 != 0x55 ) || ( preAtlasV1.SigChar1 != 0xaa ) )
    {
        tAt5Exception except;
        except.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO, "Invalid preamble" ) );
        throw except; 
    }

    // Now read header again to get proper version

    boost::shared_ptr< tChPreAtlasHdr > xPreAtlas( new tChPreAtlasHdr( tAt5AtlasVersion( preAtlasV1.MajorAtlasVer, preAtlasV1.MinorAtlasVer ) ) ); 

    // see if enough data in i/o to read header, return NULL if not
    //
    if ( Qd.size() < xPreAtlas->DataSize() )
    {
        tAt5Exception except;
        except.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO, "Insufficient amount of data in I/O" ) );
        throw except; 
    }

    strm.Reset();    

    try
    {
        strm.InsStrm( Qd, 0, 0, 0, xPreAtlas->DataSize() );
        strm >> *xPreAtlas;
    }
    catch( tAt5Exception Excpt )
    {
        Excpt.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO ) );
        throw Excpt;
    }

    // TODO: Insert checksum test here if version 6 or above.    

    return xPreAtlas;
}
Esempio n. 21
0
void MemoryMap::diffWith(MemoryMap* other)
{
    _pmemDiff.clear();

    QIODevice* dev = _vmem->physMem();
    QIODevice* otherDev = other->vmem()->physMem();
    if (!otherDev || !dev)
        return;

    assert(dev != otherDev);

    // Open devices for reading, if required
    if (!dev->isReadable()) {
        if (dev->isOpen())
            dev->close();
        assert(dev->open(QIODevice::ReadOnly));
    }
    else
        assert(dev->reset());

    if (!otherDev->isReadable()) {
        if (otherDev->isOpen())
            otherDev->close();
        assert(otherDev->open(QIODevice::ReadOnly));
    }
    else
        assert(otherDev->reset());

    QTime timer;
    timer.start();
    bool wasEqual = true, equal = true;
    quint64 addr = 0, startAddr = 0, length = 0;
    const int bufsize = 1024;
    const int granularity = 16;
    char buf1[bufsize], buf2[bufsize];
    qint64 readSize1, readSize2;
    qint64 done, prevDone = -1;
    qint64 totalSize = qMin(dev->size(), otherDev->size());
    if (totalSize < 0)
        totalSize = qMax(dev->size(), otherDev->size());

    // Compare the complete physical address space
    while (!Console::interrupted() && !dev->atEnd() && !otherDev->atEnd()) {
        readSize1 = dev->read(buf1, bufsize);
        readSize2 = otherDev->read(buf2, bufsize);

        if (readSize1 <= 0 || readSize2 <= 0)
            break;

        qint64 size = qMin(readSize1, readSize2);
        for (int i = 0; i < size; ++i) {
            if (buf1[i] != buf2[i])
                equal = false;
            // We only consider memory chunks of size "granularity"
            if (addr % granularity == granularity - 1) {
                // Memory is equal
                if (equal) {
                    // Add difference to tree
                    if (!wasEqual)
                        _pmemDiff.insert(Difference(startAddr, length));
                }
                // Memory differs
                else {
                    // Start new difference
                    if (wasEqual) {
                        startAddr = addr - (addr % granularity);
                        length = granularity;
                    }
                    // Enlarge difference
                    else
                        length += granularity;
                }
                wasEqual = equal;
            }
            ++addr;
            equal = true;
        }

        done = (int) (addr / (float) totalSize * 100);
        if (prevDone < 0 || (done != prevDone && timer.elapsed() > 500)) {
            Console::out() << "\rComparing memory dumps: " << done << "%" << flush;
            prevDone = done;
            timer.restart();
        }
    }

    // Add last difference, if any
    if (!wasEqual)
        _pmemDiff.insert(Difference(startAddr, length));

    Console::out() << "\rComparing memory dumps finished." << endl;

//    debugmsg("No. of differences: " << _pmemDiff.objectCount());
}