HTTPServerRequestImpl::HTTPServerRequestImpl(HTTPServerResponse& response, HTTPServerSession& session, HTTPServerParams* pParams): _response(response), _pStream(0), _pParams(pParams) { poco_check_ptr (_pParams); _pParams->duplicate(); HTTPHeaderInputStream hs(session); read(hs); // Now that we know socket is still connected, obtain addresses _clientAddress = session.clientAddress(); _serverAddress = session.serverAddress(); if (getChunkedTransferEncoding()) _pStream = new HTTPChunkedInputStream(session); else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH) _pStream = new HTTPFixedLengthInputStream(session, getContentLength()); else if (getMethod() == HTTPRequest::HTTP_GET || getMethod() == HTTPRequest::HTTP_HEAD) _pStream = new HTTPFixedLengthInputStream(session, 0); else _pStream = new HTTPInputStream(session); }
HttpParseResult HttpRequest::parsePostData(HttpServer *server, pbuf* buf) { int start = 0; // First enter if (requestPostParameters == NULL) { int headerEnd = NetUtils::pbufFindStr(buf, "\r\n\r\n"); if (headerEnd == -1) return eHPR_Failed; if (headerEnd + getContentLength() > NETWORK_MAX_HTTP_PARSING_LEN) { debugf("NETWORK_MAX_HTTP_PARSING_LEN"); return eHPR_Failed; } requestPostParameters = new HashMap<String, String>(); start = headerEnd + 4; combinePostFrag = false; } else if (combinePostFrag) { String cur = requestPostParameters->keyAt(requestPostParameters->count() - 1); debugf("Continue POST frag %s", cur.c_str()); int delimItem = NetUtils::pbufFindChar(buf, '&', 0); if (delimItem == -1) delimItem = buf->tot_len; else combinePostFrag = false; String itemValue = NetUtils::pbufStrCopy(buf, 0, delimItem); //debugf("Continue POST len %d", itemValue.length()); char* buf = uri_unescape(NULL, 0, itemValue.c_str(), -1); itemValue = buf; free(buf); (*requestPostParameters)[cur] += itemValue; start = delimItem + 1; postDataProcessed += start; } bool notFinished = extractParsingItemsList(buf, start, buf->tot_len, '&', ' ', requestPostParameters); if (notFinished) combinePostFrag = true; // continue reading this parameter value //TODO: continue for param name postDataProcessed += buf->tot_len - start; if (postDataProcessed == getContentLength()) return eHPR_Successful; else return eHPR_Wait; }
static int getHttpResponseParam(HttpStateData *httpState,char *buf, ssize_t len) { HttpReply *reply = httpState->entry->mem_obj->reply; request_t *request = httpState->request; assert(reply); if (reply->sline.status != HTTP_OK) { debug(207, 1) ("mod_m3u8_prefetch httpState entry url: %s, reply status = %d is not 200\n",storeUrl(httpState->entry),reply->sline.status); return 0; } request_param *r= cc_get_mod_private_data(REQUEST_T_PRIVATE_DATA, request, mod); if (!r) { r = request_param_pool_alloc(); r->m3u8_fd = -1; r->content_length = -1; r->remain_clen = -1; strncpy(r->default_prefix, request->canonical, strlen(request->canonical)); char *end= strstr(r->default_prefix, ".m3u8"); *end ='\0'; debug(207, 3) ("Debug input_buf1=[%s]\n",r->default_prefix); end = strrchr(r->default_prefix,'/'); *(end+1) = '\0'; debug(207, 3)("Debug input_buf=[%s]\n",r->default_prefix); cc_register_mod_private_data(REQUEST_T_PRIVATE_DATA, request,r, free_request_param,mod); } long content_length = getContentLength(httpState); if (content_length > 0) { r->content_length = content_length; r->remain_clen = content_length; } debug(207, 1) ("mod_m3u8_prefetch getHttpResponseParam url=%s,content_length=%ld,remain_clen=%ld\n",storeUrl(httpState->entry),r->content_length, r->remain_clen); return 0; }
HttpParseResult HttpRequest::parsePostData(HttpServer *server, pbuf* buf) { int start = 0; tmpbuf += NetUtils::pbufStrCopy(buf, 0, buf->tot_len); // First enter if (requestPostParameters == NULL) { int headerEnd = NetUtils::pbufFindStr(buf, "\r\n\r\n"); if (headerEnd == -1) return eHPR_Failed; if (headerEnd + getContentLength() > NETWORK_MAX_HTTP_PARSING_LEN) { debugf("NETWORK_MAX_HTTP_PARSING_LEN"); return eHPR_Failed; } requestPostParameters = new HashMap<String, String>(); start = headerEnd + 4; tmpbuf = tmpbuf.substring(start, tmpbuf.length()); } //parse if it is FormUrlEncoded - otherwise keep in buffer String contType = getContentType(); contType.toLowerCase(); if (contType.indexOf(ContentType::FormUrlEncoded) != -1) { tmpbuf = extractParsingItemsList(tmpbuf, 0, tmpbuf.length(), '&', ' ', requestPostParameters); } postDataProcessed += buf->tot_len - start ; if (postDataProcessed == getContentLength()) { return eHPR_Successful; } else if (postDataProcessed > getContentLength()) { //avoid bufferoverflow if client announces non-correct content-length debugf("NETWORK_MAX_HTTP_PARSING_LEN"); return eHPR_Failed; } else { return eHPR_Wait; } }
uint HttpMessage::getSize() { int lineReturnSize = 1; int headersSize = 0; for(auto x : headers) headersSize += x.first.size() + x.second.size() + 2 + lineReturnSize; return getHeadSize() + getContentLength() + headersSize + lineReturnSize * 2; }
/* Extracts the body of the response (null-terminated response) */ char* receiveResponse(int socketFd) { int bytes, received, total; int responseLength = 200; /* Should be sufficiently large to accommodate the full HTTP header section */ char* responseBody; char* response = (char*)malloc(sizeof(char)*responseLength); memset(response,0,sizeof(char)*responseLength); /* Initialize response buffer */ total = responseLength; received = 0; int capturedLen; char* newBuffer; int foundContentSize = 0; int totalResponseSize=0; int separatorIndex; do { bytes = read(socketFd,response+received,total-received); if (bytes < 0) { printErrorAndExit("ERROR reading message from socket"); return NULL; } received+=bytes; if (foundContentSize==0) /* Don't perform this action if "Content-Length" has been found already */ { capturedLen = getContentLength(response,received); separatorIndex = getHeaderBodySeparatorIndex(response, received); if ((capturedLen!=-1) && (separatorIndex!=-1)) { totalResponseSize=separatorIndex+4+capturedLen; if (totalResponseSize>total) { /* allocate larger array */ newBuffer = (char*)malloc(sizeof(char)*(totalResponseSize)); memcpy(newBuffer,response,received); free(response); response = newBuffer; total = totalResponseSize; } foundContentSize=1; } } if ((foundContentSize==1) && (received==totalResponseSize)) break; if (bytes == 0) break; } while (received < total); responseBody=NULL; int index=getHeaderBodySeparatorIndex(response, total); if ((index==-1) || (foundContentSize==0) || (capturedLen==0)) return NULL; if (response[received-1]=='\n') capturedLen--; responseBody = (char*)malloc(sizeof(char)*(capturedLen+1)); memcpy(responseBody,response+index+4,capturedLen); responseBody[capturedLen]='\0'; free(response); return responseBody; }
int setCgiEnv(char *message) { char msg[MESSAGE_MAX_LEN]; memcpy(msg, message, MESSAGE_MAX_LEN); setenv("REQUEST_METHOD", getMethod(msg), 1); setenv("CONTENT_LENGTH", getContentLength(msg), 1); setenv("QUERY_STRING", getQueryString(msg), 1); return 0; }
float BaseProgressArgs::getProgress() const { std::streamsize contentLength = getContentLength(); if (Poco::Net::HTTPMessage::UNKNOWN_CONTENT_LENGTH == contentLength) { return Poco::Net::HTTPMessage::UNKNOWN_CONTENT_LENGTH; } else { return _totalBytesTransferred / (float)contentLength; } }
cgicc::CgiEnvironment::CgiEnvironment(CgiInput *input) { // Create a local CgiInput object for us to use // In the vast majority of cases, this will be used // For FastCGI applications it won't but the performance hit of // an empty inline constructor is negligible CgiInput local_input; if(0 == input) readEnvironmentVariables(&local_input); else readEnvironmentVariables(input); // On Win32, use binary read to avoid CRLF conversion #ifdef WIN32 # ifdef __BORLANDC__ setmode(_fileno(stdin), O_BINARY); # else _setmode(_fileno(stdin), _O_BINARY); # endif #endif if(stringsAreEqual(fRequestMethod, "post")) { // Don't use auto_ptr, but vector instead // Bug reported by [email protected] std::vector<char> data(fContentLength); if(getenv("CGICC_MAX_CONTENTLENGTH")&&getContentLength()>atoi(getenv("CGICC_MAX_CONTENTLENGTH"))) { exit(1); } else // If input is 0, use the default implementation of CgiInput if ( getContentLength() ) { // If input is 0, use the default implementation of CgiInput if ( input == 0 ) { if ( local_input.read( &data[0], getContentLength() ) != getContentLength() ) throw std::runtime_error("I/O error"); } else if ( input->read( &data[0], getContentLength() ) != getContentLength() ) throw std::runtime_error("I/O error"); fPostData = std::string( &data[0], getContentLength() ); } } fCookies.reserve(10); parseCookies(); }
gridfs_offset GridFile::write( ostream & out ) { _exists(); const int num = getNumChunks(); for ( int i=0; i<num; i++ ) { GridFSChunk c = getChunk( i ); int len; const char * data = c.data( len ); out.write( data , len ); } return getContentLength(); }
/** * Save the file located at the given path to the SD card with the provided * local name. * * \param[in] path The path to the file on the host. * \param[in] localName The desired name for the local copy of the file. * * \return true if the download is successfull, false in case of failure. */ bool Download::save(const char* path, const char* localName) { // check socket if (!wifly_->connectedTo_P(host_)) return false; // load host name to SRAM char host[DOWNLOAD_HOST_BUFFER_SIZE]; strlcpy_P(host, host_, DOWNLOAD_HOST_BUFFER_SIZE); // fetch content length and compute the number of pieces uint32_t fileSize = getContentLength(buffer_, bufferSize_, host, path); if (fileSize == 0) return false; uint16_t nbPieces = (fileSize - 1)/bufferSize_ + 1; // create the local file if (!sd_->init(SPI_EIGHTH_SPEED, sdChipSelectPin_)) { sd_->initErrorHalt(); return false; } if (sd_->exists(localName)) sd_->remove(localName); if (!open(localName, O_CREAT | O_WRITE)) { return false; } // download the file piece by piece uint32_t firstByte, lastByte; for (uint32_t i = 0; i < nbPieces; i++) { firstByte = i * bufferSize_; if (i < nbPieces - 1) lastByte = firstByte + bufferSize_ - 1; else if (i == nbPieces - 1) lastByte = fileSize - 1; while (!getRange(buffer_, bufferSize_, host, path, firstByte, lastByte)); write(buffer_, lastByte - firstByte + 1); sync(); } // close the file close(); return true; }
std::ostream& HTTPServerResponseImpl::send() { poco_assert (!_pStream); if ((_pRequest && _pRequest->getMethod() == HTTPRequest::HTTP_HEAD) || getStatus() < 200 || getStatus() == HTTPResponse::HTTP_NO_CONTENT || getStatus() == HTTPResponse::HTTP_NOT_MODIFIED) { Poco::CountingOutputStream cs; write(cs); _pStream = new HTTPFixedLengthOutputStream(_session, cs.chars()); write(*_pStream); } else if (getChunkedTransferEncoding()) { HTTPHeaderOutputStream hs(_session); write(hs); _pStream = new HTTPChunkedOutputStream(_session); } else if (hasContentLength()) { Poco::CountingOutputStream cs; write(cs); #if defined(POCO_HAVE_INT64) _pStream = new HTTPFixedLengthOutputStream(_session, getContentLength64() + cs.chars()); #else _pStream = new HTTPFixedLengthOutputStream(_session, getContentLength() + cs.chars()); #endif write(*_pStream); } else { _pStream = new HTTPOutputStream(_session); setKeepAlive(false); write(*_pStream); } return *_pStream; }