Beispiel #1
0
void BrisaEventProxy::renew(const int &newTimeout) {
    QHttpRequestHeader *renewReq = getRenewRequest(newTimeout);
    http->setHost(host, port);
    requestId = http->request(*renewReq);
    qDebug() << requestId << " renew: " << renewReq->toString();
    delete renewReq;
}
void MusicBrainzDownloader::loadNextPage()
{
LAST_STEP("MusicBrainzDownloader::loadNextPage");
    CB_ASSERT (!m_pQHttp->hasPendingRequests());
    CB_ASSERT (!m_pImageQHttp->hasPendingRequests());

    ++m_nLastLoadedPage;
    CB_ASSERT (m_nLastLoadedPage <= m_nTotalPages - 1);

    //m_eState = NEXT;
    setWaiting(SEARCH);
    //char a [20];
    //sprintf(a, "&page=%d", m_nLastLoadedPage + 1);
    //string s (m_strQuery + a);

    QHttpRequestHeader header ("GET", convStr(m_strQuery));
    //header.setValue("Host", "www.musicbrainz.org");
    header.setValue("Host", "musicbrainz.org");
    //header.setValue("Accept-Encoding", "gzip");
    delay();
    //qDebug("--------------\npath %s", header.path().toUtf8().constData());
    //qDebug("qry %s", m_strQuery.c_str());
    m_pQHttp->request(header);
    //cout << "sent search " << m_pQHttp->request(header) << " for page " << (m_nLastLoadedPage + 1) << endl;
}
Beispiel #3
0
void Translator::translate(const QString &text, const QString &language, QObject *sender) {
	qDebug() << "Translator::translate() " + text;

	Configuration *config = Configuration::getInstance();

	QUrl translatorUrl("http://ajax.googleapis.com/ajax/services/language/translate");
	QString request = "?v=1.0&q=" + QUrl::toPercentEncoding(text) + "&format=html&langpair=%7C" + language;

	QHttpRequestHeader header;
	header.setRequest("GET", translatorUrl.path() + request);
	header.setValue("Host", translatorUrl.host());
	header.setValue("Referer", "Qwit");

	if (config->useProxy) {
		http->setProxy(config->proxyAddress, config->proxyPort, config->proxyUsername, config->proxyPassword);
	} else {
		http->setProxy(QNetworkProxy(QNetworkProxy::NoProxy));
	}

	if(translatorUrl.toString().indexOf("https") == 0) {
		http->setHost(translatorUrl.host(), QHttp::ConnectionModeHttps, translatorUrl.port(443));
	} else {
		http->setHost(translatorUrl.host(), QHttp::ConnectionModeHttp, translatorUrl.port(80));
	}

	buffer = new QBuffer(this);
	buffer->open(QIODevice::WriteOnly);
	int requestId = http->request(header, 0, buffer);
	requestSender[requestId] = sender;
}
Beispiel #4
0
void BrisaEventProxy::unsubscribe(void) {
    QHttpRequestHeader *unsubscribeReq = getUnsubscriptionRequest();
    http->setHost(host, port);
    int unsubId = http->request(*unsubscribeReq);
    qDebug() << unsubId << " unsubscription: " << unsubscribeReq->toString();
    delete unsubscribeReq;
}
Beispiel #5
0
/*!
  Loads a network request, \a req, into this frame.

  \note The view remains the same until enough data has arrived to display the new url.
*/
void QWebFrame::load(const QWebNetworkRequest &req)
{
    if (d->parentFrame())
        d->page->d->insideOpenCall = true;

    QUrl url = ensureAbsoluteUrl(req.url());
    QHttpRequestHeader httpHeader = req.httpHeader();
    QByteArray postData = req.postData();

    WebCore::ResourceRequest request(url);

    QString method = httpHeader.method();
    if (!method.isEmpty())
        request.setHTTPMethod(method);

    QList<QPair<QString, QString> > values = httpHeader.values();
    for (int i = 0; i < values.size(); ++i) {
        const QPair<QString, QString> &val = values.at(i);
        request.addHTTPHeaderField(val.first, val.second);
    }

    if (!postData.isEmpty())
        request.setHTTPBody(WebCore::FormData::create(postData.constData(), postData.size()));

    d->frame->loader()->load(request, false);

    if (d->parentFrame())
        d->page->d->insideOpenCall = false;
}
Beispiel #6
0
void BrisaEventProxy::subscribe(const int timeout) {
    QHttpRequestHeader *subscribeReq = getSubscriptionRequest(timeout);
    http->setHost(host, port);
    requestId = http->request(*subscribeReq);
    qDebug() << requestId << " subscription: " << subscribeReq->toString();
    delete subscribeReq;
}
Beispiel #7
0
	void HttpServer::handlePost(HttpClientHandler* hdlr,const QHttpRequestHeader & hdr,const QByteArray & data)
	{
		Out(SYS_WEB|LOG_DEBUG) << "POST " << hdr.path() << endl;
		KUrl url;
		url.setEncodedPathAndQuery(hdr.path());
		WebContentGenerator* gen = content_generators.find(url.path());
		if (gen)
		{
			if ((gen->getPermissions() == WebContentGenerator::LOGIN_REQUIRED && (!session.logged_in || !checkSession(hdr))) && WebInterfacePluginSettings::authentication())
			{
				// redirect to login page
				redirectToLoginPage(hdlr);
			}
			else
			{
				gen->post(hdlr,hdr,data);
			}
		}
		else
		{
			KUrl url;
			url.setEncodedPathAndQuery(hdr.path());
			QString path = commonDir() + url.path();
			// first try the common dir
			if (!bt::Exists(path)) // doesn't exist so it must be in the skin dir
				path = skinDir() + url.path();
			
			handleFile(hdlr,hdr,path);
		}
	}
Beispiel #8
0
void SendImgJob::run()
{
    QString send_url;
    QString host;
    if (  sendimg_type_ == kOffpic )
    {
        send_url = "/ftn_access/upload_offline_pic?time=" + QString::number(QDateTime::currentMSecsSinceEpoch());
;
        host = "weboffline.ftn.qq.com";
    }
    else if ( sendimg_type_ == kGroupImg )
    {
        send_url = "/cgi-bin/cface_upload?time=" + QString::number(QDateTime::currentMSecsSinceEpoch());
;
        host = "up.web2.qq.com";
    }

    QHttpRequestHeader header;

    header.setRequest("POST", send_url);
    header.addValue("Host", host);
    header.addValue("Content-Length", QString::number(data_.length()));
    header.addValue("Cache-Control", "max-age=0");
    header.addValue("Origin", "http://web.qq.com");
    header.addValue("Content-Type", "multipart/form-data; boundary="+Protocol::QQProtocol::instance()->imgSender()->boundary());
    header.addValue("Referer", "http://web.qq.com/");
    header.addValue("Cookie", CaptchaInfo::instance()->cookie());

    http_.setHost(host);
    http_.request(header, data_);
}
Beispiel #9
0
	void HttpServer::handleFile(HttpClientHandler* hdlr,const QHttpRequestHeader & hdr,const QString & path)
	{
		// check if the file exists (if not send 404)
		if (!bt::Exists(path))
		{
			HttpResponseHeader rhdr(404,hdr.majorVersion(),hdr.minorVersion());
			setDefaultResponseHeaders(rhdr,"text/html",false);
			hdlr->send404(rhdr,path);
			return;
		}
		
		QString file = hdr.path();
		if (file == "/" && WebInterfacePluginSettings::authentication())
			file = "/login.html";
		else if (file == "/")
			file = "/interface.html";
		
		QFileInfo fi(path);
		QString ext = fi.suffix();;

		if (ext == "html")
		{
			// html pages require a login unless it is the login.html page
			if ((file != "/login.html" && (!session.logged_in || !checkSession(hdr))) && WebInterfacePluginSettings::authentication())
			{
				// redirect to login page
				redirectToLoginPage(hdlr);
				return;
			}
			
			HttpResponseHeader rhdr(200,hdr.majorVersion(),hdr.minorVersion());
			setDefaultResponseHeaders(rhdr,"text/html",true);
			if (path.endsWith("login.html"))
			{
				// clear cookie in case of login page
				QDateTime dt = QDateTime::currentDateTime().addDays(-1);
				QString cookie = QString("KT_SESSID=666; expires=%1 +0000").arg(DateTimeToString(dt,true));
				rhdr.setValue("Set-Cookie",cookie);
			}
			
			if (!hdlr->sendFile(rhdr,path))
			{
				HttpResponseHeader nhdr(404,hdr.majorVersion(),hdr.minorVersion());
				setDefaultResponseHeaders(nhdr,"text/html",false);
				hdlr->send404(nhdr,path);
			}
		}
		else if (ext == "css" || ext == "js" || ext == "png" || ext == "ico" || ext == "gif" || ext == "jpg")
		{
			handleNormalFile(hdlr,hdr,path);
		}
		else
		{
			HttpResponseHeader rhdr(404,hdr.majorVersion(),hdr.minorVersion());
			setDefaultResponseHeaders(rhdr,"text/html",false);
			hdlr->send404(rhdr,file);
		}
	}
/*---------------------------------------------------------------------------*/
QVariant HttpRecognizer::comment( IConnection* connection )
{
	Q_ASSERT (connection);
	if (!mConnections.contains( connection->networkInfo() ))
		return "No comment yet";

	const HttpConnection con = mConnections.value( connection->networkInfo() );
	const QHttpRequestHeader request = con.lastRequestHeader();
	const QHttpResponseHeader response = con.lastResponseHeader();

	return request.method() + " " + request.value( "host" ) + request.path()
		+ (response.isValid() ? "\nHTTP " + QString::number( response.statusCode() ) + " " + response.reasonPhrase() : "" );
}
Beispiel #11
0
QByteArray TTSGoogle::CreateNewSound(QString text, QString voice, bool forceOverwrite)
{
	QEventLoop loop;

	if(!voiceList.contains(voice))
		voice = "fr";

	// Check (and create if needed) output folder
	QDir outputFolder = ttsFolder;
	if(!outputFolder.exists(voice))
		outputFolder.mkdir(voice);
	
	if(!outputFolder.cd(voice))
	{
		LogError(QString("Cant create TTS Folder : %1").arg(ttsFolder.absoluteFilePath(voice)));
		return QByteArray();
	}
	
	// Compute fileName
	QString fileName = QCryptographicHash::hash(text.toAscii(), QCryptographicHash::Md5).toHex().append(".mp3");
	QString filePath = outputFolder.absoluteFilePath(fileName);

	if(!forceOverwrite && QFile::exists(filePath))
		return ttsHTTPUrl.arg(voice, fileName).toAscii();

	// Fetch MP3
	QHttp http("translate.google.com");
	QObject::connect(&http, SIGNAL(done(bool)), &loop, SLOT(quit()));

	QByteArray ContentData;
	ContentData += "q=" + QUrl::toPercentEncoding(text) + "&tl=" + voice;

	QHttpRequestHeader Header;
	Header.addValue("Host", "translate.google.com");

	Header.setContentLength(ContentData.length());
	Header.setRequest("POST", "/translate_tts", 1, 1);

	http.request(Header, ContentData);
	loop.exec();

	QFile file(filePath);
	if (!file.open(QIODevice::WriteOnly))
	{
		LogError("Cannot open sound file for writing");
		return QByteArray();
	}
	file.write(http.readAll());
	file.close();
	return ttsHTTPUrl.arg(voice, fileName).toAscii();
}
Beispiel #12
0
QHttpRequestHeader *BrisaEventProxy::getRenewRequest(const int timeout) const {
    if (this->getSid().isEmpty()) {
        qWarning() << "Renew failed: SID field not filled.";
        return NULL;
    }

    QHttpRequestHeader *request = new QHttpRequestHeader("SUBSCRIBE", eventSub);
    request->setValue("HOST", host + ":" + port);
    request->setValue("SID", getSid());
    request->setValue("TIMEOUT", (timeout > 0)
                                    ? "Second-" + QString().setNum(timeout)
                                    : "INFINITE");
    return request;
}
Beispiel #13
0
void RefuseFileJob::run()
{
    QString send_url = "/channel/refuse_file2?to=%1&lcid=%2&clientid=5412354841&psessionid=%3&t=%4";
    QString host = "d.web2.qq.com";

    QHttpRequestHeader header;
    header.setRequest("GET", send_url.arg(to_id_).arg(session_id_).arg(CaptchaInfo::instance()->psessionid()).arg(QDateTime::currentMSecsSinceEpoch()));
    header.addValue("Host", host);
    header.addValue("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");
    header.addValue("Cookie", CaptchaInfo::instance()->cookie());

    http_.setHost(host);
    http_.request(header);
}
Beispiel #14
0
	void HttpServer::handleNormalFile(HttpClientHandler* hdlr,const QHttpRequestHeader & hdr,const QString & path)
	{
		QFileInfo fi(path);
		QString ext = fi.suffix();
		
		if (hdr.hasKey("If-Modified-Since"))
		{
			QDateTime dt = parseDate(hdr.value("If-Modified-Since"));
			if (dt.isValid() && dt < fi.lastModified())
			{	
				HttpResponseHeader rhdr(304,hdr.majorVersion(),hdr.minorVersion());
				setDefaultResponseHeaders(rhdr,"text/html",true);
				rhdr.setValue("Cache-Control","max-age=0");
				rhdr.setValue("Last-Modified",DateTimeToString(fi.lastModified(),false));
				rhdr.setValue("Expires",DateTimeToString(QDateTime::currentDateTime().toUTC().addSecs(3600),false));
				hdlr->sendResponse(rhdr);
				return;
			}
		}
			
		HttpResponseHeader rhdr(200,hdr.majorVersion(),hdr.minorVersion());
		setDefaultResponseHeaders(rhdr,ExtensionToContentType(ext),true);
		rhdr.setValue("Last-Modified",DateTimeToString(fi.lastModified(),false));
		rhdr.setValue("Expires",DateTimeToString(QDateTime::currentDateTime().toUTC().addSecs(3600),false));
		rhdr.setValue("Cache-Control","private");
		if (!hdlr->sendFile(rhdr,path))
		{
			HttpResponseHeader nhdr(404,hdr.majorVersion(),hdr.minorVersion());
			setDefaultResponseHeaders(nhdr,"text/html",false);
			hdlr->send404(nhdr,path);
		}
	}
Beispiel #15
0
QString ImportIconsWizard::wget(QUrl& url,const QString& strParam )
{
    QByteArray raw(strParam.toAscii());
    QBuffer data(&raw);
    QHttpRequestHeader header;

    header.setContentType(QString("application/x-www-form-urlencoded"));
    header.setContentLength(raw.size());

    header.setValue("User-Agent", "MythTV Channel Icon lookup bot");

    QString str = HttpComms::postHttp(url,&header,&data);

    return str;
}
Beispiel #16
0
QString Protocol::MsgSender::getGroupSig(QString gid, QString to_id)
{
    if ( group_sigs_.contains(gid+to_id) )
        return group_sigs_.value(gid+to_id);

    QString msg_sig_url = "/channel/get_c2cmsg_sig2?id="+ gid +"&to_uin=" + to_id +
        "&service_type=0&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

    QHttpRequestHeader header;
    QString host = "d.web2.qq.com";
    header.setRequest("GET", msg_sig_url);
    header.addValue("Host", host);
    header.addValue("Content-Type", "utf-8");
    header.addValue("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002");
    header.addValue("Cookie", CaptchaInfo::instance()->cookie());

    QTcpSocket fd;
    fd.connectToHost(host, 80);
    fd.write(header.toString().toAscii());

    QByteArray result;
    socketReceive(&fd, result);
    fd.close();

    int sig_s_idx = result.indexOf("value")+8;
    int sig_e_idx = result.indexOf('"', sig_s_idx);
    QString sig = result.mid(sig_s_idx, sig_e_idx - sig_s_idx);

    group_sigs_.insert(gid+to_id, sig);

    return sig;
}
Beispiel #17
0
	void HttpServer::handlePost(HttpClientHandler* hdlr,const QHttpRequestHeader & hdr,const QByteArray & data)
	{
		// this is either a file or a login
		if (hdr.value("Content-Type").startsWith("multipart/form-data"))
		{
			handleTorrentPost(hdlr,hdr,data);
		}
		else if (!checkLogin(hdr,data))
		{
			QHttpRequestHeader tmp = hdr;
			tmp.setRequest("GET","/login.html",1,1);
			handleGet(hdlr,tmp);
		}
		else
		{
			handleGet(hdlr,hdr,true);
		}
	}
Beispiel #18
0
	bool HttpServer::checkSession(const QHttpRequestHeader & hdr)
	{
		// check session in cookie
		int session_id = 0;
		if (hdr.hasKey("Cookie"))
		{
			QString cookie = hdr.value("Cookie");
			int idx = cookie.find("KT_SESSID=");
			if (idx == -1)
				return false;
			
			QString number;
			idx += QString("KT_SESSID=").length();
			while (idx < cookie.length())
			{
				if (cookie[idx] >= '0' && cookie[idx] <= '9')
					number += cookie[idx];
				else
					break;
				
				idx++;
			}
					
			session_id = number.toInt();
		}
		
	
		if (session_id == session.sessionId)
		{
			// check if the session hasn't expired yet
			if(session.last_access.secsTo(QTime::currentTime())<WebInterfacePluginSettings::sessionTTL())
			{
				session.last_access=QTime::currentTime();
			}
			else
			{
				return false;
			}
		}
		else
			return false;

		return true;
	}
Beispiel #19
0
	void HttpServer::handleGet(HttpClientHandler* hdlr,const QHttpRequestHeader & hdr)
	{
		if (rootDir.isEmpty())
		{
			HttpResponseHeader rhdr(500,hdr.majorVersion(),hdr.minorVersion());
			setDefaultResponseHeaders(rhdr,"text/html",false);
			hdlr->send500(rhdr,i18n("Cannot find web interface skins."));
			return;
		}
		
		QString file = hdr.path();
		if (file == "/" && WebInterfacePluginSettings::authentication())
			file = "/login.html";
		else if (file == "/")
			file = "/interface.html";
			
		KUrl url;
		url.setEncodedPathAndQuery(file);
		
		Out(SYS_WEB|LOG_DEBUG) << "GET " << hdr.path() << endl;
		WebContentGenerator* gen = content_generators.find(url.path());
		if (gen)
		{
			if ((gen->getPermissions() == WebContentGenerator::LOGIN_REQUIRED && (!session.logged_in || !checkSession(hdr))) && WebInterfacePluginSettings::authentication())
			{
				// redirect to login page
				redirectToLoginPage(hdlr);
			}
			else
			{
				gen->get(hdlr,hdr);
			}
		}
		else
		{
			QString path = commonDir() + url.path();
			// first try the common dir
			if (!bt::Exists(path)) // doesn't exist so it must be in the skin dir
				path = skinDir() + url.path();
			
			handleFile(hdlr,hdr,path);
		}
	}
void MusicBrainzDownloader::requestAlbum(int nAlbum)
{
LAST_STEP("MusicBrainzDownloader::requestAlbum");
    //CB_ASSERT (!m_pQHttp->hasPendingRequests() && !m_pImageQHttp->hasPendingRequests());  // ttt1 triggered: https://sourceforge.net/apps/mantisbt/mp3diags/view.php?id=36 ?? perhaps might happen when MB returns errors ; see also DiscogsDownloader::requestAlbum
    CB_ASSERT (!m_pQHttp->hasPendingRequests());
    CB_ASSERT (!m_pImageQHttp->hasPendingRequests());

    m_nLoadingAlbum = nAlbum;
    setWaiting(ALBUM);
    //string s ("/release/" + m_vAlbums[nAlbum].m_strId + "?f=xml&api_key=f51e9c8f6c");
    string s ("/ws/1/release/" + m_vAlbums[nAlbum].m_strId + "?type=xml&inc=tracks+artist+release-events+url-rels");

    QHttpRequestHeader header ("GET", convStr(s));
    header.setValue("Host", "musicbrainz.org");
    //header.setValue("Accept-Encoding", "gzip");
    delay();
    m_pQHttp->request(header);
    //cout << "sent album " << m_vAlbums[nAlbum].m_strId << " - " << m_pQHttp->request(header) << endl;
    addNote("getting album info ...");
}
QString ImportIconsWizard::wget(QUrl& url,const QString& strParam )
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QByteArray raw(strParam.toLatin1());
    QBuffer data(&raw);
    QHttpRequestHeader header;

    header.setContentType(QString("application/x-www-form-urlencoded"));
    header.setContentLength(raw.size());

    header.setValue("User-Agent", "MythTV Channel Icon lookup bot");

    QString str = HttpComms::postHttp(url,&header,&data);

    return str;
#else
#warning ImportIconsWizard::wget() not ported to Qt5
    return QString();
#endif
}
Beispiel #22
0
	bool HttpServer::checkLogin(const QHttpRequestHeader & hdr,const QByteArray & data)
	{
		// Authentication is disabled
		if (!WebInterfacePluginSettings::authentication())
		{
			session.logged_in = true;
			session.sessionId = rand();
			session.last_access = QTime::currentTime();
			Out(SYS_WEB|LOG_NOTICE) << "Webgui login successful ! (auth disable)" << endl;
			challenge = QString();
			return true;
		}

		if (hdr.contentType() != "application/x-www-form-urlencoded")
		{
			Out(SYS_WEB|LOG_NOTICE) << "Webgui login failed ! 1" << endl;
			challenge = QString();
			return false;
		}
		
		QString username;
		QString challenge_hash;
		QStringList params = QString(data).split("&");
		for (QStringList::iterator i = params.begin();i != params.end();i++)
		{
			QString t = *i;
			if (t.section("=",0,0) == "username")
				username = t.section("=",1,1);
			else if (t.section("=",0,0) == "challenge")
				challenge_hash = t.section("=",1,1);
		}

		if (username.isNull() || challenge.isNull() || username != WebInterfacePluginSettings::username())
		{
			Out(SYS_WEB|LOG_NOTICE) << "Webgui login failed ! 2" << endl;
			challenge = QString();
			return false;
		}
		
		QByteArray s = (QString(challenge + WebInterfacePluginSettings::password())).toUtf8();
		bt::SHA1Hash hash = bt::SHA1Hash::generate((const bt::Uint8*)s.data(),s.length());
		if (hash.toString() == challenge_hash)
		{
			session.logged_in = true;
			session.sessionId=rand();
			session.last_access=QTime::currentTime();
			Out(SYS_WEB|LOG_NOTICE) << "Webgui login successful !" << endl;
			challenge = QString();
			return true;
		}
		challenge = QString();
		Out(SYS_WEB|LOG_NOTICE) << "Webgui login failed ! 3" << endl;
		return false;
	}
static PyObject *meth_QHttpRequestHeader_setRequest(PyObject *sipSelf, PyObject *sipArgs, PyObject *sipKwds)
{
    PyObject *sipParseErr = NULL;

    {
        const QString* a0;
        int a0State = 0;
        const QString* a1;
        int a1State = 0;
        int a2 = 1;
        int a3 = 1;
        QHttpRequestHeader *sipCpp;

        static const char *sipKwdList[] = {
            NULL,
            NULL,
            sipName_major,
            sipName_minor,
        };

        if (sipParseKwdArgs(&sipParseErr, sipArgs, sipKwds, sipKwdList, NULL, "BJ1J1|ii", &sipSelf, sipType_QHttpRequestHeader, &sipCpp, sipType_QString,&a0, &a0State, sipType_QString,&a1, &a1State, &a2, &a3))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setRequest(*a0,*a1,a2,a3);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);
            sipReleaseType(const_cast<QString *>(a1),sipType_QString,a1State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QHttpRequestHeader, sipName_setRequest, doc_QHttpRequestHeader_setRequest);

    return NULL;
}
Beispiel #24
0
    void TorrentPostHandler::post(HttpClientHandler* hdlr, const QHttpRequestHeader& hdr, const QByteArray& data)
    {
        const char* ptr = data.data();
        int len = data.size();
        int pos = QString(data).indexOf("\r\n\r\n");

        if (pos == -1 || pos + 4 >= len)
        {
            HttpResponseHeader rhdr(500);
            server->setDefaultResponseHeaders(rhdr, "text/html", false);
            hdlr->send500(rhdr, i18n("Invalid data received"));
            return;
        }

        // save torrent to a temporary file
        QString save_file = kt::DataDir() + "webgui_load_torrent";
        QFile tmp_file(save_file);

        if (!tmp_file.open(QIODevice::WriteOnly))
        {
            HttpResponseHeader rhdr(500);
            server->setDefaultResponseHeaders(rhdr, "text/html", false);
            hdlr->send500(rhdr, i18n("Failed to open temporary file"));
            return;
        }

        QDataStream out(&tmp_file);
        out.writeRawData(ptr + (pos + 4), len - (pos + 4));
        tmp_file.close();

        Out(SYS_WEB | LOG_NOTICE) << "Loading file " << save_file << endl;
        core->loadSilently(KUrl(save_file), QString());

        KUrl url;
        url.setEncodedPathAndQuery(hdr.path());
        QString page = url.queryItem("page");
        // there needs to be a page to send back
        if (page.isEmpty())
        {
            server->redirectToLoginPage(hdlr);
        }
        else
        {
            // redirect to page mentioned in page parameter
            HttpResponseHeader rhdr(301);
            server->setDefaultResponseHeaders(rhdr, "text/html", true);
            rhdr.setValue("Location", "/" + page);
            hdlr->send(rhdr, QByteArray());
        }
    }
QString GoogleTranslateHttp::request(const QString &text, const QString &fromLanguage,
                                                          const QString &toLanguage)
{
    const QString &word = GoogleTranslateUtil::getSearchWord(text);
    qDebug() << "Searching " << word << " from = " << fromLanguage << " to = " << toLanguage;
    QString url = QString("/translate_a/t?client=t&sl="+
                           fromLanguage +
                           "&tl=" +
                           toLanguage);
    setHost("www.google.com");

    QHttpRequestHeader header = QHttpRequestHeader("POST", url, 1, 1);
    header.setValue("Host", "www.google.com");
    header.setValue("User-Agent", "Mozilla/5.0");
    header.setContentLength(word.length());

    QByteArray ba("text=");
    ba.append(word.toUtf8());
    QHttp::request(header, ba);

    loop.exec();
    return QString::fromUtf8(readAll());
}
Beispiel #26
0
	bool HttpServer::checkSession(const QHttpRequestHeader & hdr)
	{
		// check session in cookie
		int session_id = 0;
		if (hdr.hasKey("Cookie"))
		{
			QString cookie = hdr.value("Cookie");
			QRegExp rx("KT_SESSID=(\\d+)",Qt::CaseInsensitive);
			int pos = 0;
			
			while ((pos = rx.indexIn(cookie, pos)) != -1) 
			{
				session_id = rx.cap(1).toInt();
				if (session_id == session.sessionId)
					break;
				pos += rx.matchedLength();
			}
		}
		
	
		if (session_id == session.sessionId)
		{
			// check if the session hasn't expired yet
			if(session.last_access.secsTo(QTime::currentTime())<WebInterfacePluginSettings::sessionTTL())
			{
				session.last_access=QTime::currentTime();
			}
			else
			{
				return false;
			}
		}
		else
			return false;

		return true;
	}
Beispiel #27
0
QHttpRequestHeader *BrisaEventProxy::getSubscriptionRequest(const int timeout) {
    QHttpRequestHeader *request = new QHttpRequestHeader("SUBSCRIBE", eventSub);

    // Remote host
    request->setValue("HOST", host + ":" + QString().setNum(port));

    // Our URL for receiving notifications
    const QUrl url = this->getUrl();

    qDebug() << "Url: " << url.host() << " port: " << url.port();
    request->setValue("CALLBACK", "<http://"
                                    + url.host()
                                    + ":"
                                    + QString().setNum(url.port())
                                    + "/"
                                    + QString().setNum(deliveryPath)
                                    + ">");

    request->setValue("NT", "upnp:event");
    request->setValue("TIMEOUT", (timeout > 0)
                                    ? "Second-" + QString().setNum(timeout)
                                    : "INFINITE"); // INFINITE is obsolete in UPnP 1.1
    return request;
}
Beispiel #28
0
	bool HttpServer::checkLogin(const QHttpRequestHeader & hdr,const QByteArray & data)
	{
		if (hdr.contentType() != "application/x-www-form-urlencoded")
			return false;
		
		QString username;
		QString password;
		QStringList params = QStringList::split("&",QString(data));
		for (QStringList::iterator i = params.begin();i != params.end();i++)
		{
			QString t = *i;
			if (t.section("=",0,0) == "username")
				username = t.section("=",1,1);
			else if (t.section("=",0,0) == "password")
				password = t.section("=",1,1);
			
			// check for passwords with url encoded stuff in them and decode them if necessary
			int idx = 0;
			while ((idx = password.find('%',idx)) > 0)
			{
				if (idx + 2 < password.length())
				{
					idx = DecodeEscapedChar(password,idx);
				}
				else
					break;
			}
		}

		if (!username.isNull() && !password.isNull())
		{
			KMD5 context(password.utf8());

			if(username == WebInterfacePluginSettings::username() && 
				context.hexDigest().data() == WebInterfacePluginSettings::password())
			{
				session.logged_in = true;
				session.sessionId=rand();
				session.last_access=QTime::currentTime();
				Out(SYS_WEB|LOG_NOTICE) << "Webgui login succesfull !" << endl;
				return true;
			}
		}

		return false;
	}
Beispiel #29
0
void SendMsgJob::sendMsg()
{
    QString send_url = getPath();
    QByteArray data = getData();

    QHttpRequestHeader header;
    header.setRequest("POST", send_url);
    header.addValue("Host", "d.web2.qq.com");
    header.addValue("Cookie", CaptchaInfo::instance()->cookie());
    header.addValue("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002");
    header.addValue("Content-Length", QString::number(data.length()));
    header.addValue("Content-Type", "application/x-www-form-urlencoded");

    http_.setHost("d.web2.qq.com");
    http_.request(header, data);
}
Beispiel #30
0
void HttpThread::run()
{
    QHttpRequestHeader header;
    header.setRequest("GET",url.path());
    header.setValue("Range","bytes="+QString::number(startByte)+"-"+QString::number(endByte));
    QString userAgent = "getit/0.1";
    header.setValue("Host", url.host());
    header.setValue("Accept", "*/*");
    header.setValue("User-Agent", userAgent);
    http.setHost(url.host());
    http.request(header);
    connect(&http,SIGNAL(readyRead(QHttpResponseHeader)),this,SLOT(writeToFile(QHttpResponseHeader)));
    connect(&http,SIGNAL(done(bool)),this,SLOT(finished(bool)));
    this->exec();
}