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