void HTTPCookieAuth::handleUnauthorized(HTTPRequestPtr& http_request,
	TCPConnectionPtr& tcp_conn)
{
	// if redirection option is used, send redirect
	if (!m_redirect.empty()) {
		handleRedirection(http_request,tcp_conn,m_redirect,"",false);
		return;
	}

	// authentication failed, send 401.....
	static const std::string CONTENT =
		" <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
		"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">"
		"<HTML>"
		"<HEAD>"
		"<TITLE>Error</TITLE>"
		"<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">"
		"</HEAD>"
		"<BODY><H1>401 Unauthorized.</H1></BODY>"
		"</HTML> ";
	HTTPResponseWriterPtr writer(HTTPResponseWriter::create(tcp_conn, *http_request,
	boost::bind(&TCPConnection::finish, tcp_conn)));
	writer->getResponse().setStatusCode(HTTPTypes::RESPONSE_CODE_UNAUTHORIZED);
	writer->getResponse().setStatusMessage(HTTPTypes::RESPONSE_MESSAGE_UNAUTHORIZED);
	writer->writeNoCopy(CONTENT);
	writer->send();
}
Exemple #2
0
/**
 * Chooses which I/O redirection to perform and sends arguments based on that
 * to handleRedirection(). If there is no redirection specified in the command,
 * nothing will happen.
 *
 * @param tokens  A character string array containing the tokens from parsing
 *
 * @returns nothing
 */
void redirect(char** tokens)
{
    for(int i = 0; tokens[i] != NULL; i++)
    {
        if(strCompare(tokens[i], ">"))
        {
            handleRedirection(tokens, &i, 1, O_CREAT | O_WRONLY | O_TRUNC);
        }

        if(strCompare(tokens[i], ">>"))
        {
            handleRedirection(tokens, &i, 1, O_WRONLY | O_APPEND);
        }

        if(strCompare(tokens[i], "<"))
        {
            handleRedirection(tokens, &i, 0, O_RDONLY);
        }
    }
}
void Net::DownloadHandler::processFinishedDownload()
{
    QString url = m_reply->url().toString();
    qDebug("Download finished: %s", qUtf8Printable(url));
    // Check if the request was successful
    if (m_reply->error() != QNetworkReply::NoError) {
        // Failure
        qDebug("Download failure (%s), reason: %s", qUtf8Printable(url), qUtf8Printable(errorCodeToString(m_reply->error())));
        emit downloadFailed(m_downloadRequest.url(), errorCodeToString(m_reply->error()));
        this->deleteLater();
    }
    else {
        // Check if the server ask us to redirect somewhere else
        const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (redirection.isValid()) {
            // We should redirect
            handleRedirection(redirection.toUrl());
        }
        else {
            // Success
            QByteArray replyData = m_reply->readAll();
            if (m_reply->rawHeader("Content-Encoding") == "gzip") {
                // decompress gzip reply
                replyData = Utils::Gzip::decompress(replyData);
            }

            if (m_downloadRequest.saveToFile()) {
                QString filePath;
                if (saveToFile(replyData, filePath))
                    emit downloadFinished(m_downloadRequest.url(), filePath);
                else
                    emit downloadFailed(m_downloadRequest.url(), tr("I/O Error"));
            }
            else {
                emit downloadFinished(m_downloadRequest.url(), replyData);
            }

            this->deleteLater();
        }
    }
}
bool HTTPCookieAuth::processLogin(HTTPRequestPtr& http_request, TCPConnectionPtr& tcp_conn)
{
	// strip off trailing slash if the request has one
	std::string resource(HTTPServer::stripTrailingSlash(http_request->getResource()));

	if (resource != m_login && resource != m_logout) {
		return false; // no login processing done
	}

	std::string redirect_url = HTTPTypes::url_decode(http_request->getQuery("url"));
	std::string new_cookie;
	bool delete_cookie = false;

	if (resource == m_login) {
		// process login
		// check username
		std::string username = HTTPTypes::url_decode(http_request->getQuery("user"));
		std::string password = HTTPTypes::url_decode(http_request->getQuery("pass"));

		// match username/password
		PionUserPtr user=m_user_manager->getUser(username,password);
		if (!user) { // authentication failed, process as in case of failed authentication...
			handleUnauthorized(http_request,tcp_conn);
			return true;
		}
		// ok we have a new user session, create  a new cookie, add to cache

		// create random cookie
		std::string rand_binary;
		rand_binary.reserve(RANDOM_COOKIE_BYTES);
		for (unsigned int i=0; i<RANDOM_COOKIE_BYTES ; i++) {
			rand_binary += static_cast<unsigned char>(m_random_die());
		}
		HTTPTypes::base64_encode(rand_binary, new_cookie);

		// add new session to cache
		PionDateTime time_now(boost::posix_time::second_clock::universal_time());
		boost::mutex::scoped_lock cache_lock(m_cache_mutex);
		m_user_cache.insert(std::make_pair(new_cookie,std::make_pair(time_now,user)));
	} else {
		// process logout sequence
		// if auth cookie presented - clean cache out
		const std::string auth_cookie(http_request->getCookie(AUTH_COOKIE_NAME));
		if (! auth_cookie.empty()) {
			boost::mutex::scoped_lock cache_lock(m_cache_mutex);
			PionUserCache::iterator user_cache_itr=m_user_cache.find(auth_cookie);
			if (user_cache_itr!=m_user_cache.end()) {
				m_user_cache.erase(user_cache_itr);
			}
		}
		// and remove cookie from browser
		delete_cookie = true;
	}
	
	// if redirect defined - send redirect
	if (! redirect_url.empty()) {
		handleRedirection(http_request,tcp_conn,redirect_url,new_cookie,delete_cookie);
	} else {
		// otherwise - OK
		handleOk(http_request,tcp_conn,new_cookie,delete_cookie);
	}

	// yes, we processed login/logout somehow
	return true;
}