Esempio n. 1
0
void UTPex::handlePexPacket(const Uint8* packet,Uint32 size)
{
    if (size <= 2 || packet[1] != 1)
        return;

    QByteArray tmp;
    tmp.setRawData((const char*)packet,size);
    BNode* node = 0;
    try
    {
        BDecoder dec(tmp,false,2);
        node = dec.decode();
        if (node && node->getType() == BNode::DICT)
        {
            BDictNode* dict = (BDictNode*)node;

            // ut_pex packet, emit signal to notify PeerManager
            BValueNode* val = dict->getValue("added");
            if (val)
            {
                QByteArray data = val->data().toByteArray();
                peer->emitPex(data);
            }
        }
    }
    catch (...)
    {
        // just ignore invalid packets
        Out(SYS_CON|LOG_DEBUG) << "Invalid extended packet" << endl;
    }
    delete node;
    tmp.resetRawData((const char*)packet,size);
}
Esempio n. 2
0
void Loader::slotRetrieverDone(const QByteArray &data, bool success)
{
   d->lastError = d->retriever->errorCode();

   delete d->retriever;
   d->retriever = NULL;

   Document rssDoc;
   Status status = Success;

   if (success) {
      QDomDocument doc;

      /* Some servers insert whitespace before the <?xml...?> declaration.
       * QDom doesn't tolerate that (and it's right, that's invalid XML),
       * so we strip that.
       */

      const char *charData = data.data();
      int len = data.count();

      while (len && QChar(*charData).isSpace()) {
         --len;
         ++charData;
      }

      if ( len > 3 && QChar(*charData) == QChar(0357) ) { // 0357 0273 0277
			  len -= 3;
			  charData += 3;
	  }
      QByteArray tmpData;
      tmpData.setRawData(charData, len);

      if (doc.setContent(tmpData))
      {
         rssDoc = Document(doc);
         if (!rssDoc.isValid())
         {
            discoverFeeds(tmpData);
            status = ParseError;
         }
      }
      else
      {
         discoverFeeds(tmpData);
         status = ParseError;
      }

      tmpData.resetRawData(charData, len);
   } else
      status = RetrieveError;

   emit loadingComplete(this, rssDoc, status);

   delete this;
}
Esempio n. 3
0
void kio_afpProtocol::get(const KURL& url )
{
    kdDebug(7101) << "\n\nget " << url.prettyURL() << endl;
    struct afp_url afp_url;
    int ret;
    unsigned int fileid;
    unsigned long long total=0;
    QString resumeOffset = metaData("resume");
    // bool ok;
    // struct stat stat;
    // KIO::fileoffset_t offset = resumeOffset.toLongLong(&ok);

    QString kafpurl = url.url(0,0);
    afp_default_url(&afp_url);
    afp_parse_url(&afp_url,kafpurl,0);

    if (attachvolume(&afp_url)==false) {
    kdDebug(7101) << "could not attach for get of " << url.prettyURL() << endl;
       finished();
       return;
    }

    ret=afp_sl_open(NULL,NULL,&afp_url, &fileid,0);


#if 0

    char buffer[GET_DATA_SIZE];
    QByteArray array;
    

    while (eof==0) {
       ret = afp_sl_read(&connection,&volid,fileid,0,
               offset, GET_DATA_SIZE,&received,&eof,buffer);

       array.setRawData(buffer,received);
       data(array);
       array.resetRawData(buffer,received);

       total+=received;
       offset=total;
    }


    infoMessage( i18n( "Retrieving %1 from %2...") 
      .arg(KIO::convertSize(retreived)) .arg(afp_url.servername));


#endif

    totalSize(total);

    ret=afp_sl_close(&volumeid,fileid);

}
Esempio n. 4
0
bool QPixmap::loadFromData( const uchar *buf, uint len, const char *format,
			    int conversion_flags )
{
    QByteArray a;
    a.setRawData( (char *)buf, len );
    QBuffer b( a );
    b.open( IO_ReadOnly );
    QImageIO io( &b, format );
    bool result = io.read();
    b.close();
    a.resetRawData( (char *)buf, len );
    if ( result ) {
	detach();
	result = convertFromImage( io.image(), conversion_flags );
    }
    return result;
}
Esempio n. 5
0
/* ---------------------------------------------------------------------------------- */
void ChmProtocol::get( const KURL& url )
{
    /** When :catalog is appended to the end, a plain-text representation of the catalog
      * is given out where each entry consists of four lines, an integer representing the parent
      * of the node, an integer representing a node's ID, the Title of the Node, and it's hyperlink.
      * When :contents is appended, all contained htm- and html-files will be printed, each in a line.
      */
    kdDebug() << "kio_chm::get(const KURL& url) " << url.path() << endl;

    bool catalog = false;
    bool contents = false;
    QString bigpath = url.path();

    if(bigpath.endsWith(":catalog")) {
        catalog = true;
        int len = QString(":catalog").length();
        bigpath.remove(bigpath.length() - len, len);   ///strip :catalog from the end
    }

    if(bigpath.endsWith(":contents")) {
        contents = true;
        int len = QString(":contents").length();
        bigpath.remove(bigpath.length() - len, len);   ///strip :catalog from the end
    }

    QString path;
    if ( !checkNewFile( bigpath, path ) ) {
        error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
        return;
    }


    if (m_dirMap.find(path) == m_dirMap.end()) {
        error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
        return;
    }

    QByteArray theData;

    //init..
    //added by lucida [email protected]
    QString fname = QString();
    QString chmpath = QString();
    KTempFile f("",".html");
    fname = f.name();
    QTextStream *t = f.textStream();
    QString firstPage = QString("");
    QString m_strIndex = QString("");
    QString tmpstr = QString("");
    bool m_bIndex = 0;


    if(contents) {
        QString output;
        KURL u = url;

        ChmDirectoryMap::Iterator it;
        for ( it = m_dirMap.begin(); it != m_dirMap.end(); ++it) {
            u.setPath(bigpath);
            u.addPath(it.key());
            output += u.prettyURL() + "\n";
        }

        data(output.local8Bit());
        processedSize(output.length());
        finished();
        return;
    }


    //try get some page to display, if the chm missing index
    ChmDirectoryMap::Iterator it;
    for ( it = m_dirMap.begin(); it != m_dirMap.end(); ++it) {
        tmpstr.sprintf("%s", it.key().latin1());
        if ((m_strIndex == "") &&
                (tmpstr.endsWith(".htm") || tmpstr.endsWith(".html")))
            m_strIndex = tmpstr;
        if ((tmpstr == "/index.htm") || (tmpstr == "/index.html")) {
            m_strIndex = tmpstr;
            break;
        }
    }
    m_strIndex.remove(0,1);


    if (path == "/" || catalog) {
        bool htmlOutput = !catalog;
        int offset = m_dirMap["/@contents"].offset;
        int length = m_dirMap["/@contents"].length;
        theData.setRawData(&m_contents[offset], length);
        QString s(theData);
        QString output;

        QRegExp object("<OBJECT type=\"text/sitemap\">(.*)</OBJECT>", false);
        object.setMinimal(true);

        QRegExp nameParam("<param name=\"Name\" value=\"(.*)\">", false);
        nameParam.setMinimal(true);

        QRegExp localParam("<param name=\"Local\" value=\"(.*)\">", false);
        localParam.setMinimal(true);

        QRegExp mergeParam("<param name=\"Merge\" value=\"(.*)\">", false);
        mergeParam.setMinimal(true);

        std::stack<int> parents;
        int counter = 1;
        int current = 0;
        int old = 0, pos = 0;
        parents.push(0);
        while ((pos = s.find(object, pos)) != -1) {
            if(htmlOutput) output += s.mid(old, pos - old);
            if(catalog) {
                QRegExp ex("<UL>|</UL>", false);
                ex.setMinimal(true);
                QString ms = s.mid(old, pos - old);
                int pos = 0;
                while( (pos = ms.find(ex, pos)) != -1) {
                    if(ms.mid(pos, 4) == "<UL>") {
                        parents.push(current);
                    } else {
                        if(parents.empty()) {
                        } else {
                            current = parents.top();
                            parents.pop();
                        }
                    }
                    pos++;
                }
            }
            pos += object.matchedLength();
            old = pos;
            QString obj = object.cap(1);
            QString name, local;
            if (obj.find(nameParam) != -1) {
                name = nameParam.cap(1);
                if (obj.find(localParam) != -1) {
                    local = localParam.cap(1);
                    //output += "<a href=\"" + local + "\">" + name + "</a>";
                    //added by lucida [email protected]
                    if (local != "" && local != "/") {
                        if(!catalog) {
                            output += "<a target=\"browse\" href=\"" + url.url() + local + "\">" + name + "</a>";
                        } else {
                            current = counter;
                            ++counter;
                            KURL u = url;
                            u.setPath(bigpath + local);
                            QString str;
                            output += str.sprintf("%i\n%i\n", parents.top(), current);
                            output += name + "\n" + u.prettyURL() + "\n";
                        }
                        m_bIndex = 1;
                        if (firstPage == "") firstPage = url.url()+QString::fromLocal8Bit(local.latin1());
                    }
                    else if(htmlOutput) output += name;
                } else {
                    if(htmlOutput) output += name;
                }
            }
            if (obj.find(mergeParam) != -1 && htmlOutput) {
                QString link = mergeParam.cap(1);
                QString href = link.left(link.find("::"));
                QString path = m_chmFile.left(m_chmFile.findRev("/") + 1);
                //output += " (<a href=\"" + path + href + "\">link</a>)";
                m_bIndex = 1;
                output += " (<a target=\"browse\" href=\"" + url.url() + path + href + "\">link</a>)";
                if (firstPage == "") firstPage = url.url()+QString::fromLocal8Bit(local.latin1());
            }
        }
        if(htmlOutput) output += s.mid(old);

        //set left pane
        //added by lucida, [email protected]
        QString lframe = QString("</HEAD><FRAMESET COLS=\"25%,*\">\n");
        lframe += "<FRAME NAME=\"index\" src=\"file:"+ fname+"\"" + " marginwidth=\"0\"></FRAME>\n";
        if (!m_bIndex) {
            lframe = "</HEAD><FRAMESET>";
            firstPage = url.url() + QString::fromLocal8Bit(m_strIndex.latin1());
        }
        theData.resetRawData(&m_contents[offset], length);
        //KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( output, path );
        //kdDebug() << "Emitting mimetype " << result->mimeType() << endl;
        //mimeType( result->mimeType() );
        /*        QCString output1 = (QCString)(output.latin1());
                data(output1);
                processedSize(output1.length());*/

        //construct the frame
        //added by lucida [email protected]
        QString framestr = QString("<HTML><HEAD>\n");
        framestr += lframe;
        framestr += "<FRAME NAME=\"browse\" src=\"" + firstPage + "\">\n";
        framestr += "</FRAME>\n";
        framestr += "</FRAMESET></HTML>";
        //write index file
        //added by lucida [email protected]
        *t << QString::fromLocal8Bit(output.latin1()) << endl;

        if(catalog) {
            data(output.local8Bit());
            processedSize(output.length());
        } else {
            data(framestr.local8Bit());
            processedSize(framestr.length());
        }
    } else {
        int offset = m_dirMap[path].offset;
        int length = m_dirMap[path].length;
        totalSize(length);
        theData.setRawData(&m_contents[offset], length);

        KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( theData, path );
        kdDebug() << "Emitting mimetype " << result->mimeType() << endl;
        mimeType( result->mimeType() );
        data(theData);
        theData.resetRawData(&m_contents[offset], length);
        processedSize(length);
    }

    finished();
}
Esempio n. 6
0
bool LDIFConverter::LDIFToAddressee( const QString &str, AddresseeList &addrList, QDateTime dt )
{
  if (str.isEmpty())
     return true;

  bool endldif = false, end = false;
  LDIF ldif;
  LDIF::ParseVal ret;
  const char *latinstr = str.latin1();
  int latinstrlen = qstrlen( latinstr );
  QByteArray data;
  Addressee a;
  Address homeAddr, workAddr;

  data.setRawData( latinstr, latinstrlen );
  ldif.setLDIF( data );
  if (!dt.isValid())
    dt = QDateTime::currentDateTime();
  a.setRevision(dt);
  homeAddr = Address( Address::Home );
  workAddr = Address( Address::Work );

  do {
    ret = ldif.nextItem();
    switch ( ret ) {
      case LDIF::Item: {
        QString fieldname = ldif.attr().lower();
        QString value = QString::fromUtf8( ldif.val(), ldif.val().size() );
        evaluatePair( a, homeAddr, workAddr, fieldname, value );
        break;
      }
      case LDIF::EndEntry:
      // if the new address is not empty, append it
        if ( !a.formattedName().isEmpty() || !a.name().isEmpty() ||
          !a.familyName().isEmpty() ) {
          if ( !homeAddr.isEmpty() )
            a.insertAddress( homeAddr );
          if ( !workAddr.isEmpty() )
            a.insertAddress( workAddr );
          addrList.append( a );
        }
        a = Addressee();
        a.setRevision(dt);
        homeAddr = Address( Address::Home );
        workAddr = Address( Address::Work );
        break;
      case LDIF::MoreData: {
        if ( endldif )
          end = true;
        else {
          ldif.endLDIF();
          endldif = true;
          break;
        }
      }
      default:
        break;
    }
  } while ( !end );

  data.resetRawData( latinstr, latinstrlen );

  return true;
}
Esempio n. 7
0
//===========================================================================
void SMBSlave::get( const KURL& kurl )
{
    char        buf[MAX_XFER_BUF_SIZE];
    int         filefd          = 0;
    ssize_t     bytesread       = 0;
    // time_t      curtime         = 0;
    time_t      lasttime        = 0;
    time_t      starttime       = 0;
    KIO::filesize_t totalbytesread  = 0;
    QByteArray  filedata;
    SMBUrl      url;

    kdDebug(KIO_SMB) << "SMBSlave::get on " << kurl << endl;

    // check (correct) URL
    KURL kvurl = checkURL(kurl);
    // if URL is not valid we have to redirect to correct URL
    if (kvurl != kurl) {
        redirection(kvurl);
        finished();
        return;
    }

    if(!auth_initialize_smbc())
        return;


    // Stat
    url = kurl;
    if(cache_stat(url,&st) == -1 )
    {
        if ( errno == EACCES )
           error( KIO::ERR_ACCESS_DENIED, url.prettyURL());
        else
           error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL());
        return;
    }
    if ( S_ISDIR( st.st_mode ) ) {
        error( KIO::ERR_IS_DIRECTORY, url.prettyURL());
        return;
    }

    // Set the total size
    totalSize( st.st_size );

    // Open and read the file
    filefd = smbc_open(url.toSmbcUrl(),O_RDONLY,0);
    if(filefd >= 0)
    {
        if(buf)
        {
	    bool isFirstPacket = true;
            lasttime = starttime = time(NULL);
            while(1)
            {
                bytesread = smbc_read(filefd, buf, MAX_XFER_BUF_SIZE);
                if(bytesread == 0)
                {
                    // All done reading
                    break;
                }
                else if(bytesread < 0)
                {
                    error( KIO::ERR_COULD_NOT_READ, url.prettyURL());
                    return;
                }

                filedata.setRawData(buf,bytesread);
		if (isFirstPacket)
		{
                    // We need a KMimeType::findByNameAndContent(filename,data)
                    // For now we do: find by extension, and if not found (or extension not reliable)
                    // then find by content.
                    bool accurate = false;
                    KMimeType::Ptr mime = KMimeType::findByURL( kurl, st.st_mode, false, true, &accurate );
                    if ( !mime || mime->name() == KMimeType::defaultMimeType()
                         || !accurate )
                    {
                        KMimeType::Ptr p_mimeType = KMimeType::findByContent(filedata);
                        if ( p_mimeType && p_mimeType->name() != KMimeType::defaultMimeType() )
                            mime = p_mimeType;
                    }
		    mimeType(mime->name());
		    isFirstPacket = false;
		}
                data( filedata );
                filedata.resetRawData(buf,bytesread);

                // increment total bytes read
                totalbytesread += bytesread;

		processedSize(totalbytesread);
            }
        }

        smbc_close(filefd);
        data( QByteArray() );
        processedSize(static_cast<KIO::filesize_t>(st.st_size));

    }
    else
    {
          error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL());
	  return;
    }

    finished();
}
Esempio n. 8
0
void HelpProtocol::get_file(const KURL &url)
{
    kdDebug(7119) << "get_file " << url.url() << endl;

    QCString _path(QFile::encodeName(url.path()));
    struct stat buff;
    if(::stat(_path.data(), &buff) == -1)
    {
        if(errno == EACCES)
            error(KIO::ERR_ACCESS_DENIED, url.path());
        else
            error(KIO::ERR_DOES_NOT_EXIST, url.path());
        return;
    }

    if(S_ISDIR(buff.st_mode))
    {
        error(KIO::ERR_IS_DIRECTORY, url.path());
        return;
    }
    if(S_ISFIFO(buff.st_mode) || S_ISSOCK(buff.st_mode))
    {
        error(KIO::ERR_CANNOT_OPEN_FOR_READING, url.path());
        return;
    }

    int fd = open(_path.data(), O_RDONLY);
    if(fd < 0)
    {
        error(KIO::ERR_CANNOT_OPEN_FOR_READING, url.path());
        return;
    }

    totalSize(buff.st_size);
    int processed_size = 0;

    char buffer[MAX_IPC_SIZE];
    QByteArray array;

    while(1)
    {
        int n = ::read(fd, buffer, MAX_IPC_SIZE);
        if(n == -1)
        {
            if(errno == EINTR)
                continue;
            error(KIO::ERR_COULD_NOT_READ, url.path());
            close(fd);
            return;
        }
        if(n == 0)
            break; // Finished

        array.setRawData(buffer, n);
        data(array);
        array.resetRawData(buffer, n);

        processed_size += n;
        processedSize(processed_size);
    }

    data(QByteArray());

    close(fd);

    processedSize(buff.st_size);

    finished();
}