bool QgsHttpRequestHandler::startGetFeatureResponse( QByteArray* ba, const QString& infoFormat ) { if ( !ba ) { return false; } if ( ba->size() < 1 ) { return false; } QString format; if ( infoFormat == "GeoJSON" ) format = "text/plain"; else format = "text/xml"; setInfoFormat( format ); sendHeaders(); appendBody( *ba ); // Streaming sendResponse(); return true; }
natural HttpReqImpl::write(const void* buffer, natural size) { if (!bHeaderSent) { sendHeaders(); if (!bHeaderSent) { throw ErrorMessageException(THISLOCATION, "Invalid write to stream, when status 1XX is used. New header must be prepared"); } } if (isHeadMethod) return size; if (useChunked) { if (size <= chunkBuff.getAllocatedSize() - chunkBuff.length()) { chunkBuff.append(ConstBin(reinterpret_cast<const byte *>(buffer), size)); } else if (size < chunkBuff.getAllocatedSize()) { chunkBuff.append(ConstBin(reinterpret_cast<const byte *>(buffer), size)); writeChunk(chunkBuff.data(), chunkBuff.length()); chunkBuff.clear(); } else { writeChunk(chunkBuff.data(),chunkBuff.length()); chunkBuff.clear(); writeChunk(buffer,size); } return size; } else { return inout->blockWrite(buffer, size, false); } }
void QgsHttpRequestHandler::sendResponse() { QgsMessageLog::logMessage( QString( "Sending HTTP response" ) ); if ( ! responseReady() ) { QgsMessageLog::logMessage( QString( "Trying to send out an invalid response" ) ); return; } #ifdef HAVE_SERVER_PYTHON_PLUGINS // Plugin hook // Iterate filters and call their sendResponse() method QgsServerFiltersMap::const_iterator filtersIterator; for ( filtersIterator = mPluginFilters.constBegin(); filtersIterator != mPluginFilters.constEnd(); ++filtersIterator ) { filtersIterator.value()->sendResponse(); } #endif if ( ! headersSent() ) { sendHeaders(); } sendBody(); //Clear the body to allow for streaming content to stdout clearBody(); }
void staticHandler(struct headers *request, int sockfd){ char filePath[MAX_URI_SIZE] = DOC_ROOT; char *uri = getHeader(request, "URI:"); strcat(filePath, uri); struct responseHeaders headers = {200, "OK", LOCATION, "text/html", "UTF-8", 0, false}; //defaults FILE *f = NULL; if(access(filePath, F_OK) != 0){ headers.code = 404; headers.codeName = "Not Found"; strcpy(filePath, "./not_found"); }else if(access(filePath, R_OK) != 0){ headers.code = 403; headers.codeName = "Forbidden"; strcpy(filePath, "./forbidden"); }else if(strcmp(uri, "/") == 0){ f = popen("/bin/ls", "r"); FILE *p = popen("ls | wc -c", "r"); //another pipe for finding size fscanf(p, "%d", &headers.fileSize); pclose(p); } if(f == NULL){ f = fopen(filePath, "r"); fseek(f, 0, SEEK_END); headers.fileSize = ftell(f); fseek(f, 0, SEEK_SET); } sendHeaders(headers, sockfd); sendFile(f, sockfd); }
int CCrawl::POST_data_Html(const string &url, const string &postdata) { setRequestMode(POST); m_CRequestUrl.setCRequestUrl(url); m_CRequestPostdata.setPostdata(postdata); try { sendUrl(m_httpRequest); sendHeaders(m_httpRequest); m_httpRequest->initCurlData(); sendProxy(m_httpRequest); m_httpRequest->getHeaderData(); sendPostdata(m_httpRequest); m_httpRequest->getWritaData(); m_httpRequest->perform(); }catch(std::exception &e) { cout<<e.what()<<endl; return 0; }catch(...) { printf("error catch! \n"); return 0; } return response_status_function(); }
// Client Interface uint32_t HTTPClientChannel::sendOnewayRequest( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<apache::thrift::ContextStack> ctx, unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { DestructorGuard dg(this); cb->context_ = RequestContext::saveContext(); HTTPTransactionOnewayCallback* owcb = nullptr; if (cb) { owcb = new HTTPTransactionOnewayCallback( std::move(cb), std::move(ctx), isSecurityActive()); } if (!httpSession_) { if (owcb) { TTransportException ex(TTransportException::NOT_OPEN, "HTTPSession is not open"); owcb->messageSendError( folly::make_exception_wrapper<TTransportException>(std::move(ex))); delete owcb; } return -1; } auto txn = httpSession_->newTransaction(owcb); if (!txn) { if (owcb) { TTransportException ex(TTransportException::NOT_OPEN, "Too many active requests on connection"); owcb->messageSendError( folly::make_exception_wrapper<TTransportException>(std::move(ex))); delete owcb; } return -1; } setRequestHeaderOptions(header.get()); addRpcOptionHeaders(header.get(), rpcOptions); auto msg = buildHTTPMessage(header.get()); txn->sendHeaders(msg); txn->sendBody(std::move(buf)); txn->sendEOM(); if (owcb) { owcb->sendQueued(); } return ResponseChannel::ONEWAY_REQUEST_ID; }
/** * * @param host * @param url * @return */ bool AdafruitHTTP::get(char const * host, char const *url) { printf(HTTP_METHOD_GET " %s " HTTP_VERSION, url); println(); printf("Host: %s", host); println(); sendHeaders(0); flush(); }
void HTTPReply::sendHeaders(uint responseCode, const QString &mimeType, const QVariantMap &headers) { QStringList headerList; foreach (const QString &key, headers.keys()) headerList << QString("%1: %2").arg(key, headers.value(key).toString()); sendHeaders(responseCode, mimeType, headerList); }
void sendResponse(const std::string& body) { m_transport->sendImpl(body.data(), body.length(), 200, false, true); EXPECT_EQ(m_server.m_messageQueue.size(), 1); EXPECT_CALL(m_txn, sendHeaders(_)); EXPECT_CALL(m_txn, sendBody(_)); EXPECT_CALL(m_txn, sendEOM()); m_server.deliverMessages(); }
void HttpCache::reportBadRequest(std::ostream & io, int status, const std::string & msg) { sendHeaders(io, status, "text/html", msg); io << "<html><head><title>" << status << " " << msg << "</title></head><body><h1>" << status << " - " << msg << "</h1></body></html>" << std::endl << std::flush; }
void respondString(int status, string data) { Cvar extraHeaders; extraHeaders["Content-Length"]=data.length(); extraHeaders["Content-Type"]="text/html"; sendHeaders(status, extraHeaders); sendData(asio::buffer(data)); }
void HttpCache::processQuery(std::ostream & io, const std::list<std::string> & headers) { if (headers.empty()) { reportBadRequest(io); return; } const std::string & request = headers.front(); std::string::size_type i = request.find(" "); if (i == std::string::npos) { reportBadRequest(io); return; } std::string query = request.substr(0, i); std::string path; ++i; std::string::size_type j = request.find(" ", i + 1); if (j != std::string::npos) { path = request.substr(i, j - i); } else { path = request.substr(i); } if (path == "/config") { sendHeaders(io); const varconf::sec_map & conf = global_conf->getSection(::instance); varconf::sec_map::const_iterator I = conf.begin(); varconf::sec_map::const_iterator Iend = conf.end(); for (; I != Iend; ++I) { io << I->first << " " << I->second << std::endl; } } else if (path == "/monitors") { sendHeaders(io); Monitors::instance()->send(io); } else { reportBadRequest(io, 404, "Not Found"); } io << std::flush; }
TEST_F(ProxygenTransportRepostTest, no_body) { InSequence enforceOrder; auto req = getRequest(HTTPMethod::POST); EXPECT_CALL(m_txn, sendHeaders(_)); EXPECT_CALL(m_txn, sendEOM()); m_transport->onHeadersComplete(std::move(req)); m_transport->beginPartialPostEcho(); m_transport->onEOM(); }
/** * POST with raw data useful for binary POST * @param host * @param url * @param raw_data * @param len * @return */ bool AdafruitHTTP::postRaw(char const * host, char const *url, uint8_t const* raw_data, uint16_t len ) { printf(HTTP_METHOD_POST " %s " HTTP_VERSION, url); println(); printf("Host: %s", host); println(); sendHeaders( len ); // send data write(raw_data, len); flush(); }
ITCPServerConnHandler::Command HttpReqImpl::processHandlerResponse(natural res) { //stDetach causes waiting for user wakeup. if (res == IHttpHandler::stSleep) { return ITCPServerConnHandler::cmdWaitUserWakeup; } //depend on whether headers has been sent if (bHeaderSent) { //in case of 100 response, keep connection on-line if (res == 100) { if (!isInputAvailable()) { evType = evEndOfStream; res = curHandler->onData(*this); if (res == 100) res =500; return processHandlerResponse(res); } return ITCPServerConnHandler::cmdWaitRead; } else if (res == IHttpHandler::stWaitForWrite) { return ITCPServerConnHandler::cmdWaitWrite; } else { finish(); //keep conection depend on keep-alive return keepAlive()?ITCPServerConnHandler::cmdWaitRead:ITCPServerConnHandler::cmdRemove; } } else { //in case of 100 response if (res == 100) { if (bNeedContinue) { send100continue(); } if (!isInputAvailable()) { res = curHandler->onData(*this); if (res == 100) res =500; return processHandlerResponse(res); } //keep connection alive return ITCPServerConnHandler::cmdWaitRead; } else if (res == IHttpHandler::stWaitForWrite) { sendHeaders(); return ITCPServerConnHandler::cmdWaitWrite; } //otherwise response with status page return errorPageKA(res); } }
TEST_F(ProxygenTransportRepostTest, mid_body_abort) { InSequence enforceOrder; auto req = getRequest(HTTPMethod::POST); auto body1 = folly::IOBuf::copyBuffer(std::string("hello")); auto body2 = folly::IOBuf::copyBuffer(std::string("world")); EXPECT_CALL(m_txn, sendHeaders(_)); EXPECT_CALL(m_txn, sendBody(_)) .Times(2); m_transport->onHeadersComplete(std::move(req)); m_transport->onBody(std::move(body1)); m_transport->beginPartialPostEcho(); m_transport->onBody(std::move(body2)); m_transport->abort(); }
int CCrawl::getResponseData() { try { sendUrl(m_httpRequest); sendHeaders(m_httpRequest); m_httpRequest->initCurlData(); sendProxy(m_httpRequest); m_httpRequest->getHeaderData(); if(m_requestMode == GET) { LOG4CPLUS_DEBUG(ClogCPP::m_logger,"http request mode: GET"); m_httpRequest->perform(); m_httpRequest->getContentType(); if(m_httpRequest->m_contentType.find("text", 0) == 0) { m_httpRequest->getWritaData(); m_httpRequest->perform(); } else if(m_httpRequest->m_contentType.find("image", 0) == 0) //app faild { string cmd = string("wget -P ./ ")+m_CRequestUrl.getCRequestUrl(); //cout<<cmd<<endl; system(cmd.c_str()); //m_httpRequest->getWritaDataToFile(m_CRequestUrl.getFilename()); //m_httpRequest->perform(); } } if(m_requestMode == POST) { LOG4CPLUS_DEBUG(ClogCPP::m_logger,"http request mode: POST"); sendPostdata(m_httpRequest); m_httpRequest->getWritaData(); m_httpRequest->perform(); } }catch(std::exception &e) { cout<<e.what()<<endl; return 0; }catch(...) { printf("error catch! \n"); return 0; } }
void expectPushPromiseAndHeaders( MockHTTPTransaction& pushTxn, uint8_t pri, HTTPPushTransactionHandler**pushHandlerPtr) { EXPECT_CALL(m_txn, newPushedTransaction(_)) .WillOnce(DoAll(SaveArg<0>(pushHandlerPtr), Return(&pushTxn))); EXPECT_CALL(pushTxn, sendHeaders(_)) .WillOnce(Invoke([pri] (const HTTPMessage& promise) { EXPECT_TRUE(promise.isRequest()); EXPECT_EQ(promise.getPriority(), pri); EXPECT_EQ(promise.getHeaders().getSingleOrEmpty("hello"), std::string("world")); })) .WillOnce(Invoke([] (const HTTPMessage& response) { EXPECT_TRUE(response.isResponse()); })); }
void HttpReqImpl::redirect(ConstStrA url, int code) { if (code == 0) { if (url.head(1) == ConstStrA('+')) code = 301; else code = 307; } TextParser<char> parser; if (parser("%[a-z]0://%",url)) { header(fldLocation, url); } else { StringA absurl = getAbsoluteUrl(url); header(fldLocation, absurl); } header(fldContentLength, "0"); status(code); sendHeaders(); }
bool HTTPDownstreamSession::onNativeProtocolUpgrade( HTTPCodec::StreamID streamID, CodecProtocol protocol, const std::string& protocolString, HTTPMessage& msg) { VLOG(4) << *this << " onNativeProtocolUpgrade streamID=" << streamID << " protocol=" << protocolString; auto txn = findTransaction(streamID); CHECK(txn); if (txn->canSendHeaders()) { // Create the new Codec auto codec = HTTPCodecFactory::getCodec(protocol, TransportDirection::DOWNSTREAM); CHECK(codec); if (!codec->onIngressUpgradeMessage(msg)) { VLOG(4) << *this << " codec rejected upgrade"; return false; } // Send a 101 Switching Protocols message while we still have HTTP codec // Note: it's possible that the client timed out waiting for a // 100-continue and ended up here first. In this case the 100 may go // out in the new protocol HTTPMessage switchingProtos; switchingProtos.setHTTPVersion(1, 1); switchingProtos.setStatusCode(101); switchingProtos.setStatusMessage("Switching Protocols"); switchingProtos.getHeaders().set(HTTP_HEADER_UPGRADE, protocolString); txn->sendHeaders(switchingProtos); // no sendEOM for 1xx // This will actually switch the protocol bool ret = HTTPSession::onNativeProtocolUpgradeImpl( streamID, std::move(codec), protocolString); if (ret) { codec_->addPriorityNodes(txnEgressQueue_, writeBuf_, 0); } return ret; } else { VLOG(4) << *this << " plaintext upgrade failed due to early response"; return false; } }
/** * * @param host * @param url * @param keyvalues * @param data_count * @param url_encode Perfom URL Encode on Data before POST * @note * POST Data is in form key1=value1&key2=value2 * where value[] could be url_encoded or not * @return */ bool AdafruitHTTP::post_internal(char const * host, char const *url, const char* keyvalues[][2], uint16_t count, bool url_encode) { printf(HTTP_METHOD_POST " %s " HTTP_VERSION, url); println(); printf("Host: %s", host); println(); // Determine the total data length uint16_t total_len = 0; for(uint16_t i = 0; i<count; i++) { total_len += (strlen(keyvalues[i][0]) + 1) + (url_encode ? urlEncodeLength(keyvalues[i][1]) : strlen(keyvalues[i][1])); } total_len += count-1; // number of "&" between each key=value // Send all headers sendHeaders( total_len ); // send data for(uint16_t i = 0; i<count; i++) { if (i != 0) print("&"); char const* key = keyvalues[i][0]; char const* value = keyvalues[i][1]; print(key); print("="); if (url_encode) { uint16_t bufsize = urlEncodeLength(value)+1; char* encoded_value = (char*) malloc(bufsize); urlEncode(value, encoded_value, bufsize); print(encoded_value); free(encoded_value); }else { print(value); } } println(); flush(); }
void HttpReqImpl::errorPage(natural code, ConstStrA msg, ConstStrA expl) { if (!bHeaderSent) { if (msg.empty()) msg = getStatusMessage(code); SeqFileOutput f(this); if (msg.empty()) msg = getStatusMessage(code); PrintTextA print(f); //clear some headers - they can damage output //delete content length - because we will show different page responseHdrs.erase(getHeaderFieldName(fldContentLength)); //delete transfer encoding - because we need simplest encoding responseHdrs.erase(getHeaderFieldName(fldTransferEncoding)); //delete content type - because we will set to text/html responseHdrs.erase(getHeaderFieldName(fldContentType)); //delete eTag - don't store eTag with an error page responseHdrs.erase(getHeaderFieldName(fldETag)); //delete lastModified - don't store error page responseHdrs.erase(getHeaderFieldName(fldLastModified)); status(code,msg); //set new content type header(fldContentType,"text/html"); if (code == 204 || code == 304) { //set ContentLength to zero even if it is not necesery, some clients can have issue header(fldContentLength,"0"); sendHeaders(); return; } else { closeConn = true; } print("<html><head><title>%1 %2</title></head><body><h1>%1 %2</h1>") << code << msg; if (!expl.empty()) print("<pre>%1</pre>")<< expl; print("<hr>"); print("<small><em>Powered by Bredy's JsonRpcServer - C++ http & jsonrpc server - <a href=\"https://github.com/ondra-novak/jsonrpcserver\">sources available</a></em></small>"); print("</body></html>"); } else { closeConn = true; } }
int CCrawl::GET_Html(const string &url, const string &imagefilename) { setRequestMode(GET); m_CRequestUrl.setCRequestUrl(url); m_CRequestUrl.setFilename(imagefilename); try { sendUrl(m_httpRequest); sendHeaders(m_httpRequest); m_httpRequest->initCurlData(); sendProxy(m_httpRequest); m_httpRequest->getHeaderData(); m_httpRequest->perform(); m_httpRequest->getContentType(); if(m_httpRequest->m_contentType.find("text", 0) == 0) { m_httpRequest->getWritaData(); m_httpRequest->perform(); } else if(m_httpRequest->m_contentType.find("image", 0) == 0) //img { string cmd = string("wget -P ./ ")+m_CRequestUrl.getCRequestUrl(); //cout<<cmd<<endl; system(cmd.c_str()); //m_httpRequest->getWritaDataToFile(m_CRequestUrl.getFilename()); //m_httpRequest->perform(); } }catch(std::exception &e) { cout<<e.what()<<endl; return 0; }catch(...) { printf("error catch! \n"); return 0; } return response_status_function(); }
void Pillow::HttpHandlerProxyPipe::proxiedReply_finished() { if (_proxiedReply->error() == QNetworkReply::NoError) { sendHeaders(); // Make sure headers have been sent; can cause the pipe to tear down. if (!_broken && _request->state() == Pillow::HttpConnection::SendingContent) { // The client request will still be in this state if the content-length was not specified. We must // close the connection to indicate the end of the content stream. _request->close(); } } else { if (!_broken && _request->state() == Pillow::HttpConnection::SendingHeaders) { // Finishing before sending headers means that we have a network or transport error. Let the client know about this. _request->writeResponse(503); } } }
void Server::sendResponse(Context *ctx, XmlDocSharedHelper doc) { sendHeaders(ctx); if (ctx->response()->suppressBody(ctx->request())) { return; } xmlCharEncodingHandlerPtr encoder = NULL; const std::string &encoding = ctx->documentWriter()->outputEncoding(); if (!encoding.empty() && 0 != strncasecmp(encoding.c_str(), "utf-8", sizeof("utf-8"))) { encoder = xmlFindCharEncodingHandler(encoding.c_str()); } xmlOutputBufferPtr buf = xmlOutputBufferCreateIO(writeFunc, closeFunc, ctx, encoder); XmlUtils::throwUnless(NULL != buf); try { ctx->documentWriter()->write(ctx->response(), doc.get(), buf); } catch(const std::exception &e) { xmlOutputBufferClose(buf); throw e; } }
/** Responds with messages that are in the json queue for this clients session * If the queue is empty, it doesnt send anything and returns false. * if it does respond with SOMETHING, even an error-response, it returns true. * Use abort to send an empty resonse without looking at the queue at all. * When longpoll is set to false, it always responds with data, even if the queue is empty. In this case if wont affect a waiting longpoll netid. */ bool respondJsonQueue(bool abort=false, bool longpoll=true) { string jsonStr; if (abort) { //to abort we need to reply with an empty json array: DEB(id << " cancelling longpoll"); jsonStr="[]"; httpSessionMan.endGet(id, mAuthCookie); } else { if (longpoll) { ThttpCookie authCookieClone=0; try { authCookieClone=mHeaders["x-synapse-authcookie-clone"]; } catch(...){ }; //check if there are messages in the queue, based on the authcookie from the current request: //This function will change authCookie if neccesary and fill jsonStr! httpSessionMan.getJsonQueue(id, mAuthCookie, jsonStr, authCookieClone); //authcookie was probably expired, respond with error if (!mAuthCookie) { respondError(400, "Session is expired, or session limit reached."); return(true); } } else { //we DO want to respond with something if its there, but we dont want to do long polling httpSessionMan.getJsonQueue(mAuthCookie, jsonStr); if (jsonStr=="") jsonStr="[]"; } } if (jsonStr=="") { //nothing to reply (yet), return false return(false); } else { //send headers Cvar extraHeaders; extraHeaders["Content-Length"]=jsonStr.length(); extraHeaders["Cache-Control"]="no-cache"; extraHeaders["Content-Type"]="application/json"; extraHeaders["X-Synapse-Authcookie"]=mAuthCookie; sendHeaders(200, extraHeaders); //write the json queue sendData(asio::buffer(jsonStr)); return(true); } }
RequestStream& Request::stream() { if (!_headersSent) sendHeaders(); return _stream; }
void Request::process() { Chrono totalChrono(true); Chrono sysChrono(true); _isPost = false; for (int i = 0; _fcgiRequest->envp[i] != 0; i++) { String str = _fcgiRequest->envp[i]; if (!str.contains("=")) continue; _env[str.tokenLeft("=")] = str.tokenRight("="); } /* for (Map<String, String>::Iterator i(_env); i.hasNext(); i++) std::cout << i.key() << "=" << i.value() << std::endl; //*/ _get = _env["QUERY_STRING"].secure().urlUnescape() .secure().parseQueryString(); // Don't forget to double secure() _path = _env["DOCUMENT_URI"].secure(); if (_env.get("REQUEST_METHOD", "GET") == "POST" && _env.hasKey("CONTENT_LENGTH")) { _isPost = true; int length = _env["CONTENT_LENGTH"].toInt() + 1; char* str = new char[length]; str[length - 1] = '\0'; _inputStream.read(str, length); _post = String(str).secure().urlUnescape().secure().parseQueryString(); delete[] str; } _ip = _env["REMOTE_ADDR"]; if (_env.hasKey("HTTP_COOKIE")) { StringList cookies = _env["HTTP_COOKIE"].secure().split("; "); for (String& cookie : cookies) { String key, value; if (cookie.contains("=")) { key = cookie.tokenLeft("="); value = cookie.tokenRight("="); } else key = cookie; _cookies[key] = value; } } if (System::settings()->behindProxy && _env.hasKey("HTTP_X_FORWARDED_FOR")) { try { _ip = _env["HTTP_X_FORWARDED_FOR"]; } catch (const Exceptions::BadIpAddr&) { } } if (System::setting("Sessions.Enabled")) { if (hasCookie(System::settings()->sessionIdCookieName) && hasCookie(System::settings()->sessionTokenCookieName)) { try { _session = Session::get( cookie(System::settings()->sessionIdCookieName).toInt(), cookie(System::settings()->sessionTokenCookieName), _ip); } catch (const Exceptions::NoSuchSession &e) { System::log("Security", "<" + _ip.toString() + "> " + e.message()); _session = new Session(this); } catch (const Exceptions::InvalidSessionToken &e) { System::log("Security", "<" + _ip.toString() + "> " + e.message(), System::Warning); _session = new Session(this); } catch (const Exceptions::SessionIpCheckFail &e) { System::log("Security", "<" + _ip.toString() + "> " + e.message(), System::Critical); _session = new Session(this); } } else _session = new Session(this); } setContentType(System::settings()->defaultContentType, System::settings()->defaultCharset); if (_session != nullptr) setLocale(_session->value("_LOCALE", Locale::defaultLocale()->name())); else _locale = Locale::defaultLocale(); _profile->addChronoTime(RequestProfile::System, sysChrono.elapsed()); if (System::hasExceptionHandling()) { try { try { System::get()->site()->router()->process(_path, this); } catch (const Exceptions::NoRouteToPath& e) { throw Exceptions::NotFound(uri()); } } catch (Exceptions::Segfault& e) { RequestError::segfault(this, e); } catch (Exception& e) { RequestError::exception(this, e); } catch(const std::exception& e) { RequestError::stdException(this, e); } } else System::get()->site()->router()->process(_path, this); if (!_headersSent) sendHeaders(); _profile->addChronoTime(RequestProfile::Total, totalChrono.elapsed()); }
uint32_t HTTPClientChannel::sendRequest( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<apache::thrift::ContextStack> ctx, unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { // cb is not allowed to be null. DCHECK(cb); DestructorGuard dg(this); cb->context_ = RequestContext::saveContext(); std::chrono::milliseconds timeout(timeout_); if (rpcOptions.getTimeout() > std::chrono::milliseconds(0)) { timeout = rpcOptions.getTimeout(); } auto twcb = new HTTPTransactionTwowayCallback(std::move(cb), std::move(ctx), isSecurityActive(), protocolId_, timer_.get(), std::chrono::milliseconds(timeout_)); if (!httpSession_) { TTransportException ex(TTransportException::NOT_OPEN, "HTTPSession is not open"); twcb->messageSendError( folly::make_exception_wrapper<TTransportException>(std::move(ex))); delete twcb; return -1; } auto txn = httpSession_->newTransaction(twcb); if (!txn) { TTransportException ex(TTransportException::NOT_OPEN, "Too many active requests on connection"); // Might be able to create another transaction soon ex.setOptions(TTransportException::CHANNEL_IS_VALID); twcb->messageSendError( folly::make_exception_wrapper<TTransportException>(std::move(ex))); delete twcb; return -1; } auto streamId = txn->getID(); setRequestHeaderOptions(header.get()); addRpcOptionHeaders(header.get(), rpcOptions); auto msg = buildHTTPMessage(header.get()); txn->sendHeaders(msg); txn->sendBody(std::move(buf)); txn->sendEOM(); twcb->sendQueued(); return (uint32_t)streamId; }
/* Cette fonction se reconnecte au server servername, * port serverport, toute les time secondes, avec un * maximum de _nb_tentatives. * * Si _nb_tentatives est NULL, ou égal a -1, alors il n'y * a aucune limite. * * Retourne la chausette créée */ int reconnect(int time, int _nb_tentatives, int _get_headers, icyHeaders *out_icy) { int tentatives = 0; int server_socket; serverSettings_t *settings; icyHeaders *icy; if (!time) time = 2; if (serversPool == NULL) { _ERROR("Error: not any server defined.\n"); exit(1); } /* Get an entry in the pool */ settings = getSettings(serversPool, &poolPosition); if (settings == NULL) { _ERROR("No valid settings in urlPool.\n"); exit(1); } RECO: sleep(time); while ( (server_socket = server_connect(settings->serverAddr, settings->port)) < 0) { /* Get an entry in the pool */ settings = getSettings(serversPool, &poolPosition); if (settings == NULL) { _ERROR("No valid settings in urlPool.\n"); exit(1); } tentatives++; if ((tentatives > _nb_tentatives) && (_nb_tentatives != -1)) { MESSAGE("Too many tentatives. Exiting program.\n"); exit(-2); } MESSAGE("Reconnecting to http://%s:%d%s [try %d] in %d sec.\n", settings->serverAddr, settings->port, settings->mountpoint, tentatives, time); sleep(time); } VERBOSE("Time spent to reconnect: %d seconds, %d tentatives.\n", (tentatives * time), tentatives); if (sendHeaders(server_socket, settings->mountpoint, 1) <= 0) { _ERROR("Error sending headers: 0 byte sent.\n"); goto RECO; } if (_get_headers) { if ( (icy = readicyheaders(getHeaders(server_socket))) == NULL) goto RECO; else out_icy = icy; } cPigeStats->reconnections++; return server_socket; }