示例#1
0
文件: http.c 项目: varphone/ejs-2
static int processThread(HttpConn *conn, MprEvent *event)
{
    ThreadData  *td;
    cchar       *path;
    char        *url;
    int         next;

    td = mprGetCurrentThread()->data;
    httpFollowRedirects(conn, !app->nofollow);
    httpSetTimeout(conn, app->timeout, app->timeout);

    if (strcmp(app->protocol, "HTTP/1.0") == 0) {
        httpSetKeepAliveCount(conn, 0);
        httpSetProtocol(conn, "HTTP/1.0");
    }
    if (app->username) {
        if (app->password == 0 && !strchr(app->username, ':')) {
            app->password = getPassword();
        }
        httpSetCredentials(conn, app->username, app->password);
    }
    while (!mprShouldDenyNewRequests(conn) && (app->success || app->continueOnErrors)) {
        if (app->singleStep) waitForUser();
        if (app->files && !app->upload) {
            for (next = 0; (path = mprGetNextItem(app->files, &next)) != 0; ) {
                /*
                    If URL ends with "/", assume it is a directory on the target and append each file name 
                 */
                if (app->target[strlen(app->target) - 1] == '/') {
                    url = mprJoinPath(app->target, mprGetPathBase(path));
                } else {
                    url = app->target;
                }
                app->requestFiles = mprCreateList(-1, MPR_LIST_STATIC_VALUES);
                mprAddItem(app->requestFiles, path);
                td->url = url = resolveUrl(conn, url);
                if (app->verbose) {
                    mprPrintf("putting: %s to %s\n", path, url);
                }
                if (doRequest(conn, url, app->requestFiles) < 0) {
                    app->success = 0;
                    break;
                }
            }
        } else {
            td->url = url = resolveUrl(conn, app->target);
            if (doRequest(conn, url, app->files) < 0) {
                app->success = 0;
                break;
            }
        }
        if (iterationsComplete()) {
            break;
        }
    }
    httpDestroyConn(conn);
    finishThread((MprThread*) event->data);
    return -1;
}
示例#2
0
int EDITAPI EDITShowWindow( show_method iCmdShow )
{
    if( !bConnected ) {
        return( FALSE );
    }

    // ensure iCmdShow is SW_RESTORE or SW_MINIMIZE only
    if( iCmdShow == EDIT_RESTORE || iCmdShow == EDIT_SHOWNORMAL ) {
        return( doRequest( "Restore" ) != 0 );
    } else if( iCmdShow == EDIT_MINIMIZE ) {
        return( doRequest( "Minimize" ) != 0 );
    }

    // bad argument
    return( FALSE );
}
示例#3
0
int EDITAPI EDITSaveFiles( void )
{
    if( !bConnected ) {
        return( FALSE );
    }
    return( doRequest( "PromptForSave" ) != 0 );
}
示例#4
0
int Servant::dispatch(JceCurrentPtr current, vector<char> &buffer)
{
    int ret = JCESERVERUNKNOWNERR;

    if (current->getFuncName() == "taf_ping")
    {
        LOGINFO("[TAF][Servant::dispatch] taf_ping ok from [" << current->getIp() << ":" << current->getPort() << "]" << endl);

        ret = JCESERVERSUCCESS;
    }
    else if (current->getFuncName() == "taf_bus")
 	{
 		TC_LockT<TC_ThreadRecMutex> lock(*this);

 		ret = doBus(current, buffer);
 	}
    else if (!current->getBindAdapter()->isTafProtocol())
    {
        TC_LockT<TC_ThreadRecMutex> lock(*this);

        ret = doRequest(current, buffer);
    }
    else
    {
        TC_LockT<TC_ThreadRecMutex> lock(*this);

        ret = onDispatch(current, buffer);
    }
    return ret;
}
示例#5
0
void SimpleHttpRequestTest_POST()
{
	URI uri("http://localhost:8888/simpleservlet2");
	std::string path(uri.getPath());
	if (path.empty()) path = "/";


	cout << path << endl;

	HTTPClientSession session(uri.getHost(), uri.getPort());

	HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
	/*
	request.set("username", "user");
	request.set("password", "pass");
	*/
	std::string reqBody("username=user&password=pass");

	HTTPResponse response;

	if (!doRequest(session, reqBody, request, response))
	{
		std::cerr << "something went wrong" << std::endl;
	}
}
示例#6
0
int Eiger::arm (int *sequenceId)
{
    const char *functionName = "arm";

    request_t request;
    char requestBuf[MAX_MESSAGE_SIZE];
    request.data      = requestBuf;
    request.dataLen   = sizeof(requestBuf);
    request.actualLen = epicsSnprintf(request.data, request.dataLen,
            REQUEST_PUT, sysStr[SSCommand], "arm", 0lu);

    response_t response;
    char responseBuf[MAX_MESSAGE_SIZE];
    response.data    = responseBuf;
    response.dataLen = sizeof(responseBuf);

    if(doRequest(&request, &response, DEFAULT_TIMEOUT_ARM))
    {
        ERR("[param=arm] request failed");
        return EXIT_FAILURE;
    }

    if(response.code != 200)
    {
        ERR_ARGS("[param=arm] server returned error code %d", response.code);
        return EXIT_FAILURE;
    }

    return sequenceId ? parseSequenceId(&response, sequenceId) : EXIT_SUCCESS;
}
示例#7
0
am_status_t BaseService::doHttpGet(const ServiceInfo& service,
				   const std::string& uriParameters,
				   const Http::CookieList& cookieList,
				   Http::Response& response,
				   std::size_t initialBufferLen,
				   const std::string &cert_nick_name,
				   const ServerInfo** serverInfo) const
{
    am_status_t status;

    status = doRequest(service, getPrefixChunk, uriParameters, cookieList,
		       getSuffixChunk, BodyChunkList(), response,
		       initialBufferLen, cert_nick_name, serverInfo);
    //
    // NOTE: The omission of a check of the HTTP status here, as compared
    // with doHttpPost, is intentional.  The AuthService code, which is
    // currently the only code that does a GET, performs its own analysis
    // of the HTTP status and various headers to determine the appropriate
    // return code.  Doing part of the analysis here and part in the
    // AuthService code would make things harder to implement and
    // understand.
    //

    return status;
}
示例#8
0
int Eiger::getFileSize (const char *filename, size_t *size)
{
    const char *functionName = "getFileSize";

    request_t request;
    char requestBuf[MAX_MESSAGE_SIZE];
    request.data      = requestBuf;
    request.dataLen   = sizeof(requestBuf);
    request.actualLen = epicsSnprintf(request.data, request.dataLen,
            REQUEST_HEAD, sysStr[SSData], filename);

    response_t response;
    char responseBuf[MAX_MESSAGE_SIZE];
    response.data    = responseBuf;
    response.dataLen = sizeof(responseBuf);

    if(doRequest(&request, &response))
    {
        ERR_ARGS("[file=%s] HEAD request failed", filename);
        return EXIT_FAILURE;
    }

    if(response.code != 200)
    {
        ERR_ARGS("[file=%s] server returned error code %d", filename,
                response.code);
        return EXIT_FAILURE;
    }

    *size = response.contentLength;
    return EXIT_SUCCESS;
}
示例#9
0
ImageLoader::Status ImageLoader::load(const QImage &image) const
{
    if (!ok()) return NETWORK_ERROR;

    uchar * imageData = const_cast<uchar*>(image.bits());
    QByteArray request("ANS@"), response;
    request.append(number(mId), sizeof(mId));
    qDebug() << image.byteCount();
    request.append((char *)imageData, image.byteCount());
//	for (int i = 0; i < image.height(); i++)
//		for (int j = 0; j < image.width(); j++)
//		{
//            QRgb color = image.pixel(i, j);
//			int pix =
//                    (color & 0x00ff0000 >> 24) |
//                    (color & 0x0000ff00 >> 16) |
//                    (color & 0x000000ff);
//			request.append(uchar(pix / 3));
//		}

    if(doRequest(request, response))
        return SUCCESS;

    return NETWORK_ERROR;
}
示例#10
0
ImageLoader::Status ImageLoader::get(QImage &image) const
{
    if (!ok()) return NETWORK_ERROR;

    QByteArray request("GET@"), response;
    request.append(number(mId), sizeof(mId));

    if (!doRequest(request, response))
        return NETWORK_ERROR;

    const int bytesSize = 3 * sizeImage.height * sizeImage.width;
    const int gotBytesSize = response.size();
    if (gotBytesSize == bytesSize)
    {
        qDebug() << "got image";
        image = readImage(response).copy();
        return SUCCESS;
    }
    else if (gotBytesSize == 4 && response == "->-@")
    {
        qDebug() << "done";
        return DONE;
    }
    return NETWORK_ERROR;
}
/*!
    \fn bool FacebookConnection::postMessage(const QVariantMap &message)

    Posts \a message to Facebook. Possible message posting types are status update,
    posting a link, and uploading a picture.

    Returns true if the operation was successfully started and there will be a
    postMessageCompleted() signal emitted later; otherwise returns false.

    Keys and values for creating a status update:
    \list
        \li "text" (mandatory) : "Your status update message."
        \li "url" (n/a)
        \li "description" (n/a)
    \endlist

    Keys and values for creating posting a link:
    \list
        \li "text" (mandatory) : "Your status message for the link."
        \li "url" (mandatory) : "http://url.to.your.link"
        \li "description" (optional) : "Description for your link."
    \endlist

    Keys and values for uploading a picture:
    \list
        \li "text" (mandatory) : "Text for your uploaded picture."
        \li "url" (mandatory) : "file:///path/to/your/picture.png"
        \li "description" (n/a)
    \endlist
*/
bool FacebookConnection::postMessage(const QVariantMap &message)
{    
    QString graphPath;
    QVariantMap parameters;

    if (message.contains("text")) {
        parameters.insert("message", message.value("text").toString());
        graphPath = "me/feed";
    }
    if (message.contains("url") &&
        message.value("url").toUrl().scheme().compare("file") == 0) {
        parameters.insert("picture", message.value("url").toUrl());
        graphPath = "me/photos";
    }
    else if (message.contains("url") &&
             message.value("url").toUrl().scheme().compare("http") == 0) {
        parameters.insert("link", message.value("url").toUrl());
        graphPath = "me/feed";
    }
    if (message.contains("description")) {
        parameters.insert("description", message.value("description").toString());
    }

    // The message is invalid if graph path not defined.
    if (graphPath.isEmpty()) {
        qWarning() << "Error. Invalid message.";
        return false;
    }

    m_apiCall = PostMessage;

    return doRequest("", graphPath, HTTPPost, parameters);
}
示例#12
0
	void HTTPTracker::manualUpdate()
	{
		if (!started)
			start();
		else
			doRequest();
	}
示例#13
0
INetResponse* CNetRequest::pullCookies(const String& strUrl, const String& strBody, IRhoSession* oSession)
{
	INetResponse* pResp = doRequest("POST", strUrl, strBody, oSession, null );
	if ( pResp->isOK() )
        ((CNetResponseImpl*)pResp)->getRawData() = pResp->getCookies();
		
	return pResp;
}
示例#14
0
void ProfilerThread::responseReceived()
{
  if (m_query->getErrno() == SUCCESS) incCounter();
  qDebug() << getCounter() << m_sendTime.msecsTo(QDateTime::currentDateTime()) <<  (int)(m_query->getErrno()!=SUCCESS) << m_requests_per_second;
  //QString a=QString("echo \"%1 %2 %3 %4 `ps -e -o rss,comm | grep fcgi | grep -o \\\"^[0-9 ]*\\\"`\"").arg(getCounter()).arg(m_sendTime.msecsTo(QDateTime::currentDateTime())).arg((int)(m_query->getErrno()!=SUCCESS)).arg(m_requests_per_second);
  //system(a.toStdString().c_str());
  if (m_counter == m_number_of_requests ) exit();
  emit doRequest();
}
示例#15
0
int EDITAPI EDITSaveThisFile( const char *filename )
{
    char szCommand[ _MAX_PATH + 25 ];
    if( !bConnected ) {
        return( TRUE );
    }
    sprintf( szCommand, "PromptThisFileForSave %s", filename );
    return( doRequest( szCommand ) != 0 );
}
示例#16
0
int EDITAPI EDITQueryThisFile( const char *filename )
{
    char szCommand[ _MAX_PATH + 15 ];
    if( !bConnected ) {
        return( FALSE );
    }
    sprintf( szCommand, "QueryFile %s", filename );
    return( doRequest( szCommand ) );
}
示例#17
0
am_status_t BaseService::doHttpPost(const ServiceInfo& service,
				    const std::string& uriParameters,
				    const Http::CookieList& cookieList,
				    const BodyChunkList& bodyChunkList,
				    Http::Response& response,
				    std::size_t initialBufferLen,
				    const std::string &cert_nick_name,
				    bool doFormPost,
				    bool checkHTTPRetCode,
				    const ServerInfo **serverInfo) const
{
    am_status_t status;

    if(doFormPost) {
	status = doRequest(service, postPrefixChunk, uriParameters,
			   cookieList, postFormSuffixChunk, bodyChunkList,
			   response, initialBufferLen, cert_nick_name,
			   serverInfo);
    } else {
	status = doRequest(service, postPrefixChunk, uriParameters,
			   cookieList, postSuffixChunk, bodyChunkList,
			   response, initialBufferLen, cert_nick_name,
			   serverInfo);
    }


    if (checkHTTPRetCode &&
	(AM_SUCCESS == status && Http::OK != response.getStatus())) {
	Http::Status httpStatus = response.getStatus();

	if (Http::NOT_FOUND == httpStatus) {
	    status = AM_NOT_FOUND;
	} else if (Http::FORBIDDEN == httpStatus) {
	    status = AM_ACCESS_DENIED;
	} else {
	    Log::log(logModule, Log::LOG_WARNING,
		     "BaseService::doHttpPost() failed, HTTP error = %d",
		     httpStatus);
	    status = AM_HTTP_ERROR;
	}
    }
    return status;
}
示例#18
0
文件: showTip.cpp 项目: bradenwu/oce
		virtual void run(){
			for (;;) {
				int rc = FCGX_Accept_r(&request);
				if (rc < 0) break;
				if(!doRequest(request)){
					FCGX_FPrintF(request.out, "Content-type: text/html\r\n\r\n");
					FCGX_Finish_r(&request);
				}
			}
		};
void HabiticaConnector::deleteTask(std::wstring taskID)
{
	// Create request with DELETE protocol
	web::http::http_request request(web::http::methods::DEL);
	
	web::uri_builder requestUri = apiUri;
	requestUri.append(taskID);
	request.set_request_uri(requestUri.to_string());
	doRequest(request, taskID);
}
DhcpServerMessage *DHCPD::process(DhcpClientMessage &req)
{
    DhcpServerMessage *reply = NULL;

    req.dump();

    OptServerId sid(req);
    if (sid.present() && sid.value().u != m_pConfig->getIPv4Address().u)
    {
        if (req.broadcasted() && req.messageType() == RTNET_DHCP_MT_REQUEST)
            m_db.cancelOffer(req);

        return NULL;
    }

    switch (req.messageType())
    {
        /*
         * Requests that require server's reply.
         */
        case RTNET_DHCP_MT_DISCOVER:
            reply = doDiscover(req);
            break;

        case RTNET_DHCP_MT_REQUEST:
            reply = doRequest(req);
            break;

        case RTNET_DHCP_MT_INFORM:
            reply = doInform(req);
            break;

        /*
         * Requests that don't have a reply.
         */
        case RTNET_DHCP_MT_DECLINE:
            doDecline(req);
            break;

        case RTNET_DHCP_MT_RELEASE:
            doRelease(req);
            break;

        /*
         * Unexpected or unknown message types.
         */
        case RTNET_DHCP_MT_OFFER: /* FALLTHROUGH */
        case RTNET_DHCP_MT_ACK:   /* FALLTHROUGH */
        case RTNET_DHCP_MT_NAC:   /* FALLTHROUGH */
        default:
            break;
    }

    return reply;
}
void HabiticaConnector::addTask(std::wstring taskName, std::wstring taskID)
{
	web::json::value task = createTaskBody(taskName, taskID);

	// Create request with POST protocol
	web::http::http_request request(web::http::methods::POST);
	request.set_request_uri(apiUri.to_string());
	request.set_body(task);

	doRequest(request, taskID);
} 
// static
void LLEnvironmentRequest::onRegionCapsReceived(const LLUUID& region_id)
{
	if (region_id != gAgent.getRegion()->getRegionID())
	{
		LL_INFOS("WindlightCaps") << "Got caps for a non-current region" << LL_ENDL;
		return;
	}

	LL_DEBUGS("WindlightCaps") << "Received region capabilities" << LL_ENDL;
	doRequest();
}
示例#23
0
void SocketListener::process() {
	Connection::ptr pack;
	while (!m_handler->m_term) {
		if (m_handler->m_packets.pop_front(pack, -1)) {
			if (pack->type == Net_Close) {
				doClose(pack);
			} else if (pack->type == Net_Packet) {
				doRequest(pack);
			}
		}
	}
}
示例#24
0
bool ImageLoader::connect() const
{
    mId = -1;

    QByteArray request("GET@"), response;
    request.append(number(mId), sizeof(mId));

    if (!doRequest(request, response) ||
        response.size() != sizeof(int))
        return false;

    return (mId = readID(response)) != -1;
}
示例#25
0
文件: zmfTests.cpp 项目: fetzerms/ZMF
void zmfTests::testInstance() {

    auto moduleA = std::make_shared<DummyModule>(zmf::data::ModuleUniqueId(13, 37));
    auto moduleB = std::make_shared<DummyModule>(zmf::data::ModuleUniqueId(44, 20));

    auto coreA = zmf::instance::ZmfInstance::startInstance(moduleA, {});
    auto coreB = zmf::instance::ZmfInstance::startInstance(moduleB, {});

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    moduleA->doPublish();
    moduleB->doPublish();

    moduleA->doRequest(moduleA->getUniqueId());
    moduleA->doRequest(moduleB->getUniqueId());

    moduleB->doRequest(moduleB->getUniqueId());
    moduleB->doRequest(moduleA->getUniqueId());

    std::this_thread::sleep_for(std::chrono::milliseconds(5000));

}
void HabiticaConnector::completeTask(std::wstring taskID)
{
	// Create request with POST protocol
	web::http::http_request request(web::http::methods::POST);

	// Build the URI
	web::uri_builder requestUri = apiUri;
	requestUri.append(taskID);
	requestUri.append(U("/up"));	//Completes the Habitica Todo
	request.set_request_uri(requestUri.to_string());

	doRequest(request, taskID);
}
示例#27
0
am_status_t BaseService::doHttpPost(const ServiceInfo& service,
        const std::string& uriParameters,
        const Http::CookieList& cookieList,
        const BodyChunkList& bodyChunkList,
        Http::Response& response,
        bool doFormPost,
        bool checkHTTPRetCode,
        const ServerInfo **serverInfo) const {
    am_status_t status;

    if (doFormPost) {
        status = doRequest(service, BodyChunk(std::string(HTTP_POST_PREFIX)), uriParameters,
                cookieList, BodyChunk(std::string(HTTP_POST_FORM_SUFFIX)), bodyChunkList,
                response, serverInfo);
    } else {
        status = doRequest(service, BodyChunk(std::string(HTTP_POST_PREFIX)), uriParameters,
                cookieList, BodyChunk(std::string(HTTP_POST_SUFFIX)), bodyChunkList,
                response, serverInfo);
    }


    if (checkHTTPRetCode &&
            (AM_SUCCESS == status && Http::OK != response.getStatus())) {
        Http::Status httpStatus = response.getStatus();

        if (Http::NOT_FOUND == httpStatus) {
            status = AM_NOT_FOUND;
        } else if (Http::FORBIDDEN == httpStatus) {
            status = AM_ACCESS_DENIED;
        } else {
            Log::log(logModule, Log::LOG_ERROR,
                    "BaseService::doHttpPost() failed, HTTP error = %d",
                    httpStatus);
            status = AM_HTTP_ERROR;
        }
    }
    return status;
}
示例#28
0
SQRESULT URLRequest::wait(HSQUIRRELVM v)
{
	if (_handle == NULL)
	{
		bool started = doRequest();
		if (!started)
			return NitBind::push(v, 0);
	}

	if (_scriptWaitBlock == NULL)
		_scriptWaitBlock = new ScriptWaitBlock(ScriptRuntime::getRuntime(v));

	return _scriptWaitBlock->wait(v, 0x01);
}
示例#29
0
    void MiniWebServer::accepted(int s, const SockAddr &from) {
        char buf[4096];
        int len = 0;
        while ( 1 ) {
            int x = ::recv(s, buf + len, sizeof(buf) - 1 - len, 0);
            if ( x <= 0 ) {
                return;
            }
            len += x;
            buf[ len ] = 0;
            if ( fullReceive( buf ) )
                break;
        }
        buf[len] = 0;

        string responseMsg;
        int responseCode = 599;
        vector<string> headers;
        
        try {
            doRequest(buf, parseURL( buf ), responseMsg, responseCode, headers, from);
        }
        catch ( std::exception& e ){
            responseCode = 500;
            responseMsg = "error loading page: ";
            responseMsg += e.what();
        }
        catch ( ... ){
            responseCode = 500;
            responseMsg = "unknown error loading page";
        }

        stringstream ss;
        ss << "HTTP/1.0 " << responseCode;
        if ( responseCode == 200 ) ss << " OK";
        ss << "\r\n";
        if ( headers.empty() ) {
            ss << "Content-Type: text/html\r\n";
        }
        else {
            for ( vector<string>::iterator i = headers.begin(); i != headers.end(); i++ )
                ss << *i << "\r\n";
        }
        ss << "\r\n";
        ss << responseMsg;
        string response = ss.str();

        ::send(s, response.c_str(), response.size(), 0);
    }
示例#30
0
int EDITAPI EDITLocateError( long lRow, int iCol,
                                int iLen, int idResource , LPSTR szErrmsg )
{
    char        szCommand[ 100 ];
    BOOL        rc;

    if( !bConnected ) {
        return( FALSE );
    }

    sprintf( szCommand, "Locate %ld %d %d", lRow, iCol, iLen );
    rc = doRequest( szCommand );

    // can't lookup info in help file yet
    idResource = idResource;

    if( szErrmsg != NULL ) {
        rc |= doRequest( "echo on" );
        sprintf( szCommand, "echo 1 \"%.*s\"",
                 sizeof( szCommand ) - 10,  szErrmsg );
        rc |= doRequest( szCommand );
    }
    return( rc );
}