]>
Commit | Line | Data |
---|---|---|
dd11e0b7 | 1 | /* |
262a0e14 | 2 | * $Id$ |
dd11e0b7 | 3 | * |
4 | * DEBUG: section 33 Client-side Routines | |
5 | * AUTHOR: Duane Wessels | |
6 | * | |
2b6662ba | 7 | * SQUID Web Proxy Cache http://www.squid-cache.org/ |
e25c139f | 8 | * ---------------------------------------------------------- |
dd11e0b7 | 9 | * |
2b6662ba | 10 | * Squid is the result of efforts by numerous individuals from |
11 | * the Internet community; see the CONTRIBUTORS file for full | |
12 | * details. Many organizations have provided support for Squid's | |
13 | * development; see the SPONSORS file for full details. Squid is | |
14 | * Copyrighted (C) 2001 by the Regents of the University of | |
15 | * California; see the COPYRIGHT file for full details. Squid | |
16 | * incorporates software developed and/or copyrighted by other | |
17 | * sources; see the CREDITS file for full details. | |
dd11e0b7 | 18 | * |
19 | * This program is free software; you can redistribute it and/or modify | |
20 | * it under the terms of the GNU General Public License as published by | |
21 | * the Free Software Foundation; either version 2 of the License, or | |
22 | * (at your option) any later version. | |
9e008dda | 23 | * |
dd11e0b7 | 24 | * This program is distributed in the hope that it will be useful, |
25 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
26 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
27 | * GNU General Public License for more details. | |
9e008dda | 28 | * |
dd11e0b7 | 29 | * You should have received a copy of the GNU General Public License |
30 | * along with this program; if not, write to the Free Software | |
cbdec147 | 31 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. |
e25c139f | 32 | * |
dd11e0b7 | 33 | */ |
f88bb09c | 34 | |
63be0a78 | 35 | /** |
36 | \defgroup ClientSide Client-Side Logics | |
37 | * | |
d85b8894 | 38 | \section cserrors Errors and client side |
edce4d98 | 39 | * |
63be0a78 | 40 | \par Problem the first: |
41 | * the store entry is no longer authoritative on the | |
edce4d98 | 42 | * reply status. EBITTEST (E_ABORT) is no longer a valid test outside |
43 | * of client_side_reply.c. | |
44 | * Problem the second: resources are wasted if we delay in cleaning up. | |
45 | * Problem the third we can't depend on a connection close to clean up. | |
9e008dda | 46 | * |
63be0a78 | 47 | \par Nice thing the first: |
9e008dda | 48 | * Any step in the stream can callback with data |
edce4d98 | 49 | * representing an error. |
50 | * Nice thing the second: once you stop requesting reads from upstream, | |
51 | * upstream can be stopped too. | |
52 | * | |
63be0a78 | 53 | \par Solution #1: |
54 | * Error has a callback mechanism to hand over a membuf | |
9e008dda | 55 | * with the error content. The failing node pushes that back as the |
edce4d98 | 56 | * reply. Can this be generalised to reduce duplicate efforts? |
57 | * A: Possibly. For now, only one location uses this. | |
58 | * How to deal with pre-stream errors? | |
59 | * Tell client_side_reply that we *want* an error page before any | |
60 | * stream calls occur. Then we simply read as normal. | |
63be0a78 | 61 | * |
62 | * | |
d85b8894 | 63 | \section pconn_logic Persistent connection logic: |
63be0a78 | 64 | * |
65 | \par | |
66 | * requests (httpClientRequest structs) get added to the connection | |
67 | * list, with the current one being chr | |
9e008dda | 68 | * |
63be0a78 | 69 | \par |
70 | * The request is *immediately* kicked off, and data flows through | |
71 | * to clientSocketRecipient. | |
9e008dda | 72 | * |
63be0a78 | 73 | \par |
74 | * If the data that arrives at clientSocketRecipient is not for the current | |
75 | * request, clientSocketRecipient simply returns, without requesting more | |
76 | * data, or sending it. | |
77 | * | |
78 | \par | |
9e008dda AJ |
79 | * ClientKeepAliveNextRequest will then detect the presence of data in |
80 | * the next ClientHttpRequest, and will send it, restablishing the | |
63be0a78 | 81 | * data flow. |
edce4d98 | 82 | */ |
83 | ||
f88bb09c | 84 | #include "squid.h" |
04f55905 AJ |
85 | |
86 | #include "acl/FilledChecklist.h" | |
2f1431ea | 87 | #if USE_AUTH |
04f55905 | 88 | #include "auth/UserRequest.h" |
2f1431ea | 89 | #endif |
00406b24 | 90 | #include "base/Subscription.h" |
d841c88d | 91 | #include "base/TextException.h" |
04f55905 | 92 | #include "ChunkedCodingParser.h" |
a46d2c0e | 93 | #include "client_side.h" |
04f55905 AJ |
94 | #include "client_side_reply.h" |
95 | #include "client_side_request.h" | |
d841c88d AJ |
96 | #if USE_DELAY_POOLS |
97 | #include "ClientInfo.h" | |
98 | #endif | |
04f55905 | 99 | #include "ClientRequestContext.h" |
c8be6d7b | 100 | #include "clientStream.h" |
c4b7a5a9 | 101 | #include "comm.h" |
cfd66529 | 102 | #include "comm/Connection.h" |
cbff89ba | 103 | #include "CommCalls.h" |
d841c88d | 104 | #include "comm/Loops.h" |
ec41b64c | 105 | #include "comm/Write.h" |
cbff89ba | 106 | #include "comm/TcpAcceptor.h" |
056b24a1 | 107 | #include "eui/Config.h" |
04f55905 | 108 | #include "fde.h" |
25b6a907 | 109 | #include "HttpHdrContRange.h" |
528b2c61 | 110 | #include "HttpReply.h" |
111 | #include "HttpRequest.h" | |
4daaf3cb AJ |
112 | #include "ident/Config.h" |
113 | #include "ident/Ident.h" | |
cbff89ba | 114 | #include "ipc/FdNotes.h" |
fe090a86 | 115 | #include "ipc/StartListening.h" |
0eb49b6d | 116 | #include "MemBuf.h" |
04f55905 AJ |
117 | #include "MemObject.h" |
118 | #include "ProtoPort.h" | |
1fa9b1a7 | 119 | #include "rfc1738.h" |
985c86bc | 120 | #include "SquidTime.h" |
95d2589c CT |
121 | #if USE_SSL |
122 | #include "ssl/context_storage.h" | |
123 | #include "ssl/helper.h" | |
4db984be | 124 | #include "ssl/support.h" |
95d2589c CT |
125 | #include "ssl/gadgets.h" |
126 | #endif | |
127 | #if USE_SSL_CRTD | |
128 | #include "ssl/crtd_message.h" | |
129 | #include "ssl/certificate_db.h" | |
130 | #endif | |
d841c88d | 131 | #include "Store.h" |
81a94152 | 132 | #include "TimeOrTag.h" |
95d2589c CT |
133 | |
134 | #if HAVE_LIMITS | |
135 | #include <limits> | |
136 | #endif | |
137 | ||
5492ad1d | 138 | #if LINGERING_CLOSE |
139 | #define comm_close comm_lingering_close | |
140 | #endif | |
141 | ||
cbff89ba | 142 | /// dials clientListenerConnectionOpened call |
fe090a86 AR |
143 | class ListeningStartedDialer: public CallDialer, public Ipc::StartListeningCb |
144 | { | |
145 | public: | |
8bbb16e3 AJ |
146 | typedef void (*Handler)(http_port_list *portCfg, const Ipc::FdNoteId note, const Subscription::Pointer &sub); |
147 | ListeningStartedDialer(Handler aHandler, http_port_list *aPortCfg, const Ipc::FdNoteId note, const Subscription::Pointer &aSub): | |
148 | handler(aHandler), portCfg(aPortCfg), portTypeNote(note), sub(aSub) {} | |
fe090a86 | 149 | |
5667a628 AR |
150 | virtual void print(std::ostream &os) const { |
151 | startPrint(os) << | |
8bbb16e3 | 152 | ", " << FdNote(portTypeNote) << " port=" << (void*)portCfg << ')'; |
5667a628 | 153 | } |
fe090a86 AR |
154 | |
155 | virtual bool canDial(AsyncCall &) const { return true; } | |
8bbb16e3 | 156 | virtual void dial(AsyncCall &) { (handler)(portCfg, portTypeNote, sub); } |
fe090a86 AR |
157 | |
158 | public: | |
159 | Handler handler; | |
160 | ||
161 | private: | |
cbff89ba AJ |
162 | http_port_list *portCfg; ///< from Config.Sockaddr.http |
163 | Ipc::FdNoteId portTypeNote; ///< Type of IPC socket being opened | |
cbff89ba | 164 | Subscription::Pointer sub; ///< The handler to be subscribed for this connetion listener |
fe090a86 AR |
165 | }; |
166 | ||
8bbb16e3 | 167 | static void clientListenerConnectionOpened(http_port_list *s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub); |
fe090a86 | 168 | |
edce4d98 | 169 | /* our socket-related context */ |
62e76326 | 170 | |
62e76326 | 171 | |
0655fa4d | 172 | CBDATA_CLASS_INIT(ClientSocketContext); |
62e76326 | 173 | |
0655fa4d | 174 | void * |
175 | ClientSocketContext::operator new (size_t byteCount) | |
176 | { | |
177 | /* derived classes with different sizes must implement their own new */ | |
178 | assert (byteCount == sizeof (ClientSocketContext)); | |
179 | CBDATA_INIT_TYPE(ClientSocketContext); | |
180 | return cbdataAlloc(ClientSocketContext); | |
181 | } | |
62e76326 | 182 | |
0655fa4d | 183 | void |
184 | ClientSocketContext::operator delete (void *address) | |
185 | { | |
186 | cbdataFree (address); | |
187 | } | |
7a2f978b | 188 | |
edce4d98 | 189 | /* Local functions */ |
528b2c61 | 190 | /* ClientSocketContext */ |
be364179 | 191 | static ClientSocketContext *ClientSocketContextNew(const Comm::ConnectionPointer &clientConn, ClientHttpRequest *); |
edce4d98 | 192 | /* other */ |
2b663917 | 193 | static IOCB clientWriteComplete; |
194 | static IOCB clientWriteBodyComplete; | |
e0d28505 | 195 | static IOACB httpAccept; |
40d34a62 | 196 | #if USE_SSL |
e0d28505 | 197 | static IOACB httpsAccept; |
40d34a62 | 198 | #endif |
8d77a37c | 199 | static CTCB clientLifetimeTimeout; |
719c7e0a | 200 | static ClientSocketContext *parseHttpRequestAbort(ConnStateData * conn, const char *uri); |
1cf238db | 201 | static ClientSocketContext *parseHttpRequest(ConnStateData *, HttpParser *, HttpRequestMethod *, HttpVersion *); |
3898f57f | 202 | #if USE_IDENT |
05832ae1 | 203 | static IDCB clientIdentDone; |
3898f57f | 204 | #endif |
edce4d98 | 205 | static CSCB clientSocketRecipient; |
206 | static CSD clientSocketDetach; | |
59a1efb2 | 207 | static void clientSetKeepaliveFlag(ClientHttpRequest *); |
190154cf | 208 | static int clientIsContentLengthValid(HttpRequest * r); |
47f6e231 | 209 | static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength); |
50c09fc4 | 210 | |
c8be6d7b | 211 | static void clientUpdateStatHistCounters(log_type logType, int svc_time); |
212 | static void clientUpdateStatCounters(log_type logType); | |
213 | static void clientUpdateHierCounters(HierarchyLogEntry *); | |
528b2c61 | 214 | static bool clientPingHasFinished(ping_data const *aPing); |
3ff65596 | 215 | void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry *); |
e4a67a80 | 216 | #ifndef PURIFY |
5c336a3b | 217 | static bool connIsUsable(ConnStateData * conn); |
e4a67a80 | 218 | #endif |
2324cda2 | 219 | static int responseFinishedOrFailed(HttpReply * rep, StoreIOBuffer const &receivedData); |
1cf238db | 220 | static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest, ConnStateData * conn); |
c8be6d7b | 221 | static void clientUpdateSocketStats(log_type logType, size_t size); |
222 | ||
84cc2635 | 223 | char *skipLeadingSpace(char *aString); |
3b299123 | 224 | static void connNoteUseOfBuffer(ConnStateData* conn, size_t byteCount); |
62e76326 | 225 | |
be364179 | 226 | static ConnStateData *connStateCreate(const Comm::ConnectionPointer &client, http_port_list *port); |
ae7ff0b8 | 227 | |
c8be6d7b | 228 | |
229 | clientStreamNode * | |
528b2c61 | 230 | ClientSocketContext::getTail() const |
c8be6d7b | 231 | { |
0655fa4d | 232 | if (http->client_stream.tail) |
233 | return (clientStreamNode *)http->client_stream.tail->data; | |
234 | ||
235 | return NULL; | |
c8be6d7b | 236 | } |
237 | ||
238 | clientStreamNode * | |
528b2c61 | 239 | ClientSocketContext::getClientReplyContext() const |
c8be6d7b | 240 | { |
528b2c61 | 241 | return (clientStreamNode *)http->client_stream.tail->prev->data; |
c8be6d7b | 242 | } |
243 | ||
63be0a78 | 244 | /** |
c4b7a5a9 | 245 | * This routine should be called to grow the inbuf and then |
246 | * call comm_read(). | |
247 | */ | |
248 | void | |
a46d2c0e | 249 | ConnStateData::readSomeData() |
c4b7a5a9 | 250 | { |
a46d2c0e | 251 | if (reading()) |
62e76326 | 252 | return; |
253 | ||
73c36fd9 | 254 | debugs(33, 4, HERE << clientConnection << ": reading request..."); |
62e76326 | 255 | |
90737510 | 256 | if (!maybeMakeSpaceAvailable()) |
1368d115 | 257 | return; |
62e76326 | 258 | |
1cf238db | 259 | typedef CommCbMemFunT<ConnStateData, CommIoCbParams> Dialer; |
d1c7f781 | 260 | reader = JobCallback(33, 5, Dialer, this, ConnStateData::clientReadRequest); |
73c36fd9 | 261 | comm_read(clientConnection, in.addressToReadInto(), getAvailableBufferLength(), reader); |
c4b7a5a9 | 262 | } |
62e76326 | 263 | |
c4b7a5a9 | 264 | |
c8be6d7b | 265 | void |
1cf238db | 266 | ClientSocketContext::removeFromConnectionList(ConnStateData * conn) |
c8be6d7b | 267 | { |
0655fa4d | 268 | ClientSocketContext::Pointer *tempContextPointer; |
1cf238db | 269 | assert(conn != NULL && cbdataReferenceValid(conn)); |
94a396a3 | 270 | assert(conn->getCurrentContext() != NULL); |
c8be6d7b | 271 | /* Unlink us from the connection request list */ |
0655fa4d | 272 | tempContextPointer = & conn->currentobject; |
62e76326 | 273 | |
0655fa4d | 274 | while (tempContextPointer->getRaw()) { |
62e76326 | 275 | if (*tempContextPointer == this) |
276 | break; | |
277 | ||
278 | tempContextPointer = &(*tempContextPointer)->next; | |
c8be6d7b | 279 | } |
62e76326 | 280 | |
0655fa4d | 281 | assert(tempContextPointer->getRaw() != NULL); |
528b2c61 | 282 | *tempContextPointer = next; |
283 | next = NULL; | |
c8be6d7b | 284 | } |
ea6f43cd | 285 | |
0655fa4d | 286 | ClientSocketContext::~ClientSocketContext() |
f88bb09c | 287 | { |
0655fa4d | 288 | clientStreamNode *node = getTail(); |
289 | ||
290 | if (node) { | |
291 | ClientSocketContext *streamContext = dynamic_cast<ClientSocketContext *> (node->data.getRaw()); | |
292 | ||
293 | if (streamContext) { | |
294 | /* We are *always* the tail - prevent recursive free */ | |
295 | assert(this == streamContext); | |
296 | node->data = NULL; | |
297 | } | |
298 | } | |
299 | ||
300 | if (connRegistered_) | |
301 | deRegisterWithConn(); | |
302 | ||
303 | httpRequestFree(http); | |
304 | ||
edce4d98 | 305 | /* clean up connection links to us */ |
c53577d9 | 306 | assert(this != next.getRaw()); |
0655fa4d | 307 | } |
62e76326 | 308 | |
0655fa4d | 309 | void |
310 | ClientSocketContext::registerWithConn() | |
311 | { | |
312 | assert (!connRegistered_); | |
313 | assert (http); | |
94a396a3 | 314 | assert (http->getConn() != NULL); |
0655fa4d | 315 | connRegistered_ = true; |
98242069 | 316 | http->getConn()->addContextToQueue(this); |
0655fa4d | 317 | } |
318 | ||
319 | void | |
320 | ClientSocketContext::deRegisterWithConn() | |
321 | { | |
322 | assert (connRegistered_); | |
98242069 | 323 | removeFromConnectionList(http->getConn()); |
0655fa4d | 324 | connRegistered_ = false; |
325 | } | |
326 | ||
327 | void | |
328 | ClientSocketContext::connIsFinished() | |
329 | { | |
330 | assert (http); | |
94a396a3 | 331 | assert (http->getConn() != NULL); |
0655fa4d | 332 | deRegisterWithConn(); |
333 | /* we can't handle any more stream data - detach */ | |
334 | clientStreamDetach(getTail(), http); | |
335 | } | |
336 | ||
fedd1531 | 337 | ClientSocketContext::ClientSocketContext() : http(NULL), reply(NULL), next(NULL), |
0655fa4d | 338 | writtenToSocket(0), |
339 | mayUseConnection_ (false), | |
340 | connRegistered_ (false) | |
341 | { | |
342 | memset (reqbuf, '\0', sizeof (reqbuf)); | |
343 | flags.deferred = 0; | |
344 | flags.parsed_ok = 0; | |
345 | deferredparams.node = NULL; | |
346 | deferredparams.rep = NULL; | |
f88bb09c | 347 | } |
348 | ||
528b2c61 | 349 | ClientSocketContext * |
be364179 | 350 | ClientSocketContextNew(const Comm::ConnectionPointer &client, ClientHttpRequest * http) |
f88bb09c | 351 | { |
528b2c61 | 352 | ClientSocketContext *newContext; |
edce4d98 | 353 | assert(http != NULL); |
0655fa4d | 354 | newContext = new ClientSocketContext; |
c8be6d7b | 355 | newContext->http = http; |
be364179 | 356 | newContext->clientConnection = client; |
c8be6d7b | 357 | return newContext; |
4d55827a | 358 | } |
359 | ||
655daa06 AR |
360 | void |
361 | ClientSocketContext::writeControlMsg(HttpControlMsg &msg) | |
362 | { | |
363 | HttpReply *rep = msg.reply; | |
364 | Must(rep); | |
365 | ||
366 | // apply selected clientReplyContext::buildReplyHeader() mods | |
367 | // it is not clear what headers are required for control messages | |
368 | rep->header.removeHopByHopEntries(); | |
369 | rep->header.putStr(HDR_CONNECTION, "keep-alive"); | |
370 | httpHdrMangleList(&rep->header, http->request, ROR_REPLY); | |
371 | ||
372 | // remember the callback | |
373 | cbControlMsgSent = msg.cbSuccess; | |
374 | ||
375 | MemBuf *mb = rep->pack(); | |
376 | ||
1ce34ddd AJ |
377 | debugs(11, 2, "HTTP Client " << clientConnection); |
378 | debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb->buf << "\n----------"); | |
379 | ||
655daa06 AR |
380 | AsyncCall::Pointer call = commCbCall(33, 5, "ClientSocketContext::wroteControlMsg", |
381 | CommIoCbPtrFun(&WroteControlMsg, this)); | |
73c36fd9 | 382 | Comm::Write(clientConnection, mb, call); |
655daa06 AR |
383 | |
384 | delete mb; | |
385 | } | |
386 | ||
387 | /// called when we wrote the 1xx response | |
388 | void | |
e0d28505 | 389 | ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer &conn, char *, size_t, comm_err_t errflag, int xerrno) |
655daa06 AR |
390 | { |
391 | if (errflag == COMM_ERR_CLOSING) | |
392 | return; | |
393 | ||
394 | if (errflag == COMM_OK) { | |
395 | ScheduleCallHere(cbControlMsgSent); | |
396 | return; | |
397 | } | |
398 | ||
399 | debugs(33, 3, HERE << "1xx writing failed: " << xstrerr(xerrno)); | |
400 | // no error notification: see HttpControlMsg.h for rationale and | |
401 | // note that some errors are detected elsewhere (e.g., close handler) | |
402 | ||
403 | // close on 1xx errors to be conservative and to simplify the code | |
404 | // (if we do not close, we must notify the source of a failure!) | |
80463bb4 | 405 | conn->close(); |
655daa06 AR |
406 | } |
407 | ||
408 | /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob | |
409 | void | |
e0d28505 | 410 | ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data) |
655daa06 AR |
411 | { |
412 | ClientSocketContext *context = static_cast<ClientSocketContext*>(data); | |
e0d28505 | 413 | context->wroteControlMsg(conn, bufnotused, size, errflag, xerrno); |
655daa06 AR |
414 | } |
415 | ||
edce4d98 | 416 | #if USE_IDENT |
4d55827a | 417 | static void |
edce4d98 | 418 | clientIdentDone(const char *ident, void *data) |
4d55827a | 419 | { |
cc59d02a | 420 | ConnStateData *conn = (ConnStateData *)data; |
73c36fd9 | 421 | xstrncpy(conn->clientConnection->rfc931, ident ? ident : dash_str, USER_IDENT_SZ); |
e81957b7 | 422 | } |
447e176b | 423 | #endif |
7a2f978b | 424 | |
c8be6d7b | 425 | void |
426 | clientUpdateStatCounters(log_type logType) | |
a7c05555 | 427 | { |
83704487 | 428 | statCounter.client_http.requests++; |
62e76326 | 429 | |
c8be6d7b | 430 | if (logTypeIsATcpHit(logType)) |
62e76326 | 431 | statCounter.client_http.hits++; |
432 | ||
c8be6d7b | 433 | if (logType == LOG_TCP_HIT) |
62e76326 | 434 | statCounter.client_http.disk_hits++; |
c8be6d7b | 435 | else if (logType == LOG_TCP_MEM_HIT) |
62e76326 | 436 | statCounter.client_http.mem_hits++; |
c8be6d7b | 437 | } |
438 | ||
439 | void | |
440 | clientUpdateStatHistCounters(log_type logType, int svc_time) | |
441 | { | |
83704487 | 442 | statHistCount(&statCounter.client_http.all_svc_time, svc_time); |
63be0a78 | 443 | /** |
ee1679df | 444 | * The idea here is not to be complete, but to get service times |
445 | * for only well-defined types. For example, we don't include | |
1d7ab0f4 | 446 | * LOG_TCP_REFRESH_FAIL because its not really a cache hit |
ee1679df | 447 | * (we *tried* to validate it, but failed). |
448 | */ | |
62e76326 | 449 | |
c8be6d7b | 450 | switch (logType) { |
62e76326 | 451 | |
1d7ab0f4 | 452 | case LOG_TCP_REFRESH_UNMODIFIED: |
62e76326 | 453 | statHistCount(&statCounter.client_http.nh_svc_time, svc_time); |
454 | break; | |
455 | ||
ee1679df | 456 | case LOG_TCP_IMS_HIT: |
62e76326 | 457 | statHistCount(&statCounter.client_http.nm_svc_time, svc_time); |
458 | break; | |
459 | ||
ee1679df | 460 | case LOG_TCP_HIT: |
62e76326 | 461 | |
ee1679df | 462 | case LOG_TCP_MEM_HIT: |
62e76326 | 463 | |
b540e168 | 464 | case LOG_TCP_OFFLINE_HIT: |
62e76326 | 465 | statHistCount(&statCounter.client_http.hit_svc_time, svc_time); |
466 | break; | |
467 | ||
ee1679df | 468 | case LOG_TCP_MISS: |
62e76326 | 469 | |
ee1679df | 470 | case LOG_TCP_CLIENT_REFRESH_MISS: |
62e76326 | 471 | statHistCount(&statCounter.client_http.miss_svc_time, svc_time); |
472 | break; | |
473 | ||
ee1679df | 474 | default: |
62e76326 | 475 | /* make compiler warnings go away */ |
476 | break; | |
ee1679df | 477 | } |
c8be6d7b | 478 | } |
479 | ||
528b2c61 | 480 | bool |
c8be6d7b | 481 | clientPingHasFinished(ping_data const *aPing) |
482 | { | |
483 | if (0 != aPing->stop.tv_sec && 0 != aPing->start.tv_sec) | |
62e76326 | 484 | return true; |
485 | ||
528b2c61 | 486 | return false; |
c8be6d7b | 487 | } |
488 | ||
489 | void | |
490 | clientUpdateHierCounters(HierarchyLogEntry * someEntry) | |
491 | { | |
492 | ping_data *i; | |
62e76326 | 493 | |
c8547a11 | 494 | switch (someEntry->code) { |
495 | #if USE_CACHE_DIGESTS | |
62e76326 | 496 | |
c8547a11 | 497 | case CD_PARENT_HIT: |
62e76326 | 498 | |
a196e1e4 | 499 | case CD_SIBLING_HIT: |
62e76326 | 500 | statCounter.cd.times_used++; |
501 | break; | |
c8547a11 | 502 | #endif |
62e76326 | 503 | |
c8547a11 | 504 | case SIBLING_HIT: |
62e76326 | 505 | |
c8547a11 | 506 | case PARENT_HIT: |
62e76326 | 507 | |
c8547a11 | 508 | case FIRST_PARENT_MISS: |
62e76326 | 509 | |
c8547a11 | 510 | case CLOSEST_PARENT_MISS: |
62e76326 | 511 | statCounter.icp.times_used++; |
512 | i = &someEntry->ping; | |
513 | ||
514 | if (clientPingHasFinished(i)) | |
515 | statHistCount(&statCounter.icp.query_svc_time, | |
516 | tvSubUsec(i->start, i->stop)); | |
517 | ||
518 | if (i->timeout) | |
519 | statCounter.icp.query_timeouts++; | |
520 | ||
521 | break; | |
522 | ||
c8547a11 | 523 | case CLOSEST_PARENT: |
62e76326 | 524 | |
c8547a11 | 525 | case CLOSEST_DIRECT: |
62e76326 | 526 | statCounter.netdb.times_used++; |
527 | ||
528 | break; | |
529 | ||
69c95dd3 | 530 | default: |
62e76326 | 531 | break; |
17b6e784 | 532 | } |
a7c05555 | 533 | } |
534 | ||
528b2c61 | 535 | void |
536 | ClientHttpRequest::updateCounters() | |
c8be6d7b | 537 | { |
528b2c61 | 538 | clientUpdateStatCounters(logType); |
62e76326 | 539 | |
528b2c61 | 540 | if (request->errType != ERR_NONE) |
62e76326 | 541 | statCounter.client_http.errors++; |
542 | ||
528b2c61 | 543 | clientUpdateStatHistCounters(logType, |
1cf238db | 544 | tvSubMsec(start_time, current_time)); |
62e76326 | 545 | |
528b2c61 | 546 | clientUpdateHierCounters(&request->hier); |
c8be6d7b | 547 | } |
548 | ||
edce4d98 | 549 | void |
3ff65596 | 550 | prepareLogWithRequestDetails(HttpRequest * request, AccessLogEntry * aLogEntry) |
7a2f978b | 551 | { |
c8be6d7b | 552 | assert(request); |
553 | assert(aLogEntry); | |
7684c4b1 | 554 | |
555 | if (Config.onoff.log_mime_hdrs) { | |
556 | Packer p; | |
557 | MemBuf mb; | |
2fe7eff9 | 558 | mb.init(); |
7684c4b1 | 559 | packerToMemInit(&p, &mb); |
a9925b40 | 560 | request->header.packInto(&p); |
105d1937 A |
561 | //This is the request after adaptation or redirection |
562 | aLogEntry->headers.adapted_request = xstrdup(mb.buf); | |
563 | ||
564 | // the virgin request is saved to aLogEntry->request | |
565 | if (aLogEntry->request) { | |
566 | packerClean(&p); | |
567 | mb.reset(); | |
568 | packerToMemInit(&p, &mb); | |
569 | aLogEntry->request->header.packInto(&p); | |
570 | aLogEntry->headers.request = xstrdup(mb.buf); | |
571 | } | |
3ff65596 | 572 | |
5038f9d8 AR |
573 | #if USE_ADAPTATION |
574 | const Adaptation::History::Pointer ah = request->adaptLogHistory(); | |
575 | if (ah != NULL) { | |
576 | packerClean(&p); | |
577 | mb.reset(); | |
578 | packerToMemInit(&p, &mb); | |
579 | ah->lastMeta.packInto(&p); | |
99690f32 | 580 | aLogEntry->adapt.last_meta = xstrdup(mb.buf); |
5038f9d8 | 581 | } |
3ff65596 AR |
582 | #endif |
583 | ||
7684c4b1 | 584 | packerClean(&p); |
2fe7eff9 | 585 | mb.clean(); |
7684c4b1 | 586 | } |
587 | ||
3ff65596 | 588 | #if ICAP_CLIENT |
5038f9d8 | 589 | const Adaptation::Icap::History::Pointer ih = request->icapHistory(); |
3ff65596 AR |
590 | if (ih != NULL) |
591 | aLogEntry->icap.processingTime = ih->processingTime(); | |
592 | #endif | |
593 | ||
c8be6d7b | 594 | aLogEntry->http.method = request->method; |
595 | aLogEntry->http.version = request->http_ver; | |
c8be6d7b | 596 | aLogEntry->hier = request->hier; |
3ff65596 AR |
597 | if (request->content_length > 0) // negative when no body or unknown length |
598 | aLogEntry->cache.requestSize += request->content_length; | |
5b4117d8 | 599 | aLogEntry->cache.extuser = request->extacl_user.termedBuf(); |
abb929f0 | 600 | |
2f1431ea | 601 | #if USE_AUTH |
a33a428a | 602 | if (request->auth_user_request != NULL) { |
f5691f9c | 603 | if (request->auth_user_request->username()) |
a33a428a | 604 | aLogEntry->cache.authuser = xstrdup(request->auth_user_request->username()); |
7a2f978b | 605 | } |
2f1431ea | 606 | #endif |
64b66b76 | 607 | |
a119c6ad AR |
608 | // Adapted request, if any, inherits and then collects all the stats, but |
609 | // the virgin request gets logged instead; copy the stats to log them. | |
610 | // TODO: avoid losses by keeping these stats in a shared history object? | |
64b66b76 | 611 | if (aLogEntry->request) { |
a119c6ad | 612 | aLogEntry->request->dnsWait = request->dnsWait; |
64b66b76 CT |
613 | aLogEntry->request->errType = request->errType; |
614 | aLogEntry->request->errDetail = request->errDetail; | |
615 | } | |
c8be6d7b | 616 | } |
617 | ||
618 | void | |
528b2c61 | 619 | ClientHttpRequest::logRequest() |
620 | { | |
f5f9e44c | 621 | if (!out.size && !logType) |
6fd1086a AR |
622 | debugs(33, 5, HERE << "logging half-baked transaction: " << log_uri); |
623 | ||
624 | al.icp.opcode = ICP_INVALID; | |
625 | al.url = log_uri; | |
626 | debugs(33, 9, "clientLogRequest: al.url='" << al.url << "'"); | |
62e76326 | 627 | |
6fd1086a AR |
628 | if (al.reply) { |
629 | al.http.code = al.reply->sline.status; | |
630 | al.http.content_type = al.reply->content_type.termedBuf(); | |
631 | } else if (loggingEntry() && loggingEntry()->mem_obj) { | |
632 | al.http.code = loggingEntry()->mem_obj->getReply()->sline.status; | |
633 | al.http.content_type = loggingEntry()->mem_obj->getReply()->content_type.termedBuf(); | |
634 | } | |
5f8252d2 | 635 | |
6fd1086a | 636 | debugs(33, 9, "clientLogRequest: http.code='" << al.http.code << "'"); |
90a8964c | 637 | |
6fd1086a AR |
638 | if (loggingEntry() && loggingEntry()->mem_obj) |
639 | al.cache.objectSize = loggingEntry()->contentLen(); | |
cc192b50 | 640 | |
6fd1086a | 641 | al.cache.caddr.SetNoAddr(); |
90a8964c | 642 | |
28417506 CT |
643 | if (getConn() != NULL) { |
644 | al.cache.caddr = getConn()->log_addr; | |
645 | al.cache.port = cbdataReference(getConn()->port); | |
646 | } | |
1a86db31 | 647 | |
6fd1086a AR |
648 | al.cache.requestSize = req_sz; |
649 | al.cache.requestHeadersSize = req_sz; | |
90a8964c | 650 | |
6fd1086a AR |
651 | al.cache.replySize = out.size; |
652 | al.cache.replyHeadersSize = out.headers_sz; | |
90a8964c | 653 | |
6fd1086a | 654 | al.cache.highOffset = out.offset; |
90a8964c | 655 | |
6fd1086a | 656 | al.cache.code = logType; |
62e76326 | 657 | |
6fd1086a | 658 | al.cache.msec = tvSubMsec(start_time, current_time); |
62e76326 | 659 | |
6fd1086a AR |
660 | if (request) |
661 | prepareLogWithRequestDetails(request, &al); | |
62e76326 | 662 | |
1b76e6c1 AJ |
663 | if (getConn() != NULL && getConn()->clientConnection != NULL && getConn()->clientConnection->rfc931[0]) |
664 | al.cache.rfc931 = getConn()->clientConnection->rfc931; | |
62e76326 | 665 | |
2ea1afad | 666 | #if USE_SSL && 0 |
62e76326 | 667 | |
6fd1086a AR |
668 | /* This is broken. Fails if the connection has been closed. Needs |
669 | * to snarf the ssl details some place earlier.. | |
670 | */ | |
671 | if (getConn() != NULL) | |
672 | al.cache.ssluser = sslGetUserEmail(fd_table[getConn()->fd].ssl); | |
62e76326 | 673 | |
a7ad6e4e | 674 | #endif |
62e76326 | 675 | |
6fd1086a | 676 | ACLFilledChecklist *checklist = clientAclChecklistCreate(Config.accessList.log, this); |
62e76326 | 677 | |
6fd1086a AR |
678 | if (al.reply) |
679 | checklist->reply = HTTPMSGLOCK(al.reply); | |
62e76326 | 680 | |
2efeb0b7 | 681 | if (!Config.accessList.log || checklist->fastCheck() == ACCESS_ALLOWED) { |
6fd1086a AR |
682 | if (request) |
683 | al.adapted_request = HTTPMSGLOCK(request); | |
684 | accessLogLog(&al, checklist); | |
685 | updateCounters(); | |
7684c4b1 | 686 | |
1b76e6c1 AJ |
687 | if (getConn() != NULL && getConn()->clientConnection != NULL) |
688 | clientdbUpdate(getConn()->clientConnection->remote, logType, AnyP::PROTO_HTTP, out.size); | |
7a2f978b | 689 | } |
2a6ab636 | 690 | |
6fd1086a AR |
691 | delete checklist; |
692 | ||
2a6ab636 | 693 | accessLogFreeMemory(&al); |
c8be6d7b | 694 | } |
695 | ||
696 | void | |
528b2c61 | 697 | ClientHttpRequest::freeResources() |
c8be6d7b | 698 | { |
528b2c61 | 699 | safe_free(uri); |
700 | safe_free(log_uri); | |
701 | safe_free(redirect.location); | |
30abd221 | 702 | range_iter.boundary.clean(); |
6dd9f4bd | 703 | HTTPMSGUNLOCK(request); |
62e76326 | 704 | |
528b2c61 | 705 | if (client_stream.tail) |
62e76326 | 706 | clientStreamAbort((clientStreamNode *)client_stream.tail->data, this); |
c8be6d7b | 707 | } |
708 | ||
709 | void | |
710 | httpRequestFree(void *data) | |
711 | { | |
59a1efb2 | 712 | ClientHttpRequest *http = (ClientHttpRequest *)data; |
c8be6d7b | 713 | assert(http != NULL); |
528b2c61 | 714 | delete http; |
7a2f978b | 715 | } |
716 | ||
a46d2c0e | 717 | bool |
718 | ConnStateData::areAllContextsForThisConnection() const | |
c8be6d7b | 719 | { |
a46d2c0e | 720 | assert(this != NULL); |
0655fa4d | 721 | ClientSocketContext::Pointer context = getCurrentContext(); |
62e76326 | 722 | |
0655fa4d | 723 | while (context.getRaw()) { |
98242069 | 724 | if (context->http->getConn() != this) |
a46d2c0e | 725 | return false; |
62e76326 | 726 | |
727 | context = context->next; | |
c8be6d7b | 728 | } |
62e76326 | 729 | |
a46d2c0e | 730 | return true; |
c8be6d7b | 731 | } |
732 | ||
733 | void | |
a46d2c0e | 734 | ConnStateData::freeAllContexts() |
c8be6d7b | 735 | { |
0655fa4d | 736 | ClientSocketContext::Pointer context; |
62e76326 | 737 | |
c53577d9 | 738 | while ((context = getCurrentContext()).getRaw() != NULL) { |
0655fa4d | 739 | assert(getCurrentContext() != |
740 | getCurrentContext()->next); | |
741 | context->connIsFinished(); | |
742 | assert (context != currentobject); | |
c8be6d7b | 743 | } |
744 | } | |
745 | ||
f692498b AJ |
746 | /// propagates abort event to all contexts |
747 | void | |
748 | ConnStateData::notifyAllContexts(int xerrno) | |
749 | { | |
750 | typedef ClientSocketContext::Pointer CSCP; | |
751 | for (CSCP c = getCurrentContext(); c.getRaw(); c = c->next) | |
752 | c->noteIoError(xerrno); | |
753 | } | |
754 | ||
7a2f978b | 755 | /* This is a handler normally called by comm_close() */ |
1cf238db | 756 | void ConnStateData::connStateClosed(const CommCloseCbParams &io) |
7a2f978b | 757 | { |
6e1d409c | 758 | deleteThis("ConnStateData::connStateClosed"); |
a46d2c0e | 759 | } |
62e76326 | 760 | |
6e1d409c | 761 | // cleans up before destructor is called |
a2ac85d9 | 762 | void |
6e1d409c | 763 | ConnStateData::swanSong() |
a46d2c0e | 764 | { |
73c36fd9 | 765 | debugs(33, 2, HERE << clientConnection); |
f35961af | 766 | flags.readMore = false; |
73c36fd9 | 767 | clientdbEstablished(clientConnection->remote, -1); /* decrement */ |
a46d2c0e | 768 | assert(areAllContextsForThisConnection()); |
769 | freeAllContexts(); | |
2f1431ea | 770 | #if USE_AUTH |
6bf4f823 | 771 | if (auth_user_request != NULL) { |
6e1d409c | 772 | debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request << "' (this is '" << this << "')"); |
f5691f9c | 773 | auth_user_request->onConnectionClose(this); |
6bf4f823 | 774 | } |
2f1431ea | 775 | #endif |
6e1d409c | 776 | |
73c36fd9 AJ |
777 | if (Comm::IsConnOpen(pinning.serverConnection)) |
778 | pinning.serverConnection->close(); | |
779 | pinning.serverConnection = NULL; | |
e3a4aecc | 780 | |
73c36fd9 AJ |
781 | if (Comm::IsConnOpen(clientConnection)) |
782 | clientConnection->close(); | |
783 | clientConnection = NULL; | |
d67acb4e | 784 | |
6e1d409c AR |
785 | BodyProducer::swanSong(); |
786 | flags.swanSang = true; | |
a2ac85d9 | 787 | } |
788 | ||
789 | bool | |
790 | ConnStateData::isOpen() const | |
791 | { | |
10b06767 | 792 | return cbdataReferenceValid(this) && // XXX: checking "this" in a method |
73c36fd9 AJ |
793 | Comm::IsConnOpen(clientConnection) && |
794 | !fd_table[clientConnection->fd].closing(); | |
a2ac85d9 | 795 | } |
796 | ||
797 | ConnStateData::~ConnStateData() | |
798 | { | |
799 | assert(this != NULL); | |
73c36fd9 | 800 | debugs(33, 3, HERE << clientConnection); |
a2ac85d9 | 801 | |
802 | if (isOpen()) | |
73c36fd9 | 803 | debugs(33, 1, "BUG: ConnStateData did not close " << clientConnection); |
6e1d409c AR |
804 | |
805 | if (!flags.swanSang) | |
73c36fd9 | 806 | debugs(33, 1, "BUG: ConnStateData was not destroyed properly; " << clientConnection); |
62e76326 | 807 | |
e0db3481 | 808 | cbdataReferenceDone(port); |
83fdd41a | 809 | |
279152e7 AJ |
810 | if (bodyPipe != NULL) |
811 | stopProducingFor(bodyPipe, false); | |
7a2f978b | 812 | } |
813 | ||
63be0a78 | 814 | /** |
c68e9c6b | 815 | * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive. |
816 | * This is the client-side persistent connection flag. We need | |
817 | * to set this relatively early in the request processing | |
818 | * to handle hacks for broken servers and clients. | |
819 | */ | |
820 | static void | |
59a1efb2 | 821 | clientSetKeepaliveFlag(ClientHttpRequest * http) |
c68e9c6b | 822 | { |
190154cf | 823 | HttpRequest *request = http->request; |
f6329bc3 | 824 | |
bf8fe701 | 825 | debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " << |
826 | request->http_ver.major << "." << request->http_ver.minor); | |
827 | debugs(33, 3, "clientSetKeepaliveFlag: method = " << | |
60745f24 | 828 | RequestMethodStr(request->method)); |
62e76326 | 829 | |
4a1acc56 AJ |
830 | // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply. |
831 | request->flags.proxy_keepalive = request->persistent() ? 1 : 0; | |
c68e9c6b | 832 | } |
833 | ||
31be8b80 | 834 | static int |
190154cf | 835 | clientIsContentLengthValid(HttpRequest * r) |
31be8b80 | 836 | { |
914b89a2 | 837 | switch (r->method.id()) { |
62e76326 | 838 | |
ffc128c4 | 839 | case METHOD_GET: |
62e76326 | 840 | |
ffc128c4 | 841 | case METHOD_HEAD: |
62e76326 | 842 | /* We do not want to see a request entity on GET/HEAD requests */ |
843 | return (r->content_length <= 0 || Config.onoff.request_entities); | |
844 | ||
ffc128c4 | 845 | default: |
62e76326 | 846 | /* For other types of requests we don't care */ |
847 | return 1; | |
ffc128c4 | 848 | } |
62e76326 | 849 | |
ffc128c4 | 850 | /* NOT REACHED */ |
31be8b80 | 851 | } |
852 | ||
c8be6d7b | 853 | int |
47f6e231 | 854 | clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength) |
efd900cb | 855 | { |
c8be6d7b | 856 | if (Config.maxRequestBodySize && |
62e76326 | 857 | bodyLength > Config.maxRequestBodySize) |
858 | return 1; /* too large */ | |
859 | ||
efd900cb | 860 | return 0; |
861 | } | |
862 | ||
e4a67a80 | 863 | #ifndef PURIFY |
5c336a3b | 864 | bool |
1cf238db | 865 | connIsUsable(ConnStateData * conn) |
c8be6d7b | 866 | { |
73c36fd9 | 867 | if (conn == NULL || !cbdataReferenceValid(conn) || !Comm::IsConnOpen(conn->clientConnection)) |
5c336a3b | 868 | return false; |
62e76326 | 869 | |
5c336a3b | 870 | return true; |
c8be6d7b | 871 | } |
872 | ||
e4a67a80 | 873 | #endif |
874 | ||
39cb8c41 | 875 | // careful: the "current" context may be gone if we wrote an early response |
0655fa4d | 876 | ClientSocketContext::Pointer |
877 | ConnStateData::getCurrentContext() const | |
c8be6d7b | 878 | { |
0655fa4d | 879 | assert(this); |
880 | return currentobject; | |
c8be6d7b | 881 | } |
882 | ||
883 | void | |
2324cda2 | 884 | ClientSocketContext::deferRecipientForLater(clientStreamNode * node, HttpReply * rep, StoreIOBuffer receivedData) |
528b2c61 | 885 | { |
bf8fe701 | 886 | debugs(33, 2, "clientSocketRecipient: Deferring request " << http->uri); |
528b2c61 | 887 | assert(flags.deferred == 0); |
888 | flags.deferred = 1; | |
889 | deferredparams.node = node; | |
890 | deferredparams.rep = rep; | |
2324cda2 | 891 | deferredparams.queuedBuffer = receivedData; |
c8be6d7b | 892 | return; |
893 | } | |
894 | ||
895 | int | |
2324cda2 | 896 | responseFinishedOrFailed(HttpReply * rep, StoreIOBuffer const & receivedData) |
c8be6d7b | 897 | { |
2324cda2 | 898 | if (rep == NULL && receivedData.data == NULL && receivedData.length == 0) |
62e76326 | 899 | return 1; |
900 | ||
c8be6d7b | 901 | return 0; |
902 | } | |
903 | ||
0655fa4d | 904 | bool |
905 | ClientSocketContext::startOfOutput() const | |
c8be6d7b | 906 | { |
0655fa4d | 907 | return http->out.size == 0; |
c8be6d7b | 908 | } |
909 | ||
528b2c61 | 910 | size_t |
47f6e231 | 911 | ClientSocketContext::lengthToSend(Range<int64_t> const &available) |
528b2c61 | 912 | { |
47f6e231 | 913 | /*the size of available range can always fit in a size_t type*/ |
914 | size_t maximum = (size_t)available.size(); | |
2512d159 | 915 | |
528b2c61 | 916 | if (!http->request->range) |
62e76326 | 917 | return maximum; |
918 | ||
528b2c61 | 919 | assert (canPackMoreRanges()); |
62e76326 | 920 | |
528b2c61 | 921 | if (http->range_iter.debt() == -1) |
62e76326 | 922 | return maximum; |
923 | ||
528b2c61 | 924 | assert (http->range_iter.debt() > 0); |
62e76326 | 925 | |
2512d159 | 926 | /* TODO this + the last line could be a range intersection calculation */ |
47f6e231 | 927 | if (available.start < http->range_iter.currentSpec()->offset) |
2512d159 | 928 | return 0; |
929 | ||
d85c3078 | 930 | return min(http->range_iter.debt(), (int64_t)maximum); |
528b2c61 | 931 | } |
932 | ||
c8be6d7b | 933 | void |
528b2c61 | 934 | ClientSocketContext::noteSentBodyBytes(size_t bytes) |
935 | { | |
936 | http->out.offset += bytes; | |
62e76326 | 937 | |
528b2c61 | 938 | if (!http->request->range) |
62e76326 | 939 | return; |
940 | ||
528b2c61 | 941 | if (http->range_iter.debt() != -1) { |
62e76326 | 942 | http->range_iter.debt(http->range_iter.debt() - bytes); |
943 | assert (http->range_iter.debt() >= 0); | |
528b2c61 | 944 | } |
62e76326 | 945 | |
dd272b8e | 946 | /* debt() always stops at -1, below that is a bug */ |
947 | assert (http->range_iter.debt() >= -1); | |
528b2c61 | 948 | } |
62e76326 | 949 | |
528b2c61 | 950 | bool |
951 | ClientHttpRequest::multipartRangeRequest() const | |
952 | { | |
953 | return request->multipartRangeRequest(); | |
954 | } | |
955 | ||
956 | bool | |
957 | ClientSocketContext::multipartRangeRequest() const | |
958 | { | |
959 | return http->multipartRangeRequest(); | |
960 | } | |
961 | ||
962 | void | |
963 | ClientSocketContext::sendBody(HttpReply * rep, StoreIOBuffer bodyData) | |
c8be6d7b | 964 | { |
965 | assert(rep == NULL); | |
528b2c61 | 966 | |
4ad60609 | 967 | if (!multipartRangeRequest() && !http->request->flags.chunked_reply) { |
2512d159 | 968 | size_t length = lengthToSend(bodyData.range()); |
62e76326 | 969 | noteSentBodyBytes (length); |
9e008dda AJ |
970 | AsyncCall::Pointer call = commCbCall(33, 5, "clientWriteBodyComplete", |
971 | CommIoCbPtrFun(clientWriteBodyComplete, this)); | |
73c36fd9 | 972 | Comm::Write(clientConnection, bodyData.data, length, call, NULL); |
62e76326 | 973 | return; |
528b2c61 | 974 | } |
975 | ||
976 | MemBuf mb; | |
2fe7eff9 | 977 | mb.init(); |
4ad60609 AR |
978 | if (multipartRangeRequest()) |
979 | packRange(bodyData, &mb); | |
980 | else | |
981 | packChunk(bodyData, mb); | |
2512d159 | 982 | |
9e008dda | 983 | if (mb.contentSize()) { |
2512d159 | 984 | /* write */ |
9e008dda AJ |
985 | AsyncCall::Pointer call = commCbCall(33, 5, "clientWriteComplete", |
986 | CommIoCbPtrFun(clientWriteComplete, this)); | |
73c36fd9 | 987 | Comm::Write(clientConnection, &mb, call); |
1cf238db | 988 | } else |
73c36fd9 | 989 | writeComplete(clientConnection, NULL, 0, COMM_OK); |
c8be6d7b | 990 | } |
991 | ||
4ad60609 AR |
992 | /** |
993 | * Packs bodyData into mb using chunked encoding. Packs the last-chunk | |
994 | * if bodyData is empty. | |
995 | */ | |
996 | void | |
997 | ClientSocketContext::packChunk(const StoreIOBuffer &bodyData, MemBuf &mb) | |
998 | { | |
999 | const uint64_t length = | |
1000 | static_cast<uint64_t>(lengthToSend(bodyData.range())); | |
1001 | noteSentBodyBytes(length); | |
1002 | ||
1003 | mb.Printf("%"PRIX64"\r\n", length); | |
1004 | mb.append(bodyData.data, length); | |
1005 | mb.Printf("\r\n"); | |
1006 | } | |
1007 | ||
63be0a78 | 1008 | /** put terminating boundary for multiparts */ |
528b2c61 | 1009 | static void |
30abd221 | 1010 | clientPackTermBound(String boundary, MemBuf * mb) |
528b2c61 | 1011 | { |
826a1fed | 1012 | mb->Printf("\r\n--" SQUIDSTRINGPH "--\r\n", SQUIDSTRINGPRINT(boundary)); |
4a7a3d56 | 1013 | debugs(33, 6, "clientPackTermBound: buf offset: " << mb->size); |
528b2c61 | 1014 | } |
1015 | ||
63be0a78 | 1016 | /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */ |
528b2c61 | 1017 | static void |
30abd221 | 1018 | clientPackRangeHdr(const HttpReply * rep, const HttpHdrRangeSpec * spec, String boundary, MemBuf * mb) |
528b2c61 | 1019 | { |
75faaa7a | 1020 | HttpHeader hdr(hoReply); |
528b2c61 | 1021 | Packer p; |
1022 | assert(rep); | |
1023 | assert(spec); | |
1024 | ||
1025 | /* put boundary */ | |
5b4117d8 | 1026 | debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary); |
528b2c61 | 1027 | /* rfc2046 requires to _prepend_ boundary with <crlf>! */ |
826a1fed | 1028 | mb->Printf("\r\n--" SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(boundary)); |
528b2c61 | 1029 | |
1030 | /* stuff the header with required entries and pack it */ | |
62e76326 | 1031 | |
a9925b40 | 1032 | if (rep->header.has(HDR_CONTENT_TYPE)) |
1033 | hdr.putStr(HDR_CONTENT_TYPE, rep->header.getStr(HDR_CONTENT_TYPE)); | |
62e76326 | 1034 | |
528b2c61 | 1035 | httpHeaderAddContRange(&hdr, *spec, rep->content_length); |
62e76326 | 1036 | |
528b2c61 | 1037 | packerToMemInit(&p, mb); |
62e76326 | 1038 | |
a9925b40 | 1039 | hdr.packInto(&p); |
62e76326 | 1040 | |
528b2c61 | 1041 | packerClean(&p); |
62e76326 | 1042 | |
519e0948 | 1043 | hdr.clean(); |
528b2c61 | 1044 | |
1045 | /* append <crlf> (we packed a header, not a reply) */ | |
2fe7eff9 | 1046 | mb->Printf("\r\n"); |
528b2c61 | 1047 | } |
1048 | ||
63be0a78 | 1049 | /** |
bb790702 | 1050 | * extracts a "range" from *buf and appends them to mb, updating |
528b2c61 | 1051 | * all offsets and such. |
1052 | */ | |
c8be6d7b | 1053 | void |
2512d159 | 1054 | ClientSocketContext::packRange(StoreIOBuffer const &source, MemBuf * mb) |
528b2c61 | 1055 | { |
1056 | HttpHdrRangeIter * i = &http->range_iter; | |
47f6e231 | 1057 | Range<int64_t> available (source.range()); |
b65351fa | 1058 | char const *buf = source.data; |
62e76326 | 1059 | |
2512d159 | 1060 | while (i->currentSpec() && available.size()) { |
62e76326 | 1061 | const size_t copy_sz = lengthToSend(available); |
62e76326 | 1062 | |
2512d159 | 1063 | if (copy_sz) { |
1064 | /* | |
1065 | * intersection of "have" and "need" ranges must not be empty | |
1066 | */ | |
1067 | assert(http->out.offset < i->currentSpec()->offset + i->currentSpec()->length); | |
13c2229a | 1068 | assert(http->out.offset + (int64_t)available.size() > i->currentSpec()->offset); |
2512d159 | 1069 | |
1070 | /* | |
1071 | * put boundary and headers at the beginning of a range in a | |
1072 | * multi-range | |
1073 | */ | |
1074 | ||
1075 | if (http->multipartRangeRequest() && i->debt() == i->currentSpec()->length) { | |
1076 | assert(http->memObject()); | |
1077 | clientPackRangeHdr( | |
1078 | http->memObject()->getReply(), /* original reply */ | |
1079 | i->currentSpec(), /* current range */ | |
1080 | i->boundary, /* boundary, the same for all */ | |
1081 | mb); | |
1082 | } | |
62e76326 | 1083 | |
2512d159 | 1084 | /* |
1085 | * append content | |
1086 | */ | |
4a7a3d56 | 1087 | debugs(33, 3, "clientPackRange: appending " << copy_sz << " bytes"); |
62e76326 | 1088 | |
2512d159 | 1089 | noteSentBodyBytes (copy_sz); |
62e76326 | 1090 | |
2fe7eff9 | 1091 | mb->append(buf, copy_sz); |
62e76326 | 1092 | |
2512d159 | 1093 | /* |
1094 | * update offsets | |
1095 | */ | |
1096 | available.start += copy_sz; | |
62e76326 | 1097 | |
2512d159 | 1098 | buf += copy_sz; |
62e76326 | 1099 | |
2512d159 | 1100 | } |
62e76326 | 1101 | |
c7329b75 | 1102 | if (!canPackMoreRanges()) { |
bf8fe701 | 1103 | debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges."); |
c7329b75 | 1104 | |
1105 | if (i->debt() == 0) | |
1106 | /* put terminating boundary for multiparts */ | |
1107 | clientPackTermBound(i->boundary, mb); | |
62e76326 | 1108 | |
62e76326 | 1109 | return; |
c7329b75 | 1110 | } |
62e76326 | 1111 | |
8bcf08e0 | 1112 | int64_t nextOffset = getNextRangeOffset(); |
62e76326 | 1113 | |
8bcf08e0 | 1114 | assert (nextOffset >= http->out.offset); |
62e76326 | 1115 | |
8bcf08e0 | 1116 | int64_t skip = nextOffset - http->out.offset; |
62e76326 | 1117 | |
2512d159 | 1118 | /* adjust for not to be transmitted bytes */ |
8bcf08e0 | 1119 | http->out.offset = nextOffset; |
2512d159 | 1120 | |
c16f948b | 1121 | if (available.size() <= (uint64_t)skip) |
62e76326 | 1122 | return; |
1123 | ||
2512d159 | 1124 | available.start += skip; |
62e76326 | 1125 | |
2512d159 | 1126 | buf += skip; |
1127 | ||
1128 | if (copy_sz == 0) | |
1129 | return; | |
528b2c61 | 1130 | } |
1131 | } | |
1132 | ||
63be0a78 | 1133 | /** returns expected content length for multi-range replies |
528b2c61 | 1134 | * note: assumes that httpHdrRangeCanonize has already been called |
1135 | * warning: assumes that HTTP headers for individual ranges at the | |
1136 | * time of the actuall assembly will be exactly the same as | |
1137 | * the headers when clientMRangeCLen() is called */ | |
1138 | int | |
1139 | ClientHttpRequest::mRangeCLen() | |
c8be6d7b | 1140 | { |
47f6e231 | 1141 | int64_t clen = 0; |
c8be6d7b | 1142 | MemBuf mb; |
528b2c61 | 1143 | |
86a2f789 | 1144 | assert(memObject()); |
528b2c61 | 1145 | |
2fe7eff9 | 1146 | mb.init(); |
528b2c61 | 1147 | HttpHdrRange::iterator pos = request->range->begin(); |
62e76326 | 1148 | |
528b2c61 | 1149 | while (pos != request->range->end()) { |
62e76326 | 1150 | /* account for headers for this range */ |
2fe7eff9 | 1151 | mb.reset(); |
86a2f789 | 1152 | clientPackRangeHdr(memObject()->getReply(), |
62e76326 | 1153 | *pos, range_iter.boundary, &mb); |
1154 | clen += mb.size; | |
528b2c61 | 1155 | |
62e76326 | 1156 | /* account for range content */ |
1157 | clen += (*pos)->length; | |
528b2c61 | 1158 | |
4a7a3d56 | 1159 | debugs(33, 6, "clientMRangeCLen: (clen += " << mb.size << " + " << (*pos)->length << ") == " << clen); |
62e76326 | 1160 | ++pos; |
528b2c61 | 1161 | } |
62e76326 | 1162 | |
528b2c61 | 1163 | /* account for the terminating boundary */ |
2fe7eff9 | 1164 | mb.reset(); |
62e76326 | 1165 | |
528b2c61 | 1166 | clientPackTermBound(range_iter.boundary, &mb); |
62e76326 | 1167 | |
528b2c61 | 1168 | clen += mb.size; |
1169 | ||
2fe7eff9 | 1170 | mb.clean(); |
62e76326 | 1171 | |
528b2c61 | 1172 | return clen; |
1173 | } | |
1174 | ||
63be0a78 | 1175 | /** |
528b2c61 | 1176 | * returns true if If-Range specs match reply, false otherwise |
1177 | */ | |
1178 | static int | |
59a1efb2 | 1179 | clientIfRangeMatch(ClientHttpRequest * http, HttpReply * rep) |
528b2c61 | 1180 | { |
a9925b40 | 1181 | const TimeOrTag spec = http->request->header.getTimeOrTag(HDR_IF_RANGE); |
528b2c61 | 1182 | /* check for parsing falure */ |
62e76326 | 1183 | |
528b2c61 | 1184 | if (!spec.valid) |
62e76326 | 1185 | return 0; |
1186 | ||
528b2c61 | 1187 | /* got an ETag? */ |
1188 | if (spec.tag.str) { | |
a9925b40 | 1189 | ETag rep_tag = rep->header.getETag(HDR_ETAG); |
bf8fe701 | 1190 | debugs(33, 3, "clientIfRangeMatch: ETags: " << spec.tag.str << " and " << |
1191 | (rep_tag.str ? rep_tag.str : "<none>")); | |
62e76326 | 1192 | |
1193 | if (!rep_tag.str) | |
1194 | return 0; /* entity has no etag to compare with! */ | |
1195 | ||
1196 | if (spec.tag.weak || rep_tag.weak) { | |
bf8fe701 | 1197 | debugs(33, 1, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec.tag.str << " ? " << rep_tag.str); |
62e76326 | 1198 | return 0; /* must use strong validator for sub-range requests */ |
1199 | } | |
1200 | ||
bd76482d | 1201 | return etagIsStrongEqual(rep_tag, spec.tag); |
528b2c61 | 1202 | } |
62e76326 | 1203 | |
528b2c61 | 1204 | /* got modification time? */ |
1205 | if (spec.time >= 0) { | |
86a2f789 | 1206 | return http->storeEntry()->lastmod <= spec.time; |
528b2c61 | 1207 | } |
62e76326 | 1208 | |
528b2c61 | 1209 | assert(0); /* should not happen */ |
1210 | return 0; | |
1211 | } | |
1212 | ||
63be0a78 | 1213 | /** |
1214 | * generates a "unique" boundary string for multipart responses | |
528b2c61 | 1215 | * the caller is responsible for cleaning the string */ |
30abd221 | 1216 | String |
528b2c61 | 1217 | ClientHttpRequest::rangeBoundaryStr() const |
1218 | { | |
1219 | assert(this); | |
1220 | const char *key; | |
7dbca7a4 AJ |
1221 | String b(APP_FULLNAME); |
1222 | b.append(":",1); | |
86a2f789 | 1223 | key = storeEntry()->getMD5Text(); |
528b2c61 | 1224 | b.append(key, strlen(key)); |
1225 | return b; | |
1226 | } | |
1227 | ||
63be0a78 | 1228 | /** adds appropriate Range headers if needed */ |
528b2c61 | 1229 | void |
1230 | ClientSocketContext::buildRangeHeader(HttpReply * rep) | |
1231 | { | |
1232 | HttpHeader *hdr = rep ? &rep->header : 0; | |
1233 | const char *range_err = NULL; | |
190154cf | 1234 | HttpRequest *request = http->request; |
528b2c61 | 1235 | assert(request->range); |
1236 | /* check if we still want to do ranges */ | |
62e76326 | 1237 | |
11e3fa1c AJ |
1238 | int64_t roffLimit = request->getRangeOffsetLimit(); |
1239 | ||
528b2c61 | 1240 | if (!rep) |
62e76326 | 1241 | range_err = "no [parse-able] reply"; |
528b2c61 | 1242 | else if ((rep->sline.status != HTTP_OK) && (rep->sline.status != HTTP_PARTIAL_CONTENT)) |
62e76326 | 1243 | range_err = "wrong status code"; |
a9925b40 | 1244 | else if (hdr->has(HDR_CONTENT_RANGE)) |
62e76326 | 1245 | range_err = "origin server does ranges"; |
528b2c61 | 1246 | else if (rep->content_length < 0) |
62e76326 | 1247 | range_err = "unknown length"; |
86a2f789 | 1248 | else if (rep->content_length != http->memObject()->getReply()->content_length) |
62e76326 | 1249 | range_err = "INCONSISTENT length"; /* a bug? */ |
96cbbe03 | 1250 | |
1251 | /* hits only - upstream peer determines correct behaviour on misses, and client_side_reply determines | |
9e008dda | 1252 | * hits candidates |
96cbbe03 | 1253 | */ |
a9925b40 | 1254 | else if (logTypeIsATcpHit(http->logType) && http->request->header.has(HDR_IF_RANGE) && !clientIfRangeMatch(http, rep)) |
62e76326 | 1255 | range_err = "If-Range match failed"; |
528b2c61 | 1256 | else if (!http->request->range->canonize(rep)) |
62e76326 | 1257 | range_err = "canonization failed"; |
528b2c61 | 1258 | else if (http->request->range->isComplex()) |
62e76326 | 1259 | range_err = "too complex range header"; |
11e3fa1c | 1260 | else if (!logTypeIsATcpHit(http->logType) && http->request->range->offsetLimitExceeded(roffLimit)) |
62e76326 | 1261 | range_err = "range outside range_offset_limit"; |
1262 | ||
528b2c61 | 1263 | /* get rid of our range specs on error */ |
1264 | if (range_err) { | |
b631f31c | 1265 | /* XXX We do this here because we need canonisation etc. However, this current |
9e008dda | 1266 | * code will lead to incorrect store offset requests - the store will have the |
b631f31c | 1267 | * offset data, but we won't be requesting it. |
1268 | * So, we can either re-request, or generate an error | |
1269 | */ | |
bf8fe701 | 1270 | debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err << "."); |
00d77d6b | 1271 | delete http->request->range; |
62e76326 | 1272 | http->request->range = NULL; |
c8be6d7b | 1273 | } else { |
3cff087f | 1274 | /* XXX: TODO: Review, this unconditional set may be wrong. - TODO: review. */ |
1275 | httpStatusLineSet(&rep->sline, rep->sline.version, | |
1276 | HTTP_PARTIAL_CONTENT, NULL); | |
fedd1531 | 1277 | // web server responded with a valid, but unexpected range. |
1278 | // will (try-to) forward as-is. | |
1279 | //TODO: we should cope with multirange request/responses | |
1280 | bool replyMatchRequest = rep->content_range != NULL ? | |
1281 | request->range->contains(rep->content_range->spec) : | |
1282 | true; | |
62e76326 | 1283 | const int spec_count = http->request->range->specs.count; |
47f6e231 | 1284 | int64_t actual_clen = -1; |
62e76326 | 1285 | |
47f6e231 | 1286 | debugs(33, 3, "clientBuildRangeHeader: range spec count: " << |
9e008dda | 1287 | spec_count << " virgin clen: " << rep->content_length); |
62e76326 | 1288 | assert(spec_count > 0); |
62e76326 | 1289 | /* append appropriate header(s) */ |
1290 | ||
1291 | if (spec_count == 1) { | |
fedd1531 | 1292 | if (!replyMatchRequest) { |
1293 | hdr->delById(HDR_CONTENT_RANGE); | |
1294 | hdr->putContRange(rep->content_range); | |
1295 | actual_clen = rep->content_length; | |
1296 | //http->range_iter.pos = rep->content_range->spec.begin(); | |
1297 | (*http->range_iter.pos)->offset = rep->content_range->spec.offset; | |
1298 | (*http->range_iter.pos)->length = rep->content_range->spec.length; | |
1299 | ||
1300 | } else { | |
1301 | HttpHdrRange::iterator pos = http->request->range->begin(); | |
1302 | assert(*pos); | |
1303 | /* append Content-Range */ | |
1304 | ||
1305 | if (!hdr->has(HDR_CONTENT_RANGE)) { | |
1306 | /* No content range, so this was a full object we are | |
1307 | * sending parts of. | |
1308 | */ | |
1309 | httpHeaderAddContRange(hdr, **pos, rep->content_length); | |
1310 | } | |
1311 | ||
1312 | /* set new Content-Length to the actual number of bytes | |
1313 | * transmitted in the message-body */ | |
1314 | actual_clen = (*pos)->length; | |
62e76326 | 1315 | } |
62e76326 | 1316 | } else { |
1317 | /* multipart! */ | |
1318 | /* generate boundary string */ | |
1319 | http->range_iter.boundary = http->rangeBoundaryStr(); | |
1320 | /* delete old Content-Type, add ours */ | |
a9925b40 | 1321 | hdr->delById(HDR_CONTENT_TYPE); |
62e76326 | 1322 | httpHeaderPutStrf(hdr, HDR_CONTENT_TYPE, |
826a1fed FC |
1323 | "multipart/byteranges; boundary=\"" SQUIDSTRINGPH "\"", |
1324 | SQUIDSTRINGPRINT(http->range_iter.boundary)); | |
62e76326 | 1325 | /* Content-Length is not required in multipart responses |
1326 | * but it is always nice to have one */ | |
1327 | actual_clen = http->mRangeCLen(); | |
2512d159 | 1328 | /* http->out needs to start where we want data at */ |
1329 | http->out.offset = http->range_iter.currentSpec()->offset; | |
62e76326 | 1330 | } |
1331 | ||
1332 | /* replace Content-Length header */ | |
1333 | assert(actual_clen >= 0); | |
1334 | ||
a9925b40 | 1335 | hdr->delById(HDR_CONTENT_LENGTH); |
62e76326 | 1336 | |
47f6e231 | 1337 | hdr->putInt64(HDR_CONTENT_LENGTH, actual_clen); |
62e76326 | 1338 | |
bf8fe701 | 1339 | debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen); |
62e76326 | 1340 | |
1341 | /* And start the range iter off */ | |
1342 | http->range_iter.updateSpec(); | |
c8be6d7b | 1343 | } |
528b2c61 | 1344 | } |
1345 | ||
1346 | void | |
1347 | ClientSocketContext::prepareReply(HttpReply * rep) | |
1348 | { | |
fedd1531 | 1349 | reply = rep; |
1350 | ||
528b2c61 | 1351 | if (http->request->range) |
62e76326 | 1352 | buildRangeHeader(rep); |
528b2c61 | 1353 | } |
1354 | ||
1355 | void | |
1356 | ClientSocketContext::sendStartOfMessage(HttpReply * rep, StoreIOBuffer bodyData) | |
1357 | { | |
1358 | prepareReply(rep); | |
528b2c61 | 1359 | assert (rep); |
06a5ae20 | 1360 | MemBuf *mb = rep->pack(); |
1ce34ddd AJ |
1361 | |
1362 | // dump now, so we dont output any body. | |
1363 | debugs(11, 2, "HTTP Client " << clientConnection); | |
1364 | debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb->buf << "\n----------"); | |
1365 | ||
528b2c61 | 1366 | /* Save length of headers for persistent conn checks */ |
032785bf | 1367 | http->out.headers_sz = mb->contentSize(); |
528b2c61 | 1368 | #if HEADERS_LOG |
62e76326 | 1369 | |
528b2c61 | 1370 | headersLog(0, 0, http->request->method, rep); |
1371 | #endif | |
62e76326 | 1372 | |
c8be6d7b | 1373 | if (bodyData.data && bodyData.length) { |
4ad60609 AR |
1374 | if (multipartRangeRequest()) |
1375 | packRange(bodyData, mb); | |
1376 | else if (http->request->flags.chunked_reply) { | |
1377 | packChunk(bodyData, *mb); | |
1378 | } else { | |
2512d159 | 1379 | size_t length = lengthToSend(bodyData.range()); |
62e76326 | 1380 | noteSentBodyBytes (length); |
1381 | ||
2fe7eff9 | 1382 | mb->append(bodyData.data, length); |
62e76326 | 1383 | } |
c8be6d7b | 1384 | } |
62e76326 | 1385 | |
c8be6d7b | 1386 | /* write */ |
425802c8 | 1387 | debugs(33,7, HERE << "sendStartOfMessage schedules clientWriteComplete"); |
9e008dda AJ |
1388 | AsyncCall::Pointer call = commCbCall(33, 5, "clientWriteComplete", |
1389 | CommIoCbPtrFun(clientWriteComplete, this)); | |
73c36fd9 | 1390 | Comm::Write(clientConnection, mb, call); |
032785bf | 1391 | delete mb; |
c8be6d7b | 1392 | } |
1393 | ||
63be0a78 | 1394 | /** |
7dc5f514 | 1395 | * Write a chunk of data to a client socket. If the reply is present, |
1396 | * send the reply headers down the wire too, and clean them up when | |
1397 | * finished. | |
9e008dda | 1398 | * Pre-condition: |
edce4d98 | 1399 | * The request is one backed by a connection, not an internal request. |
1400 | * data context is not NULL | |
1401 | * There are no more entries in the stream chain. | |
2246b732 | 1402 | */ |
edce4d98 | 1403 | static void |
59a1efb2 | 1404 | clientSocketRecipient(clientStreamNode * node, ClientHttpRequest * http, |
2324cda2 | 1405 | HttpReply * rep, StoreIOBuffer receivedData) |
edce4d98 | 1406 | { |
edce4d98 | 1407 | /* Test preconditions */ |
1408 | assert(node != NULL); | |
559da936 | 1409 | PROF_start(clientSocketRecipient); |
62e76326 | 1410 | /* TODO: handle this rather than asserting |
9e008dda AJ |
1411 | * - it should only ever happen if we cause an abort and |
1412 | * the callback chain loops back to here, so we can simply return. | |
1413 | * However, that itself shouldn't happen, so it stays as an assert for now. | |
edce4d98 | 1414 | */ |
1415 | assert(cbdataReferenceValid(node)); | |
edce4d98 | 1416 | assert(node->node.next == NULL); |
0655fa4d | 1417 | ClientSocketContext::Pointer context = dynamic_cast<ClientSocketContext *>(node->data.getRaw()); |
94a396a3 | 1418 | assert(context != NULL); |
98242069 | 1419 | assert(connIsUsable(http->getConn())); |
5c336a3b | 1420 | |
528b2c61 | 1421 | /* TODO: check offset is what we asked for */ |
62e76326 | 1422 | |
98242069 | 1423 | if (context != http->getConn()->getCurrentContext()) { |
2324cda2 | 1424 | context->deferRecipientForLater(node, rep, receivedData); |
559da936 | 1425 | PROF_stop(clientSocketRecipient); |
62e76326 | 1426 | return; |
edce4d98 | 1427 | } |
62e76326 | 1428 | |
4ad60609 AR |
1429 | // After sending Transfer-Encoding: chunked (at least), always send |
1430 | // the last-chunk if there was no error, ignoring responseFinishedOrFailed. | |
1431 | const bool mustSendLastChunk = http->request->flags.chunked_reply && | |
4cb2536f | 1432 | !http->request->flags.stream_error && !context->startOfOutput(); |
4ad60609 | 1433 | if (responseFinishedOrFailed(rep, receivedData) && !mustSendLastChunk) { |
73c36fd9 | 1434 | context->writeComplete(context->clientConnection, NULL, 0, COMM_OK); |
559da936 | 1435 | PROF_stop(clientSocketRecipient); |
62e76326 | 1436 | return; |
edce4d98 | 1437 | } |
62e76326 | 1438 | |
0655fa4d | 1439 | if (!context->startOfOutput()) |
2324cda2 | 1440 | context->sendBody(rep, receivedData); |
7684c4b1 | 1441 | else { |
a4785954 | 1442 | assert(rep); |
90a8964c | 1443 | http->al.reply = HTTPMSGLOCK(rep); |
2324cda2 | 1444 | context->sendStartOfMessage(rep, receivedData); |
7684c4b1 | 1445 | } |
fc68f6b1 | 1446 | |
559da936 | 1447 | PROF_stop(clientSocketRecipient); |
edce4d98 | 1448 | } |
1449 | ||
63be0a78 | 1450 | /** |
1451 | * Called when a downstream node is no longer interested in | |
edce4d98 | 1452 | * our data. As we are a terminal node, this means on aborts |
1453 | * only | |
1454 | */ | |
1455 | void | |
59a1efb2 | 1456 | clientSocketDetach(clientStreamNode * node, ClientHttpRequest * http) |
edce4d98 | 1457 | { |
edce4d98 | 1458 | /* Test preconditions */ |
1459 | assert(node != NULL); | |
62e76326 | 1460 | /* TODO: handle this rather than asserting |
9e008dda AJ |
1461 | * - it should only ever happen if we cause an abort and |
1462 | * the callback chain loops back to here, so we can simply return. | |
edce4d98 | 1463 | * However, that itself shouldn't happen, so it stays as an assert for now. |
1464 | */ | |
1465 | assert(cbdataReferenceValid(node)); | |
1466 | /* Set null by ContextFree */ | |
edce4d98 | 1467 | assert(node->node.next == NULL); |
0655fa4d | 1468 | /* this is the assert discussed above */ |
e4a67a80 | 1469 | assert(NULL == dynamic_cast<ClientSocketContext *>(node->data.getRaw())); |
edce4d98 | 1470 | /* We are only called when the client socket shutsdown. |
1471 | * Tell the prev pipeline member we're finished | |
1472 | */ | |
1473 | clientStreamDetach(node, http); | |
7a2f978b | 1474 | } |
1475 | ||
f4f278b5 | 1476 | static void |
e0d28505 | 1477 | clientWriteBodyComplete(const Comm::ConnectionPointer &conn, char *buf, size_t size, comm_err_t errflag, int xerrno, void *data) |
f4f278b5 | 1478 | { |
425802c8 | 1479 | debugs(33,7, HERE << "clientWriteBodyComplete schedules clientWriteComplete"); |
e0d28505 | 1480 | clientWriteComplete(conn, NULL, size, errflag, xerrno, data); |
c8be6d7b | 1481 | } |
1482 | ||
1483 | void | |
a46d2c0e | 1484 | ConnStateData::readNextRequest() |
c8be6d7b | 1485 | { |
73c36fd9 | 1486 | debugs(33, 5, HERE << clientConnection << " reading next req"); |
bf8fe701 | 1487 | |
97b32442 | 1488 | fd_note(clientConnection->fd, "Idle client: Waiting for next request"); |
63be0a78 | 1489 | /** |
c8be6d7b | 1490 | * Set the timeout BEFORE calling clientReadRequest(). |
1491 | */ | |
1cf238db | 1492 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 1493 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
4cb2536f | 1494 | TimeoutDialer, this, ConnStateData::requestTimeout); |
97b32442 | 1495 | commSetConnTimeout(clientConnection, Config.Timeout.clientIdlePconn, timeoutCall); |
1cf238db | 1496 | |
a46d2c0e | 1497 | readSomeData(); |
63be0a78 | 1498 | /** Please don't do anything with the FD past here! */ |
c8be6d7b | 1499 | } |
1500 | ||
09d3938c | 1501 | static void |
1cf238db | 1502 | ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest, ConnStateData * conn) |
c8be6d7b | 1503 | { |
73c36fd9 | 1504 | debugs(33, 2, HERE << conn->clientConnection << " Sending next"); |
bf8fe701 | 1505 | |
63be0a78 | 1506 | /** If the client stream is waiting on a socket write to occur, then */ |
62e76326 | 1507 | |
c8be6d7b | 1508 | if (deferredRequest->flags.deferred) { |
63be0a78 | 1509 | /** NO data is allowed to have been sent. */ |
62e76326 | 1510 | assert(deferredRequest->http->out.size == 0); |
63be0a78 | 1511 | /** defer now. */ |
62e76326 | 1512 | clientSocketRecipient(deferredRequest->deferredparams.node, |
1513 | deferredRequest->http, | |
1514 | deferredRequest->deferredparams.rep, | |
1515 | deferredRequest->deferredparams.queuedBuffer); | |
c8be6d7b | 1516 | } |
62e76326 | 1517 | |
63be0a78 | 1518 | /** otherwise, the request is still active in a callbacksomewhere, |
c8be6d7b | 1519 | * and we are done |
f4f278b5 | 1520 | */ |
f4f278b5 | 1521 | } |
1522 | ||
cf6eb29e | 1523 | /// called when we have successfully finished writing the response |
0655fa4d | 1524 | void |
1525 | ClientSocketContext::keepaliveNextRequest() | |
1a92a1e2 | 1526 | { |
1cf238db | 1527 | ConnStateData * conn = http->getConn(); |
bd4e6ec8 | 1528 | |
73c36fd9 | 1529 | debugs(33, 3, HERE << "ConnnStateData(" << conn->clientConnection << "), Context(" << clientConnection << ")"); |
0655fa4d | 1530 | connIsFinished(); |
1531 | ||
73c36fd9 AJ |
1532 | if (conn->pinning.pinned && !Comm::IsConnOpen(conn->pinning.serverConnection)) { |
1533 | debugs(33, 2, HERE << conn->clientConnection << " Connection was pinned but server side gone. Terminating client connection"); | |
1534 | conn->clientConnection->close(); | |
d67acb4e AJ |
1535 | return; |
1536 | } | |
1537 | ||
cf6eb29e CT |
1538 | /** \par |
1539 | * We are done with the response, and we are either still receiving request | |
1540 | * body (early response!) or have already stopped receiving anything. | |
1541 | * | |
1542 | * If we are still receiving, then clientParseRequest() below will fail. | |
1543 | * (XXX: but then we will call readNextRequest() which may succeed and | |
1544 | * execute a smuggled request as we are not done with the current request). | |
1545 | * | |
1546 | * If we stopped because we got everything, then try the next request. | |
1547 | * | |
1548 | * If we stopped receiving because of an error, then close now to avoid | |
1549 | * getting stuck and to prevent accidental request smuggling. | |
1550 | */ | |
1551 | ||
1552 | if (const char *reason = conn->stoppedReceiving()) { | |
1553 | debugs(33, 3, HERE << "closing for earlier request error: " << reason); | |
1554 | conn->clientConnection->close(); | |
1555 | return; | |
1556 | } | |
1557 | ||
63be0a78 | 1558 | /** \par |
f900210a | 1559 | * Attempt to parse a request from the request buffer. |
1560 | * If we've been fed a pipelined request it may already | |
1561 | * be in our read buffer. | |
1562 | * | |
63be0a78 | 1563 | \par |
f900210a | 1564 | * This needs to fall through - if we're unlucky and parse the _last_ request |
1565 | * from our read buffer we may never re-register for another client read. | |
1566 | */ | |
1567 | ||
f35961af | 1568 | if (conn->clientParseRequests()) { |
73c36fd9 | 1569 | debugs(33, 3, HERE << conn->clientConnection << ": parsed next request from buffer"); |
f900210a | 1570 | } |
1571 | ||
63be0a78 | 1572 | /** \par |
f900210a | 1573 | * Either we need to kick-start another read or, if we have |
1574 | * a half-closed connection, kill it after the last request. | |
1575 | * This saves waiting for half-closed connections to finished being | |
1576 | * half-closed _AND_ then, sometimes, spending "Timeout" time in | |
1577 | * the keepalive "Waiting for next request" state. | |
1578 | */ | |
73c36fd9 | 1579 | if (commIsHalfClosed(conn->clientConnection->fd) && (conn->getConcurrentRequestCount() == 0)) { |
bf8fe701 | 1580 | debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing"); |
73c36fd9 | 1581 | conn->clientConnection->close(); |
f900210a | 1582 | return; |
1583 | } | |
1584 | ||
0655fa4d | 1585 | ClientSocketContext::Pointer deferredRequest; |
62e76326 | 1586 | |
63be0a78 | 1587 | /** \par |
f900210a | 1588 | * At this point we either have a parsed request (which we've |
1589 | * kicked off the processing for) or not. If we have a deferred | |
1590 | * request (parsed but deferred for pipeling processing reasons) | |
1591 | * then look at processing it. If not, simply kickstart | |
1592 | * another read. | |
1593 | */ | |
1594 | ||
1595 | if ((deferredRequest = conn->getCurrentContext()).getRaw()) { | |
73c36fd9 | 1596 | debugs(33, 3, HERE << conn->clientConnection << ": calling PushDeferredIfNeeded"); |
62e76326 | 1597 | ClientSocketContextPushDeferredIfNeeded(deferredRequest, conn); |
f35961af | 1598 | } else if (conn->flags.readMore) { |
73c36fd9 | 1599 | debugs(33, 3, HERE << conn->clientConnection << ": calling conn->readNextRequest()"); |
f900210a | 1600 | conn->readNextRequest(); |
f35961af AR |
1601 | } else { |
1602 | // XXX: Can this happen? CONNECT tunnels have deferredRequest set. | |
1b76e6c1 | 1603 | debugs(33, DBG_IMPORTANT, HERE << "abandoning " << conn->clientConnection); |
f900210a | 1604 | } |
1a92a1e2 | 1605 | } |
1606 | ||
c8be6d7b | 1607 | void |
1608 | clientUpdateSocketStats(log_type logType, size_t size) | |
1609 | { | |
1610 | if (size == 0) | |
62e76326 | 1611 | return; |
1612 | ||
c8be6d7b | 1613 | kb_incr(&statCounter.client_http.kbytes_out, size); |
62e76326 | 1614 | |
c8be6d7b | 1615 | if (logTypeIsATcpHit(logType)) |
62e76326 | 1616 | kb_incr(&statCounter.client_http.hit_kbytes_out, size); |
c8be6d7b | 1617 | } |
1618 | ||
63be0a78 | 1619 | /** |
528b2c61 | 1620 | * increments iterator "i" |
63be0a78 | 1621 | * used by clientPackMoreRanges |
1622 | * | |
1623 | \retval true there is still data available to pack more ranges | |
9e008dda | 1624 | \retval false |
63be0a78 | 1625 | */ |
528b2c61 | 1626 | bool |
1627 | ClientSocketContext::canPackMoreRanges() const | |
1628 | { | |
63be0a78 | 1629 | /** first update iterator "i" if needed */ |
62e76326 | 1630 | |
528b2c61 | 1631 | if (!http->range_iter.debt()) { |
73c36fd9 | 1632 | debugs(33, 5, HERE << "At end of current range spec for " << clientConnection); |
62e76326 | 1633 | |
1634 | if (http->range_iter.pos.incrementable()) | |
1635 | ++http->range_iter.pos; | |
1636 | ||
1637 | http->range_iter.updateSpec(); | |
528b2c61 | 1638 | } |
62e76326 | 1639 | |
528b2c61 | 1640 | assert(!http->range_iter.debt() == !http->range_iter.currentSpec()); |
63be0a78 | 1641 | |
528b2c61 | 1642 | /* paranoid sync condition */ |
1643 | /* continue condition: need_more_data */ | |
bf8fe701 | 1644 | debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http->range_iter.currentSpec() ? true : false)); |
528b2c61 | 1645 | return http->range_iter.currentSpec() ? true : false; |
1646 | } | |
1647 | ||
47f6e231 | 1648 | int64_t |
528b2c61 | 1649 | ClientSocketContext::getNextRangeOffset() const |
1650 | { | |
1651 | if (http->request->range) { | |
62e76326 | 1652 | /* offset in range specs does not count the prefix of an http msg */ |
47f6e231 | 1653 | debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http->out.offset); |
62e76326 | 1654 | /* check: reply was parsed and range iterator was initialized */ |
1655 | assert(http->range_iter.valid); | |
1656 | /* filter out data according to range specs */ | |
1657 | assert (canPackMoreRanges()); | |
1658 | { | |
47f6e231 | 1659 | int64_t start; /* offset of still missing data */ |
62e76326 | 1660 | assert(http->range_iter.currentSpec()); |
1661 | start = http->range_iter.currentSpec()->offset + http->range_iter.currentSpec()->length - http->range_iter.debt(); | |
47f6e231 | 1662 | debugs(33, 3, "clientPackMoreRanges: in: offset: " << http->out.offset); |
1663 | debugs(33, 3, "clientPackMoreRanges: out:" | |
9e008dda AJ |
1664 | " start: " << start << |
1665 | " spec[" << http->range_iter.pos - http->request->range->begin() << "]:" << | |
1666 | " [" << http->range_iter.currentSpec()->offset << | |
1667 | ", " << http->range_iter.currentSpec()->offset + http->range_iter.currentSpec()->length << ")," | |
1668 | " len: " << http->range_iter.currentSpec()->length << | |
1669 | " debt: " << http->range_iter.debt()); | |
62e76326 | 1670 | if (http->range_iter.currentSpec()->length != -1) |
1671 | assert(http->out.offset <= start); /* we did not miss it */ | |
1672 | ||
1673 | return start; | |
1674 | } | |
1675 | ||
fedd1531 | 1676 | } else if (reply && reply->content_range) { |
1677 | /* request does not have ranges, but reply does */ | |
63be0a78 | 1678 | /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range |
1679 | * becomes HttpHdrRange rather than HttpHdrRangeSpec. | |
1680 | */ | |
fedd1531 | 1681 | return http->out.offset + reply->content_range->spec.offset; |
528b2c61 | 1682 | } |
1683 | ||
1684 | return http->out.offset; | |
1685 | } | |
1686 | ||
c8be6d7b | 1687 | void |
528b2c61 | 1688 | ClientSocketContext::pullData() |
c8be6d7b | 1689 | { |
73c36fd9 | 1690 | debugs(33, 5, HERE << clientConnection << " attempting to pull upstream data"); |
bf8fe701 | 1691 | |
c8be6d7b | 1692 | /* More data will be coming from the stream. */ |
528b2c61 | 1693 | StoreIOBuffer readBuffer; |
1694 | /* XXX: Next requested byte in the range sequence */ | |
1695 | /* XXX: length = getmaximumrangelenfgth */ | |
1696 | readBuffer.offset = getNextRangeOffset(); | |
c8be6d7b | 1697 | readBuffer.length = HTTP_REQBUF_SZ; |
528b2c61 | 1698 | readBuffer.data = reqbuf; |
1699 | /* we may note we have reached the end of the wanted ranges */ | |
1700 | clientStreamRead(getTail(), http, readBuffer); | |
1701 | } | |
1702 | ||
62e76326 | 1703 | clientStream_status_t |
528b2c61 | 1704 | ClientSocketContext::socketState() |
1705 | { | |
1706 | switch (clientStreamStatus(getTail(), http)) { | |
62e76326 | 1707 | |
1708 | case STREAM_NONE: | |
528b2c61 | 1709 | /* check for range support ending */ |
62e76326 | 1710 | |
528b2c61 | 1711 | if (http->request->range) { |
62e76326 | 1712 | /* check: reply was parsed and range iterator was initialized */ |
1713 | assert(http->range_iter.valid); | |
1714 | /* filter out data according to range specs */ | |
1715 | ||
1716 | if (!canPackMoreRanges()) { | |
920ba08d | 1717 | debugs(33, 5, HERE << "Range request at end of returnable " << |
73c36fd9 | 1718 | "range sequence on " << clientConnection); |
62e76326 | 1719 | |
1720 | if (http->request->flags.proxy_keepalive) | |
1721 | return STREAM_COMPLETE; | |
1722 | else | |
1723 | return STREAM_UNPLANNED_COMPLETE; | |
1724 | } | |
fedd1531 | 1725 | } else if (reply && reply->content_range) { |
425802c8 | 1726 | /* reply has content-range, but Squid is not managing ranges */ |
1727 | const int64_t &bytesSent = http->out.offset; | |
1728 | const int64_t &bytesExpected = reply->content_range->spec.length; | |
fedd1531 | 1729 | |
425802c8 | 1730 | debugs(33, 7, HERE << "body bytes sent vs. expected: " << |
9e008dda AJ |
1731 | bytesSent << " ? " << bytesExpected << " (+" << |
1732 | reply->content_range->spec.offset << ")"); | |
425802c8 | 1733 | |
1734 | // did we get at least what we expected, based on range specs? | |
1735 | ||
65058d64 CT |
1736 | if (bytesSent == bytesExpected) { // got everything |
1737 | if (http->request->flags.proxy_keepalive) | |
1738 | return STREAM_COMPLETE; | |
1739 | else | |
1740 | return STREAM_UNPLANNED_COMPLETE; | |
1741 | } | |
425802c8 | 1742 | |
1743 | // The logic below is not clear: If we got more than we | |
1744 | // expected why would persistency matter? Should not this | |
1745 | // always be an error? | |
1746 | if (bytesSent > bytesExpected) { // got extra | |
fedd1531 | 1747 | if (http->request->flags.proxy_keepalive) |
1748 | return STREAM_COMPLETE; | |
1749 | else | |
1750 | return STREAM_UNPLANNED_COMPLETE; | |
1751 | } | |
425802c8 | 1752 | |
1753 | // did not get enough yet, expecting more | |
62e76326 | 1754 | } |
1755 | ||
1756 | return STREAM_NONE; | |
1757 | ||
1758 | case STREAM_COMPLETE: | |
528b2c61 | 1759 | return STREAM_COMPLETE; |
62e76326 | 1760 | |
1761 | case STREAM_UNPLANNED_COMPLETE: | |
1762 | return STREAM_UNPLANNED_COMPLETE; | |
1763 | ||
1764 | case STREAM_FAILED: | |
1765 | return STREAM_FAILED; | |
528b2c61 | 1766 | } |
62e76326 | 1767 | |
528b2c61 | 1768 | fatal ("unreachable code\n"); |
1769 | return STREAM_NONE; | |
c8be6d7b | 1770 | } |
edce4d98 | 1771 | |
63be0a78 | 1772 | /** |
1773 | * A write has just completed to the client, or we have just realised there is | |
edce4d98 | 1774 | * no more data to send. |
1775 | */ | |
e6ccf245 | 1776 | void |
e0d28505 | 1777 | clientWriteComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data) |
7a2f978b | 1778 | { |
528b2c61 | 1779 | ClientSocketContext *context = (ClientSocketContext *)data; |
e0d28505 | 1780 | context->writeComplete(conn, bufnotused, size, errflag); |
0655fa4d | 1781 | } |
1782 | ||
f692498b AJ |
1783 | /// remembers the abnormal connection termination for logging purposes |
1784 | void | |
1785 | ClientSocketContext::noteIoError(const int xerrno) | |
1786 | { | |
1787 | if (http) { | |
1788 | if (xerrno == ETIMEDOUT) | |
1789 | http->al.http.timedout = true; | |
1790 | else // even if xerrno is zero (which means read abort/eof) | |
1791 | http->al.http.aborted = true; | |
1792 | } | |
1793 | } | |
1794 | ||
1795 | ||
55e44db9 | 1796 | void |
1797 | ClientSocketContext::doClose() | |
1798 | { | |
73c36fd9 | 1799 | clientConnection->close(); |
55e44db9 | 1800 | } |
1801 | ||
cf6eb29e | 1802 | /// called when we encounter a response-related error |
55e44db9 | 1803 | void |
5f8252d2 | 1804 | ClientSocketContext::initiateClose(const char *reason) |
55e44db9 | 1805 | { |
cf6eb29e CT |
1806 | http->getConn()->stopSending(reason); // closes ASAP |
1807 | } | |
5f8252d2 | 1808 | |
cf6eb29e CT |
1809 | void |
1810 | ConnStateData::stopSending(const char *error) | |
1811 | { | |
1812 | debugs(33, 4, HERE << "sending error (" << clientConnection << "): " << error << | |
1813 | "; old receiving error: " << | |
1814 | (stoppedReceiving() ? stoppedReceiving_ : "none")); | |
fc68f6b1 | 1815 | |
cf6eb29e CT |
1816 | if (const char *oldError = stoppedSending()) { |
1817 | debugs(33, 3, HERE << "already stopped sending: " << oldError); | |
1818 | return; // nothing has changed as far as this connection is concerned | |
1819 | } | |
1820 | stoppedSending_ = error; | |
fc68f6b1 | 1821 | |
cf6eb29e CT |
1822 | if (!stoppedReceiving()) { |
1823 | if (const int64_t expecting = mayNeedToReadMoreBody()) { | |
1824 | debugs(33, 5, HERE << "must still read " << expecting << | |
1825 | " request body bytes with " << in.notYetUsed << " unused"); | |
1826 | return; // wait for the request receiver to finish reading | |
3b299123 | 1827 | } |
55e44db9 | 1828 | } |
1829 | ||
cf6eb29e | 1830 | clientConnection->close(); |
55e44db9 | 1831 | } |
1832 | ||
0655fa4d | 1833 | void |
e0d28505 | 1834 | ClientSocketContext::writeComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag) |
0655fa4d | 1835 | { |
5ad038e1 | 1836 | const StoreEntry *entry = http->storeEntry(); |
7a2f978b | 1837 | http->out.size += size; |
e0d28505 | 1838 | debugs(33, 5, HERE << conn << ", sz " << size << |
e4049756 | 1839 | ", err " << errflag << ", off " << http->out.size << ", len " << |
5ad038e1 | 1840 | (entry ? entry->objectLen() : 0)); |
c8be6d7b | 1841 | clientUpdateSocketStats(http->logType, size); |
62e76326 | 1842 | |
5f8252d2 | 1843 | /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */ |
fc68f6b1 | 1844 | |
24bf76b5 | 1845 | if (errflag == COMM_ERR_CLOSING || !Comm::IsConnOpen(conn)) |
5f8252d2 | 1846 | return; |
1847 | ||
e0d28505 | 1848 | if (errflag || clientHttpRequestStatus(conn->fd, http)) { |
5f8252d2 | 1849 | initiateClose("failure or true request status"); |
62e76326 | 1850 | /* Do we leak here ? */ |
1851 | return; | |
edce4d98 | 1852 | } |
62e76326 | 1853 | |
0655fa4d | 1854 | switch (socketState()) { |
62e76326 | 1855 | |
edce4d98 | 1856 | case STREAM_NONE: |
0655fa4d | 1857 | pullData(); |
62e76326 | 1858 | break; |
1859 | ||
edce4d98 | 1860 | case STREAM_COMPLETE: |
e0d28505 | 1861 | debugs(33, 5, HERE << conn << " Keeping Alive"); |
0655fa4d | 1862 | keepaliveNextRequest(); |
62e76326 | 1863 | return; |
1864 | ||
edce4d98 | 1865 | case STREAM_UNPLANNED_COMPLETE: |
6e1d409c AR |
1866 | initiateClose("STREAM_UNPLANNED_COMPLETE"); |
1867 | return; | |
62e76326 | 1868 | |
edce4d98 | 1869 | case STREAM_FAILED: |
6e1d409c | 1870 | initiateClose("STREAM_FAILED"); |
62e76326 | 1871 | return; |
1872 | ||
edce4d98 | 1873 | default: |
62e76326 | 1874 | fatal("Hit unreachable code in clientWriteComplete\n"); |
7a2f978b | 1875 | } |
1876 | } | |
1877 | ||
e6ccf245 | 1878 | extern "C" CSR clientGetMoreData; |
1879 | extern "C" CSS clientReplyStatus; | |
1880 | extern "C" CSD clientReplyDetach; | |
edce4d98 | 1881 | |
528b2c61 | 1882 | static ClientSocketContext * |
be364179 | 1883 | parseHttpRequestAbort(ConnStateData * csd, const char *uri) |
038eb4ed | 1884 | { |
59a1efb2 | 1885 | ClientHttpRequest *http; |
528b2c61 | 1886 | ClientSocketContext *context; |
1887 | StoreIOBuffer tempBuffer; | |
be364179 AJ |
1888 | http = new ClientHttpRequest(csd); |
1889 | http->req_sz = csd->in.notYetUsed; | |
edce4d98 | 1890 | http->uri = xstrdup(uri); |
c4b7a5a9 | 1891 | setLogUri (http, uri); |
73c36fd9 | 1892 | context = ClientSocketContextNew(csd->clientConnection, http); |
c8be6d7b | 1893 | tempBuffer.data = context->reqbuf; |
1894 | tempBuffer.length = HTTP_REQBUF_SZ; | |
edce4d98 | 1895 | clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach, |
0655fa4d | 1896 | clientReplyStatus, new clientReplyContext(http), clientSocketRecipient, |
62e76326 | 1897 | clientSocketDetach, context, tempBuffer); |
edce4d98 | 1898 | return context; |
038eb4ed | 1899 | } |
1900 | ||
c8be6d7b | 1901 | char * |
1902 | skipLeadingSpace(char *aString) | |
1903 | { | |
1904 | char *result = aString; | |
62e76326 | 1905 | |
c8be6d7b | 1906 | while (xisspace(*aString)) |
62e76326 | 1907 | ++aString; |
1908 | ||
c8be6d7b | 1909 | return result; |
1910 | } | |
1911 | ||
63be0a78 | 1912 | /** |
d4a04ed5 | 1913 | * 'end' defaults to NULL for backwards compatibility |
1914 | * remove default value if we ever get rid of NULL-terminated | |
1915 | * request buffers. | |
1916 | */ | |
1917 | const char * | |
1918 | findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end) | |
c8be6d7b | 1919 | { |
d4a04ed5 | 1920 | if (NULL == end) { |
1921 | end = uriAndHTTPVersion + strcspn(uriAndHTTPVersion, "\r\n"); | |
1922 | assert(end); | |
1923 | } | |
62e76326 | 1924 | |
d4a04ed5 | 1925 | for (; end > uriAndHTTPVersion; end--) { |
1926 | if (*end == '\n' || *end == '\r') | |
62e76326 | 1927 | continue; |
1928 | ||
d4a04ed5 | 1929 | if (xisspace(*end)) { |
1930 | if (strncasecmp(end + 1, "HTTP/", 5) == 0) | |
1931 | return end + 1; | |
62e76326 | 1932 | else |
1933 | break; | |
1934 | } | |
c8be6d7b | 1935 | } |
62e76326 | 1936 | |
3f38a55e | 1937 | return NULL; |
c8be6d7b | 1938 | } |
1939 | ||
c8be6d7b | 1940 | void |
727552f4 | 1941 | setLogUri(ClientHttpRequest * http, char const *uri, bool cleanUrl) |
c8be6d7b | 1942 | { |
a46d0227 | 1943 | safe_free(http->log_uri); |
62e76326 | 1944 | |
727552f4 CT |
1945 | if (!cleanUrl) |
1946 | // The uri is already clean just dump it. | |
62e76326 | 1947 | http->log_uri = xstrndup(uri, MAX_URL); |
727552f4 | 1948 | else { |
2bea559d A |
1949 | int flags = 0; |
1950 | switch (Config.uri_whitespace) { | |
1951 | case URI_WHITESPACE_ALLOW: | |
1952 | flags |= RFC1738_ESCAPE_NOSPACE; | |
1953 | ||
1954 | case URI_WHITESPACE_ENCODE: | |
1955 | flags |= RFC1738_ESCAPE_UNESCAPED; | |
1956 | http->log_uri = xstrndup(rfc1738_do_escape(uri, flags), MAX_URL); | |
1957 | break; | |
727552f4 | 1958 | |
2bea559d A |
1959 | case URI_WHITESPACE_CHOP: { |
1960 | flags |= RFC1738_ESCAPE_NOSPACE; | |
1961 | flags |= RFC1738_ESCAPE_UNESCAPED; | |
1962 | http->log_uri = xstrndup(rfc1738_do_escape(uri, flags), MAX_URL); | |
1963 | int pos = strcspn(http->log_uri, w_space); | |
1964 | http->log_uri[pos] = '\0'; | |
1965 | } | |
1966 | break; | |
1967 | ||
1968 | case URI_WHITESPACE_DENY: | |
1969 | case URI_WHITESPACE_STRIP: | |
1970 | default: { | |
1971 | const char *t; | |
1972 | char *tmp_uri = static_cast<char*>(xmalloc(strlen(uri) + 1)); | |
1973 | char *q = tmp_uri; | |
1974 | t = uri; | |
1975 | while (*t) { | |
1976 | if (!xisspace(*t)) | |
1977 | *q++ = *t; | |
1978 | t++; | |
727552f4 | 1979 | } |
2bea559d A |
1980 | *q = '\0'; |
1981 | http->log_uri = xstrndup(rfc1738_escape_unescaped(tmp_uri), MAX_URL); | |
1982 | xfree(tmp_uri); | |
1983 | } | |
1984 | break; | |
1985 | } | |
727552f4 | 1986 | } |
c8be6d7b | 1987 | } |
1988 | ||
3f38a55e | 1989 | static void |
1cf238db | 1990 | prepareAcceleratedURL(ConnStateData * conn, ClientHttpRequest *http, char *url, const char *req_hdr) |
62e76326 | 1991 | { |
3f38a55e | 1992 | int vhost = conn->port->vhost; |
1993 | int vport = conn->port->vport; | |
1994 | char *host; | |
de12d836 | 1995 | char ipbuf[MAX_IPSTRLEN]; |
c8be6d7b | 1996 | |
3f38a55e | 1997 | http->flags.accel = 1; |
c8be6d7b | 1998 | |
3f38a55e | 1999 | /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */ |
c8be6d7b | 2000 | |
34399323 | 2001 | if (strncasecmp(url, "cache_object://", 15) == 0) |
2002 | return; /* already in good shape */ | |
2003 | ||
3f38a55e | 2004 | if (*url != '/') { |
62e76326 | 2005 | if (conn->port->vhost) |
2006 | return; /* already in good shape */ | |
2007 | ||
2008 | /* else we need to ignore the host name */ | |
2009 | url = strstr(url, "//"); | |
2010 | ||
3f38a55e | 2011 | #if SHOULD_REJECT_UNKNOWN_URLS |
62e76326 | 2012 | |
719c7e0a AJ |
2013 | if (!url) { |
2014 | hp->request_parse_status = HTTP_BAD_REQUEST; | |
62e76326 | 2015 | return parseHttpRequestAbort(conn, "error:invalid-request"); |
719c7e0a | 2016 | } |
c8be6d7b | 2017 | #endif |
62e76326 | 2018 | |
2019 | if (url) | |
2020 | url = strchr(url + 2, '/'); | |
2021 | ||
2022 | if (!url) | |
2023 | url = (char *) "/"; | |
3f38a55e | 2024 | } |
2025 | ||
2026 | if (internalCheck(url)) { | |
62e76326 | 2027 | /* prepend our name & port */ |
2028 | http->uri = xstrdup(internalLocalUri(NULL, url)); | |
8f489ad7 AJ |
2029 | // We just re-wrote the URL. Must replace the Host: header. |
2030 | // But have not parsed there yet!! flag for local-only handling. | |
2031 | http->flags.internal = 1; | |
ae7ff0b8 | 2032 | return; |
2033 | } | |
2034 | ||
5463e4b9 AJ |
2035 | if (vport < 0) |
2036 | vport = http->getConn()->clientConnection->local.GetPort(); | |
2037 | ||
ae7ff0b8 | 2038 | const bool switchedToHttps = conn->switchedToHttps(); |
2039 | const bool tryHostHeader = vhost || switchedToHttps; | |
2040 | if (tryHostHeader && (host = mime_get_header(req_hdr, "Host")) != NULL) { | |
5463e4b9 AJ |
2041 | debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host << " + vport=" << vport); |
2042 | char thost[256]; | |
2043 | if (vport > 0) { | |
2044 | thost[0] = '\0'; | |
2045 | char *t = NULL; | |
2046 | if (host[strlen(host)] != ']' && (t = strrchr(host,':')) != NULL) { | |
2047 | strncpy(thost, host, (t-host)); | |
2048 | snprintf(thost+(t-host), sizeof(thost)-(t-host), ":%d", vport); | |
2049 | host = thost; | |
2050 | } else if (!t) { | |
2051 | snprintf(thost, sizeof(thost), "%s:%d",host, vport); | |
2052 | host = thost; | |
2053 | } | |
2054 | } // else nothing to alter port-wise. | |
62e76326 | 2055 | int url_sz = strlen(url) + 32 + Config.appendDomainLen + |
2056 | strlen(host); | |
2057 | http->uri = (char *)xcalloc(url_sz, 1); | |
ae7ff0b8 | 2058 | const char *protocol = switchedToHttps ? |
9e008dda | 2059 | "https" : conn->port->protocol; |
ae7ff0b8 | 2060 | snprintf(http->uri, url_sz, "%s://%s%s", protocol, host, url); |
bf8fe701 | 2061 | debugs(33, 5, "ACCEL VHOST REWRITE: '" << http->uri << "'"); |
5463e4b9 AJ |
2062 | } else if (conn->port->defaultsite /* && !vhost */) { |
2063 | debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn->port->defaultsite << " + vport=" << vport); | |
62e76326 | 2064 | int url_sz = strlen(url) + 32 + Config.appendDomainLen + |
2065 | strlen(conn->port->defaultsite); | |
2066 | http->uri = (char *)xcalloc(url_sz, 1); | |
5463e4b9 AJ |
2067 | char vportStr[32]; |
2068 | vportStr[0] = '\0'; | |
2069 | if (vport > 0) { | |
2070 | snprintf(vportStr, sizeof(vportStr),":%d",vport); | |
2071 | } | |
2072 | snprintf(http->uri, url_sz, "%s://%s%s%s", | |
2073 | conn->port->protocol, conn->port->defaultsite, vportStr, url); | |
bf8fe701 | 2074 | debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http->uri <<"'"); |
5463e4b9 AJ |
2075 | } else if (vport > 0 /* && (!vhost || no Host:) */) { |
2076 | debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport); | |
2077 | /* Put the local socket IP address as the hostname, with whatever vport we found */ | |
62e76326 | 2078 | int url_sz = strlen(url) + 32 + Config.appendDomainLen; |
2079 | http->uri = (char *)xcalloc(url_sz, 1); | |
73c36fd9 | 2080 | http->getConn()->clientConnection->local.ToHostname(ipbuf,MAX_IPSTRLEN); |
62e76326 | 2081 | snprintf(http->uri, url_sz, "%s://%s:%d%s", |
98242069 | 2082 | http->getConn()->port->protocol, |
de12d836 | 2083 | ipbuf, vport, url); |
bf8fe701 | 2084 | debugs(33, 5, "ACCEL VPORT REWRITE: '" << http->uri << "'"); |
3f38a55e | 2085 | } |
2086 | } | |
2087 | ||
2088 | static void | |
1cf238db | 2089 | prepareTransparentURL(ConnStateData * conn, ClientHttpRequest *http, char *url, const char *req_hdr) |
62e76326 | 2090 | { |
3f38a55e | 2091 | char *host; |
de12d836 | 2092 | char ipbuf[MAX_IPSTRLEN]; |
3f38a55e | 2093 | |
3f38a55e | 2094 | if (*url != '/') |
62e76326 | 2095 | return; /* already in good shape */ |
3f38a55e | 2096 | |
2097 | /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */ | |
c057c49e | 2098 | // BUG 2976: Squid only accepts intercepted HTTP. |
3f38a55e | 2099 | |
f024c970 | 2100 | if ((host = mime_get_header(req_hdr, "Host")) != NULL) { |
62e76326 | 2101 | int url_sz = strlen(url) + 32 + Config.appendDomainLen + |
2102 | strlen(host); | |
2103 | http->uri = (char *)xcalloc(url_sz, 1); | |
c057c49e | 2104 | snprintf(http->uri, url_sz, "http://%s%s", /*conn->port->protocol,*/ host, url); |
bf8fe701 | 2105 | debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http->uri <<"'"); |
c8be6d7b | 2106 | } else { |
62e76326 | 2107 | /* Put the local socket IP address as the hostname. */ |
2108 | int url_sz = strlen(url) + 32 + Config.appendDomainLen; | |
2109 | http->uri = (char *)xcalloc(url_sz, 1); | |
73c36fd9 | 2110 | http->getConn()->clientConnection->local.ToHostname(ipbuf,MAX_IPSTRLEN), |
c057c49e AJ |
2111 | snprintf(http->uri, url_sz, "http://%s:%d%s", |
2112 | // http->getConn()->port->protocol, | |
73c36fd9 | 2113 | ipbuf, http->getConn()->clientConnection->local.GetPort(), url); |
bf8fe701 | 2114 | debugs(33, 5, "TRANSPARENT REWRITE: '" << http->uri << "'"); |
c8be6d7b | 2115 | } |
c8be6d7b | 2116 | } |
2117 | ||
63be0a78 | 2118 | /** |
7a2f978b | 2119 | * parseHttpRequest() |
9e008dda | 2120 | * |
7a2f978b | 2121 | * Returns |
c4b7a5a9 | 2122 | * NULL on incomplete requests |
528b2c61 | 2123 | * a ClientSocketContext structure on success or failure. |
c4b7a5a9 | 2124 | * Sets result->flags.parsed_ok to 0 if failed to parse the request. |
2125 | * Sets result->flags.parsed_ok to 1 if we have a good request. | |
7a2f978b | 2126 | */ |
528b2c61 | 2127 | static ClientSocketContext * |
be364179 | 2128 | parseHttpRequest(ConnStateData *csd, HttpParser *hp, HttpRequestMethod * method_p, HttpVersion *http_ver) |
7a2f978b | 2129 | { |
7a2f978b | 2130 | char *req_hdr = NULL; |
2334c194 | 2131 | char *end; |
c68e9c6b | 2132 | size_t req_sz; |
59a1efb2 | 2133 | ClientHttpRequest *http; |
528b2c61 | 2134 | ClientSocketContext *result; |
2135 | StoreIOBuffer tempBuffer; | |
84cc2635 | 2136 | int r; |
7a2f978b | 2137 | |
6792f0d3 | 2138 | /* pre-set these values to make aborting simpler */ |
6792f0d3 | 2139 | *method_p = METHOD_NONE; |
6792f0d3 | 2140 | |
7ed7d3da AJ |
2141 | /* NP: don't be tempted to move this down or remove again. |
2142 | * It's the only DDoS protection old-String has against long URL */ | |
2143 | if ( hp->bufsiz <= 0) { | |
2144 | debugs(33, 5, "Incomplete request, waiting for end of request line"); | |
2145 | return NULL; | |
e1381638 | 2146 | } else if ( (size_t)hp->bufsiz >= Config.maxRequestHeaderSize && headersEnd(hp->buf, Config.maxRequestHeaderSize) == 0) { |
7ed7d3da | 2147 | debugs(33, 5, "parseHttpRequest: Too large request"); |
719c7e0a | 2148 | hp->request_parse_status = HTTP_HEADER_TOO_LARGE; |
be364179 | 2149 | return parseHttpRequestAbort(csd, "error:request-too-large"); |
7ed7d3da AJ |
2150 | } |
2151 | ||
84cc2635 | 2152 | /* Attempt to parse the first line; this'll define the method, url, version and header begin */ |
2153 | r = HttpParserParseReqLine(hp); | |
fc68f6b1 | 2154 | |
84cc2635 | 2155 | if (r == 0) { |
bf8fe701 | 2156 | debugs(33, 5, "Incomplete request, waiting for end of request line"); |
fc68f6b1 | 2157 | return NULL; |
7a2f978b | 2158 | } |
fc68f6b1 | 2159 | |
84cc2635 | 2160 | if (r == -1) { |
be364179 | 2161 | return parseHttpRequestAbort(csd, "error:invalid-request"); |
84cc2635 | 2162 | } |
fc68f6b1 | 2163 | |
84cc2635 | 2164 | /* Request line is valid here .. */ |
74f478f8 | 2165 | *http_ver = HttpVersion(hp->req.v_maj, hp->req.v_min); |
62e76326 | 2166 | |
52512f28 | 2167 | /* This call scans the entire request, not just the headers */ |
74f478f8 | 2168 | if (hp->req.v_maj > 0) { |
a5baffba | 2169 | if ((req_sz = headersEnd(hp->buf, hp->bufsiz)) == 0) { |
bf8fe701 | 2170 | debugs(33, 5, "Incomplete request, waiting for end of headers"); |
62e76326 | 2171 | return NULL; |
2172 | } | |
3f38a55e | 2173 | } else { |
bf8fe701 | 2174 | debugs(33, 3, "parseHttpRequest: Missing HTTP identifier"); |
84cc2635 | 2175 | req_sz = HttpParserReqSz(hp); |
3f38a55e | 2176 | } |
2177 | ||
bb790702 | 2178 | /* We know the whole request is in hp->buf now */ |
52512f28 | 2179 | |
a5baffba | 2180 | assert(req_sz <= (size_t) hp->bufsiz); |
fc68f6b1 | 2181 | |
a5baffba | 2182 | /* Will the following be true with HTTP/0.9 requests? probably not .. */ |
2183 | /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */ | |
2184 | assert(req_sz > 0); | |
fc68f6b1 | 2185 | |
a5baffba | 2186 | hp->hdr_end = req_sz - 1; |
fc68f6b1 | 2187 | |
74f478f8 | 2188 | hp->hdr_start = hp->req.end + 1; |
3f38a55e | 2189 | |
5b648f60 | 2190 | /* Enforce max_request_size */ |
5b648f60 | 2191 | if (req_sz >= Config.maxRequestHeaderSize) { |
bf8fe701 | 2192 | debugs(33, 5, "parseHttpRequest: Too large request"); |
719c7e0a | 2193 | hp->request_parse_status = HTTP_HEADER_TOO_LARGE; |
be364179 | 2194 | return parseHttpRequestAbort(csd, "error:request-too-large"); |
5b648f60 | 2195 | } |
2196 | ||
84cc2635 | 2197 | /* Set method_p */ |
74f478f8 | 2198 | *method_p = HttpRequestMethod(&hp->buf[hp->req.m_start], &hp->buf[hp->req.m_end]+1); |
fc68f6b1 | 2199 | |
adf29627 | 2200 | /* deny CONNECT via accelerated ports */ |
be364179 AJ |
2201 | if (*method_p == METHOD_CONNECT && csd && csd->port && csd->port->accel) { |
2202 | debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << csd->port->protocol << " Accelerator port " << csd->port->s.GetPort() ); | |
adf29627 AJ |
2203 | /* XXX need a way to say "this many character length string" */ |
2204 | debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->buf); | |
719c7e0a | 2205 | hp->request_parse_status = HTTP_METHOD_NOT_ALLOWED; |
be364179 | 2206 | return parseHttpRequestAbort(csd, "error:method-not-allowed"); |
adf29627 AJ |
2207 | } |
2208 | ||
84cc2635 | 2209 | if (*method_p == METHOD_NONE) { |
fc68f6b1 | 2210 | /* XXX need a way to say "this many character length string" */ |
bf8fe701 | 2211 | debugs(33, 1, "clientParseRequestMethod: Unsupported method in request '" << hp->buf << "'"); |
719c7e0a | 2212 | hp->request_parse_status = HTTP_METHOD_NOT_ALLOWED; |
be364179 | 2213 | return parseHttpRequestAbort(csd, "error:unsupported-request-method"); |
3f38a55e | 2214 | } |
7a2f978b | 2215 | |
c68e9c6b | 2216 | /* |
2217 | * Process headers after request line | |
c8be6d7b | 2218 | * TODO: Use httpRequestParse here. |
c68e9c6b | 2219 | */ |
84cc2635 | 2220 | /* XXX this code should be modified to take a const char * later! */ |
74f478f8 | 2221 | req_hdr = (char *) hp->buf + hp->req.end + 1; |
fc68f6b1 | 2222 | |
bf8fe701 | 2223 | debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr << "}"); |
fc68f6b1 | 2224 | |
52512f28 | 2225 | end = (char *) hp->buf + hp->hdr_end; |
fc68f6b1 | 2226 | |
bf8fe701 | 2227 | debugs(33, 3, "parseHttpRequest: end = {" << end << "}"); |
99edd1c3 | 2228 | |
bf8fe701 | 2229 | debugs(33, 3, "parseHttpRequest: prefix_sz = " << |
2230 | (int) HttpParserRequestLen(hp) << ", req_line_sz = " << | |
2231 | HttpParserReqSz(hp)); | |
62e76326 | 2232 | |
7a2f978b | 2233 | /* Ok, all headers are received */ |
be364179 | 2234 | http = new ClientHttpRequest(csd); |
62e76326 | 2235 | |
a5baffba | 2236 | http->req_sz = HttpParserRequestLen(hp); |
73c36fd9 | 2237 | result = ClientSocketContextNew(csd->clientConnection, http); |
c8be6d7b | 2238 | tempBuffer.data = result->reqbuf; |
2239 | tempBuffer.length = HTTP_REQBUF_SZ; | |
62e76326 | 2240 | |
0655fa4d | 2241 | ClientStreamData newServer = new clientReplyContext(http); |
0655fa4d | 2242 | ClientStreamData newClient = result; |
edce4d98 | 2243 | clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach, |
0655fa4d | 2244 | clientReplyStatus, newServer, clientSocketRecipient, |
2245 | clientSocketDetach, newClient, tempBuffer); | |
62e76326 | 2246 | |
bf8fe701 | 2247 | debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp->buf) + hp->hdr_start); |
3f38a55e | 2248 | |
3ff65596 AR |
2249 | /* set url */ |
2250 | /* | |
2251 | * XXX this should eventually not use a malloc'ed buffer; the transformation code | |
2252 | * below needs to be modified to not expect a mutable nul-terminated string. | |
2253 | */ | |
74f478f8 | 2254 | char *url = (char *)xmalloc(hp->req.u_end - hp->req.u_start + 16); |
3ff65596 | 2255 | |
74f478f8 | 2256 | memcpy(url, hp->buf + hp->req.u_start, hp->req.u_end - hp->req.u_start + 1); |
3ff65596 | 2257 | |
74f478f8 | 2258 | url[hp->req.u_end - hp->req.u_start + 1] = '\0'; |
3ff65596 | 2259 | |
ba9ebd0a | 2260 | #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION |
62e76326 | 2261 | |
7a2f978b | 2262 | if ((t = strchr(url, '#'))) /* remove HTML anchors */ |
62e76326 | 2263 | *t = '\0'; |
2264 | ||
ba9ebd0a | 2265 | #endif |
7a2f978b | 2266 | |
5463e4b9 | 2267 | debugs(33,5, HERE << "repare absolute URL from " << (csd->transparent()?"intercept":(csd->port->accel ? "accel":""))); |
3f38a55e | 2268 | /* Rewrite the URL in transparent or accelerator mode */ |
89272111 AJ |
2269 | /* NP: there are several cases to traverse here: |
2270 | * - standard mode (forward proxy) | |
2271 | * - transparent mode (TPROXY) | |
2272 | * - transparent mode with failures | |
2273 | * - intercept mode (NAT) | |
2274 | * - intercept mode with failures | |
2275 | * - accelerator mode (reverse proxy) | |
2276 | * - internal URL | |
2277 | * - mixed combos of the above with internal URL | |
2278 | */ | |
be364179 | 2279 | if (csd->transparent()) { |
89272111 | 2280 | /* intercept or transparent mode, properly working with no failures */ |
be364179 | 2281 | prepareTransparentURL(csd, http, url, req_hdr); |
89272111 | 2282 | |
be364179 | 2283 | } else if (csd->port->accel || csd->switchedToHttps()) { |
89272111 | 2284 | /* accelerator mode */ |
be364179 | 2285 | prepareAcceleratedURL(csd, http, url, req_hdr); |
89272111 | 2286 | |
2f2749d7 | 2287 | } else if (internalCheck(url)) { |
89272111 | 2288 | /* internal URL mode */ |
2f2749d7 | 2289 | /* prepend our name & port */ |
2290 | http->uri = xstrdup(internalLocalUri(NULL, url)); | |
2f2749d7 | 2291 | http->flags.accel = 1; |
3f38a55e | 2292 | } |
2293 | ||
2294 | if (!http->uri) { | |
62e76326 | 2295 | /* No special rewrites have been applied above, use the |
2296 | * requested url. may be rewritten later, so make extra room */ | |
2297 | int url_sz = strlen(url) + Config.appendDomainLen + 5; | |
2298 | http->uri = (char *)xcalloc(url_sz, 1); | |
2299 | strcpy(http->uri, url); | |
3f38a55e | 2300 | } |
62e76326 | 2301 | |
bf8fe701 | 2302 | debugs(33, 5, "parseHttpRequest: Complete request received"); |
1ce34ddd AJ |
2303 | |
2304 | // XXX: crop this dump at the end of headers. No need for extras | |
2305 | debugs(11, 2, "HTTP Client " << csd->clientConnection); | |
2306 | debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp->buf) + hp->req.m_start << "\n----------"); | |
2307 | ||
c4b7a5a9 | 2308 | result->flags.parsed_ok = 1; |
84cc2635 | 2309 | xfree(url); |
c8be6d7b | 2310 | return result; |
7a2f978b | 2311 | } |
2312 | ||
c8be6d7b | 2313 | int |
a46d2c0e | 2314 | ConnStateData::getAvailableBufferLength() const |
c8be6d7b | 2315 | { |
f5f9e44c AR |
2316 | assert (in.allocatedSize > in.notYetUsed); // allocated more than used |
2317 | const size_t result = in.allocatedSize - in.notYetUsed - 1; | |
2318 | // huge request_header_max_size may lead to more than INT_MAX unused space | |
2319 | assert (static_cast<ssize_t>(result) <= INT_MAX); | |
1a419b96 | 2320 | return result; |
c8be6d7b | 2321 | } |
2322 | ||
1368d115 CT |
2323 | bool |
2324 | ConnStateData::maybeMakeSpaceAvailable() | |
c8be6d7b | 2325 | { |
a46d2c0e | 2326 | if (getAvailableBufferLength() < 2) { |
90737510 A |
2327 | size_t newSize; |
2328 | if (in.allocatedSize >= Config.maxRequestBufferSize) { | |
2329 | debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config.maxRequestBufferSize); | |
2330 | return false; | |
2331 | } | |
2332 | if ((newSize=in.allocatedSize * 2) > Config.maxRequestBufferSize) { | |
2333 | newSize=Config.maxRequestBufferSize; | |
2334 | } | |
2335 | in.buf = (char *)memReallocBuf(in.buf, newSize, &in.allocatedSize); | |
2336 | debugs(33, 2, "growing request buffer: notYetUsed=" << in.notYetUsed << " size=" << in.allocatedSize); | |
c8be6d7b | 2337 | } |
1368d115 | 2338 | return true; |
c8be6d7b | 2339 | } |
2340 | ||
2341 | void | |
0655fa4d | 2342 | ConnStateData::addContextToQueue(ClientSocketContext * context) |
c8be6d7b | 2343 | { |
0655fa4d | 2344 | ClientSocketContext::Pointer *S; |
62e76326 | 2345 | |
0655fa4d | 2346 | for (S = (ClientSocketContext::Pointer *) & currentobject; S->getRaw(); |
3d0ac046 | 2347 | S = &(*S)->next); |
c8be6d7b | 2348 | *S = context; |
62e76326 | 2349 | |
0655fa4d | 2350 | ++nrequests; |
c8be6d7b | 2351 | } |
2352 | ||
2353 | int | |
0655fa4d | 2354 | ConnStateData::getConcurrentRequestCount() const |
c8be6d7b | 2355 | { |
2356 | int result = 0; | |
0655fa4d | 2357 | ClientSocketContext::Pointer *T; |
62e76326 | 2358 | |
0655fa4d | 2359 | for (T = (ClientSocketContext::Pointer *) ¤tobject; |
3d0ac046 | 2360 | T->getRaw(); T = &(*T)->next, ++result); |
c8be6d7b | 2361 | return result; |
2362 | } | |
2363 | ||
2364 | int | |
1cf238db | 2365 | ConnStateData::connReadWasError(comm_err_t flag, int size, int xerrno) |
c8be6d7b | 2366 | { |
c4b7a5a9 | 2367 | if (flag != COMM_OK) { |
73c36fd9 | 2368 | debugs(33, 2, "connReadWasError: FD " << clientConnection << ": got flag " << flag); |
62e76326 | 2369 | return 1; |
c4b7a5a9 | 2370 | } |
62e76326 | 2371 | |
c8be6d7b | 2372 | if (size < 0) { |
f3400a93 | 2373 | if (!ignoreErrno(xerrno)) { |
73c36fd9 | 2374 | debugs(33, 2, "connReadWasError: FD " << clientConnection << ": " << xstrerr(xerrno)); |
62e76326 | 2375 | return 1; |
1cf238db | 2376 | } else if (in.notYetUsed == 0) { |
73c36fd9 | 2377 | debugs(33, 2, "connReadWasError: FD " << clientConnection << ": no data to process (" << xstrerr(xerrno) << ")"); |
62e76326 | 2378 | } |
c8be6d7b | 2379 | } |
62e76326 | 2380 | |
c8be6d7b | 2381 | return 0; |
2382 | } | |
2383 | ||
2384 | int | |
1cf238db | 2385 | ConnStateData::connFinishedWithConn(int size) |
c8be6d7b | 2386 | { |
2387 | if (size == 0) { | |
1cf238db | 2388 | if (getConcurrentRequestCount() == 0 && in.notYetUsed == 0) { |
62e76326 | 2389 | /* no current or pending requests */ |
73c36fd9 | 2390 | debugs(33, 4, HERE << clientConnection << " closed"); |
62e76326 | 2391 | return 1; |
2392 | } else if (!Config.onoff.half_closed_clients) { | |
2393 | /* admin doesn't want to support half-closed client sockets */ | |
73c36fd9 | 2394 | debugs(33, 3, HERE << clientConnection << " aborted (half_closed_clients disabled)"); |
f692498b | 2395 | notifyAllContexts(0); // no specific error implies abort |
62e76326 | 2396 | return 1; |
2397 | } | |
c8be6d7b | 2398 | } |
62e76326 | 2399 | |
c8be6d7b | 2400 | return 0; |
2401 | } | |
2402 | ||
2403 | void | |
3b299123 | 2404 | connNoteUseOfBuffer(ConnStateData* conn, size_t byteCount) |
c8be6d7b | 2405 | { |
2406 | assert(byteCount > 0 && byteCount <= conn->in.notYetUsed); | |
2407 | conn->in.notYetUsed -= byteCount; | |
d5fa7219 | 2408 | debugs(33, 5, HERE << "conn->in.notYetUsed = " << conn->in.notYetUsed); |
c8be6d7b | 2409 | /* |
9e008dda | 2410 | * If there is still data that will be used, |
c8be6d7b | 2411 | * move it to the beginning. |
2412 | */ | |
62e76326 | 2413 | |
c8be6d7b | 2414 | if (conn->in.notYetUsed > 0) |
41d00cd3 | 2415 | memmove(conn->in.buf, conn->in.buf + byteCount, conn->in.notYetUsed); |
c8be6d7b | 2416 | } |
2417 | ||
39cb8c41 AR |
2418 | /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size |
2419 | void | |
2420 | ConnStateData::checkHeaderLimits() | |
c8be6d7b | 2421 | { |
39cb8c41 AR |
2422 | if (in.notYetUsed < Config.maxRequestHeaderSize) |
2423 | return; // can accumulte more header data | |
3ff65596 | 2424 | |
39cb8c41 | 2425 | debugs(33, 3, "Request header is too large (" << in.notYetUsed << " > " << |
de48b288 | 2426 | Config.maxRequestHeaderSize << " bytes)"); |
c8be6d7b | 2427 | |
39cb8c41 | 2428 | ClientSocketContext *context = parseHttpRequestAbort(this, "error:request-too-large"); |
528b2c61 | 2429 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2430 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2431 | assert (repContext); | |
2432 | repContext->setReplyToError(ERR_TOO_BIG, | |
39cb8c41 | 2433 | HTTP_BAD_REQUEST, METHOD_NONE, NULL, |
73c36fd9 | 2434 | clientConnection->remote, NULL, NULL, NULL); |
0655fa4d | 2435 | context->registerWithConn(); |
528b2c61 | 2436 | context->pullData(); |
c8be6d7b | 2437 | } |
2438 | ||
1cf238db | 2439 | void |
f35961af | 2440 | ConnStateData::clientAfterReadingRequests() |
c4b7a5a9 | 2441 | { |
39cb8c41 | 2442 | // Were we expecting to read more request body from half-closed connection? |
73c36fd9 AJ |
2443 | if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection->fd)) { |
2444 | debugs(33, 3, HERE << "truncated body: closing half-closed " << clientConnection); | |
2445 | clientConnection->close(); | |
39cb8c41 | 2446 | return; |
c4b7a5a9 | 2447 | } |
2448 | ||
f35961af AR |
2449 | if (flags.readMore) |
2450 | readSomeData(); | |
c4b7a5a9 | 2451 | } |
2452 | ||
c4b7a5a9 | 2453 | static void |
1cf238db | 2454 | clientProcessRequest(ConnStateData *conn, HttpParser *hp, ClientSocketContext *context, const HttpRequestMethod& method, HttpVersion http_ver) |
c4b7a5a9 | 2455 | { |
59a1efb2 | 2456 | ClientHttpRequest *http = context->http; |
190154cf | 2457 | HttpRequest *request = NULL; |
5f8252d2 | 2458 | bool notedUseOfBuffer = false; |
39cb8c41 | 2459 | bool chunked = false; |
e18b8316 | 2460 | bool mustReplyToOptions = false; |
3ff65596 | 2461 | bool unsupportedTe = false; |
39cb8c41 | 2462 | bool expectBody = false; |
5f8252d2 | 2463 | |
c4b7a5a9 | 2464 | /* We have an initial client stream in place should it be needed */ |
2465 | /* setup our private context */ | |
0655fa4d | 2466 | context->registerWithConn(); |
c4b7a5a9 | 2467 | |
2468 | if (context->flags.parsed_ok == 0) { | |
62e76326 | 2469 | clientStreamNode *node = context->getClientReplyContext(); |
f4762666 | 2470 | debugs(33, 2, "clientProcessRequest: Invalid Request"); |
727552f4 CT |
2471 | // setLogUri should called before repContext->setReplyToError |
2472 | setLogUri(http, http->uri, true); | |
0655fa4d | 2473 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2474 | assert (repContext); | |
e212e5e3 | 2475 | switch (hp->request_parse_status) { |
719c7e0a | 2476 | case HTTP_HEADER_TOO_LARGE: |
73c36fd9 | 2477 | repContext->setReplyToError(ERR_TOO_BIG, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, conn->in.buf, NULL); |
719c7e0a AJ |
2478 | break; |
2479 | case HTTP_METHOD_NOT_ALLOWED: | |
be364179 | 2480 | repContext->setReplyToError(ERR_UNSUP_REQ, HTTP_METHOD_NOT_ALLOWED, method, http->uri, |
73c36fd9 | 2481 | conn->clientConnection->remote, NULL, conn->in.buf, NULL); |
719c7e0a AJ |
2482 | break; |
2483 | default: | |
9815f129 | 2484 | repContext->setReplyToError(ERR_INVALID_REQ, hp->request_parse_status, method, http->uri, |
73c36fd9 | 2485 | conn->clientConnection->remote, NULL, conn->in.buf, NULL); |
719c7e0a | 2486 | } |
62e76326 | 2487 | assert(context->http->out.offset == 0); |
2488 | context->pullData(); | |
f35961af | 2489 | conn->flags.readMore = false; |
fc68f6b1 | 2490 | goto finish; |
c4b7a5a9 | 2491 | } |
2492 | ||
c21ad0f5 | 2493 | if ((request = HttpRequest::CreateFromUrlAndMethod(http->uri, method)) == NULL) { |
62e76326 | 2494 | clientStreamNode *node = context->getClientReplyContext(); |
bf8fe701 | 2495 | debugs(33, 5, "Invalid URL: " << http->uri); |
727552f4 CT |
2496 | // setLogUri should called before repContext->setReplyToError |
2497 | setLogUri(http, http->uri, true); | |
0655fa4d | 2498 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2499 | assert (repContext); | |
73c36fd9 | 2500 | repContext->setReplyToError(ERR_INVALID_URL, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL); |
62e76326 | 2501 | assert(context->http->out.offset == 0); |
2502 | context->pullData(); | |
f35961af | 2503 | conn->flags.readMore = false; |
fc68f6b1 | 2504 | goto finish; |
62e76326 | 2505 | } |
c4b7a5a9 | 2506 | |
e57c1885 AJ |
2507 | /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */ |
2508 | /* We currently only accept 0.9, 1.0, 1.1 */ | |
2509 | if ( (http_ver.major == 0 && http_ver.minor != 9) || | |
af6a12ee AJ |
2510 | (http_ver.major == 1 && http_ver.minor > 1 ) || |
2511 | (http_ver.major > 1) ) { | |
e57c1885 AJ |
2512 | |
2513 | clientStreamNode *node = context->getClientReplyContext(); | |
2514 | debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp)); | |
727552f4 CT |
2515 | // setLogUri should called before repContext->setReplyToError |
2516 | setLogUri(http, http->uri, true); | |
e57c1885 AJ |
2517 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2518 | assert (repContext); | |
be364179 | 2519 | repContext->setReplyToError(ERR_UNSUP_HTTPVERSION, HTTP_HTTP_VERSION_NOT_SUPPORTED, method, http->uri, |
73c36fd9 | 2520 | conn->clientConnection->remote, NULL, HttpParserHdrBuf(hp), NULL); |
e57c1885 AJ |
2521 | assert(context->http->out.offset == 0); |
2522 | context->pullData(); | |
f35961af | 2523 | conn->flags.readMore = false; |
e57c1885 AJ |
2524 | goto finish; |
2525 | } | |
2526 | ||
528b2c61 | 2527 | /* compile headers */ |
2528 | /* we should skip request line! */ | |
666f514b | 2529 | /* XXX should actually know the damned buffer size here */ |
38e82382 | 2530 | if (http_ver.major >= 1 && !request->parseHeader(HttpParserHdrBuf(hp), HttpParserHdrSz(hp))) { |
47ac2ebe | 2531 | clientStreamNode *node = context->getClientReplyContext(); |
bf8fe701 | 2532 | debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp)); |
727552f4 CT |
2533 | // setLogUri should called before repContext->setReplyToError |
2534 | setLogUri(http, http->uri, true); | |
47ac2ebe | 2535 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2536 | assert (repContext); | |
73c36fd9 | 2537 | repContext->setReplyToError(ERR_INVALID_REQ, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL); |
47ac2ebe | 2538 | assert(context->http->out.offset == 0); |
2539 | context->pullData(); | |
f35961af | 2540 | conn->flags.readMore = false; |
fc68f6b1 | 2541 | goto finish; |
47ac2ebe | 2542 | } |
c4b7a5a9 | 2543 | |
40d34a62 AJ |
2544 | request->clientConnectionManager = conn; |
2545 | ||
c4b7a5a9 | 2546 | request->flags.accelerated = http->flags.accel; |
b68415a1 | 2547 | request->flags.sslBumped = conn->switchedToHttps(); |
432bc83c | 2548 | request->flags.ignore_cc = conn->port->ignore_cc; |
7f7bdd96 | 2549 | request->flags.no_direct = request->flags.accelerated ? !conn->port->allow_direct : 0; |
2ad20b4f AJ |
2550 | |
2551 | /** \par | |
2552 | * If transparent or interception mode is working clone the transparent and interception flags | |
2553 | * from the port settings to the request. | |
2554 | */ | |
40d34a62 | 2555 | if (http->clientConnection != NULL) { |
304a6180 CT |
2556 | request->flags.intercepted = ((http->clientConnection->flags & COMM_INTERCEPTION) != 0); |
2557 | request->flags.spoof_client_ip = ((http->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ; | |
2ad20b4f | 2558 | } |
fc68f6b1 | 2559 | |
5b4117d8 | 2560 | if (internalCheck(request->urlpath.termedBuf())) { |
cc192b50 | 2561 | if (internalHostnameIs(request->GetHost()) && |
f024c970 | 2562 | request->port == getMyPort()) { |
2563 | http->flags.internal = 1; | |
9c175897 | 2564 | } else if (Config.onoff.global_internal_static && internalStaticCheck(request->urlpath.termedBuf())) { |
cc192b50 | 2565 | request->SetHost(internalHostname()); |
f024c970 | 2566 | request->port = getMyPort(); |
2567 | http->flags.internal = 1; | |
62e76326 | 2568 | } |
f024c970 | 2569 | } |
e72a0ec0 | 2570 | |
f024c970 | 2571 | if (http->flags.internal) { |
0c3d3f65 | 2572 | request->protocol = AnyP::PROTO_HTTP; |
f024c970 | 2573 | request->login[0] = '\0'; |
c4b7a5a9 | 2574 | } |
2575 | ||
c4b7a5a9 | 2576 | request->flags.internal = http->flags.internal; |
2577 | setLogUri (http, urlCanonicalClean(request)); | |
73c36fd9 | 2578 | request->client_addr = conn->clientConnection->remote; // XXX: remove reuest->client_addr member. |
3d674977 | 2579 | #if FOLLOW_X_FORWARDED_FOR |
40d34a62 AJ |
2580 | // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:) |
2581 | // not a details about teh TCP connection itself | |
73c36fd9 | 2582 | request->indirect_client_addr = conn->clientConnection->remote; |
3d674977 | 2583 | #endif /* FOLLOW_X_FORWARDED_FOR */ |
73c36fd9 | 2584 | request->my_addr = conn->clientConnection->local; |
35fb56c9 | 2585 | request->myportname = conn->port->name; |
8ae66e43 | 2586 | request->http_ver = http_ver; |
62e76326 | 2587 | |
9174ba3d AJ |
2588 | // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it |
2589 | // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later. | |
2590 | request->clientConnectionManager = conn; | |
2591 | ||
39cb8c41 AR |
2592 | if (request->header.chunked()) { |
2593 | chunked = true; | |
2594 | } else if (request->header.has(HDR_TRANSFER_ENCODING)) { | |
2595 | const String te = request->header.getList(HDR_TRANSFER_ENCODING); | |
2596 | // HTTP/1.1 requires chunking to be the last encoding if there is one | |
2597 | unsupportedTe = te.size() && te != "identity"; | |
2598 | } // else implied identity coding | |
de48b288 | 2599 | |
34ee6e73 | 2600 | mustReplyToOptions = (method == METHOD_OPTIONS) && |
d916dcb8 | 2601 | (request->header.getInt64(HDR_MAX_FORWARDS) == 0); |
e18b8316 | 2602 | if (!urlCheckRequest(request) || mustReplyToOptions || unsupportedTe) { |
62e76326 | 2603 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2604 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2605 | assert (repContext); | |
be364179 | 2606 | repContext->setReplyToError(ERR_UNSUP_REQ, HTTP_NOT_IMPLEMENTED, request->method, NULL, |
73c36fd9 | 2607 | conn->clientConnection->remote, request, NULL, NULL); |
62e76326 | 2608 | assert(context->http->out.offset == 0); |
2609 | context->pullData(); | |
f35961af | 2610 | conn->flags.readMore = false; |
fc68f6b1 | 2611 | goto finish; |
c4b7a5a9 | 2612 | } |
2613 | ||
2614 | ||
39cb8c41 | 2615 | if (!chunked && !clientIsContentLengthValid(request)) { |
62e76326 | 2616 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2617 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2618 | assert (repContext); | |
2619 | repContext->setReplyToError(ERR_INVALID_REQ, | |
2620 | HTTP_LENGTH_REQUIRED, request->method, NULL, | |
73c36fd9 | 2621 | conn->clientConnection->remote, request, NULL, NULL); |
62e76326 | 2622 | assert(context->http->out.offset == 0); |
2623 | context->pullData(); | |
f35961af | 2624 | conn->flags.readMore = false; |
fc68f6b1 | 2625 | goto finish; |
c4b7a5a9 | 2626 | } |
2627 | ||
52b601ff | 2628 | if (request->header.has(HDR_EXPECT)) { |
655daa06 AR |
2629 | const String expect = request->header.getList(HDR_EXPECT); |
2630 | const bool supportedExpect = (expect.caseCmp("100-continue") == 0); | |
2631 | if (!supportedExpect) { | |
52b601ff AJ |
2632 | clientStreamNode *node = context->getClientReplyContext(); |
2633 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
2634 | assert (repContext); | |
be364179 | 2635 | repContext->setReplyToError(ERR_INVALID_REQ, HTTP_EXPECTATION_FAILED, request->method, http->uri, |
73c36fd9 | 2636 | conn->clientConnection->remote, request, NULL, NULL); |
52b601ff AJ |
2637 | assert(context->http->out.offset == 0); |
2638 | context->pullData(); | |
f35961af | 2639 | conn->flags.readMore = false; |
52b601ff AJ |
2640 | goto finish; |
2641 | } | |
2642 | } | |
2643 | ||
6dd9f4bd | 2644 | http->request = HTTPMSGLOCK(request); |
c4b7a5a9 | 2645 | clientSetKeepaliveFlag(http); |
62e76326 | 2646 | |
f35961af AR |
2647 | // Let tunneling code be fully responsible for CONNECT requests |
2648 | if (http->request->method == METHOD_CONNECT) { | |
b66e0e86 | 2649 | context->mayUseConnection(true); |
f35961af AR |
2650 | conn->flags.readMore = false; |
2651 | } | |
fc68f6b1 | 2652 | |
b66e0e86 | 2653 | /* Do we expect a request-body? */ |
39cb8c41 AR |
2654 | expectBody = chunked || request->content_length > 0; |
2655 | if (!context->mayUseConnection() && expectBody) { | |
2656 | request->body_pipe = conn->expectRequestBody( | |
de48b288 | 2657 | chunked ? -1 : request->content_length); |
5f8252d2 | 2658 | |
2659 | // consume header early so that body pipe gets just the body | |
1cf238db | 2660 | connNoteUseOfBuffer(conn, http->req_sz); |
5f8252d2 | 2661 | notedUseOfBuffer = true; |
2662 | ||
62e76326 | 2663 | /* Is it too large? */ |
39cb8c41 | 2664 | if (!chunked && // if chunked, we will check as we accumulate |
de48b288 | 2665 | clientIsRequestBodyTooLargeForPolicy(request->content_length)) { |
62e76326 | 2666 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2667 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2668 | assert (repContext); | |
2669 | repContext->setReplyToError(ERR_TOO_BIG, | |
2670 | HTTP_REQUEST_ENTITY_TOO_LARGE, METHOD_NONE, NULL, | |
73c36fd9 | 2671 | conn->clientConnection->remote, http->request, NULL, NULL); |
62e76326 | 2672 | assert(context->http->out.offset == 0); |
2673 | context->pullData(); | |
f35961af | 2674 | conn->flags.readMore = false; |
5f8252d2 | 2675 | goto finish; |
62e76326 | 2676 | } |
2677 | ||
39cb8c41 AR |
2678 | // We may stop producing, comm_close, and/or call setReplyToError() |
2679 | // below, so quit on errors to avoid http->doCallouts() | |
2680 | if (!conn->handleRequestBodyData()) | |
de48b288 | 2681 | goto finish; |
39cb8c41 | 2682 | |
f35961af AR |
2683 | if (!request->body_pipe->productionEnded()) { |
2684 | debugs(33, 5, HERE << "need more request body"); | |
2685 | context->mayUseConnection(true); | |
2686 | assert(conn->flags.readMore); | |
2687 | } | |
c4b7a5a9 | 2688 | } |
2689 | ||
de31d06f | 2690 | http->calloutContext = new ClientRequestContext(http); |
2691 | ||
2692 | http->doCallouts(); | |
9e008dda | 2693 | |
4c29340e | 2694 | finish: |
5f8252d2 | 2695 | if (!notedUseOfBuffer) |
1cf238db | 2696 | connNoteUseOfBuffer(conn, http->req_sz); |
52c2c8a8 | 2697 | |
2698 | /* | |
2699 | * DPW 2007-05-18 | |
2700 | * Moved the TCP_RESET feature from clientReplyContext::sendMoreData | |
2701 | * to here because calling comm_reset_close() causes http to | |
2702 | * be freed and the above connNoteUseOfBuffer() would hit an | |
2703 | * assertion, not to mention that we were accessing freed memory. | |
2704 | */ | |
73c36fd9 AJ |
2705 | if (http->request->flags.resetTCP() && Comm::IsConnOpen(conn->clientConnection)) { |
2706 | debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection); | |
f35961af | 2707 | conn->flags.readMore = false; |
73c36fd9 | 2708 | comm_reset_close(conn->clientConnection); |
52c2c8a8 | 2709 | } |
c4b7a5a9 | 2710 | } |
2711 | ||
2712 | static void | |
1cf238db | 2713 | connStripBufferWhitespace (ConnStateData * conn) |
c4b7a5a9 | 2714 | { |
2715 | while (conn->in.notYetUsed > 0 && xisspace(conn->in.buf[0])) { | |
41d00cd3 | 2716 | memmove(conn->in.buf, conn->in.buf + 1, conn->in.notYetUsed - 1); |
62e76326 | 2717 | --conn->in.notYetUsed; |
c4b7a5a9 | 2718 | } |
2719 | } | |
2720 | ||
2721 | static int | |
1cf238db | 2722 | connOkToAddRequest(ConnStateData * conn) |
c4b7a5a9 | 2723 | { |
0655fa4d | 2724 | int result = conn->getConcurrentRequestCount() < (Config.onoff.pipeline_prefetch ? 2 : 1); |
62e76326 | 2725 | |
c4b7a5a9 | 2726 | if (!result) { |
73c36fd9 AJ |
2727 | debugs(33, 3, HERE << conn->clientConnection << " max concurrent requests reached"); |
2728 | debugs(33, 5, HERE << conn->clientConnection << " defering new request until one is done"); | |
c4b7a5a9 | 2729 | } |
62e76326 | 2730 | |
c4b7a5a9 | 2731 | return result; |
2732 | } | |
2733 | ||
63be0a78 | 2734 | /** |
f900210a | 2735 | * Attempt to parse one or more requests from the input buffer. |
2736 | * If a request is successfully parsed, even if the next request | |
2737 | * is only partially parsed, it will return TRUE. | |
f900210a | 2738 | */ |
4959e21e | 2739 | bool |
f35961af | 2740 | ConnStateData::clientParseRequests() |
f900210a | 2741 | { |
60745f24 | 2742 | HttpRequestMethod method; |
f900210a | 2743 | bool parsed_req = false; |
8ae66e43 | 2744 | HttpVersion http_ver; |
f900210a | 2745 | |
1b76e6c1 | 2746 | debugs(33, 5, HERE << clientConnection << ": attempting to parse"); |
f900210a | 2747 | |
39cb8c41 | 2748 | // Loop while we have read bytes that are not needed for producing the body |
f35961af AR |
2749 | // On errors, bodyPipe may become nil, but readMore will be cleared |
2750 | while (in.notYetUsed > 0 && !bodyPipe && flags.readMore) { | |
4959e21e | 2751 | connStripBufferWhitespace(this); |
f900210a | 2752 | |
fc68f6b1 | 2753 | /* Don't try to parse if the buffer is empty */ |
4959e21e | 2754 | if (in.notYetUsed == 0) |
fc68f6b1 | 2755 | break; |
4681057e | 2756 | |
f900210a | 2757 | /* Limit the number of concurrent requests to 2 */ |
4959e21e | 2758 | if (!connOkToAddRequest(this)) { |
f900210a | 2759 | break; |
2760 | } | |
2761 | ||
2762 | /* Should not be needed anymore */ | |
2763 | /* Terminate the string */ | |
4959e21e | 2764 | in.buf[in.notYetUsed] = '\0'; |
f900210a | 2765 | |
fc68f6b1 | 2766 | /* Begin the parsing */ |
fc68f6b1 | 2767 | PROF_start(parseHttpRequest); |
4959e21e | 2768 | HttpParserInit(&parser_, in.buf, in.notYetUsed); |
fc68f6b1 | 2769 | |
4959e21e AJ |
2770 | /* Process request */ |
2771 | ClientSocketContext *context = parseHttpRequest(this, &parser_, &method, &http_ver); | |
fc68f6b1 | 2772 | PROF_stop(parseHttpRequest); |
f900210a | 2773 | |
2774 | /* partial or incomplete request */ | |
2775 | if (!context) { | |
39cb8c41 AR |
2776 | // TODO: why parseHttpRequest can just return parseHttpRequestAbort |
2777 | // (which becomes context) but checkHeaderLimits cannot? | |
4959e21e | 2778 | checkHeaderLimits(); |
f900210a | 2779 | break; |
2780 | } | |
2781 | ||
2782 | /* status -1 or 1 */ | |
2783 | if (context) { | |
1b76e6c1 | 2784 | debugs(33, 5, HERE << clientConnection << ": parsed a request"); |
8d77a37c | 2785 | AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout", |
dc49061a | 2786 | CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http)); |
1b76e6c1 | 2787 | commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall); |
f900210a | 2788 | |
4959e21e | 2789 | clientProcessRequest(this, &parser_, context, method, http_ver); |
f900210a | 2790 | |
4959e21e | 2791 | parsed_req = true; // XXX: do we really need to parse everything right NOW ? |
f900210a | 2792 | |
2793 | if (context->mayUseConnection()) { | |
f35961af | 2794 | debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection"); |
f900210a | 2795 | break; |
2796 | } | |
f900210a | 2797 | } |
39cb8c41 | 2798 | } |
fc68f6b1 | 2799 | |
a5baffba | 2800 | /* XXX where to 'finish' the parsing pass? */ |
f900210a | 2801 | return parsed_req; |
2802 | } | |
2803 | ||
1cf238db | 2804 | void |
2805 | ConnStateData::clientReadRequest(const CommIoCbParams &io) | |
c4b7a5a9 | 2806 | { |
be364179 | 2807 | debugs(33,5,HERE << io.conn << " size " << io.size); |
f84dd7eb AR |
2808 | Must(reading()); |
2809 | reader = NULL; | |
c4b7a5a9 | 2810 | |
c4b7a5a9 | 2811 | /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */ |
62e76326 | 2812 | |
1cf238db | 2813 | if (io.flag == COMM_ERR_CLOSING) { |
be364179 | 2814 | debugs(33,5, HERE << io.conn << " closing Bailout."); |
c4b7a5a9 | 2815 | return; |
2816 | } | |
62e76326 | 2817 | |
73c36fd9 AJ |
2818 | assert(Comm::IsConnOpen(clientConnection)); |
2819 | assert(io.conn->fd == clientConnection->fd); | |
5c336a3b | 2820 | |
44db45e8 | 2821 | /* |
2822 | * Don't reset the timeout value here. The timeout value will be | |
2823 | * set to Config.Timeout.request by httpAccept() and | |
2824 | * clientWriteComplete(), and should apply to the request as a | |
2825 | * whole, not individual read() calls. Plus, it breaks our | |
2826 | * lame half-close detection | |
2827 | */ | |
1cf238db | 2828 | if (connReadWasError(io.flag, io.size, io.xerrno)) { |
f692498b | 2829 | notifyAllContexts(io.xerrno); |
be364179 | 2830 | io.conn->close(); |
62e76326 | 2831 | return; |
7a2f978b | 2832 | } |
c4b7a5a9 | 2833 | |
1cf238db | 2834 | if (io.flag == COMM_OK) { |
2835 | if (io.size > 0) { | |
2836 | kb_incr(&statCounter.client_http.kbytes_in, io.size); | |
3b299123 | 2837 | |
39cb8c41 AR |
2838 | // may comm_close or setReplyToError |
2839 | if (!handleReadData(io.buf, io.size)) | |
9e008dda | 2840 | return; |
a31a78fb | 2841 | |
1cf238db | 2842 | } else if (io.size == 0) { |
be364179 | 2843 | debugs(33, 5, HERE << io.conn << " closed?"); |
62e76326 | 2844 | |
1cf238db | 2845 | if (connFinishedWithConn(io.size)) { |
73c36fd9 | 2846 | clientConnection->close(); |
62e76326 | 2847 | return; |
2848 | } | |
2849 | ||
2850 | /* It might be half-closed, we can't tell */ | |
be364179 | 2851 | fd_table[io.conn->fd].flags.socket_eof = 1; |
62e76326 | 2852 | |
be364179 | 2853 | commMarkHalfClosed(io.conn->fd); |
a46d2c0e | 2854 | |
be364179 | 2855 | fd_note(io.conn->fd, "half-closed"); |
62e76326 | 2856 | |
2857 | /* There is one more close check at the end, to detect aborted | |
2858 | * (partial) requests. At this point we can't tell if the request | |
2859 | * is partial. | |
2860 | */ | |
2861 | /* Continue to process previously read data */ | |
2862 | } | |
c4b7a5a9 | 2863 | } |
2864 | ||
94439e4e | 2865 | /* Process next request */ |
1cf238db | 2866 | if (getConcurrentRequestCount() == 0) |
5c336a3b | 2867 | fd_note(io.fd, "Reading next request"); |
c8be6d7b | 2868 | |
f35961af | 2869 | if (!clientParseRequests()) { |
9e008dda AJ |
2870 | if (!isOpen()) |
2871 | return; | |
f900210a | 2872 | /* |
2873 | * If the client here is half closed and we failed | |
2874 | * to parse a request, close the connection. | |
2875 | * The above check with connFinishedWithConn() only | |
2876 | * succeeds _if_ the buffer is empty which it won't | |
2877 | * be if we have an incomplete request. | |
6e1d409c | 2878 | * XXX: This duplicates ClientSocketContext::keepaliveNextRequest |
f900210a | 2879 | */ |
5c336a3b | 2880 | if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io.fd)) { |
be364179 | 2881 | debugs(33, 5, HERE << io.conn << ": half-closed connection, no completed request parsed, connection closing."); |
73c36fd9 | 2882 | clientConnection->close(); |
ee6f0213 | 2883 | return; |
62e76326 | 2884 | } |
f900210a | 2885 | } |
ee6f0213 | 2886 | |
1cf238db | 2887 | if (!isOpen()) |
2e216b1d | 2888 | return; |
2889 | ||
f35961af | 2890 | clientAfterReadingRequests(); |
94439e4e | 2891 | } |
2892 | ||
63be0a78 | 2893 | /** |
2894 | * called when new request data has been read from the socket | |
39cb8c41 AR |
2895 | * |
2896 | * \retval false called comm_close or setReplyToError (the caller should bail) | |
2897 | * \retval true we did not call comm_close or setReplyToError | |
63be0a78 | 2898 | */ |
39cb8c41 | 2899 | bool |
5f8252d2 | 2900 | ConnStateData::handleReadData(char *buf, size_t size) |
94439e4e | 2901 | { |
5f8252d2 | 2902 | char *current_buf = in.addressToReadInto(); |
62e76326 | 2903 | |
5f8252d2 | 2904 | if (buf != current_buf) |
41d00cd3 | 2905 | memmove(current_buf, buf, size); |
3b299123 | 2906 | |
5f8252d2 | 2907 | in.notYetUsed += size; |
fc68f6b1 | 2908 | |
5f8252d2 | 2909 | in.buf[in.notYetUsed] = '\0'; /* Terminate the string */ |
3b299123 | 2910 | |
5f8252d2 | 2911 | // if we are reading a body, stuff data into the body pipe |
2912 | if (bodyPipe != NULL) | |
39cb8c41 AR |
2913 | return handleRequestBodyData(); |
2914 | return true; | |
94439e4e | 2915 | } |
2916 | ||
63be0a78 | 2917 | /** |
bb790702 | 2918 | * called when new request body data has been buffered in in.buf |
63be0a78 | 2919 | * may close the connection if we were closing and piped everything out |
39cb8c41 AR |
2920 | * |
2921 | * \retval false called comm_close or setReplyToError (the caller should bail) | |
2922 | * \retval true we did not call comm_close or setReplyToError | |
63be0a78 | 2923 | */ |
39cb8c41 | 2924 | bool |
5f8252d2 | 2925 | ConnStateData::handleRequestBodyData() |
94439e4e | 2926 | { |
5f8252d2 | 2927 | assert(bodyPipe != NULL); |
2928 | ||
e1381638 | 2929 | size_t putSize = 0; |
3ff65596 | 2930 | |
39cb8c41 AR |
2931 | if (in.bodyParser) { // chunked encoding |
2932 | if (const err_type error = handleChunkedRequestBody(putSize)) { | |
2933 | abortChunkedRequestBody(error); | |
2934 | return false; | |
3ff65596 | 2935 | } |
39cb8c41 | 2936 | } else { // identity encoding |
73c36fd9 | 2937 | debugs(33,5, HERE << "handling plain request body for " << clientConnection); |
3ff65596 AR |
2938 | putSize = bodyPipe->putMoreData(in.buf, in.notYetUsed); |
2939 | if (!bodyPipe->mayNeedMoreData()) { | |
2940 | // BodyPipe will clear us automagically when we produced everything | |
2941 | bodyPipe = NULL; | |
2942 | } | |
2943 | } | |
2944 | ||
2945 | if (putSize > 0) | |
2946 | connNoteUseOfBuffer(this, putSize); | |
5f8252d2 | 2947 | |
3ff65596 | 2948 | if (!bodyPipe) { |
73c36fd9 | 2949 | debugs(33,5, HERE << "produced entire request body for " << clientConnection); |
62e76326 | 2950 | |
cf6eb29e | 2951 | if (const char *reason = stoppedSending()) { |
5f8252d2 | 2952 | /* we've finished reading like good clients, |
2953 | * now do the close that initiateClose initiated. | |
5f8252d2 | 2954 | */ |
cf6eb29e | 2955 | debugs(33, 3, HERE << "closing for earlier sending error: " << reason); |
73c36fd9 | 2956 | clientConnection->close(); |
39cb8c41 AR |
2957 | return false; |
2958 | } | |
2959 | } | |
2960 | ||
2961 | return true; | |
2962 | } | |
2963 | ||
2964 | /// parses available chunked encoded body bytes, checks size, returns errors | |
2965 | err_type | |
2966 | ConnStateData::handleChunkedRequestBody(size_t &putSize) | |
2967 | { | |
73c36fd9 | 2968 | debugs(33,7, HERE << "chunked from " << clientConnection << ": " << in.notYetUsed); |
39cb8c41 AR |
2969 | |
2970 | try { // the parser will throw on errors | |
2971 | ||
2972 | if (!in.notYetUsed) // nothing to do (MemBuf::init requires this check) | |
2973 | return ERR_NONE; | |
2974 | ||
2975 | MemBuf raw; // ChunkedCodingParser only works with MemBufs | |
2976 | // add one because MemBuf will assert if it cannot 0-terminate | |
2977 | raw.init(in.notYetUsed, in.notYetUsed+1); | |
2978 | raw.append(in.buf, in.notYetUsed); | |
2979 | ||
2980 | const mb_size_t wasContentSize = raw.contentSize(); | |
2981 | BodyPipeCheckout bpc(*bodyPipe); | |
2982 | const bool parsed = in.bodyParser->parse(&raw, &bpc.buf); | |
2983 | bpc.checkIn(); | |
2984 | putSize = wasContentSize - raw.contentSize(); | |
2985 | ||
2986 | // dechunk then check: the size limit applies to _dechunked_ content | |
2987 | if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize())) | |
2988 | return ERR_TOO_BIG; | |
2989 | ||
2990 | if (parsed) { | |
2991 | finishDechunkingRequest(true); | |
2992 | Must(!bodyPipe); | |
2993 | return ERR_NONE; // nil bodyPipe implies body end for the caller | |
5f8252d2 | 2994 | } |
39cb8c41 AR |
2995 | |
2996 | // if chunk parser needs data, then the body pipe must need it too | |
2997 | Must(!in.bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData()); | |
2998 | ||
2999 | // if parser needs more space and we can consume nothing, we will stall | |
3000 | Must(!in.bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent()); | |
3001 | } catch (...) { // TODO: be more specific | |
3002 | debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status()); | |
3003 | return ERR_INVALID_REQ; | |
94439e4e | 3004 | } |
39cb8c41 AR |
3005 | |
3006 | debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status()); | |
3007 | return ERR_NONE; | |
3008 | } | |
3009 | ||
3010 | /// quit on errors related to chunked request body handling | |
3011 | void | |
3012 | ConnStateData::abortChunkedRequestBody(const err_type error) | |
3013 | { | |
3014 | finishDechunkingRequest(false); | |
3015 | ||
3016 | // XXX: The code below works if we fail during initial request parsing, | |
3017 | // but if we fail when the server-side works already, the server may send | |
3018 | // us its response too, causing various assertions. How to prevent that? | |
3019 | #if WE_KNOW_HOW_TO_SEND_ERRORS | |
3020 | ClientSocketContext::Pointer context = getCurrentContext(); | |
3021 | if (context != NULL && !context->http->out.offset) { // output nothing yet | |
3022 | clientStreamNode *node = context->getClientReplyContext(); | |
3023 | clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw()); | |
3024 | assert(repContext); | |
3025 | const http_status scode = (error == ERR_TOO_BIG) ? | |
de48b288 | 3026 | HTTP_REQUEST_ENTITY_TOO_LARGE : HTTP_BAD_REQUEST; |
39cb8c41 AR |
3027 | repContext->setReplyToError(error, scode, |
3028 | repContext->http->request->method, | |
3029 | repContext->http->uri, | |
3030 | peer, | |
3031 | repContext->http->request, | |
3032 | in.buf, NULL); | |
3033 | context->pullData(); | |
3034 | } else { | |
3035 | // close or otherwise we may get stuck as nobody will notice the error? | |
73c36fd9 | 3036 | comm_reset_close(clientConnection); |
39cb8c41 AR |
3037 | } |
3038 | #else | |
3039 | debugs(33, 3, HERE << "aborting chunked request without error " << error); | |
73c36fd9 | 3040 | comm_reset_close(clientConnection); |
39cb8c41 | 3041 | #endif |
f35961af | 3042 | flags.readMore = false; |
5f8252d2 | 3043 | } |
55e44db9 | 3044 | |
5f8252d2 | 3045 | void |
1cf238db | 3046 | ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer ) |
5f8252d2 | 3047 | { |
90737510 | 3048 | if (!handleRequestBodyData()) |
1368d115 CT |
3049 | return; |
3050 | ||
6bec3b16 | 3051 | // too late to read more body |
cf6eb29e | 3052 | if (!isOpen() || stoppedReceiving()) |
6bec3b16 AR |
3053 | return; |
3054 | ||
1368d115 | 3055 | readSomeData(); |
5f8252d2 | 3056 | } |
3057 | ||
3058 | void | |
1cf238db | 3059 | ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer ) |
5f8252d2 | 3060 | { |
cf6eb29e CT |
3061 | // request reader may get stuck waiting for space if nobody consumes body |
3062 | if (bodyPipe != NULL) | |
3063 | bodyPipe->enableAutoConsumption(); | |
3064 | ||
3065 | stopReceiving("virgin request body consumer aborted"); // closes ASAP | |
94439e4e | 3066 | } |
3067 | ||
63be0a78 | 3068 | /** general lifetime handler for HTTP requests */ |
1cf238db | 3069 | void |
3070 | ConnStateData::requestTimeout(const CommTimeoutCbParams &io) | |
7a2f978b | 3071 | { |
ad63ceea | 3072 | #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS |
1cf238db | 3073 | debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired."); |
62e76326 | 3074 | |
1cf238db | 3075 | if (COMMIO_FD_WRITECB(io.fd)->active) { |
dec5db5d | 3076 | /* FIXME: If this code is reinstated, check the conn counters, |
3077 | * not the fd table state | |
3078 | */ | |
62e76326 | 3079 | /* |
3080 | * Some data has been sent to the client, just close the FD | |
3081 | */ | |
73c36fd9 | 3082 | clientConnection->close(); |
1cf238db | 3083 | } else if (nrequests) { |
62e76326 | 3084 | /* |
3085 | * assume its a persistent connection; just close it | |
3086 | */ | |
73c36fd9 | 3087 | clientConnection->close(); |
7a2f978b | 3088 | } else { |
62e76326 | 3089 | /* |
3090 | * Generate an error | |
3091 | */ | |
59a1efb2 | 3092 | ClientHttpRequest **H; |
62e76326 | 3093 | clientStreamNode *node; |
719c7e0a | 3094 | ClientHttpRequest *http = parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired"); |
62e76326 | 3095 | node = http->client_stream.tail->prev->data; |
0655fa4d | 3096 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
3097 | assert (repContext); | |
3098 | repContext->setReplyToError(ERR_LIFETIME_EXP, | |
1cf238db | 3099 | HTTP_REQUEST_TIMEOUT, METHOD_NONE, "N/A", &peer.sin_addr, |
0655fa4d | 3100 | NULL, NULL, NULL); |
62e76326 | 3101 | /* No requests can be outstanded */ |
1cf238db | 3102 | assert(chr == NULL); |
62e76326 | 3103 | /* add to the client request queue */ |
3104 | ||
3d0ac046 | 3105 | for (H = &chr; *H; H = &(*H)->next); |
62e76326 | 3106 | *H = http; |
3107 | ||
3108 | clientStreamRead(http->client_stream.tail->data, http, 0, | |
3109 | HTTP_REQBUF_SZ, context->reqbuf); | |
3110 | ||
3111 | /* | |
3112 | * if we don't close() here, we still need a timeout handler! | |
3113 | */ | |
9e008dda | 3114 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 AR |
3115 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
3116 | TimeoutDialer, this, ConnStateData::requestTimeout); | |
8d77a37c | 3117 | commSetConnTimeout(io.conn, 30, timeoutCall); |
62e76326 | 3118 | |
3119 | /* | |
3120 | * Aha, but we don't want a read handler! | |
3121 | */ | |
d841c88d | 3122 | Comm::SetSelect(io.fd, COMM_SELECT_READ, NULL, NULL, 0); |
7a2f978b | 3123 | } |
62e76326 | 3124 | |
af57a2e3 | 3125 | #else |
3126 | /* | |
62e76326 | 3127 | * Just close the connection to not confuse browsers |
3128 | * using persistent connections. Some browsers opens | |
3129 | * an connection and then does not use it until much | |
3130 | * later (presumeably because the request triggering | |
3131 | * the open has already been completed on another | |
3132 | * connection) | |
3133 | */ | |
1cf238db | 3134 | debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired."); |
8d77a37c | 3135 | io.conn->close(); |
af57a2e3 | 3136 | #endif |
7a2f978b | 3137 | } |
3138 | ||
b5c39993 | 3139 | static void |
8d77a37c | 3140 | clientLifetimeTimeout(const CommTimeoutCbParams &io) |
b5c39993 | 3141 | { |
8d77a37c | 3142 | ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data); |
cb61ec47 AJ |
3143 | debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout"); |
3144 | debugs(33, DBG_IMPORTANT, "\t" << http->uri); | |
f692498b | 3145 | http->al.http.timedout = true; |
8d77a37c AJ |
3146 | if (Comm::IsConnOpen(io.conn)) |
3147 | io.conn->close(); | |
b5c39993 | 3148 | } |
3149 | ||
c8be6d7b | 3150 | ConnStateData * |
be364179 | 3151 | connStateCreate(const Comm::ConnectionPointer &client, http_port_list *port) |
c8be6d7b | 3152 | { |
a46d2c0e | 3153 | ConnStateData *result = new ConnStateData; |
2ad20b4f | 3154 | |
73c36fd9 | 3155 | result->clientConnection = client; |
be364179 | 3156 | result->log_addr = client->remote; |
055421ee | 3157 | result->log_addr.ApplyMask(Config.Addrs.client_netmask); |
e6ccf245 | 3158 | result->in.buf = (char *)memAllocBuf(CLIENT_REQ_BUF_SZ, &result->in.allocatedSize); |
3f38a55e | 3159 | result->port = cbdataReference(port); |
62e76326 | 3160 | |
5529ca8a | 3161 | if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF && |
9e008dda | 3162 | (result->transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) { |
5529ca8a | 3163 | #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT) |
3164 | int i = IP_PMTUDISC_DONT; | |
be364179 | 3165 | setsockopt(client->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof i); |
5529ca8a | 3166 | #else |
5529ca8a | 3167 | static int reported = 0; |
3168 | ||
3169 | if (!reported) { | |
bf8fe701 | 3170 | debugs(33, 1, "Notice: httpd_accel_no_pmtu_disc not supported on your platform"); |
5529ca8a | 3171 | reported = 1; |
3172 | } | |
89aec9b6 AJ |
3173 | #endif |
3174 | } | |
5529ca8a | 3175 | |
89aec9b6 AJ |
3176 | typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer; |
3177 | AsyncCall::Pointer call = JobCallback(33, 5, Dialer, result, ConnStateData::connStateClosed); | |
3178 | comm_add_close_handler(client->fd, call); | |
5529ca8a | 3179 | |
89aec9b6 AJ |
3180 | if (Config.onoff.log_fqdn) |
3181 | fqdncache_gethostbyaddr(client->remote, FQDN_LOOKUP_IF_MISS); | |
3182 | ||
3183 | #if USE_IDENT | |
3184 | if (Ident::TheConfig.identLookup) { | |
3185 | ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL); | |
3186 | identChecklist.src_addr = client->remote; | |
3187 | identChecklist.my_addr = client->local; | |
2efeb0b7 | 3188 | if (identChecklist.fastCheck() == ACCESS_ALLOWED) |
89aec9b6 AJ |
3189 | Ident::Start(client, clientIdentDone, result); |
3190 | } | |
5529ca8a | 3191 | #endif |
3192 | ||
89aec9b6 AJ |
3193 | #if USE_SQUID_EUI |
3194 | if (Eui::TheConfig.euiLookup) { | |
3195 | if (client->remote.IsIPv4()) { | |
3196 | result->clientConnection->remoteEui48.lookup(client->remote); | |
3197 | } else if (client->remote.IsIPv6()) { | |
3198 | result->clientConnection->remoteEui64.lookup(client->remote); | |
3199 | } | |
5529ca8a | 3200 | } |
89aec9b6 AJ |
3201 | #endif |
3202 | ||
3203 | clientdbEstablished(client->remote, 1); | |
5529ca8a | 3204 | |
f35961af | 3205 | result->flags.readMore = true; |
c8be6d7b | 3206 | return result; |
3207 | } | |
3208 | ||
63be0a78 | 3209 | /** Handle a new connection on HTTP socket. */ |
7a2f978b | 3210 | void |
449f0115 | 3211 | httpAccept(const CommAcceptCbParams ¶ms) |
7a2f978b | 3212 | { |
449f0115 | 3213 | http_port_list *s = (http_port_list *)params.data; |
02d1422b | 3214 | |
449f0115 | 3215 | if (params.flag != COMM_OK) { |
cbff89ba | 3216 | // Its possible the call was still queued when the client disconnected |
449f0115 | 3217 | debugs(33, 2, "httpAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno)); |
62e76326 | 3218 | return; |
3219 | } | |
3220 | ||
449f0115 AJ |
3221 | debugs(33, 4, HERE << params.conn << ": accepted"); |
3222 | fd_note(params.conn->fd, "client http connect"); | |
1cf238db | 3223 | |
89aec9b6 | 3224 | if (s->tcp_keepalive.enabled) { |
449f0115 | 3225 | commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); |
89aec9b6 | 3226 | } |
62e76326 | 3227 | |
89aec9b6 AJ |
3228 | incoming_sockets_accepted++; |
3229 | ||
3230 | // Socket is ready, setup the connection manager to start using it | |
449f0115 | 3231 | ConnStateData *connState = connStateCreate(params.conn, s); |
62e76326 | 3232 | |
9e008dda | 3233 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 3234 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
4cb2536f | 3235 | TimeoutDialer, connState, ConnStateData::requestTimeout); |
449f0115 | 3236 | commSetConnTimeout(params.conn, Config.Timeout.read, timeoutCall); |
b2130d58 | 3237 | |
a46d2c0e | 3238 | connState->readSomeData(); |
62e76326 | 3239 | |
9a0a18de | 3240 | #if USE_DELAY_POOLS |
449f0115 | 3241 | fd_table[params.conn->fd].clientInfo = NULL; |
b4cd430a | 3242 | |
f33d34a8 | 3243 | if (Config.onoff.client_db) { |
b4cd430a CT |
3244 | /* it was said several times that client write limiter does not work if client_db is disabled */ |
3245 | ||
3246 | ClientDelayPools& pools(Config.ClientDelay.pools); | |
2efeb0b7 | 3247 | ACLFilledChecklist ch(NULL, NULL, NULL); |
b4cd430a | 3248 | |
2efeb0b7 AJ |
3249 | // TODO: we check early to limit error response bandwith but we |
3250 | // should recheck when we can honor delay_pool_uses_indirect | |
3251 | // TODO: we should also pass the port details for myportname here. | |
449f0115 AJ |
3252 | ch.src_addr = params.conn->remote; |
3253 | ch.my_addr = params.conn->local; | |
b4cd430a | 3254 | |
2efeb0b7 | 3255 | for (unsigned int pool = 0; pool < pools.size(); pool++) { |
b4cd430a | 3256 | |
2efeb0b7 AJ |
3257 | /* pools require explicit 'allow' to assign a client into them */ |
3258 | if (pools[pool].access) { | |
3259 | ch.accessList = pools[pool].access; | |
3260 | allow_t answer = ch.fastCheck(); | |
3261 | if (answer == ACCESS_ALLOWED) { | |
3262 | ||
3263 | /* request client information from db after we did all checks | |
3264 | this will save hash lookup if client failed checks */ | |
449f0115 | 3265 | ClientInfo * cli = clientdbGetInfo(params.conn->remote); |
2efeb0b7 AJ |
3266 | assert(cli); |
3267 | ||
3268 | /* put client info in FDE */ | |
449f0115 | 3269 | fd_table[params.conn->fd].clientInfo = cli; |
2efeb0b7 AJ |
3270 | |
3271 | /* setup write limiter for this request */ | |
3272 | const double burst = floor(0.5 + | |
3273 | (pools[pool].highwatermark * Config.ClientDelay.initial)/100.0); | |
3274 | cli->setWriteLimiter(pools[pool].rate, burst, pools[pool].highwatermark); | |
3275 | break; | |
3276 | } else { | |
3277 | debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer); | |
3278 | } | |
b4cd430a CT |
3279 | } |
3280 | } | |
3281 | } | |
3282 | #endif | |
7a2f978b | 3283 | } |
3284 | ||
1f7c9178 | 3285 | #if USE_SSL |
3286 | ||
63be0a78 | 3287 | /** Create SSL connection structure and update fd_table */ |
ae7ff0b8 | 3288 | static SSL * |
449f0115 | 3289 | httpsCreate(const Comm::ConnectionPointer &conn, SSL_CTX *sslContext) |
ae7ff0b8 | 3290 | { |
3291 | SSL *ssl = SSL_new(sslContext); | |
3292 | ||
3293 | if (!ssl) { | |
3294 | const int ssl_error = ERR_get_error(); | |
449f0115 AJ |
3295 | debugs(83, DBG_IMPORTANT, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error, NULL) ); |
3296 | conn->close(); | |
ae7ff0b8 | 3297 | return NULL; |
3298 | } | |
3299 | ||
449f0115 AJ |
3300 | SSL_set_fd(ssl, conn->fd); |
3301 | fd_table[conn->fd].ssl = ssl; | |
3302 | fd_table[conn->fd].read_method = &ssl_read_method; | |
3303 | fd_table[conn->fd].write_method = &ssl_write_method; | |
ae7ff0b8 | 3304 | |
449f0115 AJ |
3305 | debugs(33, 5, "httpsCreate: will negotate SSL on " << conn); |
3306 | fd_note(conn->fd, "client https start"); | |
ae7ff0b8 | 3307 | |
3308 | return ssl; | |
3309 | } | |
3310 | ||
63be0a78 | 3311 | /** negotiate an SSL connection */ |
1f7c9178 | 3312 | static void |
3313 | clientNegotiateSSL(int fd, void *data) | |
3314 | { | |
e6ccf245 | 3315 | ConnStateData *conn = (ConnStateData *)data; |
1f7c9178 | 3316 | X509 *client_cert; |
a7ad6e4e | 3317 | SSL *ssl = fd_table[fd].ssl; |
1f7c9178 | 3318 | int ret; |
3319 | ||
a7ad6e4e | 3320 | if ((ret = SSL_accept(ssl)) <= 0) { |
62e76326 | 3321 | int ssl_error = SSL_get_error(ssl, ret); |
3322 | ||
3323 | switch (ssl_error) { | |
3324 | ||
3325 | case SSL_ERROR_WANT_READ: | |
d841c88d | 3326 | Comm::SetSelect(fd, COMM_SELECT_READ, clientNegotiateSSL, conn, 0); |
62e76326 | 3327 | return; |
3328 | ||
3329 | case SSL_ERROR_WANT_WRITE: | |
d841c88d | 3330 | Comm::SetSelect(fd, COMM_SELECT_WRITE, clientNegotiateSSL, conn, 0); |
62e76326 | 3331 | return; |
3332 | ||
6de9e64b | 3333 | case SSL_ERROR_SYSCALL: |
3334 | ||
3335 | if (ret == 0) { | |
bf8fe701 | 3336 | debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Aborted by client"); |
6de9e64b | 3337 | comm_close(fd); |
3338 | return; | |
3339 | } else { | |
3340 | int hard = 1; | |
3341 | ||
3342 | if (errno == ECONNRESET) | |
3343 | hard = 0; | |
3344 | ||
9e008dda | 3345 | debugs(83, hard ? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << |
bf8fe701 | 3346 | fd << ": " << strerror(errno) << " (" << errno << ")"); |
6de9e64b | 3347 | |
3348 | comm_close(fd); | |
3349 | ||
3350 | return; | |
3351 | } | |
3352 | ||
3353 | case SSL_ERROR_ZERO_RETURN: | |
bf8fe701 | 3354 | debugs(83, 1, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Closed by client"); |
6de9e64b | 3355 | comm_close(fd); |
3356 | return; | |
3357 | ||
62e76326 | 3358 | default: |
9e008dda AJ |
3359 | debugs(83, 1, "clientNegotiateSSL: Error negotiating SSL connection on FD " << |
3360 | fd << ": " << ERR_error_string(ERR_get_error(), NULL) << | |
3361 | " (" << ssl_error << "/" << ret << ")"); | |
62e76326 | 3362 | comm_close(fd); |
3363 | return; | |
3364 | } | |
3365 | ||
3366 | /* NOTREACHED */ | |
1f7c9178 | 3367 | } |
62e76326 | 3368 | |
6de9e64b | 3369 | if (SSL_session_reused(ssl)) { |
bf8fe701 | 3370 | debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl) << |
3371 | " reused on FD " << fd << " (" << fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << ")"); | |
6de9e64b | 3372 | } else { |
3373 | if (do_debug(83, 4)) { | |
3374 | /* Write out the SSL session details.. actually the call below, but | |
3375 | * OpenSSL headers do strange typecasts confusing GCC.. */ | |
3376 | /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */ | |
afdd443f | 3377 | #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L |
9f3de01a | 3378 | PEM_ASN1_write((i2d_of_void *)i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); |
2930f303 | 3379 | |
0fd2205b | 3380 | #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1) |
2930f303 | 3381 | |
0fd2205b | 3382 | /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here. |
3383 | * This is caused by an unpredicatble gcc behaviour on a cast of the first argument | |
3384 | * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it, | |
3385 | * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1. | |
3386 | * Because there are two possible usable cast, if you get an error here, try the other | |
3387 | * commented line. */ | |
3388 | ||
3389 | PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); | |
3390 | /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */ | |
2930f303 | 3391 | |
0e33d58c | 3392 | #else |
3393 | ||
bf8fe701 | 3394 | debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." ); |
0fd2205b | 3395 | |
0e33d58c | 3396 | #endif |
6de9e64b | 3397 | /* Note: This does not automatically fflush the log file.. */ |
3398 | } | |
3399 | ||
bf8fe701 | 3400 | debugs(83, 2, "clientNegotiateSSL: New session " << |
3401 | SSL_get_session(ssl) << " on FD " << fd << " (" << | |
3402 | fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << | |
3403 | ")"); | |
6de9e64b | 3404 | } |
3405 | ||
bf8fe701 | 3406 | debugs(83, 3, "clientNegotiateSSL: FD " << fd << " negotiated cipher " << |
3407 | SSL_get_cipher(ssl)); | |
1f7c9178 | 3408 | |
6de9e64b | 3409 | client_cert = SSL_get_peer_certificate(ssl); |
62e76326 | 3410 | |
1f7c9178 | 3411 | if (client_cert != NULL) { |
bf8fe701 | 3412 | debugs(83, 3, "clientNegotiateSSL: FD " << fd << |
3413 | " client certificate: subject: " << | |
3414 | X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0)); | |
3415 | ||
3416 | debugs(83, 3, "clientNegotiateSSL: FD " << fd << | |
3417 | " client certificate: issuer: " << | |
3418 | X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0)); | |
1f7c9178 | 3419 | |
1f7c9178 | 3420 | |
62e76326 | 3421 | X509_free(client_cert); |
1f7c9178 | 3422 | } else { |
bf8fe701 | 3423 | debugs(83, 5, "clientNegotiateSSL: FD " << fd << |
3424 | " has no certificate."); | |
1f7c9178 | 3425 | } |
3426 | ||
a46d2c0e | 3427 | conn->readSomeData(); |
1f7c9178 | 3428 | } |
3429 | ||
63be0a78 | 3430 | /** handle a new HTTPS connection */ |
1f7c9178 | 3431 | static void |
449f0115 | 3432 | httpsAccept(const CommAcceptCbParams ¶ms) |
1f7c9178 | 3433 | { |
449f0115 | 3434 | https_port_list *s = (https_port_list *)params.data; |
c4b7a5a9 | 3435 | |
449f0115 | 3436 | if (params.flag != COMM_OK) { |
cbff89ba | 3437 | // Its possible the call was still queued when the client disconnected |
449f0115 | 3438 | debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno)); |
62e76326 | 3439 | return; |
c4b7a5a9 | 3440 | } |
62e76326 | 3441 | |
89aec9b6 | 3442 | SSL_CTX *sslContext = s->staticSslContext.get(); |
ae7ff0b8 | 3443 | SSL *ssl = NULL; |
449f0115 | 3444 | if (!(ssl = httpsCreate(params.conn, sslContext))) |
62e76326 | 3445 | return; |
94c3d66f | 3446 | |
449f0115 AJ |
3447 | debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation."); |
3448 | fd_note(params.conn->fd, "client https connect"); | |
62e76326 | 3449 | |
b2130d58 | 3450 | if (s->http.tcp_keepalive.enabled) { |
449f0115 | 3451 | commSetTcpKeepalive(params.conn->fd, s->http.tcp_keepalive.idle, s->http.tcp_keepalive.interval, s->http.tcp_keepalive.timeout); |
b2130d58 | 3452 | } |
3453 | ||
89aec9b6 | 3454 | incoming_sockets_accepted++; |
62e76326 | 3455 | |
89aec9b6 | 3456 | // Socket is ready, setup the connection manager to start using it |
449f0115 | 3457 | ConnStateData *connState = connStateCreate(params.conn, &s->http); |
62e76326 | 3458 | |
9e008dda | 3459 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 AR |
3460 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
3461 | TimeoutDialer, connState, ConnStateData::requestTimeout); | |
449f0115 | 3462 | commSetConnTimeout(params.conn, Config.Timeout.request, timeoutCall); |
62e76326 | 3463 | |
449f0115 | 3464 | Comm::SetSelect(params.conn->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0); |
1f7c9178 | 3465 | } |
3466 | ||
95d2589c CT |
3467 | void |
3468 | ConnStateData::sslCrtdHandleReplyWrapper(void *data, char *reply) | |
ae7ff0b8 | 3469 | { |
95d2589c CT |
3470 | ConnStateData * state_data = (ConnStateData *)(data); |
3471 | state_data->sslCrtdHandleReply(reply); | |
3472 | } | |
ae7ff0b8 | 3473 | |
95d2589c CT |
3474 | void |
3475 | ConnStateData::sslCrtdHandleReply(const char * reply) | |
3476 | { | |
3477 | if (!reply) { | |
3478 | debugs(1, 1, HERE << "\"ssl_crtd\" helper return <NULL> reply"); | |
3479 | } else { | |
3480 | Ssl::CrtdMessage reply_message; | |
3481 | if (reply_message.parse(reply, strlen(reply)) != Ssl::CrtdMessage::OK) { | |
3482 | debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslHostName << " is incorrect"); | |
3483 | } else { | |
419ac015 | 3484 | if (reply_message.getCode() != "OK") { |
95d2589c CT |
3485 | debugs(33, 5, HERE << "Certificate for " << sslHostName << " cannot be generated. ssl_crtd response: " << reply_message.getBody()); |
3486 | } else { | |
3487 | debugs(33, 5, HERE << "Certificate for " << sslHostName << " was successfully recieved from ssl_crtd"); | |
a594dbfa CT |
3488 | SSL_CTX *ctx = Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str()); |
3489 | getSslContextDone(ctx, true); | |
95d2589c CT |
3490 | return; |
3491 | } | |
3492 | } | |
3493 | } | |
3494 | getSslContextDone(NULL); | |
3495 | } | |
ae7ff0b8 | 3496 | |
95d2589c CT |
3497 | bool |
3498 | ConnStateData::getSslContextStart() | |
3499 | { | |
3500 | char const * host = sslHostName.termedBuf(); | |
3501 | if (port->generateHostCertificates && host && strcmp(host, "") != 0) { | |
3502 | debugs(33, 5, HERE << "Finding SSL certificate for " << host << " in cache"); | |
3503 | Ssl::LocalContextStorage & ssl_ctx_cache(Ssl::TheGlobalContextStorage.getLocalStorage(port->s)); | |
3504 | SSL_CTX * dynCtx = ssl_ctx_cache.find(host); | |
3505 | if (dynCtx) { | |
3506 | debugs(33, 5, HERE << "SSL certificate for " << host << " have found in cache"); | |
3507 | if (Ssl::verifySslCertificateDate(dynCtx)) { | |
3508 | debugs(33, 5, HERE << "Cached SSL certificate for " << host << " is valid"); | |
3509 | return getSslContextDone(dynCtx); | |
3510 | } else { | |
3511 | debugs(33, 5, HERE << "Cached SSL certificate for " << host << " is out of date. Delete this certificate from cache"); | |
3512 | ssl_ctx_cache.remove(host); | |
3513 | } | |
3514 | } else { | |
3515 | debugs(33, 5, HERE << "SSL certificate for " << host << " haven't found in cache"); | |
3516 | } | |
3517 | ||
b5faa519 | 3518 | #if USE_SSL_CRTD |
95d2589c CT |
3519 | debugs(33, 5, HERE << "Generating SSL certificate for " << host << " using ssl_crtd."); |
3520 | Ssl::CrtdMessage request_message; | |
3521 | request_message.setCode(Ssl::CrtdMessage::code_new_certificate); | |
3522 | Ssl::CrtdMessage::BodyParams map; | |
3523 | map.insert(std::make_pair(Ssl::CrtdMessage::param_host, host)); | |
3524 | std::string bufferToWrite; | |
3525 | Ssl::writeCertAndPrivateKeyToMemory(port->signingCert, port->signPkey, bufferToWrite); | |
3526 | request_message.composeBody(map, bufferToWrite); | |
3527 | Ssl::Helper::GetInstance()->sslSubmit(request_message, sslCrtdHandleReplyWrapper, this); | |
3528 | return true; | |
3529 | #else | |
3530 | debugs(33, 5, HERE << "Generating SSL certificate for " << host); | |
b5faa519 | 3531 | dynCtx = Ssl::generateSslContext(host, port->signingCert, port->signPkey); |
95d2589c CT |
3532 | return getSslContextDone(dynCtx, true); |
3533 | #endif //USE_SSL_CRTD | |
3534 | } | |
3535 | return getSslContextDone(NULL); | |
3536 | } | |
3537 | ||
3538 | bool | |
3539 | ConnStateData::getSslContextDone(SSL_CTX * sslContext, bool isNew) | |
3540 | { | |
3541 | // Try to add generated ssl context to storage. | |
3542 | if (port->generateHostCertificates && isNew) { | |
a594dbfa CT |
3543 | |
3544 | Ssl::addChainToSslContext(sslContext, port->certsToChain.get()); | |
3545 | ||
95d2589c CT |
3546 | Ssl::LocalContextStorage & ssl_ctx_cache(Ssl::TheGlobalContextStorage.getLocalStorage(port->s)); |
3547 | if (sslContext && sslHostName != "") { | |
3548 | if (!ssl_ctx_cache.add(sslHostName.termedBuf(), sslContext)) { | |
3549 | // If it is not in storage delete after using. Else storage deleted it. | |
73c36fd9 | 3550 | fd_table[clientConnection->fd].dynamicSslContext = sslContext; |
95d2589c CT |
3551 | } |
3552 | } else { | |
3553 | debugs(33, 2, HERE << "Failed to generate SSL cert for " << sslHostName); | |
3554 | } | |
3555 | } | |
3556 | ||
3557 | // If generated ssl context = NULL, try to use static ssl context. | |
3558 | if (!sslContext) { | |
3559 | if (!port->staticSslContext) { | |
73c36fd9 AJ |
3560 | debugs(83, 1, "Closing SSL " << clientConnection->remote << " as lacking SSL context"); |
3561 | clientConnection->close(); | |
95d2589c CT |
3562 | return false; |
3563 | } else { | |
3564 | debugs(33, 5, HERE << "Using static ssl context."); | |
3565 | sslContext = port->staticSslContext.get(); | |
3566 | } | |
3567 | } | |
ae7ff0b8 | 3568 | |
ae7ff0b8 | 3569 | SSL *ssl = NULL; |
73c36fd9 | 3570 | if (!(ssl = httpsCreate(clientConnection, sslContext))) |
ae7ff0b8 | 3571 | return false; |
3572 | ||
8d77a37c | 3573 | // commSetConnTimeout() was called for this request before we switched. |
ae7ff0b8 | 3574 | |
3575 | // Disable the client read handler until peer selection is complete | |
73c36fd9 AJ |
3576 | Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0); |
3577 | Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, clientNegotiateSSL, this, 0); | |
ae7ff0b8 | 3578 | switchedToHttps_ = true; |
3579 | return true; | |
3580 | } | |
3581 | ||
95d2589c CT |
3582 | bool |
3583 | ConnStateData::switchToHttps(const char *host) | |
3584 | { | |
3585 | assert(!switchedToHttps_); | |
3586 | ||
3587 | sslHostName = host; | |
3588 | ||
3589 | //HTTPMSGLOCK(currentobject->http->request); | |
3590 | assert(areAllContextsForThisConnection()); | |
3591 | freeAllContexts(); | |
3592 | //currentobject->connIsFinished(); | |
3593 | ||
83d4cd15 CT |
3594 | // We are going to read new request |
3595 | flags.readMore = true; | |
73c36fd9 | 3596 | debugs(33, 5, HERE << "converting " << clientConnection << " to SSL"); |
95d2589c CT |
3597 | |
3598 | return getSslContextStart(); | |
3599 | } | |
3600 | ||
1f7c9178 | 3601 | #endif /* USE_SSL */ |
3602 | ||
00516be1 AR |
3603 | /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed |
3604 | static bool | |
73c36fd9 | 3605 | OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType) |
00516be1 | 3606 | { |
73c36fd9 | 3607 | if (!Comm::IsConnOpen(c)) { |
00516be1 AR |
3608 | Must(NHttpSockets > 0); // we tried to open some |
3609 | --NHttpSockets; // there will be fewer sockets than planned | |
3610 | Must(HttpSockets[NHttpSockets] < 0); // no extra fds received | |
3611 | ||
3612 | if (!NHttpSockets) // we could not open any listen sockets at all | |
cbff89ba | 3613 | fatalf("Unable to open %s",FdNote(portType)); |
00516be1 AR |
3614 | |
3615 | return false; | |
3616 | } | |
3617 | return true; | |
3618 | } | |
3619 | ||
3620 | /// find any unused HttpSockets[] slot and store fd there or return false | |
3621 | static bool | |
e0d28505 | 3622 | AddOpenedHttpSocket(const Comm::ConnectionPointer &conn) |
00516be1 AR |
3623 | { |
3624 | bool found = false; | |
3625 | for (int i = 0; i < NHttpSockets && !found; i++) { | |
3626 | if ((found = HttpSockets[i] < 0)) | |
e0d28505 | 3627 | HttpSockets[i] = conn->fd; |
00516be1 AR |
3628 | } |
3629 | return found; | |
3630 | } | |
15df8349 | 3631 | |
d193a436 | 3632 | static void |
15df8349 | 3633 | clientHttpConnectionsOpen(void) |
3634 | { | |
cc192b50 | 3635 | http_port_list *s = NULL; |
62e76326 | 3636 | |
7e3ce7b9 | 3637 | for (s = Config.Sockaddr.http; s; s = s->next) { |
62e76326 | 3638 | if (MAXHTTPPORTS == NHttpSockets) { |
bf8fe701 | 3639 | debugs(1, 1, "WARNING: You have too many 'http_port' lines."); |
3640 | debugs(1, 1, " The limit is " << MAXHTTPPORTS); | |
62e76326 | 3641 | continue; |
3642 | } | |
3643 | ||
ae7ff0b8 | 3644 | #if USE_SSL |
3d61b18e AJ |
3645 | if (s->sslBump && !Config.accessList.ssl_bump) { |
3646 | debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s->protocol << "_port " << s->http.s); | |
3647 | s->sslBump = 0; | |
3648 | } | |
3649 | ||
3650 | if (s->sslBump && !s->staticSslContext && !s->generateHostCertificates) { | |
3651 | debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->http.s << " due to SSL initialization failure."); | |
ae7ff0b8 | 3652 | s->sslBump = 0; |
3653 | } | |
95d2589c | 3654 | if (s->sslBump) { |
95d2589c CT |
3655 | // Create ssl_ctx cache for this port. |
3656 | Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize); | |
3657 | } | |
ae7ff0b8 | 3658 | #endif |
3659 | ||
e0d28505 | 3660 | // Fill out a Comm::Connection which IPC will open as a listener for us |
8bbb16e3 | 3661 | // then pass back when active so we can start a TcpAcceptor subscription. |
e0d28505 AJ |
3662 | s->listenConn = new Comm::Connection; |
3663 | s->listenConn->local = s->s; | |
40d34a62 | 3664 | s->listenConn->flags = COMM_NONBLOCKING | (s->spoof_client_ip ? COMM_TRANSPARENT : 0) | (s->intercepted ? COMM_INTERCEPTION : 0); |
c303f6e3 | 3665 | |
cbff89ba AJ |
3666 | // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP |
3667 | typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall; | |
3668 | RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, s)); | |
3669 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
62e76326 | 3670 | |
cbff89ba | 3671 | AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened", |
8bbb16e3 AJ |
3672 | ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub)); |
3673 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall); | |
62e76326 | 3674 | |
cbff89ba | 3675 | HttpSockets[NHttpSockets++] = -1; // set in clientListenerConnectionOpened |
15df8349 | 3676 | } |
d193a436 | 3677 | } |
3678 | ||
3679 | #if USE_SSL | |
3680 | static void | |
3681 | clientHttpsConnectionsOpen(void) | |
3682 | { | |
3683 | https_port_list *s; | |
62e76326 | 3684 | |
3f38a55e | 3685 | for (s = Config.Sockaddr.https; s; s = (https_port_list *)s->http.next) { |
62e76326 | 3686 | if (MAXHTTPPORTS == NHttpSockets) { |
ae7ff0b8 | 3687 | debugs(1, 1, "Ignoring 'https_port' lines exceeding the limit."); |
3688 | debugs(1, 1, "The limit is " << MAXHTTPPORTS << " HTTPS ports."); | |
62e76326 | 3689 | continue; |
3690 | } | |
3691 | ||
95d2589c | 3692 | if (!s->staticSslContext) { |
ae7ff0b8 | 3693 | debugs(1, 1, "Ignoring https_port " << s->http.s << |
3694 | " due to SSL initialization failure."); | |
3695 | continue; | |
f9ad0106 | 3696 | } |
3697 | ||
e0d28505 AJ |
3698 | // Fill out a Comm::Connection which IPC will open as a listener for us |
3699 | s->http.listenConn = new Comm::Connection; | |
3700 | s->http.listenConn->local = s->http.s; | |
40d34a62 AJ |
3701 | s->http.listenConn->flags = COMM_NONBLOCKING | (s->http.spoof_client_ip ? COMM_TRANSPARENT : 0) | |
3702 | (s->http.intercepted ? COMM_INTERCEPTION : 0); | |
62e76326 | 3703 | |
cbff89ba AJ |
3704 | // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS |
3705 | typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall; | |
3706 | RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, s)); | |
3707 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
62e76326 | 3708 | |
cbff89ba | 3709 | AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened", |
8bbb16e3 | 3710 | ListeningStartedDialer(&clientListenerConnectionOpened, |
db98b2bd | 3711 | &s->http, Ipc::fdnHttpsSocket, sub)); |
8bbb16e3 | 3712 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall); |
cbff89ba AJ |
3713 | HttpSockets[NHttpSockets++] = -1; |
3714 | } | |
d193a436 | 3715 | } |
d193a436 | 3716 | #endif |
3717 | ||
e0d28505 | 3718 | /// process clientHttpConnectionsOpen result |
00516be1 | 3719 | static void |
8bbb16e3 | 3720 | clientListenerConnectionOpened(http_port_list *s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub) |
00516be1 | 3721 | { |
8bbb16e3 | 3722 | if (!OpenedHttpSocket(s->listenConn, portTypeNote)) |
00516be1 | 3723 | return; |
62e76326 | 3724 | |
00516be1 | 3725 | Must(s); |
e0d28505 | 3726 | Must(Comm::IsConnOpen(s->listenConn)); |
62e76326 | 3727 | |
8bbb16e3 AJ |
3728 | // TCP: setup a job to handle accept() with subscribed handler |
3729 | AsyncJob::Start(new Comm::TcpAcceptor(s->listenConn, FdNote(portTypeNote), sub)); | |
3730 | ||
1b76e6c1 AJ |
3731 | debugs(1, 1, "Accepting " << |
3732 | (s->intercepted ? "NAT intercepted " : "") << | |
3733 | (s->spoof_client_ip ? "TPROXY spoofing " : "") << | |
3734 | (s->sslBump ? "SSL bumped " : "") << | |
3735 | (s->accel ? "reverse-proxy " : "") | |
8bbb16e3 AJ |
3736 | << FdNote(portTypeNote) << " connections at " |
3737 | << s->listenConn); | |
62e76326 | 3738 | |
e0d28505 | 3739 | Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for |
d193a436 | 3740 | } |
3741 | ||
d193a436 | 3742 | void |
3743 | clientOpenListenSockets(void) | |
3744 | { | |
3745 | clientHttpConnectionsOpen(); | |
3746 | #if USE_SSL | |
3747 | clientHttpsConnectionsOpen(); | |
1f7c9178 | 3748 | #endif |
62e76326 | 3749 | |
15df8349 | 3750 | if (NHttpSockets < 1) |
598c41da | 3751 | fatal("No HTTP or HTTPS ports configured"); |
15df8349 | 3752 | } |
edce4d98 | 3753 | |
c0fbae16 | 3754 | void |
3755 | clientHttpConnectionsClose(void) | |
3756 | { | |
04f55905 | 3757 | for (http_port_list *s = Config.Sockaddr.http; s; s = s->next) { |
00406b24 | 3758 | if (s->listenConn != NULL) { |
e0d28505 | 3759 | debugs(1, 1, "Closing HTTP port " << s->listenConn->local); |
00406b24 AJ |
3760 | s->listenConn->close(); |
3761 | s->listenConn = NULL; | |
04f55905 AJ |
3762 | } |
3763 | } | |
62e76326 | 3764 | |
04f55905 AJ |
3765 | #if USE_SSL |
3766 | for (http_port_list *s = Config.Sockaddr.https; s; s = s->next) { | |
00406b24 | 3767 | if (s->listenConn != NULL) { |
e0d28505 | 3768 | debugs(1, 1, "Closing HTTPS port " << s->listenConn->local); |
00406b24 AJ |
3769 | s->listenConn->close(); |
3770 | s->listenConn = NULL; | |
62e76326 | 3771 | } |
c0fbae16 | 3772 | } |
04f55905 AJ |
3773 | #endif |
3774 | ||
3775 | // TODO see if we can drop HttpSockets array entirely */ | |
3776 | for (int i = 0; i < NHttpSockets; i++) { | |
3777 | HttpSockets[i] = -1; | |
3778 | } | |
62e76326 | 3779 | |
c0fbae16 | 3780 | NHttpSockets = 0; |
3781 | } | |
f66a9ef4 | 3782 | |
3783 | int | |
190154cf | 3784 | varyEvaluateMatch(StoreEntry * entry, HttpRequest * request) |
f66a9ef4 | 3785 | { |
3786 | const char *vary = request->vary_headers; | |
a9925b40 | 3787 | int has_vary = entry->getReply()->header.has(HDR_VARY); |
f66a9ef4 | 3788 | #if X_ACCELERATOR_VARY |
62e76326 | 3789 | |
edce4d98 | 3790 | has_vary |= |
a9925b40 | 3791 | entry->getReply()->header.has(HDR_X_ACCELERATOR_VARY); |
f66a9ef4 | 3792 | #endif |
62e76326 | 3793 | |
f66a9ef4 | 3794 | if (!has_vary || !entry->mem_obj->vary_headers) { |
62e76326 | 3795 | if (vary) { |
3796 | /* Oops... something odd is going on here.. */ | |
9e008dda AJ |
3797 | debugs(33, 1, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" << |
3798 | entry->mem_obj->url << "' '" << vary << "'"); | |
62e76326 | 3799 | safe_free(request->vary_headers); |
3800 | return VARY_CANCEL; | |
3801 | } | |
3802 | ||
3803 | if (!has_vary) { | |
3804 | /* This is not a varying object */ | |
3805 | return VARY_NONE; | |
3806 | } | |
3807 | ||
3808 | /* virtual "vary" object found. Calculate the vary key and | |
3809 | * continue the search | |
3810 | */ | |
3811 | vary = httpMakeVaryMark(request, entry->getReply()); | |
3812 | ||
3813 | if (vary) { | |
3814 | request->vary_headers = xstrdup(vary); | |
3815 | return VARY_OTHER; | |
3816 | } else { | |
3817 | /* Ouch.. we cannot handle this kind of variance */ | |
3818 | /* XXX This cannot really happen, but just to be complete */ | |
3819 | return VARY_CANCEL; | |
3820 | } | |
f66a9ef4 | 3821 | } else { |
62e76326 | 3822 | if (!vary) { |
3823 | vary = httpMakeVaryMark(request, entry->getReply()); | |
3824 | ||
3825 | if (vary) | |
3826 | request->vary_headers = xstrdup(vary); | |
3827 | } | |
3828 | ||
3829 | if (!vary) { | |
3830 | /* Ouch.. we cannot handle this kind of variance */ | |
3831 | /* XXX This cannot really happen, but just to be complete */ | |
3832 | return VARY_CANCEL; | |
3833 | } else if (strcmp(vary, entry->mem_obj->vary_headers) == 0) { | |
3834 | return VARY_MATCH; | |
3835 | } else { | |
3836 | /* Oops.. we have already been here and still haven't | |
3837 | * found the requested variant. Bail out | |
3838 | */ | |
bf8fe701 | 3839 | debugs(33, 1, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" << |
9e008dda | 3840 | entry->mem_obj->url << "' '" << vary << "'"); |
62e76326 | 3841 | return VARY_CANCEL; |
3842 | } | |
f66a9ef4 | 3843 | } |
3844 | } | |
28d4805a | 3845 | |
c0941a6a | 3846 | ACLFilledChecklist * |
59a1efb2 | 3847 | clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http) |
28d4805a | 3848 | { |
1cf238db | 3849 | ConnStateData * conn = http->getConn(); |
c0941a6a | 3850 | ACLFilledChecklist *ch = new ACLFilledChecklist(acl, http->request, |
73c36fd9 | 3851 | cbdataReferenceValid(conn) && conn != NULL && conn->clientConnection != NULL ? conn->clientConnection->rfc931 : dash_str); |
28d4805a | 3852 | |
3853 | /* | |
3854 | * hack for ident ACL. It needs to get full addresses, and a place to store | |
3855 | * the ident result on persistent connections... | |
3856 | */ | |
3857 | /* connection oriented auth also needs these two lines for it's operation. */ | |
3858 | /* | |
3859 | * Internal requests do not have a connection reference, because: A) their | |
3860 | * byte count may be transformed before being applied to an outbound | |
3861 | * connection B) they are internal - any limiting on them should be done on | |
3862 | * the server end. | |
3863 | */ | |
62e76326 | 3864 | |
1cf238db | 3865 | if (conn != NULL) |
c0941a6a | 3866 | ch->conn(conn); /* unreferenced in FilledCheckList.cc */ |
28d4805a | 3867 | |
3868 | return ch; | |
3869 | } | |
a46d2c0e | 3870 | |
3871 | CBDATA_CLASS_INIT(ConnStateData); | |
3872 | ||
5c336a3b AJ |
3873 | ConnStateData::ConnStateData() : |
3874 | AsyncJob("ConnStateData"), | |
cf6eb29e CT |
3875 | switchedToHttps_(false), |
3876 | stoppedSending_(NULL), | |
3877 | stoppedReceiving_(NULL) | |
b65351fa | 3878 | { |
d67acb4e AJ |
3879 | pinning.pinned = false; |
3880 | pinning.auth = false; | |
b65351fa | 3881 | } |
a46d2c0e | 3882 | |
3883 | bool | |
3884 | ConnStateData::transparent() const | |
3885 | { | |
40d34a62 | 3886 | return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION)); |
a46d2c0e | 3887 | } |
3888 | ||
3889 | bool | |
3890 | ConnStateData::reading() const | |
3891 | { | |
f84dd7eb | 3892 | return reader != NULL; |
a46d2c0e | 3893 | } |
3894 | ||
3895 | void | |
f84dd7eb | 3896 | ConnStateData::stopReading() |
a46d2c0e | 3897 | { |
f84dd7eb | 3898 | if (reading()) { |
73c36fd9 | 3899 | comm_read_cancel(clientConnection->fd, reader); |
f84dd7eb AR |
3900 | reader = NULL; |
3901 | } | |
a46d2c0e | 3902 | } |
3903 | ||
5f8252d2 | 3904 | |
3905 | BodyPipe::Pointer | |
3e62bd58 | 3906 | ConnStateData::expectRequestBody(int64_t size) |
5f8252d2 | 3907 | { |
3908 | bodyPipe = new BodyPipe(this); | |
39cb8c41 AR |
3909 | if (size >= 0) |
3910 | bodyPipe->setBodySize(size); | |
3911 | else | |
3912 | startDechunkingRequest(); | |
5f8252d2 | 3913 | return bodyPipe; |
3914 | } | |
3915 | ||
39cb8c41 AR |
3916 | int64_t |
3917 | ConnStateData::mayNeedToReadMoreBody() const | |
3918 | { | |
3919 | if (!bodyPipe) | |
3920 | return 0; // request without a body or read/produced all body bytes | |
3921 | ||
3922 | if (!bodyPipe->bodySizeKnown()) | |
3923 | return -1; // probably need to read more, but we cannot be sure | |
3924 | ||
3925 | const int64_t needToProduce = bodyPipe->unproducedSize(); | |
3926 | const int64_t haveAvailable = static_cast<int64_t>(in.notYetUsed); | |
3927 | ||
3928 | if (needToProduce <= haveAvailable) | |
3929 | return 0; // we have read what we need (but are waiting for pipe space) | |
3930 | ||
3931 | return needToProduce - haveAvailable; | |
3932 | } | |
3933 | ||
55e44db9 | 3934 | void |
cf6eb29e | 3935 | ConnStateData::stopReceiving(const char *error) |
55e44db9 | 3936 | { |
cf6eb29e CT |
3937 | debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error << |
3938 | "; old sending error: " << | |
3939 | (stoppedSending() ? stoppedSending_ : "none")); | |
5f8252d2 | 3940 | |
cf6eb29e CT |
3941 | if (const char *oldError = stoppedReceiving()) { |
3942 | debugs(33, 3, HERE << "already stopped receiving: " << oldError); | |
3943 | return; // nothing has changed as far as this connection is concerned | |
3944 | } | |
5f8252d2 | 3945 | |
cf6eb29e | 3946 | stoppedReceiving_ = error; |
5f8252d2 | 3947 | |
cf6eb29e CT |
3948 | if (const char *sendError = stoppedSending()) { |
3949 | debugs(33, 3, HERE << "closing because also stopped sending: " << sendError); | |
3950 | clientConnection->close(); | |
3951 | } | |
55e44db9 | 3952 | } |
3953 | ||
eb44b2d7 | 3954 | void |
e29ccb57 A |
3955 | ConnStateData::expectNoForwarding() |
3956 | { | |
eb44b2d7 CT |
3957 | if (bodyPipe != NULL) { |
3958 | debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status()); | |
3959 | bodyPipe->expectNoConsumption(); | |
3960 | } | |
3961 | } | |
3962 | ||
39cb8c41 | 3963 | /// initialize dechunking state |
3ff65596 | 3964 | void |
39cb8c41 | 3965 | ConnStateData::startDechunkingRequest() |
3ff65596 | 3966 | { |
39cb8c41 AR |
3967 | Must(bodyPipe != NULL); |
3968 | debugs(33, 5, HERE << "start dechunking" << bodyPipe->status()); | |
3ff65596 AR |
3969 | assert(!in.bodyParser); |
3970 | in.bodyParser = new ChunkedCodingParser; | |
3ff65596 AR |
3971 | } |
3972 | ||
39cb8c41 | 3973 | /// put parsed content into input buffer and clean up |
3ff65596 | 3974 | void |
39cb8c41 | 3975 | ConnStateData::finishDechunkingRequest(bool withSuccess) |
3ff65596 | 3976 | { |
39cb8c41 | 3977 | debugs(33, 5, HERE << "finish dechunking: " << withSuccess); |
3ff65596 | 3978 | |
39cb8c41 AR |
3979 | if (bodyPipe != NULL) { |
3980 | debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status()); | |
3981 | BodyPipe::Pointer myPipe = bodyPipe; | |
3982 | stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize() | |
3983 | Must(!bodyPipe); // we rely on it being nil after we are done with body | |
3984 | if (withSuccess) { | |
3985 | Must(myPipe->bodySizeKnown()); | |
3986 | ClientSocketContext::Pointer context = getCurrentContext(); | |
3987 | if (context != NULL && context->http && context->http->request) | |
3988 | context->http->request->setContentLength(myPipe->bodySize()); | |
3989 | } | |
3ff65596 | 3990 | } |
3ff65596 | 3991 | |
39cb8c41 AR |
3992 | delete in.bodyParser; |
3993 | in.bodyParser = NULL; | |
3ff65596 AR |
3994 | } |
3995 | ||
a46d2c0e | 3996 | char * |
3997 | ConnStateData::In::addressToReadInto() const | |
3998 | { | |
3999 | return buf + notYetUsed; | |
4000 | } | |
4001 | ||
3ff65596 | 4002 | ConnStateData::In::In() : bodyParser(NULL), |
39cb8c41 | 4003 | buf (NULL), notYetUsed (0), allocatedSize (0) |
a46d2c0e | 4004 | {} |
4005 | ||
4006 | ConnStateData::In::~In() | |
4007 | { | |
4008 | if (allocatedSize) | |
4009 | memFreeBuf(allocatedSize, buf); | |
39cb8c41 | 4010 | delete bodyParser; // TODO: pool |
a46d2c0e | 4011 | } |
d67acb4e | 4012 | |
655daa06 AR |
4013 | void |
4014 | ConnStateData::sendControlMsg(HttpControlMsg msg) | |
4015 | { | |
eedd4182 AR |
4016 | if (!isOpen()) { |
4017 | debugs(33, 3, HERE << "ignoring 1xx due to earlier closure"); | |
655daa06 AR |
4018 | return; |
4019 | } | |
4020 | ||
eedd4182 AR |
4021 | ClientSocketContext::Pointer context = getCurrentContext(); |
4022 | if (context != NULL) { | |
4023 | context->writeControlMsg(msg); // will call msg.cbSuccess | |
655daa06 AR |
4024 | return; |
4025 | } | |
4026 | ||
4027 | debugs(33, 3, HERE << " closing due to missing context for 1xx"); | |
73c36fd9 | 4028 | clientConnection->close(); |
655daa06 AR |
4029 | } |
4030 | ||
d67acb4e AJ |
4031 | /* This is a comm call normally scheduled by comm_close() */ |
4032 | void | |
4033 | ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io) | |
4034 | { | |
e3a4aecc | 4035 | unpinConnection(); |
d67acb4e AJ |
4036 | } |
4037 | ||
b1cf2350 | 4038 | void |
73c36fd9 | 4039 | ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, struct peer *aPeer, bool auth) |
9e008dda | 4040 | { |
d67acb4e AJ |
4041 | char desc[FD_DESC_SZ]; |
4042 | ||
73c36fd9 AJ |
4043 | if (Comm::IsConnOpen(pinning.serverConnection)) { |
4044 | if (pinning.serverConnection->fd == pinServer->fd) | |
e3a4aecc | 4045 | return; |
9e008dda | 4046 | |
e3a4aecc | 4047 | unpinConnection(); // clears fields ready for re-use. Prevent close() scheduling our close handler. |
73c36fd9 | 4048 | pinning.serverConnection->close(); |
e3a4aecc AJ |
4049 | } else |
4050 | unpinConnection(); // clears fields ready for re-use. | |
9e008dda | 4051 | |
73c36fd9 | 4052 | pinning.serverConnection = pinServer; |
d67acb4e AJ |
4053 | pinning.host = xstrdup(request->GetHost()); |
4054 | pinning.port = request->port; | |
4055 | pinning.pinned = true; | |
8bcf08e0 FC |
4056 | if (aPeer) |
4057 | pinning.peer = cbdataReference(aPeer); | |
d67acb4e | 4058 | pinning.auth = auth; |
e3a4aecc AJ |
4059 | char stmp[MAX_IPSTRLEN]; |
4060 | snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)", | |
73c36fd9 AJ |
4061 | (auth || !aPeer) ? request->GetHost() : aPeer->name, clientConnection->remote.ToURL(stmp,MAX_IPSTRLEN), clientConnection->fd); |
4062 | fd_note(pinning.serverConnection->fd, desc); | |
9e008dda | 4063 | |
d67acb4e | 4064 | typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer; |
4299f876 | 4065 | pinning.closeHandler = JobCallback(33, 5, |
4cb2536f | 4066 | Dialer, this, ConnStateData::clientPinnedConnectionClosed); |
73c36fd9 | 4067 | comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler); |
d67acb4e AJ |
4068 | } |
4069 | ||
e3a4aecc | 4070 | const Comm::ConnectionPointer |
b1cf2350 | 4071 | ConnStateData::validatePinnedConnection(HttpRequest *request, const struct peer *aPeer) |
d67acb4e AJ |
4072 | { |
4073 | bool valid = true; | |
73c36fd9 | 4074 | if (!Comm::IsConnOpen(pinning.serverConnection)) |
e3a4aecc | 4075 | valid = false; |
d67acb4e | 4076 | if (pinning.auth && request && strcasecmp(pinning.host, request->GetHost()) != 0) { |
9e008dda | 4077 | valid = false; |
d67acb4e | 4078 | } |
9e008dda AJ |
4079 | if (request && pinning.port != request->port) { |
4080 | valid = false; | |
d67acb4e | 4081 | } |
9e008dda AJ |
4082 | if (pinning.peer && !cbdataReferenceValid(pinning.peer)) { |
4083 | valid = false; | |
d67acb4e | 4084 | } |
8bcf08e0 | 4085 | if (aPeer != pinning.peer) { |
9e008dda | 4086 | valid = false; |
d67acb4e AJ |
4087 | } |
4088 | ||
9e008dda | 4089 | if (!valid) { |
b1cf2350 | 4090 | /* The pinning info is not safe, remove any pinning info */ |
9e008dda | 4091 | unpinConnection(); |
d67acb4e AJ |
4092 | } |
4093 | ||
73c36fd9 | 4094 | return pinning.serverConnection; |
d67acb4e AJ |
4095 | } |
4096 | ||
b1cf2350 AJ |
4097 | void |
4098 | ConnStateData::unpinConnection() | |
d67acb4e | 4099 | { |
9e008dda AJ |
4100 | if (pinning.peer) |
4101 | cbdataReferenceDone(pinning.peer); | |
d67acb4e | 4102 | |
9e008dda | 4103 | if (pinning.closeHandler != NULL) { |
73c36fd9 | 4104 | comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler); |
9e008dda | 4105 | pinning.closeHandler = NULL; |
d67acb4e | 4106 | } |
b1cf2350 | 4107 | /// also close the server side socket, we should not use it for any future requests... |
1b76e6c1 | 4108 | pinning.serverConnection->close(); |
d67acb4e | 4109 | safe_free(pinning.host); |
e3a4aecc AJ |
4110 | |
4111 | /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host | |
4112 | * connection has gone away */ | |
d67acb4e | 4113 | } |