Http1Server.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2018 The Squid Software Foundation and contributors
3  *
4  * Squid software is distributed under GPLv2+ license and includes
5  * contributions from numerous individuals and organizations.
6  * Please see the COPYING and CONTRIBUTORS files for details.
7  */
8 
9 /* DEBUG: section 33 Client-side Routines */
10 
11 #include "squid.h"
12 #include "acl/FilledChecklist.h"
13 #include "client_side.h"
14 #include "client_side_reply.h"
15 #include "client_side_request.h"
16 #include "comm/Write.h"
17 #include "http/one/RequestParser.h"
18 #include "http/Stream.h"
19 #include "HttpHeaderTools.h"
20 #include "profiler/Profiler.h"
21 #include "servers/Http1Server.h"
22 #include "SquidConfig.h"
23 #include "Store.h"
24 
26 
27 Http::One::Server::Server(const MasterXaction::Pointer &xact, bool beHttpsServer):
28  AsyncJob("Http1::Server"),
29  ConnStateData(xact),
30  isHttpsServer(beHttpsServer)
31 {
32 }
33 
34 time_t
36 {
38 }
39 
40 void
42 {
44 
45  // XXX: Until we create an HttpsServer class, use this hack to allow old
46  // client_side.cc code to manipulate ConnStateData object directly
47  if (isHttpsServer) {
48  postHttpsAccept();
49  return;
50  }
51 
52  typedef CommCbMemFunT<Server, CommTimeoutCbParams> TimeoutDialer;
53  AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
54  TimeoutDialer, this, Http1::Server::requestTimeout);
55  commSetConnTimeout(clientConnection, Config.Timeout.request_start_timeout, timeoutCall);
56  readSomeData();
57 }
58 
59 void
61 {
62  if (!handleRequestBodyData())
63  return;
64 
65  // too late to read more body
66  if (!isOpen() || stoppedReceiving())
67  return;
68 
69  readSomeData();
70 }
71 
74 {
75  PROF_start(HttpServer_parseOneRequest);
76 
77  // parser is incremental. Generate new parser state if we,
78  // a) do not have one already
79  // b) have completed the previous request parsing already
80  if (!parser_ || !parser_->needsMoreData())
81  parser_ = new Http1::RequestParser(mayTunnelUnsupportedProto());
82 
83  /* Process request */
84  Http::Stream *context = parseHttpRequest(this, parser_);
85 
86  PROF_stop(HttpServer_parseOneRequest);
87  return context;
88 }
89 
92 
93 bool
95 {
97  ClientHttpRequest *http = context->http;
98  if (context->flags.parsed_ok == 0) {
99  debugs(33, 2, "Invalid Request");
100  // determine which error page templates to use for specific parsing errors
101  err_type errPage = ERR_INVALID_REQ;
102  switch (parser_->parseStatusCode) {
104  // fall through to next case
105  case Http::scUriTooLong:
106  errPage = ERR_TOO_BIG;
107  break;
109  errPage = ERR_UNSUP_REQ;
110  break;
112  errPage = ERR_UNSUP_HTTPVERSION;
113  break;
114  default:
115  if (parser_->method() == METHOD_NONE || parser_->requestUri().length() == 0)
116  // no method or url parsed, probably is wrong protocol
117  errPage = ERR_PROTOCOL_UNKNOWN;
118  // else use default ERR_INVALID_REQ set above.
119  break;
120  }
121  // setLogUri should called before repContext->setReplyToError
122  setLogUri(http, http->uri, true);
123  const char * requestErrorBytes = inBuf.c_str();
124  if (!clientTunnelOnError(this, context, request, parser_->method(), errPage)) {
125  setReplyError(context, request, parser_->method(), errPage, parser_->parseStatusCode, requestErrorBytes);
126  // HttpRequest object not build yet, there is no reason to call
127  // clientProcessRequestFinished method
128  }
129 
130  return false;
131  }
132 
133  // TODO: move URL parse into Http Parser and INVALID_URL into the above parse error handling
135  mx->tcpClient = clientConnection;
136  if ((request = HttpRequest::FromUrl(http->uri, mx, parser_->method())) == NULL) {
137  debugs(33, 5, "Invalid URL: " << http->uri);
138  // setLogUri should called before repContext->setReplyToError
139  setLogUri(http, http->uri, true);
140 
141  const char * requestErrorBytes = inBuf.c_str();
142  if (!clientTunnelOnError(this, context, request, parser_->method(), ERR_INVALID_URL)) {
143  setReplyError(context, request, parser_->method(), ERR_INVALID_URL, Http::scBadRequest, requestErrorBytes);
144  // HttpRequest object not build yet, there is no reason to call
145  // clientProcessRequestFinished method
146  }
147  return false;
148  }
149 
150  /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
151  /* We currently only support 0.9, 1.0, 1.1 properly */
152  /* TODO: move HTTP-specific processing into servers/HttpServer and such */
153  if ( (parser_->messageProtocol().major == 0 && parser_->messageProtocol().minor != 9) ||
154  (parser_->messageProtocol().major > 1) ) {
155 
156  debugs(33, 5, "Unsupported HTTP version discovered. :\n" << parser_->messageProtocol());
157  // setLogUri should called before repContext->setReplyToError
158  setLogUri(http, http->uri, true);
159 
160  const char * requestErrorBytes = NULL; //HttpParserHdrBuf(parser_);
161  if (!clientTunnelOnError(this, context, request, parser_->method(), ERR_UNSUP_HTTPVERSION)) {
162  setReplyError(context, request, parser_->method(), ERR_UNSUP_HTTPVERSION, Http::scHttpVersionNotSupported, requestErrorBytes);
163  clientProcessRequestFinished(this, request);
164  }
165  return false;
166  }
167 
168  /* compile headers */
169  if (parser_->messageProtocol().major >= 1 && !request->parseHeader(*parser_.getRaw())) {
170  debugs(33, 5, "Failed to parse request headers:\n" << parser_->mimeHeader());
171  // setLogUri should called before repContext->setReplyToError
172  setLogUri(http, http->uri, true);
173  const char * requestErrorBytes = NULL; //HttpParserHdrBuf(parser_);
174  if (!clientTunnelOnError(this, context, request, parser_->method(), ERR_INVALID_REQ)) {
175  setReplyError(context, request, parser_->method(), ERR_INVALID_REQ, Http::scBadRequest, requestErrorBytes);
176  clientProcessRequestFinished(this, request);
177  }
178  return false;
179  }
180 
181  // when absolute-URI is provided Host header should be ignored. However
182  // some code still uses Host directly so normalize it using the previously
183  // sanitized URL authority value.
184  // For now preserve the case where Host is completely absent. That matters.
185  if (const auto x = request->header.delById(Http::HOST)) {
186  debugs(33, 5, "normalize " << x << " Host header using " << request->url.authority());
187  SBuf tmp(request->url.authority());
188  request->header.putStr(Http::HOST, tmp.c_str());
189  }
190 
191  // TODO: We fill request notes here until we find a way to verify whether
192  // no ACL checking is performed before ClientHttpRequest::doCallouts().
193  if (hasNotes()) {
194  assert(!request->hasNotes());
195  request->notes()->append(notes().getRaw());
196  }
197 
198  http->request = request.getRaw();
199  HTTPMSGLOCK(http->request);
200 
201  return true;
202 }
203 
204 void
205 Http::One::Server::setReplyError(Http::StreamPointer &context, HttpRequest::Pointer &request, const HttpRequestMethod& method, err_type requestError, Http::StatusCode errStatusCode, const char *requestErrorBytes)
206 {
207  quitAfterError(request.getRaw());
208  if (!context->connRegistered()) {
209  debugs(33, 2, "Client stream deregister it self, nothing to do");
210  clientConnection->close();
211  return;
212  }
213  clientStreamNode *node = context->getClientReplyContext();
214  clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
215  assert (repContext);
216 
217  repContext->setReplyToError(requestError, errStatusCode, method, context->http->uri, clientConnection->remote, nullptr, requestErrorBytes, nullptr);
218 
219  assert(context->http->out.offset == 0);
220  context->pullData();
221 }
222 
223 void
225 {
226  debugs(33, 5, "Body Continuation written");
227  clientProcessRequest(this, parser_, context.getRaw());
228 }
229 
230 void
232 {
233  if (!buildHttpRequest(context))
234  return;
235 
236  ClientHttpRequest *http = context->http;
238 
239  if (request->header.has(Http::HdrType::EXPECT)) {
240  const String expect = request->header.getList(Http::HdrType::EXPECT);
241  const bool supportedExpect = (expect.caseCmp("100-continue") == 0);
242  if (!supportedExpect) {
243  clientStreamNode *node = context->getClientReplyContext();
244  quitAfterError(request.getRaw());
245  // setLogUri should called before repContext->setReplyToError
246  setLogUri(http, urlCanonicalClean(request.getRaw()));
247  clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
248  assert (repContext);
250  clientConnection->remote, request.getRaw(), NULL, NULL);
251  assert(context->http->out.offset == 0);
252  context->pullData();
253  clientProcessRequestFinished(this, request);
254  return;
255  }
256 
258  ACLFilledChecklist bodyContinuationCheck(Config.accessList.forceRequestBodyContinuation, request.getRaw(), NULL);
259  if (bodyContinuationCheck.fastCheck().allowed()) {
260  debugs(33, 5, "Body Continuation forced");
261  request->forcedBodyContinuation = true;
262  //sendControlMsg
263  HttpReply::Pointer rep = new HttpReply;
265 
267  const AsyncCall::Pointer cb = asyncCall(11, 3, "Http1::Server::proceedAfterBodyContinuation", CbDialer(this, &Http1::Server::proceedAfterBodyContinuation, Http::StreamPointer(context)));
268  sendControlMsg(HttpControlMsg(rep, cb));
269  return;
270  }
271  }
272  }
273  clientProcessRequest(this, parser_, context.getRaw());
274 }
275 
276 void
278 {
280  stopReceiving("virgin request body consumer aborted"); // closes ASAP
281 }
282 
283 void
285 {
286  // the caller guarantees that we are dealing with the current context only
287  Http::StreamPointer context = pipeline.front();
288  Must(context != nullptr);
289  const ClientHttpRequest *http = context->http;
290  Must(http != NULL);
291 
292  // After sending Transfer-Encoding: chunked (at least), always send
293  // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
294  const bool mustSendLastChunk = http->request->flags.chunkedReply &&
295  !http->request->flags.streamError &&
297  !context->startOfOutput();
298  const bool responseFinishedOrFailed = !rep &&
299  !receivedData.data &&
300  !receivedData.length;
301  if (responseFinishedOrFailed && !mustSendLastChunk) {
302  context->writeComplete(0);
303  return;
304  }
305 
306  if (!context->startOfOutput()) {
307  context->sendBody(receivedData);
308  return;
309  }
310 
311  assert(rep);
312  http->al->reply = rep;
313  HTTPMSGLOCK(http->al->reply);
314  context->sendStartOfMessage(rep, receivedData);
315 }
316 
317 bool
319 {
320  Http::StreamPointer context = pipeline.front();
321  Must(context != nullptr);
322 
323  // Ignore this late control message if we have started sending a
324  // reply to the user already (e.g., after an error).
325  if (context->reply) {
326  debugs(11, 2, "drop 1xx made late by " << context->reply);
327  return false;
328  }
329 
330  const ClientHttpRequest *http = context->http;
331 
332  // apply selected clientReplyContext::buildReplyHeader() mods
333  // it is not clear what headers are required for control messages
335  rep->header.putStr(Http::HdrType::CONNECTION, "keep-alive");
336  httpHdrMangleList(&rep->header, http->request, http->al, ROR_REPLY);
337 
338  MemBuf *mb = rep->pack();
339 
340  debugs(11, 2, "HTTP Client " << clientConnection);
341  debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb->buf << "\n----------");
342 
343  Comm::Write(clientConnection, mb, call);
344 
345  delete mb;
346  return true;
347 }
348 
351 {
352  return new Http1::Server(xact, false);
353 }
354 
357 {
358  return new Http1::Server(xact, true);
359 }
360 
int delById(Http::HdrType id)
Definition: HttpHeader.cc:672
AnyP::ProtocolVersion ProtocolVersion(unsigned int aMajor, unsigned int aMinor)
HTTP version label information.
int has(Http::HdrType id) const
Definition: HttpHeader.cc:1002
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
Definition: AsyncJobCalls.h:68
bool buildHttpRequest(Http::StreamPointer &context)
Definition: Http1Server.cc:94
#define assert(EX)
Definition: assert.h:17
bool isOpen(const int fd)
Definition: comm.cc:86
int caseCmp(char const *) const
Definition: String.cc:299
ConnStateData * NewServer(MasterXactionPointer &xact)
create a new HTTP connection handler; never returns NULL
Definition: Http1Server.cc:350
Definition: Server.h:28
void setReplyToError(err_type, Http::StatusCode, const HttpRequestMethod &, char const *, Ip::Address &, HttpRequest *, const char *, Auth::UserRequest::Pointer)
builds error using clientBuildError() and calls setReplyToError() below
void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason=NULL)
Definition: StatusLine.cc:30
virtual void processParsedRequest(Http::StreamPointer &context)
start processing a freshly parsed request
Definition: Http1Server.cc:231
Definition: SBuf.h:86
virtual time_t idleTimeout() const
timeout to use when waiting for the next request
Definition: Http1Server.cc:35
HttpRequestMethod method
Definition: HttpRequest.h:102
void setLogUri(ClientHttpRequest *http, char const *uri, bool cleanUrl)
acl_access * forceRequestBodyContinuation
Definition: SquidConfig.h:400
struct _request * request(char *urlin)
Definition: tcp-banger2.c:291
void removeHopByHopEntries()
Definition: HttpHeader.cc:1713
MemBuf * pack() const
Definition: HttpReply.cc:101
void proceedAfterBodyContinuation(Http::StreamPointer context)
Definition: Http1Server.cc:224
bool forcedBodyContinuation
whether we have responded with HTTP 100 or FTP 150 already
Definition: HttpRequest.h:183
void HTTPMSGLOCK(Http::Message *a)
Definition: Message.h:154
#define Must(condition)
Like assert() but throws an exception instead of aborting the process.
Definition: TextException.h:69
void clientProcessRequestFinished(ConnStateData *conn, const HttpRequest::Pointer &request)
CBDATA_NAMESPACED_CLASS_INIT(Http1, Server)
int conn
the current server connection FD
Definition: Transport.cc:26
void requestTimeout(const CommTimeoutCbParams &params)
AsyncCall * asyncCall(int aDebugSection, int aDebugLevel, const char *aName, const Dialer &aDialer)
Definition: AsyncCall.h:156
virtual void handleReply(HttpReply *rep, StoreIOBuffer receivedData)
Definition: Http1Server.cc:284
NotePairs::Pointer notes()
Definition: HttpRequest.cc:680
Definition: parse.c:104
StatusCode
Definition: StatusCode.h:20
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Debug.h:124
HttpReply * reply
void clientProcessRequest(ConnStateData *conn, const Http1::RequestParserPointer &hp, Http::Stream *context)
Manages a connection from an HTTP/1 or HTTP/0.9 client.
Definition: Http1Server.h:20
ConnStateData * NewServer(MasterXactionPointer &xact)
create a new HTTPS connection handler; never returns NULL
Definition: Http1Server.cc:356
bool streamError
Definition: RequestFlags.h:94
Server(const MasterXaction::Pointer &xact, const bool beHttpsServer)
Definition: Http1Server.cc:27
String getList(Http::HdrType id) const
Definition: HttpHeader.cc:819
bool chunkedReply
Definition: RequestFlags.h:92
StoreEntry * storeEntry() const
bundles HTTP 1xx reply and the "successfully forwarded" callback
AnyP::Uri url
the request URI
Definition: HttpRequest.h:103
Http::Stream * parseHttpRequest(ConnStateData *csd, const Http1::RequestParserPointer &hp)
uint16_t flags
Definition: Store.h:206
bool hasNotes() const
Definition: HttpRequest.h:233
ClientStreamData data
Definition: clientStream.h:94
AccessLogEntry::Pointer al
access.log entry
Http::StatusLine sline
Definition: HttpReply.h:60
virtual void noteBodyConsumerAborted(BodyPipe::Pointer)
Definition: Http1Server.cc:277
time_t request_start_timeout
Definition: SquidConfig.h:115
virtual void noteMoreBodySpaceAvailable(BodyPipe::Pointer)
Definition: Http1Server.cc:60
static HttpRequest * FromUrl(const char *url, const MasterXaction::Pointer &, const HttpRequestMethod &method=Http::METHOD_GET)
Definition: HttpRequest.cc:522
struct SquidConfig::@99 Timeout
bool clientTunnelOnError(ConnStateData *conn, Http::StreamPointer &context, HttpRequest::Pointer &request, const HttpRequestMethod &method, err_type requestError)
HttpHeader header
Definition: Message.h:74
char * buf
Definition: MemBuf.h:134
RequestFlags flags
Definition: HttpRequest.h:129
void putStr(Http::HdrType id, const char *str)
Definition: HttpHeader.cc:1063
#define PROF_start(probename)
Definition: Profiler.h:62
virtual Http::Stream * parseOneRequest()
Definition: Http1Server.cc:73
struct SquidConfig::@114 accessList
size_t HttpReply *STUB StoreEntry const KeyScope scope const HttpRequestMethod & method
Definition: stub_store.cc:126
time_t clientIdlePconn
Definition: SquidConfig.h:109
Definition: MemBuf.h:23
void setReplyError(Http::StreamPointer &context, HttpRequest::Pointer &request, const HttpRequestMethod &method, err_type requestError, Http::StatusCode errStatusCode, const char *requestErrorBytes)
Definition: Http1Server.cc:205
#define PROF_stop(probename)
Definition: Profiler.h:63
virtual void start()
called by AsyncStart; do not call directly
Definition: Http1Server.cc:41
virtual bool writeControlMsgAndCall(HttpReply *rep, AsyncCall::Pointer &call)
handle a control message received by context from a peer and call back
Definition: Http1Server.cc:318
SBuf & authority(bool requirePort=false) const
Definition: Uri.cc:470
char * urlCanonicalClean(const HttpRequest *request)
Definition: Uri.cc:518
bool parseHeader(Http1::Parser &)
Definition: Message.cc:223
int commSetConnTimeout(const Comm::ConnectionPointer &conn, int timeout, AsyncCall::Pointer &callback)
Definition: comm.cc:552
#define EBIT_TEST(flag, bit)
Definition: defines.h:107
C * getRaw() const
Definition: RefCount.h:74
Comm::ConnectionPointer tcpClient
the client TCP connection which originated this transaction
Definition: MasterXaction.h:53
class SquidConfig Config
Definition: SquidConfig.cc:12
void append(const NotePairs *src)
Append the entries of the src NotePairs list to our list.
Definition: Notes.cc:342
#define NULL
Definition: types.h:166
void httpHdrMangleList(HttpHeader *l, HttpRequest *request, const AccessLogEntryPointer &al, req_or_rep_t req_or_rep)
void Write(const Comm::ConnectionPointer &conn, const char *buf, int size, AsyncCall::Pointer &callback, FREE *free_func)
Definition: Write.cc:35
virtual void start()
called by AsyncStart; do not call directly
virtual void noteBodyConsumerAborted(BodyPipe::Pointer)=0
err_type
Definition: err_type.h:12

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors