Ejemplo n.º 1
0
void KIO_Delete::deleteItem( const KornMailId *item, KURL kurl, KIO::MetaData metadata, const KIO_Protocol *& protocol )
{
	KIO::Job* job = 0;

	kurl = dynamic_cast<const KornStringId*>( item )->getId();
	
	protocol->deleteMailKURL( kurl, metadata );
	
	if( kurl.port() == 0 )
		kurl.setPort( protocol->defaultPort( _kio->_ssl ) );
		
	if( protocol->deleteFunction() == KIO_Protocol::get )
	{
		job = KIO::get( kurl, true, false );
		
		if( protocol->connectionBased() )
			KIO::Scheduler::assignJobToSlave( _slave, dynamic_cast< KIO::SimpleJob* >( job ) );
		else
			KIO::Scheduler::scheduleJob( dynamic_cast< KIO::SimpleJob* >( job ) );
	}
	else if( protocol->deleteFunction() == KIO_Protocol::del )
	{
		job = KIO::del( kurl, false, false );
	}
	else
		return; //Unknown deleteFunction
		
	connect( job, SIGNAL( result( KIO::Job* ) ), this, SLOT( slotResult( KIO::Job* ) ) );
		
	job->addMetaData( metadata );
	
	_jobs->append( dynamic_cast< KIO::Job* >( job ) );
}
void FrameFetchContext::upgradeInsecureRequest(FetchRequest& fetchRequest)
{
    KURL url = fetchRequest.resourceRequest().url();

    // Tack an 'Upgrade-Insecure-Requests' header to outgoing navigational requests, as described in
    // https://w3c.github.io/webappsec/specs/upgrade/#feature-detect
    if (fetchRequest.resourceRequest().frameType() != WebURLRequest::FrameTypeNone)
        fetchRequest.mutableResourceRequest().addHTTPHeaderField("Upgrade-Insecure-Requests", "1");

    // If we don't yet have an |m_document| (because we're loading an iframe, for instance), check the FrameLoader's policy.
    WebInsecureRequestPolicy relevantPolicy = m_document ? m_document->getInsecureRequestPolicy() : frame()->loader().getInsecureRequestPolicy();
    SecurityContext::InsecureNavigationsSet* relevantNavigationSet = m_document ? m_document->insecureNavigationsToUpgrade() : frame()->loader().insecureNavigationsToUpgrade();

    if (url.protocolIs("http") && relevantPolicy & kUpgradeInsecureRequests) {
        // We always upgrade requests that meet any of the following criteria:
        //
        // 1. Are for subresources (including nested frames).
        // 2. Are form submissions.
        // 3. Whose hosts are contained in the document's InsecureNavigationSet.
        const ResourceRequest& request = fetchRequest.resourceRequest();
        if (request.frameType() == WebURLRequest::FrameTypeNone
            || request.frameType() == WebURLRequest::FrameTypeNested
            || request.requestContext() == WebURLRequest::RequestContextForm
            || (!url.host().isNull() && relevantNavigationSet->contains(url.host().impl()->hash())))
        {
            UseCounter::count(m_document, UseCounter::UpgradeInsecureRequestsUpgradedRequest);
            url.setProtocol("https");
            if (url.port() == 80)
                url.setPort(443);
            fetchRequest.mutableResourceRequest().setURL(url);
        }
    }
}
void FrameFetchContext::upgradeInsecureRequest(FetchRequest& fetchRequest)
{
    KURL url = fetchRequest.resourceRequest().url();

    // Tack an 'Upgrade-Insecure-Requests' header to outgoing navigational requests, as described in
    // https://w3c.github.io/webappsec/specs/upgrade/#feature-detect
    if (fetchRequest.resourceRequest().frameType() != WebURLRequest::FrameTypeNone)
        fetchRequest.mutableResourceRequest().addHTTPHeaderField("Upgrade-Insecure-Requests", "1");

    if (m_document && m_document->insecureRequestsPolicy() == SecurityContext::InsecureRequestsUpgrade && url.protocolIs("http")) {
        ASSERT(m_document->insecureNavigationsToUpgrade());

        // We always upgrade requests that meet any of the following criteria:
        //
        // 1. Are for subresources (including nested frames).
        // 2. Are form submissions.
        // 3. Whose hosts are contained in the document's InsecureNavigationSet.
        const ResourceRequest& request = fetchRequest.resourceRequest();
        if (request.frameType() == WebURLRequest::FrameTypeNone
            || request.frameType() == WebURLRequest::FrameTypeNested
            || request.requestContext() == WebURLRequest::RequestContextForm
            || (!url.host().isNull() && m_document->insecureNavigationsToUpgrade()->contains(url.host().impl()->hash())))
        {
            UseCounter::count(m_document, UseCounter::UpgradeInsecureRequestsUpgradedRequest);
            url.setProtocol("https");
            if (url.port() == 80)
                url.setPort(443);
            fetchRequest.mutableResourceRequest().setURL(url);
        }
    }
}
IconURL IconController::defaultURL(IconType iconType)
{
    // Don't return a favicon iconURL unless we're http or https
    KURL documentURL = m_frame->document()->url();
    if (!documentURL.protocolIsInHTTPFamily())
        return IconURL();

    KURL url;
    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
    url.setHost(documentURL.host());
    if (documentURL.hasPort())
        url.setPort(documentURL.port());

    if (iconType == Favicon) {
        url.setPath("/favicon.ico");
        return IconURL::defaultIconURL(url, Favicon);
    }
#if ENABLE(TOUCH_ICON_LOADING)
    if (iconType == TouchPrecomposedIcon) {
        url.setPath("/apple-touch-icon-precomposed.png");
        return IconURL::defaultIconURL(url, TouchPrecomposedIcon);
    }
    if (iconType == TouchIcon) {
        url.setPath("/apple-touch-icon.png");
        return IconURL::defaultIconURL(url, TouchIcon);
    }
#endif
    return IconURL();
}
Ejemplo n.º 5
0
    QValueList<Mirror>
  Sites::siteList()
  {
    KURL url;
    url.setProtocol( "http" );
    url.setHost( "freedb.freedb.org" );
    url.setPort( 80 );
    url.setPath( "/~cddb/cddb.cgi" );

    url.setQuery( QString::null );

    QString hello = QString("%1 %2 %3 %4")
        .arg(user_, localHostName_, clientName(), clientVersion());

    url.addQueryItem( "cmd", "sites" );
    url.addQueryItem( "hello", hello );
    url.addQueryItem( "proto", "5" );

    QValueList<Mirror> result;

    QString tmpFile;
    if( KIO::NetAccess::download( url, tmpFile, 0 ) )
    {
      result = readFile( tmpFile );
      KIO::NetAccess::removeTempFile( tmpFile );
    }

    return result;
  }
Ejemplo n.º 6
0
void Location::setPort(LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow, const String& portString)
{
    if (!m_frame)
        return;
    KURL url = m_frame->document()->url();
    url.setPort(portString);
    setLocation(url.string(), callingWindow, enteredWindow);
}
Ejemplo n.º 7
0
KURL SiteSettings::effectiveURL() const
{
  KURL url = KURL::fromPathOrURL(mUrl);
  if(url.port() == 0) {
    url.setPort(80);
  }
  return url;
}
Ejemplo n.º 8
0
KURL Proxy::realStreamUrl( KURL fakeStream, int sessionId )
{
    KURL realStream;
    realStream.setProtocol( "http" );
    realStream.setHost(fakeStream.host());
    realStream.setPort(fakeStream.port());
    realStream.setPath( "/databases" + fakeStream.directory() + "/items/" + fakeStream.fileName() );
    realStream.setQuery( QString("?session-id=") + QString::number(sessionId) );
    return realStream;
}
Ejemplo n.º 9
0
KURL NetworkAccount::getUrl() const
{
    KURL url;
    url.setProtocol(protocol());
    url.setUser(login());
    url.setPass(passwd());
    url.setHost(host());
    url.setPort(port());
    return url;
}
Ejemplo n.º 10
0
void KMWIpp::updatePrinter(KMPrinter *p)
{
	KURL	url;
	url.setProtocol("ipp");
	url.setHost(text(0));
	url.setPort(text(1).toInt());
	if (!p->option("kde-login").isEmpty()) url.setUser(p->option("kde-login"));
	if (!p->option("kde-password").isEmpty()) url.setPass(p->option("kde-password"));
	p->setDevice(url.url());
}
Ejemplo n.º 11
0
void Location::setPort(const String& portString, DOMWindow* activeWindow, DOMWindow* firstWindow)
{
    if (!m_frame)
        return;
    KURL url = m_frame->document()->url();
    int port = portString.toInt();
    if (port < 0 || port > 0xFFFF || portString.isEmpty())
        url.removePort();
    else
        url.setPort(port);
    setLocation(url.string(), activeWindow, firstWindow);
}
Ejemplo n.º 12
0
void KNNetAccess::startJobSmtp()
{
    if(smtpJobQueue.isEmpty())
        return;

    currentSmtpJob = smtpJobQueue.first();
    smtpJobQueue.remove(smtpJobQueue.begin());
    currentSmtpJob->prepareForExecution();
    if(currentSmtpJob->success())
    {
        KNLocalArticle *art = static_cast<KNLocalArticle *>(currentSmtpJob->data());
        // create url query part
        QString query("headers=0&from=");
        query += KURL::encode_string(art->from()->email());
        QStrList emails;
        art->to()->emails(&emails);
        for(char *e = emails.first(); e; e = emails.next())
        {
            query += "&to=" + KURL::encode_string(e);
        }
        // create url
        KURL destination;
        KNServerInfo *account = currentSmtpJob->account();
        if(account->encryption() == KNServerInfo::SSL)
            destination.setProtocol("smtps");
        else
            destination.setProtocol("smtp");
        destination.setHost(account->server());
        destination.setPort(account->port());
        destination.setQuery(query);
        if(account->needsLogon())
        {
            destination.setUser(account->user());
            destination.setPass(account->pass());
        }
        KIO::Job *job = KIO::storedPut(art->encodedContent(true), destination, -1, false, false, false);
        connect(job, SIGNAL(result(KIO::Job *)),
                SLOT(slotJobResult(KIO::Job *)));
        if(account->encryption() == KNServerInfo::TLS)
            job->addMetaData("tls", "on");
        else
            job->addMetaData("tls", "off");
        currentSmtpJob->setJob(job);

        kdDebug(5003) << "KNNetAccess::startJobSmtp(): job started" << endl;
    }
    else
    {
        threadDoneSmtp();
    }
}
Ejemplo n.º 13
0
IconURL IconURL::defaultFavicon(const KURL& documentURL) {
  DCHECK(documentURL.protocolIsInHTTPFamily());
  KURL url;
  bool couldSetProtocol = url.setProtocol(documentURL.protocol());
  DCHECK(couldSetProtocol);
  url.setHost(documentURL.host());
  if (documentURL.hasPort())
    url.setPort(documentURL.port());
  url.setPath("/favicon.ico");

  IconURL result(url, Vector<IntSize>(), emptyString(), Favicon);
  result.m_isDefaultIcon = true;
  return result;
}
Ejemplo n.º 14
0
KURL Settings::accountUrl() const
{
    KConfig config("scalixadminrc");
    KConfigGroup group(&config, "Account");

    KURL url;
    url.setProtocol(group.readBoolEntry("use-ssl") ? "imaps" : "imap");
    url.setUser(group.readEntry("user"));
    url.setPass(KStringHandler::obscure(group.readEntry("pass")));
    url.setHost(group.readEntry("host"));
    url.setPort(group.readNumEntry("port"));

    return url;
}
Ejemplo n.º 15
0
void JSLocation::setPort(ExecState* exec, JSValue value)
{
    Frame* frame = impl()->frame();
    ASSERT(frame);

    KURL url = frame->loader()->url();
    // FIXME: Could make this a little less ugly if String provided a toUnsignedShort function.
    const UString& portString = value.toString(exec);
    int port = charactersToInt(portString.data(), portString.size());
    if (port < 0 || port > 0xFFFF)
        port = 0;
    url.setPort(port);

    navigateIfAllowed(exec, frame, url, !frame->script()->anyPageIsProcessingUserGesture(), false);
}
Ejemplo n.º 16
0
void V8Location::portAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    INC_STATS("DOM.Location.port._set");
    v8::Handle<v8::Object> holder = info.Holder();
    Location* imp = V8Location::toNative(holder);
    String port = toWebCoreString(value);

    Frame* frame = imp->frame();
    if (!frame)
        return;

    KURL url = frame->loader()->url();
    url.setPort(port.toUInt());

    navigateIfAllowed(frame, url, false, false);
}
Ejemplo n.º 17
0
bool KIO_Delete::setupSlave( KURL kurl, KIO::MetaData metadata, const KIO_Protocol *& protocol )
{
	protocol->deleteMailConnectKURL( kurl, metadata );
	
	if( kurl.port() == 0 )
		kurl.setPort( protocol->defaultPort( _kio->_ssl ) );
		
	if( ! ( _slave = KIO::Scheduler::getConnectedSlave( kurl, metadata ) ) )
	{
		kdWarning() << i18n( "Could not get a connected slave; I cannot delete this way..." ) << endl;
		_valid = false;
		return false;
	}

	return true;
}
Ejemplo n.º 18
0
void HTMLAnchorElement::setPort(const String& value)
{
    KURL url = href();
    if (!url.canSetHostOrPort())
        return;

    // http://dev.w3.org/html5/spec/infrastructure.html#url-decomposition-idl-attributes
    // specifically goes against RFC 3986 (p3.2) and
    // requires setting the port to "0" if it is set to empty string.
    unsigned port = value.toUInt();
    if (isDefaultPortForProtocol(port, url.protocol()))
        url.removePort();
    else
        url.setPort(port);

    setHref(url.string());
}
Ejemplo n.º 19
0
bool LprHandler::completePrinter(KMPrinter *prt, PrintcapEntry *entry, bool)
{
	prt->setDescription(i18n("Unknown (unrecognized entry)"));
	QString val = entry->field("lp");
	KURL uri;
	if (!val.isEmpty() && val != "/dev/null")
	{
		int	p = val.find('@');
		if (p != -1)
		{
			prt->setLocation(i18n("Remote queue (%1) on %2").arg(val.left(p)).arg(val.mid(p+1)));
			uri.setProtocol("lpd");
			uri.setHost(val.mid(p+1));
			uri.setPath("/" + val.left(p));
		}
		else if ((p = val.find('%')) != -1)
		{
			prt->setLocation(i18n("Network printer (%1)").arg("socket"));
			uri.setProtocol("socket");
			uri.setHost(val.left(p));
			uri.setPort(val.mid(p+1).toInt());
		}
		else
		{
			prt->setLocation(i18n("Local printer on %1").arg(val));
			uri.setProtocol("parallel");
			uri.setPath(val);
		}
	}
	else if (!(val = entry->field("rp")).isEmpty())
	{
		QString rm = entry->has("rm") ?
				entry->field("rm") :
				LprSettings::self()->defaultRemoteHost();
		prt->setLocation(i18n("Remote queue (%1) on %2").arg(val).arg(rm));
		uri.setProtocol("lpd");
		uri.setHost(rm);
		uri.setPath("/" + val);
	}
	else
		prt->setLocation(i18n("Unknown (unrecognized entry)"));
	prt->setDevice(uri.url());
	return true;
}
Ejemplo n.º 20
0
void ProjectNewGeneral::slotLinePrjFile( const QString & )
{

  bool valid = !(linePrjFile->text().isEmpty() ||
                 linePrjName->text().isEmpty() ||
                 linePrjDir ->text().isEmpty() ||
                 linePrjTmpl->text().isEmpty() ||
                 linePrjToolbar->text().isEmpty());
  KURL url;
  QString s = lineHost->text();
  if (! s.isEmpty())
    url.setHost(s);

  s = lineUser->text();
  if (! s.isEmpty())
    url.setUser(s);
  s = linePasswd->text();
  if (! s.isEmpty())
    url.setPass(s);

  s = linePort->text();
  if (! s.isEmpty())
    url.setPort(linePort->text().toInt());

  url.setProtocol(comboProtocol->currentText());
  if (url.protocol() == i18n("Local")) url.setProtocol("file");
  url.setPath(linePrjDir->text());
  url.adjustPath(1);
  if (!url.path().startsWith("/")) url.setPath("/"+url.path());

  if (url.isValid())
  {
    emit setBaseURL(url);
    baseUrl = url;
    if (baseUrl.isLocalFile())
    {
      s = QExtFileInfo::canonicalPath(baseUrl.path());
      if (!s.isEmpty())
        baseUrl.setPath(s);
    }
  }
  emit enableNextButton( this, valid );
}
Ejemplo n.º 21
0
/*
 * Some protocols needs to a command to commit protocols.
 */
void KIO_Delete::commitDelete( KURL kurl, KIO::MetaData metadata, const KIO_Protocol *& protocol )
{
	protocol->deleteCommitKURL( kurl, metadata );
	
	if( kurl.port() == 0 )
		kurl.setPort( protocol->defaultPort( _kio->_ssl ) );
	
	KIO::TransferJob *job = KIO::get( kurl, true, false );
	job->addMetaData( metadata );
	connect( job, SIGNAL( result( KIO::Job* ) ), this, SLOT( slotResult( KIO::Job* ) ) );
	
	_jobs->append( dynamic_cast< KIO::Job* >( job ) );
	
	if( protocol->connectionBased() )
		KIO::Scheduler::assignJobToSlave( _slave, job );
	else
		KIO::Scheduler::scheduleJob( job );

	_total++;
}
Ejemplo n.º 22
0
IconURL IconController::defaultURL(IconType iconType)
{
    // Don't return a favicon iconURL unless we're http or https
    KURL documentURL = m_frame->document()->url();
    if (!documentURL.protocolIsInHTTPFamily())
        return IconURL();

    KURL url;
    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
    url.setHost(documentURL.host());
    if (documentURL.hasPort())
        url.setPort(documentURL.port());

    if (iconType == Favicon) {
        url.setPath("/favicon.ico");
        return IconURL::defaultIconURL(url, Favicon);
    }
    return IconURL();
}
Ejemplo n.º 23
0
// WebKit will make empty URLs and set components on them. kurl doesn't allow
// replacements on invalid URLs, but here we do.
TEST(KURLTest, ReplaceInvalid)
{
    KURL kurl;

    EXPECT_FALSE(kurl.isValid());
    EXPECT_TRUE(kurl.isEmpty());
    EXPECT_STREQ("", kurl.string().utf8().data());

    kurl.setProtocol("http");
    // GKURL will say that a URL with just a scheme is invalid, KURL will not.
    EXPECT_FALSE(kurl.isValid());
    EXPECT_FALSE(kurl.isEmpty());
    // At this point, we do things slightly differently if there is only a scheme.
    // We check the results here to make it more obvious what is going on, but it
    // shouldn't be a big deal if these change.
    EXPECT_STREQ("http:", kurl.string().utf8().data());

    kurl.setHost("www.google.com");
    EXPECT_TRUE(kurl.isValid());
    EXPECT_FALSE(kurl.isEmpty());
    EXPECT_STREQ("http://www.google.com/", kurl.string().utf8().data());

    kurl.setPort(8000);
    EXPECT_TRUE(kurl.isValid());
    EXPECT_FALSE(kurl.isEmpty());
    EXPECT_STREQ("http://www.google.com:8000/", kurl.string().utf8().data());

    kurl.setPath("/favicon.ico");
    EXPECT_TRUE(kurl.isValid());
    EXPECT_FALSE(kurl.isEmpty());
    EXPECT_STREQ("http://www.google.com:8000/favicon.ico", kurl.string().utf8().data());

    // Now let's test that giving an invalid replacement fails. Invalid
    // protocols fail without modifying the URL, which should remain valid.
    EXPECT_FALSE(kurl.setProtocol("f/sj#@"));
    EXPECT_TRUE(kurl.isValid());
}
static KURL findUrlForAccount(const KMail::ImapAccountBase *a)
{
    assert(a);
    const KMail::SieveConfig sieve = a->sieveConfig();
    if(!sieve.managesieveSupported())
        return KURL();
    if(sieve.reuseConfig())
    {
        // assemble Sieve url from the settings of the account:
        KURL u;
        u.setProtocol("sieve");
        u.setHost(a->host());
        u.setUser(a->login());
        u.setPass(a->passwd());
        u.setPort(sieve.port());
        // Translate IMAP LOGIN to PLAIN:
        u.setQuery("x-mech=" + (a->auth() == "*" ? "PLAIN" : a->auth()));
        return u;
    }
    else
    {
        return sieve.alternateURL();
    }
}
Ejemplo n.º 25
0
const KURL PublicService::toInvitation(const QString &host)
{
    KURL url;
    url.setProtocol("invitation");
    if(host.isEmpty())
    { // select best address
        unsigned long s_address = publicIP();
        if(!s_address)
            return KURL();
        KNetwork::KIpAddress addr(s_address);
        url.setHost(addr.toString());
    }
    else
        url.setHost(host);
    // FIXME: if there is no public interface, select any non-loopback
    url.setPort(m_port);
    url.setPath("/" + m_type + "/" + KURL::encode_string(m_serviceName));
    QString query;
    QMap< QString, QString >::ConstIterator itEnd = m_textData.end();
    for(QMap< QString, QString >::ConstIterator it = m_textData.begin(); it != itEnd; ++it)
        url.addQueryItem(it.key(), it.data());
    ;
    return url;
}
Ejemplo n.º 26
0
void KManualProxyDlg::setProxyData( const KProxyData &data )
{
    KURL url;
        
    // Set the HTTP proxy...
    if (!isValidURL(data.proxyList["http"], &url))
        mDlg->sbHttp->setValue( DEFAULT_PROXY_PORT );
    else
    {
        int port = url.port();
        if ( port <= 0 )
            port = DEFAULT_PROXY_PORT;
            
        url.setPort( 0 );
        mDlg->leHttp->setText( url.url() );
        mDlg->sbHttp->setValue( port );
    }

    bool useSameProxy = (!mDlg->leHttp->text().isEmpty () &&
                         data.proxyList["http"] == data.proxyList["https"] &&
                         data.proxyList["http"] == data.proxyList["ftp"]);

    mDlg->cbSameProxy->setChecked ( useSameProxy );

    if ( useSameProxy )
    {
      mDlg->leHttps->setText ( mDlg->leHttp->text() );
      mDlg->leFtp->setText ( mDlg->leHttp->text() );
      mDlg->sbHttps->setValue( mDlg->sbHttp->value() );
      mDlg->sbFtp->setValue( mDlg->sbHttp->value() );

      sameProxy ( true );
    }
    else
    {
      // Set the HTTPS proxy...
      if( !isValidURL( data.proxyList["https"], &url ) )
          mDlg->sbHttps->setValue( DEFAULT_PROXY_PORT );
      else
      {
          int port = url.port();
          if ( port <= 0 )
              port = DEFAULT_PROXY_PORT;

          url.setPort( 0 );
          mDlg->leHttps->setText( url.url() );
          mDlg->sbHttps->setValue( port );
      }

      // Set the FTP proxy...
      if( !isValidURL( data.proxyList["ftp"], &url ) )
          mDlg->sbFtp->setValue( DEFAULT_PROXY_PORT );
      else
      {
          int port = url.port();
          if ( port <= 0 )
              port = DEFAULT_PROXY_PORT;

          url.setPort( 0 );
          mDlg->leFtp->setText( url.url() );
          mDlg->sbFtp->setValue( port );
      }
    }

    QStringList::ConstIterator it = data.noProxyFor.begin();
    for( ; it != data.noProxyFor.end(); ++it )
    {
      // "no_proxy" is a keyword used by the environment variable
      // based configuration. We ignore it here as it is not applicable...
      if ((*it).lower() != "no_proxy" && !(*it).isEmpty())
      {
        // Validate the NOPROXYFOR entries and use only hostnames if the entry is 
        // a valid or legitimate URL. NOTE: needed to catch manual manipulation
        // of the proxy config files...
        if( isValidURL( *it ) || ((*it).length() >= 3 && (*it).startsWith(".")) )
          mDlg->lbExceptions->insertItem( *it );
      }
    }

    mDlg->cbReverseProxy->setChecked( data.useReverseProxy );
}
Ejemplo n.º 27
0
void LDAPProtocol::openConnection()
{
  if ( mLDAP ) return;

  int version,ret;

  version = ( mVer == 2 ) ? LDAP_VERSION2 : LDAP_VERSION3;

  KURL Url;
  Url.setProtocol( mProtocol );
  Url.setHost( mHost );
  Url.setPort( mPort );

  AuthInfo info;
  fillAuthInfo( info );
///////////////////////////////////////////////////////////////////////////
  kdDebug(7125) << "OpenConnection to " << mHost << ":" << mPort << endl;

  ret = ldap_initialize( &mLDAP, Url.htmlURL().utf8() );
  if ( ret != LDAP_SUCCESS ) {
    LDAPErr( Url, ret );
    return;
  }

  if ( (ldap_set_option( mLDAP, LDAP_OPT_PROTOCOL_VERSION, &version )) !=
    LDAP_OPT_SUCCESS ) {

    closeConnection();
    error( ERR_UNSUPPORTED_ACTION,
      i18n("Cannot set LDAP protocol version %1").arg(version) );
    return;
  }

  if ( mTLS ) {
    kdDebug(7125) << "start TLS" << endl;
    if ( ( ret = ldap_start_tls_s( mLDAP, NULL, NULL ) ) != LDAP_SUCCESS ) {
      LDAPErr( Url );
      return;
    }
  }

  if ( mSizeLimit ) {
    kdDebug(7125) << "sizelimit: " << mSizeLimit << endl;
    if ( ldap_set_option( mLDAP, LDAP_OPT_SIZELIMIT, &mSizeLimit ) != LDAP_SUCCESS ) {
      closeConnection();
      error( ERR_UNSUPPORTED_ACTION, 
        i18n("Cannot set size limit."));
      return;
    }
  }

  if ( mTimeLimit ) {
    kdDebug(7125) << "timelimit: " << mTimeLimit << endl;
    if ( ldap_set_option( mLDAP, LDAP_OPT_TIMELIMIT, &mTimeLimit ) != LDAP_SUCCESS ) {
      closeConnection();
      error( ERR_UNSUPPORTED_ACTION, 
        i18n("Cannot set time limit."));
      return;
    }
  }

#if !defined HAVE_SASL_H && !defined HAVE_SASL_SASL_H
  if ( mAuthSASL ) {
    closeConnection();
    error( ERR_SLAVE_DEFINED, 
      i18n("SASL authentication not compiled into the ldap ioslave.") );
    return;
  }
#endif

  bool auth = false;
  TQString mechanism = mMech.isEmpty() ? "DIGEST-MD5" : mMech;
  mFirstAuth = true; mCancel = false;

  const bool cached = checkCachedAuthentication( info );

  ret = LDAP_SUCCESS;
  while (!auth) {
    if ( !mAuthSASL && (
      ( mFirstAuth && 
      !( mBindName.isEmpty() && mPassword.isEmpty() ) && //For anonymous bind
       ( mBindName.isEmpty() || mPassword.isEmpty() ) ) || !mFirstAuth ) )
    {
      if ( ( mFirstAuth && cached ) ||
           ( mFirstAuth ?
             openPassDlg( info ) :
             openPassDlg( info, i18n("Invalid authorization information.") ) ) ) {

        mBindName = info.username;
        mPassword = info.password;
      } else {
        kdDebug(7125) << "Dialog cancelled!" << endl;
        error( ERR_USER_CANCELED, TQString::null );
        closeConnection();
        return;
      }
    }
    kdDebug(7125) << "user: "******" bindname: " << mBindName << endl;
    ret = 
#if defined HAVE_SASL_H || defined HAVE_SASL_SASL_H
      mAuthSASL ? 
        ldap_sasl_interactive_bind_s( mLDAP, NULL, mechanism.utf8(), 
          NULL, NULL, LDAP_SASL_INTERACTIVE, &kldap_sasl_interact, this ) :
#endif          
        ldap_simple_bind_s( mLDAP, mBindName.utf8(), mPassword.utf8() );
    
    mFirstAuth = false;
    if ( ret != LDAP_INVALID_CREDENTIALS && 
         ret != LDAP_INSUFFICIENT_ACCESS &&
         ret != LDAP_INAPPROPRIATE_AUTH ) {
      kdDebug(7125) << "ldap_bind retval: " << ret << endl;
      auth = true;
      if ( ret != LDAP_SUCCESS ) {
        if ( mCancel )
          error( ERR_USER_CANCELED, TQString::null );
        else
          LDAPErr( Url );
        closeConnection();
        return;
      }
    }
  }

  kdDebug(7125) << "connected!" << endl;
  connected();
}
Ejemplo n.º 28
0
void Project::slotRemove(const KURL& urlToRemove)
{
  emit statusMsg(i18n("Removing files..."));
  progressBar->setTotalSteps(d->m_projectFiles.count());
  progressBar->setValue(0);
  progressBar->setTextEnabled(true);

  KURL url;
  bool isFolder = d->m_projectFiles.isFolder(urlToRemove);
  ProjectList projectFiles = d->m_projectFiles;
  ProjectList::Iterator it(projectFiles);
  for ( ; it.current(); ++it)
  {
    url = *(it.current());
    if (urlToRemove == url || (isFolder && urlToRemove.isParentOf(url)) )
    {
      d->m_projectFiles.removeFromListAndXML(url);
      d->m_modified = true;
      emit eventHappened("after_project_remove", url.url(), QString::null);
      if (!isFolder)
        break;
    }
    progressBar->advance(1);
  }

  progressBar->setTotalSteps(1);
  progressBar->setValue(0);
  progressBar->setTextEnabled(false);

  emit statusMsg(QString::null);

  if (d->m_modified)
    setModified();  // there happens more than setting the flag !
  emit reloadTree( &(d->m_projectFiles), false, QStringList() );
  emit newStatus();

  QString urlPath = QExtFileInfo::toRelative(urlToRemove, d->baseURL).path();
  QString nice = urlPath;
  nice = KStringHandler::lsqueeze(nice, 60);
  if (KMessageBox::warningContinueCancel(d->m_mainWindow, i18n("<qt>Do you want to remove <br><b>%1</b><br> from the server(s) as well?</qt>").arg(nice), i18n("Remove From Server"), KStdGuiItem::remove(), "RemoveFromServer") == KMessageBox::Continue )
  {
    QDomNode profilesNode = d->m_sessionDom.firstChild().firstChild().namedItem("uploadprofiles");
    QDomNodeList profileList = profilesNode.toElement().elementsByTagName("profile");
    QDomElement e;
    QString s;
    for (uint i = 0; i < profileList.count(); i++)
    {
      e = profileList.item(i).toElement();
      QString path = e.attribute("remote_path","");
      if (!path.startsWith("/"))
        path.prepend("/");
      KURL baseUrl;
      baseUrl.setProtocol(e.attribute("remote_protocol","ftp"));
      baseUrl.setPort(e.attribute("remote_port","").toInt());
      baseUrl.setHost(e.attribute("remote_host",""));
      baseUrl.setPath(path);
      baseUrl.setUser(e.attribute("user",""));
      QString passwd = password(e.attribute("remote_protocol") + "://" + e.attribute("user") + "@" + e.attribute("remote_host"));
      baseUrl.setPass(passwd);
      baseUrl.addPath(urlPath);
      KIO::NetAccess::del(baseUrl, d->m_mainWindow);
    }
  }
}
Ejemplo n.º 29
0
void EMailThread::send() {
  QStringList listTo;
  QString mQuery;
  KIO::MetaData slaveConfig;
  KURL destination;
  int i, count;

  _sendOk = false;

  KIO::Scheduler::connect(SIGNAL(slaveError(KIO::Slave *, int, const QString &)), this,
                            SLOT(slaveError(KIO::Slave *, int, const QString &)));

  _strBody.insert( 0, QString("Subject:%1\n\n").arg(_strSubject).latin1());
  _strBody.insert( 0, QString("To:%1\n").arg(_strTo).latin1());

  _bodyOffset = 0;
  _bodyLength = _strBody.length();

  mQuery  = "headers=0&from=";
  mQuery += KURL::encode_string(_strFrom);
  listTo = QStringList::split(QRegExp("[ ,;]"), _strTo);
  count = listTo.count();
  if (count > 0) {
    for (i=0; i<count; i++) {
      mQuery += "&to=";
      mQuery += KURL::encode_string(listTo[i]);
    }
  } else {
    mQuery += "&to=";
    mQuery += KURL::encode_string(_strTo);
  }

  mQuery += "&size=";
  mQuery += QString::number(_bodyLength);

  if (_encryption == EMailEncryptionSSL) {
    destination.setProtocol("smtps");
  } else {
    destination.setProtocol("smtp");
  }
  destination.setHost(_strSMTPServer);
  destination.setPort((short)_iPort);
  destination.setPath("/send");
  destination.setQuery(mQuery);

  if (_useAuthentication) {
    destination.setUser(_strUsername);
    destination.setPass(_strPassword);
  }

  if (_encryption == EMailEncryptionTLS) {
    slaveConfig.insert("tls", "on");
  } else {
    slaveConfig.insert("tls", "off");
  }
  if (_useAuthentication) {
    switch (_authentication) {
      case EMailAuthenticationPLAIN:
        slaveConfig.insert("sasl", "PLAIN");
        break;
      case EMailAuthenticationLOGIN:
        slaveConfig.insert("sasl", "LOGIN");
        break;
      case EMailAuthenticationCRAMMD5:
        slaveConfig.insert("sasl", "CRAM-MD5");
        break;
      case EMailAuthenticationDIGESTMD5:
        slaveConfig.insert("sasl", "DIGEST-MD5");
        break;
      default:
        slaveConfig.insert("sasl", "PLAIN");
        break;
    }
  }
  _slave = KIO::Scheduler::getConnectedSlave(destination, slaveConfig);
  if (_slave) {
    _job = KIO::put(destination, -1, false, false, false);
    if (_job) {
      _job->addMetaData("lf2crlf+dotstuff", "slave");
      connect(_job, SIGNAL(result(KIO::Job *)), this, SLOT(result(KIO::Job *)));
      connect(_job, SIGNAL(dataReq(KIO::Job *, QByteArray &)), this, SLOT(dataReq(KIO::Job *, QByteArray &)));
      KIO::Scheduler::assignJobToSlave(_slave, _job);
      _sendOk = true;
    }
  }
}
void ElogThreadSubmit::doTransmit( ) {
  KURL destination;
  QStringList::iterator it;
  QStringList	strListAttributes;
  QStringList	strListAttribute;
  QString boundary;
  int iAttachment = 0;

  destination.setProtocol("http");
  destination.setHost(_elog->configuration()->ipAddress());
  destination.setPort((short)_elog->configuration()->portNumber());
  destination.setQuery("");
  if (!_strLogbook.isEmpty()) {
    destination.setPath(QString("/%1/").arg(_strLogbook));
  }

  srand((unsigned) time(NULL));
  boundary = QString("---------------------------%1%2%3").arg(rand(), 4, 16).arg(rand(), 4, 16).arg(rand(), 4, 16);

  //
  // add the attributes...
  //
  addAttribute( _dataStreamAll, boundary, "cmd", "Submit", false );
  addAttribute( _dataStreamAll, boundary, "unm", _strUserName, false );
  addAttribute( _dataStreamAll, boundary, "upwd", _strUserPassword, true );
  addAttribute( _dataStreamAll, boundary, "exp", _strLogbook, false );

  strListAttributes = QStringList::split( '\n', _strAttributes, FALSE );
  for ( it = strListAttributes.begin(); it != strListAttributes.end(); ++it ) {
    strListAttribute = QStringList::split( '=', *it, FALSE );
    if( strListAttribute.count() == 2 ) {
      addAttribute( _dataStreamAll, boundary,
                    strListAttribute.first().stripWhiteSpace(),
                    strListAttribute.last().stripWhiteSpace(), false );
    }
  }

  if( _bSubmitAsHTML ) {
    addAttribute( _dataStreamAll, boundary, "html", "1", false );
  }
  if( _bSuppressEmail ) {
    addAttribute( _dataStreamAll, boundary, "suppress", "1", false );
  }

  addAttribute( _dataStreamAll, boundary, "Text", _strMessage, false );
  QString str = QString("%1\r\n").arg(boundary);
  _dataStreamAll.writeRawBytes(str.ascii(), str.length());

  //
  // add the attachments...
  //
  if( _bIncludeCapture ) {
    iAttachment++;
    addAttachment( _dataStreamAll, boundary, _byteArrayCapture, iAttachment, "Capture.png" );
  }
  if( _bIncludeConfiguration ) {
    QByteArray byteArrayConfigure;
    QTextStream textStreamConfigure( byteArrayConfigure, IO_ReadWrite );
    QCustomEvent eventConfigure(KstELOGConfigureEvent);

    eventConfigure.setData( &textStreamConfigure );
    QApplication::sendEvent( (QObject*)_elog->app(), (QEvent*)&eventConfigure );
    iAttachment++;
    addAttachment( _dataStreamAll, boundary, byteArrayConfigure, iAttachment, "Configure.kst" );
  }
  if( _bIncludeDebugInfo ) {
    QByteArray byteArrayDebugInfo;
    QTextStream textStreamDebugInfo( byteArrayDebugInfo, IO_ReadWrite );
    QCustomEvent eventDebugInfo(KstELOGDebugInfoEvent);

    eventDebugInfo.setData( &textStreamDebugInfo );
    QApplication::sendEvent( (QObject*)_elog->app(), (QEvent*)&eventDebugInfo );
    iAttachment++;
    addAttachment( _dataStreamAll, boundary, byteArrayDebugInfo, iAttachment, "DebugInfo.txt" );
  }

  _job = KIO::http_post(destination, _byteArrayAll, false);
  if (_job) {
    _job->addMetaData("content-type", QString("multipart/form-data; boundary=%1").arg(boundary));
    if (!_strWritePassword.isEmpty()) {
      QCString enc = KCodecs::base64Encode(_strWritePassword.ascii());

      _job->addMetaData("cookies", "manual");
      _job->addMetaData("setcookies", QString("Cookie: wpwd=%1").arg(enc.data()));
    }

    QObject::connect(_job, SIGNAL(result(KIO::Job*)), this, SLOT(result(KIO::Job*)));
    QObject::connect(_job, SIGNAL(dataReq(KIO::Job*, QByteArray&)), this, SLOT(dataReq(KIO::Job*, QByteArray&)));
    QObject::connect(_job, SIGNAL(data(KIO::Job*, const QByteArray&)), this, SLOT(data(KIO::Job*, const QByteArray&)));

    KIO::Scheduler::scheduleJob(_job);
  } else {