]>
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 |
00406b24 | 90 | #include "base/Subscription.h" |
d841c88d | 91 | #include "base/TextException.h" |
04f55905 | 92 | #include "ChunkedCodingParser.h" |
a46d2c0e | 93 | #include "client_side.h" |
04f55905 AJ |
94 | #include "client_side_reply.h" |
95 | #include "client_side_request.h" | |
d841c88d AJ |
96 | #if USE_DELAY_POOLS |
97 | #include "ClientInfo.h" | |
98 | #endif | |
04f55905 | 99 | #include "ClientRequestContext.h" |
c8be6d7b | 100 | #include "clientStream.h" |
c4b7a5a9 | 101 | #include "comm.h" |
cfd66529 | 102 | #include "comm/Connection.h" |
cbff89ba | 103 | #include "CommCalls.h" |
d841c88d | 104 | #include "comm/Loops.h" |
ec41b64c | 105 | #include "comm/Write.h" |
cbff89ba | 106 | #include "comm/TcpAcceptor.h" |
8eb0a7ee | 107 | #include "errorpage.h" |
056b24a1 | 108 | #include "eui/Config.h" |
04f55905 | 109 | #include "fde.h" |
fd4624d7 | 110 | #include "forward.h" |
25b6a907 | 111 | #include "HttpHdrContRange.h" |
528b2c61 | 112 | #include "HttpReply.h" |
113 | #include "HttpRequest.h" | |
4daaf3cb AJ |
114 | #include "ident/Config.h" |
115 | #include "ident/Ident.h" | |
cbff89ba | 116 | #include "ipc/FdNotes.h" |
fe090a86 | 117 | #include "ipc/StartListening.h" |
0eb49b6d | 118 | #include "MemBuf.h" |
04f55905 AJ |
119 | #include "MemObject.h" |
120 | #include "ProtoPort.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: | |
8bbb16e3 AJ |
151 | typedef void (*Handler)(http_port_list *portCfg, const Ipc::FdNoteId note, const Subscription::Pointer &sub); |
152 | ListeningStartedDialer(Handler aHandler, http_port_list *aPortCfg, const Ipc::FdNoteId note, const Subscription::Pointer &aSub): | |
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: | |
cbff89ba AJ |
167 | http_port_list *portCfg; ///< from Config.Sockaddr.http |
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 | ||
8bbb16e3 | 172 | static void clientListenerConnectionOpened(http_port_list *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 | |
be364179 | 231 | static ConnStateData *connStateCreate(const Comm::ConnectionPointer &client, http_port_list *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) */ | |
c057c49e | 2097 | // BUG 2976: Squid only accepts intercepted HTTP. |
3f38a55e | 2098 | |
f024c970 | 2099 | if ((host = mime_get_header(req_hdr, "Host")) != NULL) { |
62e76326 | 2100 | int url_sz = strlen(url) + 32 + Config.appendDomainLen + |
2101 | strlen(host); | |
2102 | http->uri = (char *)xcalloc(url_sz, 1); | |
379e8c1c | 2103 | snprintf(http->uri, url_sz, "%s://%s%s", conn->port->protocol, host, url); |
bf8fe701 | 2104 | debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http->uri <<"'"); |
c8be6d7b | 2105 | } else { |
62e76326 | 2106 | /* Put the local socket IP address as the hostname. */ |
2107 | int url_sz = strlen(url) + 32 + Config.appendDomainLen; | |
2108 | http->uri = (char *)xcalloc(url_sz, 1); | |
73c36fd9 | 2109 | http->getConn()->clientConnection->local.ToHostname(ipbuf,MAX_IPSTRLEN), |
379e8c1c AR |
2110 | snprintf(http->uri, url_sz, "%s://%s:%d%s", |
2111 | http->getConn()->port->protocol, | |
73c36fd9 | 2112 | ipbuf, http->getConn()->clientConnection->local.GetPort(), url); |
bf8fe701 | 2113 | debugs(33, 5, "TRANSPARENT REWRITE: '" << http->uri << "'"); |
c8be6d7b | 2114 | } |
c8be6d7b | 2115 | } |
2116 | ||
63be0a78 | 2117 | /** |
7a2f978b | 2118 | * parseHttpRequest() |
9e008dda | 2119 | * |
7a2f978b | 2120 | * Returns |
c4b7a5a9 | 2121 | * NULL on incomplete requests |
528b2c61 | 2122 | * a ClientSocketContext structure on success or failure. |
c4b7a5a9 | 2123 | * Sets result->flags.parsed_ok to 0 if failed to parse the request. |
2124 | * Sets result->flags.parsed_ok to 1 if we have a good request. | |
7a2f978b | 2125 | */ |
528b2c61 | 2126 | static ClientSocketContext * |
be364179 | 2127 | parseHttpRequest(ConnStateData *csd, HttpParser *hp, HttpRequestMethod * method_p, HttpVersion *http_ver) |
7a2f978b | 2128 | { |
7a2f978b | 2129 | char *req_hdr = NULL; |
2334c194 | 2130 | char *end; |
c68e9c6b | 2131 | size_t req_sz; |
59a1efb2 | 2132 | ClientHttpRequest *http; |
528b2c61 | 2133 | ClientSocketContext *result; |
2134 | StoreIOBuffer tempBuffer; | |
84cc2635 | 2135 | int r; |
7a2f978b | 2136 | |
6792f0d3 | 2137 | /* pre-set these values to make aborting simpler */ |
6792f0d3 | 2138 | *method_p = METHOD_NONE; |
6792f0d3 | 2139 | |
7ed7d3da AJ |
2140 | /* NP: don't be tempted to move this down or remove again. |
2141 | * It's the only DDoS protection old-String has against long URL */ | |
2142 | if ( hp->bufsiz <= 0) { | |
2143 | debugs(33, 5, "Incomplete request, waiting for end of request line"); | |
2144 | return NULL; | |
e1381638 | 2145 | } else if ( (size_t)hp->bufsiz >= Config.maxRequestHeaderSize && headersEnd(hp->buf, Config.maxRequestHeaderSize) == 0) { |
7ed7d3da | 2146 | debugs(33, 5, "parseHttpRequest: Too large request"); |
719c7e0a | 2147 | hp->request_parse_status = HTTP_HEADER_TOO_LARGE; |
be364179 | 2148 | return parseHttpRequestAbort(csd, "error:request-too-large"); |
7ed7d3da AJ |
2149 | } |
2150 | ||
84cc2635 | 2151 | /* Attempt to parse the first line; this'll define the method, url, version and header begin */ |
2152 | r = HttpParserParseReqLine(hp); | |
fc68f6b1 | 2153 | |
84cc2635 | 2154 | if (r == 0) { |
bf8fe701 | 2155 | debugs(33, 5, "Incomplete request, waiting for end of request line"); |
fc68f6b1 | 2156 | return NULL; |
7a2f978b | 2157 | } |
fc68f6b1 | 2158 | |
84cc2635 | 2159 | if (r == -1) { |
be364179 | 2160 | return parseHttpRequestAbort(csd, "error:invalid-request"); |
84cc2635 | 2161 | } |
fc68f6b1 | 2162 | |
84cc2635 | 2163 | /* Request line is valid here .. */ |
74f478f8 | 2164 | *http_ver = HttpVersion(hp->req.v_maj, hp->req.v_min); |
62e76326 | 2165 | |
52512f28 | 2166 | /* This call scans the entire request, not just the headers */ |
74f478f8 | 2167 | if (hp->req.v_maj > 0) { |
a5baffba | 2168 | if ((req_sz = headersEnd(hp->buf, hp->bufsiz)) == 0) { |
bf8fe701 | 2169 | debugs(33, 5, "Incomplete request, waiting for end of headers"); |
62e76326 | 2170 | return NULL; |
2171 | } | |
3f38a55e | 2172 | } else { |
bf8fe701 | 2173 | debugs(33, 3, "parseHttpRequest: Missing HTTP identifier"); |
84cc2635 | 2174 | req_sz = HttpParserReqSz(hp); |
3f38a55e | 2175 | } |
2176 | ||
bb790702 | 2177 | /* We know the whole request is in hp->buf now */ |
52512f28 | 2178 | |
a5baffba | 2179 | assert(req_sz <= (size_t) hp->bufsiz); |
fc68f6b1 | 2180 | |
a5baffba | 2181 | /* Will the following be true with HTTP/0.9 requests? probably not .. */ |
2182 | /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */ | |
2183 | assert(req_sz > 0); | |
fc68f6b1 | 2184 | |
a5baffba | 2185 | hp->hdr_end = req_sz - 1; |
fc68f6b1 | 2186 | |
74f478f8 | 2187 | hp->hdr_start = hp->req.end + 1; |
3f38a55e | 2188 | |
5b648f60 | 2189 | /* Enforce max_request_size */ |
5b648f60 | 2190 | if (req_sz >= Config.maxRequestHeaderSize) { |
bf8fe701 | 2191 | debugs(33, 5, "parseHttpRequest: Too large request"); |
719c7e0a | 2192 | hp->request_parse_status = HTTP_HEADER_TOO_LARGE; |
be364179 | 2193 | return parseHttpRequestAbort(csd, "error:request-too-large"); |
5b648f60 | 2194 | } |
2195 | ||
84cc2635 | 2196 | /* Set method_p */ |
74f478f8 | 2197 | *method_p = HttpRequestMethod(&hp->buf[hp->req.m_start], &hp->buf[hp->req.m_end]+1); |
fc68f6b1 | 2198 | |
adf29627 | 2199 | /* deny CONNECT via accelerated ports */ |
be364179 AJ |
2200 | if (*method_p == METHOD_CONNECT && csd && csd->port && csd->port->accel) { |
2201 | debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << csd->port->protocol << " Accelerator port " << csd->port->s.GetPort() ); | |
adf29627 AJ |
2202 | /* XXX need a way to say "this many character length string" */ |
2203 | debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->buf); | |
719c7e0a | 2204 | hp->request_parse_status = HTTP_METHOD_NOT_ALLOWED; |
be364179 | 2205 | return parseHttpRequestAbort(csd, "error:method-not-allowed"); |
adf29627 AJ |
2206 | } |
2207 | ||
84cc2635 | 2208 | if (*method_p == METHOD_NONE) { |
fc68f6b1 | 2209 | /* XXX need a way to say "this many character length string" */ |
bf8fe701 | 2210 | debugs(33, 1, "clientParseRequestMethod: Unsupported method in request '" << hp->buf << "'"); |
719c7e0a | 2211 | hp->request_parse_status = HTTP_METHOD_NOT_ALLOWED; |
be364179 | 2212 | return parseHttpRequestAbort(csd, "error:unsupported-request-method"); |
3f38a55e | 2213 | } |
7a2f978b | 2214 | |
c68e9c6b | 2215 | /* |
2216 | * Process headers after request line | |
c8be6d7b | 2217 | * TODO: Use httpRequestParse here. |
c68e9c6b | 2218 | */ |
84cc2635 | 2219 | /* XXX this code should be modified to take a const char * later! */ |
74f478f8 | 2220 | req_hdr = (char *) hp->buf + hp->req.end + 1; |
fc68f6b1 | 2221 | |
bf8fe701 | 2222 | debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr << "}"); |
fc68f6b1 | 2223 | |
52512f28 | 2224 | end = (char *) hp->buf + hp->hdr_end; |
fc68f6b1 | 2225 | |
bf8fe701 | 2226 | debugs(33, 3, "parseHttpRequest: end = {" << end << "}"); |
99edd1c3 | 2227 | |
bf8fe701 | 2228 | debugs(33, 3, "parseHttpRequest: prefix_sz = " << |
2229 | (int) HttpParserRequestLen(hp) << ", req_line_sz = " << | |
2230 | HttpParserReqSz(hp)); | |
62e76326 | 2231 | |
7a2f978b | 2232 | /* Ok, all headers are received */ |
be364179 | 2233 | http = new ClientHttpRequest(csd); |
62e76326 | 2234 | |
a5baffba | 2235 | http->req_sz = HttpParserRequestLen(hp); |
73c36fd9 | 2236 | result = ClientSocketContextNew(csd->clientConnection, http); |
c8be6d7b | 2237 | tempBuffer.data = result->reqbuf; |
2238 | tempBuffer.length = HTTP_REQBUF_SZ; | |
62e76326 | 2239 | |
0655fa4d | 2240 | ClientStreamData newServer = new clientReplyContext(http); |
0655fa4d | 2241 | ClientStreamData newClient = result; |
edce4d98 | 2242 | clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach, |
0655fa4d | 2243 | clientReplyStatus, newServer, clientSocketRecipient, |
2244 | clientSocketDetach, newClient, tempBuffer); | |
62e76326 | 2245 | |
bf8fe701 | 2246 | debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp->buf) + hp->hdr_start); |
3f38a55e | 2247 | |
3ff65596 AR |
2248 | /* set url */ |
2249 | /* | |
2250 | * XXX this should eventually not use a malloc'ed buffer; the transformation code | |
2251 | * below needs to be modified to not expect a mutable nul-terminated string. | |
2252 | */ | |
74f478f8 | 2253 | char *url = (char *)xmalloc(hp->req.u_end - hp->req.u_start + 16); |
3ff65596 | 2254 | |
74f478f8 | 2255 | memcpy(url, hp->buf + hp->req.u_start, hp->req.u_end - hp->req.u_start + 1); |
3ff65596 | 2256 | |
74f478f8 | 2257 | url[hp->req.u_end - hp->req.u_start + 1] = '\0'; |
3ff65596 | 2258 | |
ba9ebd0a | 2259 | #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION |
62e76326 | 2260 | |
7a2f978b | 2261 | if ((t = strchr(url, '#'))) /* remove HTML anchors */ |
62e76326 | 2262 | *t = '\0'; |
2263 | ||
ba9ebd0a | 2264 | #endif |
7a2f978b | 2265 | |
5463e4b9 | 2266 | debugs(33,5, HERE << "repare absolute URL from " << (csd->transparent()?"intercept":(csd->port->accel ? "accel":""))); |
3f38a55e | 2267 | /* Rewrite the URL in transparent or accelerator mode */ |
89272111 AJ |
2268 | /* NP: there are several cases to traverse here: |
2269 | * - standard mode (forward proxy) | |
2270 | * - transparent mode (TPROXY) | |
2271 | * - transparent mode with failures | |
2272 | * - intercept mode (NAT) | |
2273 | * - intercept mode with failures | |
2274 | * - accelerator mode (reverse proxy) | |
2275 | * - internal URL | |
2276 | * - mixed combos of the above with internal URL | |
2277 | */ | |
be364179 | 2278 | if (csd->transparent()) { |
89272111 | 2279 | /* intercept or transparent mode, properly working with no failures */ |
be364179 | 2280 | prepareTransparentURL(csd, http, url, req_hdr); |
89272111 | 2281 | |
2f2749d7 | 2282 | } else if (internalCheck(url)) { |
89272111 | 2283 | /* internal URL mode */ |
2f2749d7 | 2284 | /* prepend our name & port */ |
2285 | http->uri = xstrdup(internalLocalUri(NULL, url)); | |
59c59acf AJ |
2286 | // We just re-wrote the URL. Must replace the Host: header. |
2287 | // But have not parsed there yet!! flag for local-only handling. | |
2288 | http->flags.internal = 1; | |
2289 | ||
2290 | } else if (csd->port->accel || csd->switchedToHttps()) { | |
2291 | /* accelerator mode */ | |
2292 | prepareAcceleratedURL(csd, http, url, req_hdr); | |
3f38a55e | 2293 | } |
2294 | ||
2295 | if (!http->uri) { | |
62e76326 | 2296 | /* No special rewrites have been applied above, use the |
2297 | * requested url. may be rewritten later, so make extra room */ | |
2298 | int url_sz = strlen(url) + Config.appendDomainLen + 5; | |
2299 | http->uri = (char *)xcalloc(url_sz, 1); | |
2300 | strcpy(http->uri, url); | |
3f38a55e | 2301 | } |
62e76326 | 2302 | |
bf8fe701 | 2303 | debugs(33, 5, "parseHttpRequest: Complete request received"); |
1ce34ddd AJ |
2304 | |
2305 | // XXX: crop this dump at the end of headers. No need for extras | |
2306 | debugs(11, 2, "HTTP Client " << csd->clientConnection); | |
2307 | debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp->buf) + hp->req.m_start << "\n----------"); | |
2308 | ||
c4b7a5a9 | 2309 | result->flags.parsed_ok = 1; |
84cc2635 | 2310 | xfree(url); |
c8be6d7b | 2311 | return result; |
7a2f978b | 2312 | } |
2313 | ||
c8be6d7b | 2314 | int |
a46d2c0e | 2315 | ConnStateData::getAvailableBufferLength() const |
c8be6d7b | 2316 | { |
f5f9e44c AR |
2317 | assert (in.allocatedSize > in.notYetUsed); // allocated more than used |
2318 | const size_t result = in.allocatedSize - in.notYetUsed - 1; | |
2319 | // huge request_header_max_size may lead to more than INT_MAX unused space | |
2320 | assert (static_cast<ssize_t>(result) <= INT_MAX); | |
1a419b96 | 2321 | return result; |
c8be6d7b | 2322 | } |
2323 | ||
1368d115 CT |
2324 | bool |
2325 | ConnStateData::maybeMakeSpaceAvailable() | |
c8be6d7b | 2326 | { |
a46d2c0e | 2327 | if (getAvailableBufferLength() < 2) { |
90737510 A |
2328 | size_t newSize; |
2329 | if (in.allocatedSize >= Config.maxRequestBufferSize) { | |
2330 | debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config.maxRequestBufferSize); | |
2331 | return false; | |
2332 | } | |
2333 | if ((newSize=in.allocatedSize * 2) > Config.maxRequestBufferSize) { | |
2334 | newSize=Config.maxRequestBufferSize; | |
2335 | } | |
2336 | in.buf = (char *)memReallocBuf(in.buf, newSize, &in.allocatedSize); | |
2337 | debugs(33, 2, "growing request buffer: notYetUsed=" << in.notYetUsed << " size=" << in.allocatedSize); | |
c8be6d7b | 2338 | } |
1368d115 | 2339 | return true; |
c8be6d7b | 2340 | } |
2341 | ||
2342 | void | |
0655fa4d | 2343 | ConnStateData::addContextToQueue(ClientSocketContext * context) |
c8be6d7b | 2344 | { |
0655fa4d | 2345 | ClientSocketContext::Pointer *S; |
62e76326 | 2346 | |
0655fa4d | 2347 | for (S = (ClientSocketContext::Pointer *) & currentobject; S->getRaw(); |
3d0ac046 | 2348 | S = &(*S)->next); |
c8be6d7b | 2349 | *S = context; |
62e76326 | 2350 | |
0655fa4d | 2351 | ++nrequests; |
c8be6d7b | 2352 | } |
2353 | ||
2354 | int | |
0655fa4d | 2355 | ConnStateData::getConcurrentRequestCount() const |
c8be6d7b | 2356 | { |
2357 | int result = 0; | |
0655fa4d | 2358 | ClientSocketContext::Pointer *T; |
62e76326 | 2359 | |
0655fa4d | 2360 | for (T = (ClientSocketContext::Pointer *) ¤tobject; |
3d0ac046 | 2361 | T->getRaw(); T = &(*T)->next, ++result); |
c8be6d7b | 2362 | return result; |
2363 | } | |
2364 | ||
2365 | int | |
1cf238db | 2366 | ConnStateData::connReadWasError(comm_err_t flag, int size, int xerrno) |
c8be6d7b | 2367 | { |
c4b7a5a9 | 2368 | if (flag != COMM_OK) { |
73c36fd9 | 2369 | debugs(33, 2, "connReadWasError: FD " << clientConnection << ": got flag " << flag); |
62e76326 | 2370 | return 1; |
c4b7a5a9 | 2371 | } |
62e76326 | 2372 | |
c8be6d7b | 2373 | if (size < 0) { |
f3400a93 | 2374 | if (!ignoreErrno(xerrno)) { |
73c36fd9 | 2375 | debugs(33, 2, "connReadWasError: FD " << clientConnection << ": " << xstrerr(xerrno)); |
62e76326 | 2376 | return 1; |
1cf238db | 2377 | } else if (in.notYetUsed == 0) { |
73c36fd9 | 2378 | debugs(33, 2, "connReadWasError: FD " << clientConnection << ": no data to process (" << xstrerr(xerrno) << ")"); |
62e76326 | 2379 | } |
c8be6d7b | 2380 | } |
62e76326 | 2381 | |
c8be6d7b | 2382 | return 0; |
2383 | } | |
2384 | ||
2385 | int | |
1cf238db | 2386 | ConnStateData::connFinishedWithConn(int size) |
c8be6d7b | 2387 | { |
2388 | if (size == 0) { | |
1cf238db | 2389 | if (getConcurrentRequestCount() == 0 && in.notYetUsed == 0) { |
62e76326 | 2390 | /* no current or pending requests */ |
73c36fd9 | 2391 | debugs(33, 4, HERE << clientConnection << " closed"); |
62e76326 | 2392 | return 1; |
2393 | } else if (!Config.onoff.half_closed_clients) { | |
2394 | /* admin doesn't want to support half-closed client sockets */ | |
73c36fd9 | 2395 | debugs(33, 3, HERE << clientConnection << " aborted (half_closed_clients disabled)"); |
f692498b | 2396 | notifyAllContexts(0); // no specific error implies abort |
62e76326 | 2397 | return 1; |
2398 | } | |
c8be6d7b | 2399 | } |
62e76326 | 2400 | |
c8be6d7b | 2401 | return 0; |
2402 | } | |
2403 | ||
2404 | void | |
3b299123 | 2405 | connNoteUseOfBuffer(ConnStateData* conn, size_t byteCount) |
c8be6d7b | 2406 | { |
2407 | assert(byteCount > 0 && byteCount <= conn->in.notYetUsed); | |
2408 | conn->in.notYetUsed -= byteCount; | |
d5fa7219 | 2409 | debugs(33, 5, HERE << "conn->in.notYetUsed = " << conn->in.notYetUsed); |
c8be6d7b | 2410 | /* |
9e008dda | 2411 | * If there is still data that will be used, |
c8be6d7b | 2412 | * move it to the beginning. |
2413 | */ | |
62e76326 | 2414 | |
c8be6d7b | 2415 | if (conn->in.notYetUsed > 0) |
41d00cd3 | 2416 | memmove(conn->in.buf, conn->in.buf + byteCount, conn->in.notYetUsed); |
c8be6d7b | 2417 | } |
2418 | ||
39cb8c41 AR |
2419 | /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size |
2420 | void | |
2421 | ConnStateData::checkHeaderLimits() | |
c8be6d7b | 2422 | { |
39cb8c41 AR |
2423 | if (in.notYetUsed < Config.maxRequestHeaderSize) |
2424 | return; // can accumulte more header data | |
3ff65596 | 2425 | |
39cb8c41 | 2426 | debugs(33, 3, "Request header is too large (" << in.notYetUsed << " > " << |
de48b288 | 2427 | Config.maxRequestHeaderSize << " bytes)"); |
c8be6d7b | 2428 | |
39cb8c41 | 2429 | ClientSocketContext *context = parseHttpRequestAbort(this, "error:request-too-large"); |
528b2c61 | 2430 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2431 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2432 | assert (repContext); | |
2433 | repContext->setReplyToError(ERR_TOO_BIG, | |
39cb8c41 | 2434 | HTTP_BAD_REQUEST, METHOD_NONE, NULL, |
73c36fd9 | 2435 | clientConnection->remote, NULL, NULL, NULL); |
0655fa4d | 2436 | context->registerWithConn(); |
528b2c61 | 2437 | context->pullData(); |
c8be6d7b | 2438 | } |
2439 | ||
1cf238db | 2440 | void |
f35961af | 2441 | ConnStateData::clientAfterReadingRequests() |
c4b7a5a9 | 2442 | { |
39cb8c41 | 2443 | // Were we expecting to read more request body from half-closed connection? |
73c36fd9 AJ |
2444 | if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection->fd)) { |
2445 | debugs(33, 3, HERE << "truncated body: closing half-closed " << clientConnection); | |
2446 | clientConnection->close(); | |
39cb8c41 | 2447 | return; |
c4b7a5a9 | 2448 | } |
2449 | ||
f35961af AR |
2450 | if (flags.readMore) |
2451 | readSomeData(); | |
c4b7a5a9 | 2452 | } |
2453 | ||
84c77748 AR |
2454 | void |
2455 | ConnStateData::quitAfterError(HttpRequest *request) | |
2456 | { | |
2457 | // From HTTP p.o.v., we do not have to close after every error detected | |
2458 | // at the client-side, but many such errors do require closure and the | |
2459 | // client-side code is bad at handling errors so we play it safe. | |
2460 | if (request) | |
2461 | request->flags.proxy_keepalive = 0; | |
2462 | flags.readMore = false; | |
2463 | debugs(33,4, HERE << "Will close after error: " << clientConnection); | |
2464 | } | |
2465 | ||
8eb0a7ee CT |
2466 | #if USE_SSL |
2467 | bool ConnStateData::serveDelayedError(ClientSocketContext *context) | |
2468 | { | |
2469 | ClientHttpRequest *http = context->http; | |
fd4624d7 CT |
2470 | |
2471 | if (!sslServerBump) | |
8eb0a7ee CT |
2472 | return false; |
2473 | ||
fd4624d7 CT |
2474 | assert(sslServerBump->entry); |
2475 | if (!sslServerBump->entry->isEmpty()) { | |
84c77748 AR |
2476 | quitAfterError(http->request); |
2477 | ||
8eb0a7ee CT |
2478 | //Failed? Here we should get the error from conn and send it to client |
2479 | // The error stored in ConnStateData::bumpFirstEntry, replace the | |
2480 | // ClientHttpRequest store entry with this. | |
2481 | clientStreamNode *node = context->getClientReplyContext(); | |
2482 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
2483 | assert (repContext); | |
2484 | debugs(33, 5, "Connection first has failed for " << http->uri << ". Respond with an error"); | |
fd4624d7 | 2485 | repContext->setReplyToStoreEntry(sslServerBump->entry); |
8eb0a7ee | 2486 | context->pullData(); |
8eb0a7ee CT |
2487 | return true; |
2488 | } | |
2489 | ||
2490 | // We are in ssl-bump first mode. We have not the server connect name when | |
2491 | // we connected to server so we have to check certificates subject with our server name | |
fd4624d7 | 2492 | if (sslServerBump && sslServerBump->serverCert.get()) { |
8eb0a7ee | 2493 | HttpRequest *request = http->request; |
fd4624d7 | 2494 | if (!Ssl::checkX509ServerValidity(sslServerBump->serverCert.get(), request->GetHost())) { |
8eb0a7ee CT |
2495 | debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate does not match domainname " << request->GetHost()); |
2496 | ||
2497 | ACLFilledChecklist check(Config.ssl_client.cert_error, request, dash_str); | |
7d82c5b8 | 2498 | check.sslErrorList = new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH); |
8eb0a7ee CT |
2499 | if (Comm::IsConnOpen(pinning.serverConnection)) |
2500 | check.fd(pinning.serverConnection->fd); | |
7d82c5b8 CT |
2501 | bool allowDomainMismatch = (check.fastCheck() == ACCESS_ALLOWED); |
2502 | delete check.sslErrorList; | |
2503 | check.sslErrorList = NULL; | |
8eb0a7ee | 2504 | |
7d82c5b8 | 2505 | if (!allowDomainMismatch) { |
84c77748 AR |
2506 | quitAfterError(request); |
2507 | ||
8eb0a7ee CT |
2508 | clientStreamNode *node = context->getClientReplyContext(); |
2509 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
2510 | assert (repContext); | |
2511 | ||
06b4e9c8 | 2512 | // Fill the server ip address and server hostname for use with ErrorState |
fd4624d7 CT |
2513 | HttpRequest::Pointer const & peekerRequest = sslServerBump->request; |
2514 | request->hier.note(peekerRequest->hier.tcpServer, request->GetHost()); | |
8eb0a7ee | 2515 | // Create an error object and fill it |
03f00a11 CT |
2516 | ErrorState *err = new ErrorState(ERR_SECURE_CONNECT_FAIL, HTTP_SERVICE_UNAVAILABLE, request); |
2517 | ||
8eb0a7ee CT |
2518 | err->src_addr = clientConnection->remote; |
2519 | #ifdef EPROTO | |
2520 | err->xerrno = EPROTO; | |
2521 | #else | |
2522 | err->xerrno = EACCES; | |
2523 | #endif | |
fd4624d7 | 2524 | Ssl::ErrorDetail *errDetail = new Ssl::ErrorDetail( SQUID_X509_V_ERR_DOMAIN_MISMATCH, sslServerBump->serverCert.get(), NULL); |
8eb0a7ee CT |
2525 | err->detail = errDetail; |
2526 | repContext->setReplyToError(request->method, err); | |
2527 | assert(context->http->out.offset == 0); | |
2528 | context->pullData(); | |
8eb0a7ee CT |
2529 | return true; |
2530 | } | |
2531 | } | |
2532 | } | |
2533 | ||
2534 | return false; | |
2535 | } | |
2536 | #endif //USE_SSL | |
2537 | ||
c4b7a5a9 | 2538 | static void |
1cf238db | 2539 | clientProcessRequest(ConnStateData *conn, HttpParser *hp, ClientSocketContext *context, const HttpRequestMethod& method, HttpVersion http_ver) |
c4b7a5a9 | 2540 | { |
59a1efb2 | 2541 | ClientHttpRequest *http = context->http; |
190154cf | 2542 | HttpRequest *request = NULL; |
5f8252d2 | 2543 | bool notedUseOfBuffer = false; |
39cb8c41 | 2544 | bool chunked = false; |
e18b8316 | 2545 | bool mustReplyToOptions = false; |
3ff65596 | 2546 | bool unsupportedTe = false; |
39cb8c41 | 2547 | bool expectBody = false; |
5f8252d2 | 2548 | |
c4b7a5a9 | 2549 | /* We have an initial client stream in place should it be needed */ |
2550 | /* setup our private context */ | |
0655fa4d | 2551 | context->registerWithConn(); |
c4b7a5a9 | 2552 | |
2553 | if (context->flags.parsed_ok == 0) { | |
62e76326 | 2554 | clientStreamNode *node = context->getClientReplyContext(); |
f4762666 | 2555 | debugs(33, 2, "clientProcessRequest: Invalid Request"); |
84c77748 | 2556 | conn->quitAfterError(NULL); |
727552f4 CT |
2557 | // setLogUri should called before repContext->setReplyToError |
2558 | setLogUri(http, http->uri, true); | |
0655fa4d | 2559 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2560 | assert (repContext); | |
e212e5e3 | 2561 | switch (hp->request_parse_status) { |
719c7e0a | 2562 | case HTTP_HEADER_TOO_LARGE: |
73c36fd9 | 2563 | repContext->setReplyToError(ERR_TOO_BIG, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, conn->in.buf, NULL); |
719c7e0a AJ |
2564 | break; |
2565 | case HTTP_METHOD_NOT_ALLOWED: | |
be364179 | 2566 | repContext->setReplyToError(ERR_UNSUP_REQ, HTTP_METHOD_NOT_ALLOWED, method, http->uri, |
73c36fd9 | 2567 | conn->clientConnection->remote, NULL, conn->in.buf, NULL); |
719c7e0a AJ |
2568 | break; |
2569 | default: | |
9815f129 | 2570 | repContext->setReplyToError(ERR_INVALID_REQ, hp->request_parse_status, method, http->uri, |
73c36fd9 | 2571 | conn->clientConnection->remote, NULL, conn->in.buf, NULL); |
719c7e0a | 2572 | } |
62e76326 | 2573 | assert(context->http->out.offset == 0); |
2574 | context->pullData(); | |
fc68f6b1 | 2575 | goto finish; |
c4b7a5a9 | 2576 | } |
2577 | ||
c21ad0f5 | 2578 | if ((request = HttpRequest::CreateFromUrlAndMethod(http->uri, method)) == NULL) { |
62e76326 | 2579 | clientStreamNode *node = context->getClientReplyContext(); |
bf8fe701 | 2580 | debugs(33, 5, "Invalid URL: " << http->uri); |
84c77748 | 2581 | conn->quitAfterError(request); |
727552f4 CT |
2582 | // setLogUri should called before repContext->setReplyToError |
2583 | setLogUri(http, http->uri, true); | |
0655fa4d | 2584 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2585 | assert (repContext); | |
73c36fd9 | 2586 | repContext->setReplyToError(ERR_INVALID_URL, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL); |
62e76326 | 2587 | assert(context->http->out.offset == 0); |
2588 | context->pullData(); | |
fc68f6b1 | 2589 | goto finish; |
62e76326 | 2590 | } |
c4b7a5a9 | 2591 | |
e57c1885 AJ |
2592 | /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */ |
2593 | /* We currently only accept 0.9, 1.0, 1.1 */ | |
2594 | if ( (http_ver.major == 0 && http_ver.minor != 9) || | |
af6a12ee AJ |
2595 | (http_ver.major == 1 && http_ver.minor > 1 ) || |
2596 | (http_ver.major > 1) ) { | |
e57c1885 AJ |
2597 | |
2598 | clientStreamNode *node = context->getClientReplyContext(); | |
2599 | debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp)); | |
84c77748 | 2600 | conn->quitAfterError(request); |
727552f4 CT |
2601 | // setLogUri should called before repContext->setReplyToError |
2602 | setLogUri(http, http->uri, true); | |
e57c1885 AJ |
2603 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2604 | assert (repContext); | |
be364179 | 2605 | repContext->setReplyToError(ERR_UNSUP_HTTPVERSION, HTTP_HTTP_VERSION_NOT_SUPPORTED, method, http->uri, |
73c36fd9 | 2606 | conn->clientConnection->remote, NULL, HttpParserHdrBuf(hp), NULL); |
e57c1885 AJ |
2607 | assert(context->http->out.offset == 0); |
2608 | context->pullData(); | |
e57c1885 AJ |
2609 | goto finish; |
2610 | } | |
2611 | ||
528b2c61 | 2612 | /* compile headers */ |
2613 | /* we should skip request line! */ | |
666f514b | 2614 | /* XXX should actually know the damned buffer size here */ |
38e82382 | 2615 | if (http_ver.major >= 1 && !request->parseHeader(HttpParserHdrBuf(hp), HttpParserHdrSz(hp))) { |
47ac2ebe | 2616 | clientStreamNode *node = context->getClientReplyContext(); |
bf8fe701 | 2617 | debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp)); |
84c77748 | 2618 | conn->quitAfterError(request); |
727552f4 CT |
2619 | // setLogUri should called before repContext->setReplyToError |
2620 | setLogUri(http, http->uri, true); | |
47ac2ebe | 2621 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2622 | assert (repContext); | |
73c36fd9 | 2623 | repContext->setReplyToError(ERR_INVALID_REQ, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL); |
47ac2ebe | 2624 | assert(context->http->out.offset == 0); |
2625 | context->pullData(); | |
fc68f6b1 | 2626 | goto finish; |
47ac2ebe | 2627 | } |
c4b7a5a9 | 2628 | |
40d34a62 AJ |
2629 | request->clientConnectionManager = conn; |
2630 | ||
c4b7a5a9 | 2631 | request->flags.accelerated = http->flags.accel; |
b68415a1 | 2632 | request->flags.sslBumped = conn->switchedToHttps(); |
85563fd9 | 2633 | request->flags.canRePin = request->flags.sslBumped && conn->pinning.pinned; |
432bc83c | 2634 | request->flags.ignore_cc = conn->port->ignore_cc; |
7fb65ee4 AR |
2635 | // TODO: decouple http->flags.accel from request->flags.sslBumped |
2636 | request->flags.no_direct = (request->flags.accelerated && !request->flags.sslBumped) ? | |
2637 | !conn->port->allow_direct : 0; | |
21512911 CT |
2638 | #if USE_AUTH |
2639 | if (request->flags.sslBumped) { | |
2640 | if (conn->auth_user_request != NULL) | |
2641 | request->auth_user_request = conn->auth_user_request; | |
2642 | } | |
2643 | #endif | |
2ad20b4f AJ |
2644 | |
2645 | /** \par | |
2646 | * If transparent or interception mode is working clone the transparent and interception flags | |
2647 | * from the port settings to the request. | |
2648 | */ | |
40d34a62 | 2649 | if (http->clientConnection != NULL) { |
379e8c1c AR |
2650 | request->flags.intercepted = ((http->clientConnection->flags & COMM_INTERCEPTION) != 0); |
2651 | request->flags.spoof_client_ip = ((http->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ; | |
2ad20b4f | 2652 | } |
fc68f6b1 | 2653 | |
5b4117d8 | 2654 | if (internalCheck(request->urlpath.termedBuf())) { |
cc192b50 | 2655 | if (internalHostnameIs(request->GetHost()) && |
f024c970 | 2656 | request->port == getMyPort()) { |
2657 | http->flags.internal = 1; | |
9c175897 | 2658 | } else if (Config.onoff.global_internal_static && internalStaticCheck(request->urlpath.termedBuf())) { |
cc192b50 | 2659 | request->SetHost(internalHostname()); |
f024c970 | 2660 | request->port = getMyPort(); |
2661 | http->flags.internal = 1; | |
62e76326 | 2662 | } |
f024c970 | 2663 | } |
e72a0ec0 | 2664 | |
f024c970 | 2665 | if (http->flags.internal) { |
0c3d3f65 | 2666 | request->protocol = AnyP::PROTO_HTTP; |
f024c970 | 2667 | request->login[0] = '\0'; |
c4b7a5a9 | 2668 | } |
2669 | ||
c4b7a5a9 | 2670 | request->flags.internal = http->flags.internal; |
2671 | setLogUri (http, urlCanonicalClean(request)); | |
73c36fd9 | 2672 | request->client_addr = conn->clientConnection->remote; // XXX: remove reuest->client_addr member. |
3d674977 | 2673 | #if FOLLOW_X_FORWARDED_FOR |
40d34a62 AJ |
2674 | // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:) |
2675 | // not a details about teh TCP connection itself | |
73c36fd9 | 2676 | request->indirect_client_addr = conn->clientConnection->remote; |
3d674977 | 2677 | #endif /* FOLLOW_X_FORWARDED_FOR */ |
73c36fd9 | 2678 | request->my_addr = conn->clientConnection->local; |
35fb56c9 | 2679 | request->myportname = conn->port->name; |
8ae66e43 | 2680 | request->http_ver = http_ver; |
62e76326 | 2681 | |
9174ba3d AJ |
2682 | // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it |
2683 | // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later. | |
2684 | request->clientConnectionManager = conn; | |
2685 | ||
39cb8c41 AR |
2686 | if (request->header.chunked()) { |
2687 | chunked = true; | |
2688 | } else if (request->header.has(HDR_TRANSFER_ENCODING)) { | |
2689 | const String te = request->header.getList(HDR_TRANSFER_ENCODING); | |
2690 | // HTTP/1.1 requires chunking to be the last encoding if there is one | |
2691 | unsupportedTe = te.size() && te != "identity"; | |
2692 | } // else implied identity coding | |
de48b288 | 2693 | |
34ee6e73 | 2694 | mustReplyToOptions = (method == METHOD_OPTIONS) && |
d916dcb8 | 2695 | (request->header.getInt64(HDR_MAX_FORWARDS) == 0); |
e18b8316 | 2696 | if (!urlCheckRequest(request) || mustReplyToOptions || unsupportedTe) { |
62e76326 | 2697 | clientStreamNode *node = context->getClientReplyContext(); |
84c77748 | 2698 | conn->quitAfterError(request); |
0655fa4d | 2699 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2700 | assert (repContext); | |
be364179 | 2701 | repContext->setReplyToError(ERR_UNSUP_REQ, HTTP_NOT_IMPLEMENTED, request->method, NULL, |
73c36fd9 | 2702 | conn->clientConnection->remote, request, NULL, NULL); |
62e76326 | 2703 | assert(context->http->out.offset == 0); |
2704 | context->pullData(); | |
fc68f6b1 | 2705 | goto finish; |
c4b7a5a9 | 2706 | } |
2707 | ||
2708 | ||
39cb8c41 | 2709 | if (!chunked && !clientIsContentLengthValid(request)) { |
62e76326 | 2710 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2711 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2712 | assert (repContext); | |
84c77748 | 2713 | conn->quitAfterError(request); |
0655fa4d | 2714 | repContext->setReplyToError(ERR_INVALID_REQ, |
2715 | HTTP_LENGTH_REQUIRED, request->method, NULL, | |
73c36fd9 | 2716 | conn->clientConnection->remote, request, NULL, NULL); |
62e76326 | 2717 | assert(context->http->out.offset == 0); |
2718 | context->pullData(); | |
fc68f6b1 | 2719 | goto finish; |
c4b7a5a9 | 2720 | } |
2721 | ||
52b601ff | 2722 | if (request->header.has(HDR_EXPECT)) { |
655daa06 AR |
2723 | const String expect = request->header.getList(HDR_EXPECT); |
2724 | const bool supportedExpect = (expect.caseCmp("100-continue") == 0); | |
2725 | if (!supportedExpect) { | |
52b601ff AJ |
2726 | clientStreamNode *node = context->getClientReplyContext(); |
2727 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
2728 | assert (repContext); | |
84c77748 | 2729 | conn->quitAfterError(request); |
be364179 | 2730 | repContext->setReplyToError(ERR_INVALID_REQ, HTTP_EXPECTATION_FAILED, request->method, http->uri, |
73c36fd9 | 2731 | conn->clientConnection->remote, request, NULL, NULL); |
52b601ff AJ |
2732 | assert(context->http->out.offset == 0); |
2733 | context->pullData(); | |
2734 | goto finish; | |
2735 | } | |
2736 | } | |
2737 | ||
6dd9f4bd | 2738 | http->request = HTTPMSGLOCK(request); |
c4b7a5a9 | 2739 | clientSetKeepaliveFlag(http); |
62e76326 | 2740 | |
f35961af AR |
2741 | // Let tunneling code be fully responsible for CONNECT requests |
2742 | if (http->request->method == METHOD_CONNECT) { | |
b66e0e86 | 2743 | context->mayUseConnection(true); |
f35961af AR |
2744 | conn->flags.readMore = false; |
2745 | } | |
fc68f6b1 | 2746 | |
061bbdec | 2747 | #if USE_SSL |
8eb0a7ee | 2748 | if (conn->switchedToHttps() && conn->serveDelayedError(context)) |
061bbdec | 2749 | goto finish; |
061bbdec CT |
2750 | #endif |
2751 | ||
b66e0e86 | 2752 | /* Do we expect a request-body? */ |
39cb8c41 AR |
2753 | expectBody = chunked || request->content_length > 0; |
2754 | if (!context->mayUseConnection() && expectBody) { | |
2755 | request->body_pipe = conn->expectRequestBody( | |
de48b288 | 2756 | chunked ? -1 : request->content_length); |
5f8252d2 | 2757 | |
2758 | // consume header early so that body pipe gets just the body | |
1cf238db | 2759 | connNoteUseOfBuffer(conn, http->req_sz); |
5f8252d2 | 2760 | notedUseOfBuffer = true; |
2761 | ||
62e76326 | 2762 | /* Is it too large? */ |
39cb8c41 | 2763 | if (!chunked && // if chunked, we will check as we accumulate |
de48b288 | 2764 | clientIsRequestBodyTooLargeForPolicy(request->content_length)) { |
62e76326 | 2765 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 2766 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
2767 | assert (repContext); | |
84c77748 | 2768 | conn->quitAfterError(request); |
0655fa4d | 2769 | repContext->setReplyToError(ERR_TOO_BIG, |
2770 | HTTP_REQUEST_ENTITY_TOO_LARGE, METHOD_NONE, NULL, | |
73c36fd9 | 2771 | conn->clientConnection->remote, http->request, NULL, NULL); |
62e76326 | 2772 | assert(context->http->out.offset == 0); |
2773 | context->pullData(); | |
5f8252d2 | 2774 | goto finish; |
62e76326 | 2775 | } |
2776 | ||
39cb8c41 AR |
2777 | // We may stop producing, comm_close, and/or call setReplyToError() |
2778 | // below, so quit on errors to avoid http->doCallouts() | |
2779 | if (!conn->handleRequestBodyData()) | |
de48b288 | 2780 | goto finish; |
39cb8c41 | 2781 | |
f35961af AR |
2782 | if (!request->body_pipe->productionEnded()) { |
2783 | debugs(33, 5, HERE << "need more request body"); | |
2784 | context->mayUseConnection(true); | |
2785 | assert(conn->flags.readMore); | |
2786 | } | |
c4b7a5a9 | 2787 | } |
2788 | ||
de31d06f | 2789 | http->calloutContext = new ClientRequestContext(http); |
2790 | ||
2791 | http->doCallouts(); | |
9e008dda | 2792 | |
4c29340e | 2793 | finish: |
5f8252d2 | 2794 | if (!notedUseOfBuffer) |
1cf238db | 2795 | connNoteUseOfBuffer(conn, http->req_sz); |
52c2c8a8 | 2796 | |
2797 | /* | |
2798 | * DPW 2007-05-18 | |
2799 | * Moved the TCP_RESET feature from clientReplyContext::sendMoreData | |
2800 | * to here because calling comm_reset_close() causes http to | |
2801 | * be freed and the above connNoteUseOfBuffer() would hit an | |
2802 | * assertion, not to mention that we were accessing freed memory. | |
2803 | */ | |
b8faead9 | 2804 | if (request && request->flags.resetTCP() && Comm::IsConnOpen(conn->clientConnection)) { |
73c36fd9 | 2805 | debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection); |
f35961af | 2806 | conn->flags.readMore = false; |
73c36fd9 | 2807 | comm_reset_close(conn->clientConnection); |
52c2c8a8 | 2808 | } |
c4b7a5a9 | 2809 | } |
2810 | ||
2811 | static void | |
1cf238db | 2812 | connStripBufferWhitespace (ConnStateData * conn) |
c4b7a5a9 | 2813 | { |
2814 | while (conn->in.notYetUsed > 0 && xisspace(conn->in.buf[0])) { | |
41d00cd3 | 2815 | memmove(conn->in.buf, conn->in.buf + 1, conn->in.notYetUsed - 1); |
62e76326 | 2816 | --conn->in.notYetUsed; |
c4b7a5a9 | 2817 | } |
2818 | } | |
2819 | ||
2820 | static int | |
1cf238db | 2821 | connOkToAddRequest(ConnStateData * conn) |
c4b7a5a9 | 2822 | { |
0655fa4d | 2823 | int result = conn->getConcurrentRequestCount() < (Config.onoff.pipeline_prefetch ? 2 : 1); |
62e76326 | 2824 | |
c4b7a5a9 | 2825 | if (!result) { |
73c36fd9 AJ |
2826 | debugs(33, 3, HERE << conn->clientConnection << " max concurrent requests reached"); |
2827 | debugs(33, 5, HERE << conn->clientConnection << " defering new request until one is done"); | |
c4b7a5a9 | 2828 | } |
62e76326 | 2829 | |
c4b7a5a9 | 2830 | return result; |
2831 | } | |
2832 | ||
63be0a78 | 2833 | /** |
f900210a | 2834 | * Attempt to parse one or more requests from the input buffer. |
2835 | * If a request is successfully parsed, even if the next request | |
2836 | * is only partially parsed, it will return TRUE. | |
f900210a | 2837 | */ |
4959e21e | 2838 | bool |
f35961af | 2839 | ConnStateData::clientParseRequests() |
f900210a | 2840 | { |
60745f24 | 2841 | HttpRequestMethod method; |
f900210a | 2842 | bool parsed_req = false; |
8ae66e43 | 2843 | HttpVersion http_ver; |
f900210a | 2844 | |
1b76e6c1 | 2845 | debugs(33, 5, HERE << clientConnection << ": attempting to parse"); |
f900210a | 2846 | |
39cb8c41 | 2847 | // Loop while we have read bytes that are not needed for producing the body |
f35961af AR |
2848 | // On errors, bodyPipe may become nil, but readMore will be cleared |
2849 | while (in.notYetUsed > 0 && !bodyPipe && flags.readMore) { | |
4959e21e | 2850 | connStripBufferWhitespace(this); |
f900210a | 2851 | |
fc68f6b1 | 2852 | /* Don't try to parse if the buffer is empty */ |
4959e21e | 2853 | if (in.notYetUsed == 0) |
fc68f6b1 | 2854 | break; |
4681057e | 2855 | |
f900210a | 2856 | /* Limit the number of concurrent requests to 2 */ |
4959e21e | 2857 | if (!connOkToAddRequest(this)) { |
f900210a | 2858 | break; |
2859 | } | |
2860 | ||
2861 | /* Should not be needed anymore */ | |
2862 | /* Terminate the string */ | |
4959e21e | 2863 | in.buf[in.notYetUsed] = '\0'; |
f900210a | 2864 | |
fc68f6b1 | 2865 | /* Begin the parsing */ |
fc68f6b1 | 2866 | PROF_start(parseHttpRequest); |
4959e21e | 2867 | HttpParserInit(&parser_, in.buf, in.notYetUsed); |
fc68f6b1 | 2868 | |
4959e21e AJ |
2869 | /* Process request */ |
2870 | ClientSocketContext *context = parseHttpRequest(this, &parser_, &method, &http_ver); | |
fc68f6b1 | 2871 | PROF_stop(parseHttpRequest); |
f900210a | 2872 | |
2873 | /* partial or incomplete request */ | |
2874 | if (!context) { | |
39cb8c41 AR |
2875 | // TODO: why parseHttpRequest can just return parseHttpRequestAbort |
2876 | // (which becomes context) but checkHeaderLimits cannot? | |
4959e21e | 2877 | checkHeaderLimits(); |
f900210a | 2878 | break; |
2879 | } | |
2880 | ||
2881 | /* status -1 or 1 */ | |
2882 | if (context) { | |
1b76e6c1 | 2883 | debugs(33, 5, HERE << clientConnection << ": parsed a request"); |
8d77a37c | 2884 | AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout", |
dc49061a | 2885 | CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http)); |
1b76e6c1 | 2886 | commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall); |
f900210a | 2887 | |
4959e21e | 2888 | clientProcessRequest(this, &parser_, context, method, http_ver); |
f900210a | 2889 | |
4959e21e | 2890 | parsed_req = true; // XXX: do we really need to parse everything right NOW ? |
f900210a | 2891 | |
2892 | if (context->mayUseConnection()) { | |
f35961af | 2893 | debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection"); |
f900210a | 2894 | break; |
2895 | } | |
f900210a | 2896 | } |
39cb8c41 | 2897 | } |
fc68f6b1 | 2898 | |
a5baffba | 2899 | /* XXX where to 'finish' the parsing pass? */ |
f900210a | 2900 | return parsed_req; |
2901 | } | |
2902 | ||
1cf238db | 2903 | void |
2904 | ConnStateData::clientReadRequest(const CommIoCbParams &io) | |
c4b7a5a9 | 2905 | { |
be364179 | 2906 | debugs(33,5,HERE << io.conn << " size " << io.size); |
f84dd7eb AR |
2907 | Must(reading()); |
2908 | reader = NULL; | |
c4b7a5a9 | 2909 | |
c4b7a5a9 | 2910 | /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */ |
62e76326 | 2911 | |
1cf238db | 2912 | if (io.flag == COMM_ERR_CLOSING) { |
be364179 | 2913 | debugs(33,5, HERE << io.conn << " closing Bailout."); |
c4b7a5a9 | 2914 | return; |
2915 | } | |
62e76326 | 2916 | |
73c36fd9 AJ |
2917 | assert(Comm::IsConnOpen(clientConnection)); |
2918 | assert(io.conn->fd == clientConnection->fd); | |
5c336a3b | 2919 | |
44db45e8 | 2920 | /* |
2921 | * Don't reset the timeout value here. The timeout value will be | |
2922 | * set to Config.Timeout.request by httpAccept() and | |
2923 | * clientWriteComplete(), and should apply to the request as a | |
2924 | * whole, not individual read() calls. Plus, it breaks our | |
2925 | * lame half-close detection | |
2926 | */ | |
1cf238db | 2927 | if (connReadWasError(io.flag, io.size, io.xerrno)) { |
f692498b | 2928 | notifyAllContexts(io.xerrno); |
be364179 | 2929 | io.conn->close(); |
62e76326 | 2930 | return; |
7a2f978b | 2931 | } |
c4b7a5a9 | 2932 | |
1cf238db | 2933 | if (io.flag == COMM_OK) { |
2934 | if (io.size > 0) { | |
e4f1fdae | 2935 | kb_incr(&(statCounter.client_http.kbytes_in), io.size); |
3b299123 | 2936 | |
39cb8c41 AR |
2937 | // may comm_close or setReplyToError |
2938 | if (!handleReadData(io.buf, io.size)) | |
9e008dda | 2939 | return; |
a31a78fb | 2940 | |
1cf238db | 2941 | } else if (io.size == 0) { |
be364179 | 2942 | debugs(33, 5, HERE << io.conn << " closed?"); |
62e76326 | 2943 | |
1cf238db | 2944 | if (connFinishedWithConn(io.size)) { |
73c36fd9 | 2945 | clientConnection->close(); |
62e76326 | 2946 | return; |
2947 | } | |
2948 | ||
2949 | /* It might be half-closed, we can't tell */ | |
be364179 | 2950 | fd_table[io.conn->fd].flags.socket_eof = 1; |
62e76326 | 2951 | |
be364179 | 2952 | commMarkHalfClosed(io.conn->fd); |
a46d2c0e | 2953 | |
be364179 | 2954 | fd_note(io.conn->fd, "half-closed"); |
62e76326 | 2955 | |
2956 | /* There is one more close check at the end, to detect aborted | |
2957 | * (partial) requests. At this point we can't tell if the request | |
2958 | * is partial. | |
2959 | */ | |
2960 | /* Continue to process previously read data */ | |
2961 | } | |
c4b7a5a9 | 2962 | } |
2963 | ||
94439e4e | 2964 | /* Process next request */ |
1cf238db | 2965 | if (getConcurrentRequestCount() == 0) |
5c336a3b | 2966 | fd_note(io.fd, "Reading next request"); |
c8be6d7b | 2967 | |
f35961af | 2968 | if (!clientParseRequests()) { |
9e008dda AJ |
2969 | if (!isOpen()) |
2970 | return; | |
f900210a | 2971 | /* |
2972 | * If the client here is half closed and we failed | |
2973 | * to parse a request, close the connection. | |
2974 | * The above check with connFinishedWithConn() only | |
2975 | * succeeds _if_ the buffer is empty which it won't | |
2976 | * be if we have an incomplete request. | |
6e1d409c | 2977 | * XXX: This duplicates ClientSocketContext::keepaliveNextRequest |
f900210a | 2978 | */ |
5c336a3b | 2979 | if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io.fd)) { |
be364179 | 2980 | debugs(33, 5, HERE << io.conn << ": half-closed connection, no completed request parsed, connection closing."); |
73c36fd9 | 2981 | clientConnection->close(); |
ee6f0213 | 2982 | return; |
62e76326 | 2983 | } |
f900210a | 2984 | } |
ee6f0213 | 2985 | |
1cf238db | 2986 | if (!isOpen()) |
2e216b1d | 2987 | return; |
2988 | ||
f35961af | 2989 | clientAfterReadingRequests(); |
94439e4e | 2990 | } |
2991 | ||
63be0a78 | 2992 | /** |
2993 | * called when new request data has been read from the socket | |
39cb8c41 AR |
2994 | * |
2995 | * \retval false called comm_close or setReplyToError (the caller should bail) | |
2996 | * \retval true we did not call comm_close or setReplyToError | |
63be0a78 | 2997 | */ |
39cb8c41 | 2998 | bool |
5f8252d2 | 2999 | ConnStateData::handleReadData(char *buf, size_t size) |
94439e4e | 3000 | { |
5f8252d2 | 3001 | char *current_buf = in.addressToReadInto(); |
62e76326 | 3002 | |
5f8252d2 | 3003 | if (buf != current_buf) |
41d00cd3 | 3004 | memmove(current_buf, buf, size); |
3b299123 | 3005 | |
5f8252d2 | 3006 | in.notYetUsed += size; |
fc68f6b1 | 3007 | |
5f8252d2 | 3008 | in.buf[in.notYetUsed] = '\0'; /* Terminate the string */ |
3b299123 | 3009 | |
5f8252d2 | 3010 | // if we are reading a body, stuff data into the body pipe |
3011 | if (bodyPipe != NULL) | |
39cb8c41 AR |
3012 | return handleRequestBodyData(); |
3013 | return true; | |
94439e4e | 3014 | } |
3015 | ||
63be0a78 | 3016 | /** |
bb790702 | 3017 | * called when new request body data has been buffered in in.buf |
63be0a78 | 3018 | * may close the connection if we were closing and piped everything out |
39cb8c41 AR |
3019 | * |
3020 | * \retval false called comm_close or setReplyToError (the caller should bail) | |
3021 | * \retval true we did not call comm_close or setReplyToError | |
63be0a78 | 3022 | */ |
39cb8c41 | 3023 | bool |
5f8252d2 | 3024 | ConnStateData::handleRequestBodyData() |
94439e4e | 3025 | { |
5f8252d2 | 3026 | assert(bodyPipe != NULL); |
3027 | ||
e1381638 | 3028 | size_t putSize = 0; |
3ff65596 | 3029 | |
39cb8c41 AR |
3030 | if (in.bodyParser) { // chunked encoding |
3031 | if (const err_type error = handleChunkedRequestBody(putSize)) { | |
3032 | abortChunkedRequestBody(error); | |
3033 | return false; | |
3ff65596 | 3034 | } |
39cb8c41 | 3035 | } else { // identity encoding |
73c36fd9 | 3036 | debugs(33,5, HERE << "handling plain request body for " << clientConnection); |
3ff65596 AR |
3037 | putSize = bodyPipe->putMoreData(in.buf, in.notYetUsed); |
3038 | if (!bodyPipe->mayNeedMoreData()) { | |
3039 | // BodyPipe will clear us automagically when we produced everything | |
3040 | bodyPipe = NULL; | |
3041 | } | |
3042 | } | |
3043 | ||
3044 | if (putSize > 0) | |
3045 | connNoteUseOfBuffer(this, putSize); | |
5f8252d2 | 3046 | |
3ff65596 | 3047 | if (!bodyPipe) { |
73c36fd9 | 3048 | debugs(33,5, HERE << "produced entire request body for " << clientConnection); |
62e76326 | 3049 | |
cf6eb29e | 3050 | if (const char *reason = stoppedSending()) { |
5f8252d2 | 3051 | /* we've finished reading like good clients, |
3052 | * now do the close that initiateClose initiated. | |
5f8252d2 | 3053 | */ |
cf6eb29e | 3054 | debugs(33, 3, HERE << "closing for earlier sending error: " << reason); |
73c36fd9 | 3055 | clientConnection->close(); |
39cb8c41 AR |
3056 | return false; |
3057 | } | |
3058 | } | |
3059 | ||
3060 | return true; | |
3061 | } | |
3062 | ||
3063 | /// parses available chunked encoded body bytes, checks size, returns errors | |
3064 | err_type | |
3065 | ConnStateData::handleChunkedRequestBody(size_t &putSize) | |
3066 | { | |
73c36fd9 | 3067 | debugs(33,7, HERE << "chunked from " << clientConnection << ": " << in.notYetUsed); |
39cb8c41 AR |
3068 | |
3069 | try { // the parser will throw on errors | |
3070 | ||
3071 | if (!in.notYetUsed) // nothing to do (MemBuf::init requires this check) | |
3072 | return ERR_NONE; | |
3073 | ||
3074 | MemBuf raw; // ChunkedCodingParser only works with MemBufs | |
3075 | // add one because MemBuf will assert if it cannot 0-terminate | |
3076 | raw.init(in.notYetUsed, in.notYetUsed+1); | |
3077 | raw.append(in.buf, in.notYetUsed); | |
3078 | ||
3079 | const mb_size_t wasContentSize = raw.contentSize(); | |
3080 | BodyPipeCheckout bpc(*bodyPipe); | |
3081 | const bool parsed = in.bodyParser->parse(&raw, &bpc.buf); | |
3082 | bpc.checkIn(); | |
3083 | putSize = wasContentSize - raw.contentSize(); | |
3084 | ||
3085 | // dechunk then check: the size limit applies to _dechunked_ content | |
3086 | if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize())) | |
3087 | return ERR_TOO_BIG; | |
3088 | ||
3089 | if (parsed) { | |
3090 | finishDechunkingRequest(true); | |
3091 | Must(!bodyPipe); | |
3092 | return ERR_NONE; // nil bodyPipe implies body end for the caller | |
5f8252d2 | 3093 | } |
39cb8c41 AR |
3094 | |
3095 | // if chunk parser needs data, then the body pipe must need it too | |
3096 | Must(!in.bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData()); | |
3097 | ||
3098 | // if parser needs more space and we can consume nothing, we will stall | |
3099 | Must(!in.bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent()); | |
3100 | } catch (...) { // TODO: be more specific | |
3101 | debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status()); | |
3102 | return ERR_INVALID_REQ; | |
94439e4e | 3103 | } |
39cb8c41 AR |
3104 | |
3105 | debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status()); | |
3106 | return ERR_NONE; | |
3107 | } | |
3108 | ||
3109 | /// quit on errors related to chunked request body handling | |
3110 | void | |
3111 | ConnStateData::abortChunkedRequestBody(const err_type error) | |
3112 | { | |
3113 | finishDechunkingRequest(false); | |
3114 | ||
3115 | // XXX: The code below works if we fail during initial request parsing, | |
3116 | // but if we fail when the server-side works already, the server may send | |
3117 | // us its response too, causing various assertions. How to prevent that? | |
3118 | #if WE_KNOW_HOW_TO_SEND_ERRORS | |
3119 | ClientSocketContext::Pointer context = getCurrentContext(); | |
3120 | if (context != NULL && !context->http->out.offset) { // output nothing yet | |
3121 | clientStreamNode *node = context->getClientReplyContext(); | |
3122 | clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw()); | |
3123 | assert(repContext); | |
3124 | const http_status scode = (error == ERR_TOO_BIG) ? | |
de48b288 | 3125 | HTTP_REQUEST_ENTITY_TOO_LARGE : HTTP_BAD_REQUEST; |
39cb8c41 AR |
3126 | repContext->setReplyToError(error, scode, |
3127 | repContext->http->request->method, | |
3128 | repContext->http->uri, | |
3129 | peer, | |
3130 | repContext->http->request, | |
3131 | in.buf, NULL); | |
3132 | context->pullData(); | |
3133 | } else { | |
3134 | // close or otherwise we may get stuck as nobody will notice the error? | |
73c36fd9 | 3135 | comm_reset_close(clientConnection); |
39cb8c41 AR |
3136 | } |
3137 | #else | |
3138 | debugs(33, 3, HERE << "aborting chunked request without error " << error); | |
73c36fd9 | 3139 | comm_reset_close(clientConnection); |
39cb8c41 | 3140 | #endif |
f35961af | 3141 | flags.readMore = false; |
5f8252d2 | 3142 | } |
55e44db9 | 3143 | |
5f8252d2 | 3144 | void |
1cf238db | 3145 | ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer ) |
5f8252d2 | 3146 | { |
90737510 | 3147 | if (!handleRequestBodyData()) |
1368d115 CT |
3148 | return; |
3149 | ||
6bec3b16 | 3150 | // too late to read more body |
cf6eb29e | 3151 | if (!isOpen() || stoppedReceiving()) |
6bec3b16 AR |
3152 | return; |
3153 | ||
1368d115 | 3154 | readSomeData(); |
5f8252d2 | 3155 | } |
3156 | ||
3157 | void | |
1cf238db | 3158 | ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer ) |
5f8252d2 | 3159 | { |
cf6eb29e CT |
3160 | // request reader may get stuck waiting for space if nobody consumes body |
3161 | if (bodyPipe != NULL) | |
3162 | bodyPipe->enableAutoConsumption(); | |
3163 | ||
3164 | stopReceiving("virgin request body consumer aborted"); // closes ASAP | |
94439e4e | 3165 | } |
3166 | ||
63be0a78 | 3167 | /** general lifetime handler for HTTP requests */ |
1cf238db | 3168 | void |
3169 | ConnStateData::requestTimeout(const CommTimeoutCbParams &io) | |
7a2f978b | 3170 | { |
ad63ceea | 3171 | #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS |
1cf238db | 3172 | debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired."); |
62e76326 | 3173 | |
1cf238db | 3174 | if (COMMIO_FD_WRITECB(io.fd)->active) { |
dec5db5d | 3175 | /* FIXME: If this code is reinstated, check the conn counters, |
3176 | * not the fd table state | |
3177 | */ | |
62e76326 | 3178 | /* |
3179 | * Some data has been sent to the client, just close the FD | |
3180 | */ | |
73c36fd9 | 3181 | clientConnection->close(); |
1cf238db | 3182 | } else if (nrequests) { |
62e76326 | 3183 | /* |
3184 | * assume its a persistent connection; just close it | |
3185 | */ | |
73c36fd9 | 3186 | clientConnection->close(); |
7a2f978b | 3187 | } else { |
62e76326 | 3188 | /* |
3189 | * Generate an error | |
3190 | */ | |
59a1efb2 | 3191 | ClientHttpRequest **H; |
62e76326 | 3192 | clientStreamNode *node; |
719c7e0a | 3193 | ClientHttpRequest *http = parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired"); |
62e76326 | 3194 | node = http->client_stream.tail->prev->data; |
0655fa4d | 3195 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
3196 | assert (repContext); | |
3197 | repContext->setReplyToError(ERR_LIFETIME_EXP, | |
1cf238db | 3198 | HTTP_REQUEST_TIMEOUT, METHOD_NONE, "N/A", &peer.sin_addr, |
0655fa4d | 3199 | NULL, NULL, NULL); |
62e76326 | 3200 | /* No requests can be outstanded */ |
1cf238db | 3201 | assert(chr == NULL); |
62e76326 | 3202 | /* add to the client request queue */ |
3203 | ||
3d0ac046 | 3204 | for (H = &chr; *H; H = &(*H)->next); |
62e76326 | 3205 | *H = http; |
3206 | ||
3207 | clientStreamRead(http->client_stream.tail->data, http, 0, | |
3208 | HTTP_REQBUF_SZ, context->reqbuf); | |
3209 | ||
3210 | /* | |
3211 | * if we don't close() here, we still need a timeout handler! | |
3212 | */ | |
9e008dda | 3213 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 AR |
3214 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
3215 | TimeoutDialer, this, ConnStateData::requestTimeout); | |
8d77a37c | 3216 | commSetConnTimeout(io.conn, 30, timeoutCall); |
62e76326 | 3217 | |
3218 | /* | |
3219 | * Aha, but we don't want a read handler! | |
3220 | */ | |
d841c88d | 3221 | Comm::SetSelect(io.fd, COMM_SELECT_READ, NULL, NULL, 0); |
7a2f978b | 3222 | } |
62e76326 | 3223 | |
af57a2e3 | 3224 | #else |
3225 | /* | |
62e76326 | 3226 | * Just close the connection to not confuse browsers |
3227 | * using persistent connections. Some browsers opens | |
3228 | * an connection and then does not use it until much | |
3229 | * later (presumeably because the request triggering | |
3230 | * the open has already been completed on another | |
3231 | * connection) | |
3232 | */ | |
1cf238db | 3233 | debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired."); |
8d77a37c | 3234 | io.conn->close(); |
af57a2e3 | 3235 | #endif |
7a2f978b | 3236 | } |
3237 | ||
b5c39993 | 3238 | static void |
8d77a37c | 3239 | clientLifetimeTimeout(const CommTimeoutCbParams &io) |
b5c39993 | 3240 | { |
8d77a37c | 3241 | ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data); |
cb61ec47 AJ |
3242 | debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout"); |
3243 | debugs(33, DBG_IMPORTANT, "\t" << http->uri); | |
f692498b | 3244 | http->al.http.timedout = true; |
8d77a37c AJ |
3245 | if (Comm::IsConnOpen(io.conn)) |
3246 | io.conn->close(); | |
b5c39993 | 3247 | } |
3248 | ||
c8be6d7b | 3249 | ConnStateData * |
be364179 | 3250 | connStateCreate(const Comm::ConnectionPointer &client, http_port_list *port) |
c8be6d7b | 3251 | { |
a46d2c0e | 3252 | ConnStateData *result = new ConnStateData; |
2ad20b4f | 3253 | |
73c36fd9 | 3254 | result->clientConnection = client; |
be364179 | 3255 | result->log_addr = client->remote; |
055421ee | 3256 | result->log_addr.ApplyMask(Config.Addrs.client_netmask); |
e6ccf245 | 3257 | result->in.buf = (char *)memAllocBuf(CLIENT_REQ_BUF_SZ, &result->in.allocatedSize); |
3f38a55e | 3258 | result->port = cbdataReference(port); |
62e76326 | 3259 | |
5529ca8a | 3260 | if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF && |
9e008dda | 3261 | (result->transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) { |
5529ca8a | 3262 | #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT) |
3263 | int i = IP_PMTUDISC_DONT; | |
be364179 | 3264 | setsockopt(client->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof i); |
5529ca8a | 3265 | #else |
5529ca8a | 3266 | static int reported = 0; |
3267 | ||
3268 | if (!reported) { | |
bf8fe701 | 3269 | debugs(33, 1, "Notice: httpd_accel_no_pmtu_disc not supported on your platform"); |
5529ca8a | 3270 | reported = 1; |
3271 | } | |
89aec9b6 AJ |
3272 | #endif |
3273 | } | |
5529ca8a | 3274 | |
89aec9b6 AJ |
3275 | typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer; |
3276 | AsyncCall::Pointer call = JobCallback(33, 5, Dialer, result, ConnStateData::connStateClosed); | |
3277 | comm_add_close_handler(client->fd, call); | |
5529ca8a | 3278 | |
89aec9b6 AJ |
3279 | if (Config.onoff.log_fqdn) |
3280 | fqdncache_gethostbyaddr(client->remote, FQDN_LOOKUP_IF_MISS); | |
3281 | ||
3282 | #if USE_IDENT | |
3283 | if (Ident::TheConfig.identLookup) { | |
3284 | ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL); | |
3285 | identChecklist.src_addr = client->remote; | |
3286 | identChecklist.my_addr = client->local; | |
2efeb0b7 | 3287 | if (identChecklist.fastCheck() == ACCESS_ALLOWED) |
89aec9b6 AJ |
3288 | Ident::Start(client, clientIdentDone, result); |
3289 | } | |
5529ca8a | 3290 | #endif |
3291 | ||
89aec9b6 AJ |
3292 | #if USE_SQUID_EUI |
3293 | if (Eui::TheConfig.euiLookup) { | |
3294 | if (client->remote.IsIPv4()) { | |
3295 | result->clientConnection->remoteEui48.lookup(client->remote); | |
3296 | } else if (client->remote.IsIPv6()) { | |
3297 | result->clientConnection->remoteEui64.lookup(client->remote); | |
3298 | } | |
5529ca8a | 3299 | } |
89aec9b6 AJ |
3300 | #endif |
3301 | ||
3302 | clientdbEstablished(client->remote, 1); | |
5529ca8a | 3303 | |
f35961af | 3304 | result->flags.readMore = true; |
c8be6d7b | 3305 | return result; |
3306 | } | |
3307 | ||
63be0a78 | 3308 | /** Handle a new connection on HTTP socket. */ |
7a2f978b | 3309 | void |
449f0115 | 3310 | httpAccept(const CommAcceptCbParams ¶ms) |
7a2f978b | 3311 | { |
449f0115 | 3312 | http_port_list *s = (http_port_list *)params.data; |
02d1422b | 3313 | |
449f0115 | 3314 | if (params.flag != COMM_OK) { |
cbff89ba | 3315 | // Its possible the call was still queued when the client disconnected |
449f0115 | 3316 | debugs(33, 2, "httpAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno)); |
62e76326 | 3317 | return; |
3318 | } | |
3319 | ||
449f0115 AJ |
3320 | debugs(33, 4, HERE << params.conn << ": accepted"); |
3321 | fd_note(params.conn->fd, "client http connect"); | |
1cf238db | 3322 | |
89aec9b6 | 3323 | if (s->tcp_keepalive.enabled) { |
449f0115 | 3324 | commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); |
89aec9b6 | 3325 | } |
62e76326 | 3326 | |
89aec9b6 AJ |
3327 | incoming_sockets_accepted++; |
3328 | ||
3329 | // Socket is ready, setup the connection manager to start using it | |
449f0115 | 3330 | ConnStateData *connState = connStateCreate(params.conn, s); |
62e76326 | 3331 | |
9e008dda | 3332 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 3333 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
4cb2536f | 3334 | TimeoutDialer, connState, ConnStateData::requestTimeout); |
6b2a2108 | 3335 | commSetConnTimeout(params.conn, Config.Timeout.request, timeoutCall); |
b2130d58 | 3336 | |
a46d2c0e | 3337 | connState->readSomeData(); |
62e76326 | 3338 | |
9a0a18de | 3339 | #if USE_DELAY_POOLS |
449f0115 | 3340 | fd_table[params.conn->fd].clientInfo = NULL; |
b4cd430a | 3341 | |
f33d34a8 | 3342 | if (Config.onoff.client_db) { |
b4cd430a CT |
3343 | /* it was said several times that client write limiter does not work if client_db is disabled */ |
3344 | ||
3345 | ClientDelayPools& pools(Config.ClientDelay.pools); | |
2efeb0b7 | 3346 | ACLFilledChecklist ch(NULL, NULL, NULL); |
b4cd430a | 3347 | |
2efeb0b7 AJ |
3348 | // TODO: we check early to limit error response bandwith but we |
3349 | // should recheck when we can honor delay_pool_uses_indirect | |
3350 | // TODO: we should also pass the port details for myportname here. | |
449f0115 AJ |
3351 | ch.src_addr = params.conn->remote; |
3352 | ch.my_addr = params.conn->local; | |
b4cd430a | 3353 | |
2efeb0b7 | 3354 | for (unsigned int pool = 0; pool < pools.size(); pool++) { |
b4cd430a | 3355 | |
2efeb0b7 AJ |
3356 | /* pools require explicit 'allow' to assign a client into them */ |
3357 | if (pools[pool].access) { | |
3358 | ch.accessList = pools[pool].access; | |
3359 | allow_t answer = ch.fastCheck(); | |
3360 | if (answer == ACCESS_ALLOWED) { | |
3361 | ||
3362 | /* request client information from db after we did all checks | |
3363 | this will save hash lookup if client failed checks */ | |
449f0115 | 3364 | ClientInfo * cli = clientdbGetInfo(params.conn->remote); |
2efeb0b7 AJ |
3365 | assert(cli); |
3366 | ||
3367 | /* put client info in FDE */ | |
449f0115 | 3368 | fd_table[params.conn->fd].clientInfo = cli; |
2efeb0b7 AJ |
3369 | |
3370 | /* setup write limiter for this request */ | |
3371 | const double burst = floor(0.5 + | |
3372 | (pools[pool].highwatermark * Config.ClientDelay.initial)/100.0); | |
3373 | cli->setWriteLimiter(pools[pool].rate, burst, pools[pool].highwatermark); | |
3374 | break; | |
3375 | } else { | |
3376 | debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer); | |
3377 | } | |
b4cd430a CT |
3378 | } |
3379 | } | |
3380 | } | |
3381 | #endif | |
7a2f978b | 3382 | } |
3383 | ||
1f7c9178 | 3384 | #if USE_SSL |
3385 | ||
63be0a78 | 3386 | /** Create SSL connection structure and update fd_table */ |
ae7ff0b8 | 3387 | static SSL * |
449f0115 | 3388 | httpsCreate(const Comm::ConnectionPointer &conn, SSL_CTX *sslContext) |
ae7ff0b8 | 3389 | { |
3390 | SSL *ssl = SSL_new(sslContext); | |
3391 | ||
3392 | if (!ssl) { | |
3393 | const int ssl_error = ERR_get_error(); | |
449f0115 AJ |
3394 | debugs(83, DBG_IMPORTANT, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error, NULL) ); |
3395 | conn->close(); | |
ae7ff0b8 | 3396 | return NULL; |
3397 | } | |
3398 | ||
449f0115 AJ |
3399 | SSL_set_fd(ssl, conn->fd); |
3400 | fd_table[conn->fd].ssl = ssl; | |
3401 | fd_table[conn->fd].read_method = &ssl_read_method; | |
3402 | fd_table[conn->fd].write_method = &ssl_write_method; | |
ae7ff0b8 | 3403 | |
449f0115 AJ |
3404 | debugs(33, 5, "httpsCreate: will negotate SSL on " << conn); |
3405 | fd_note(conn->fd, "client https start"); | |
ae7ff0b8 | 3406 | |
3407 | return ssl; | |
3408 | } | |
3409 | ||
63be0a78 | 3410 | /** negotiate an SSL connection */ |
1f7c9178 | 3411 | static void |
3412 | clientNegotiateSSL(int fd, void *data) | |
3413 | { | |
e6ccf245 | 3414 | ConnStateData *conn = (ConnStateData *)data; |
1f7c9178 | 3415 | X509 *client_cert; |
a7ad6e4e | 3416 | SSL *ssl = fd_table[fd].ssl; |
1f7c9178 | 3417 | int ret; |
3418 | ||
a7ad6e4e | 3419 | if ((ret = SSL_accept(ssl)) <= 0) { |
62e76326 | 3420 | int ssl_error = SSL_get_error(ssl, ret); |
3421 | ||
3422 | switch (ssl_error) { | |
3423 | ||
3424 | case SSL_ERROR_WANT_READ: | |
d841c88d | 3425 | Comm::SetSelect(fd, COMM_SELECT_READ, clientNegotiateSSL, conn, 0); |
62e76326 | 3426 | return; |
3427 | ||
3428 | case SSL_ERROR_WANT_WRITE: | |
d841c88d | 3429 | Comm::SetSelect(fd, COMM_SELECT_WRITE, clientNegotiateSSL, conn, 0); |
62e76326 | 3430 | return; |
3431 | ||
6de9e64b | 3432 | case SSL_ERROR_SYSCALL: |
3433 | ||
3434 | if (ret == 0) { | |
bf8fe701 | 3435 | debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Aborted by client"); |
6de9e64b | 3436 | comm_close(fd); |
3437 | return; | |
3438 | } else { | |
3439 | int hard = 1; | |
3440 | ||
3441 | if (errno == ECONNRESET) | |
3442 | hard = 0; | |
3443 | ||
9e008dda | 3444 | debugs(83, hard ? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << |
bf8fe701 | 3445 | fd << ": " << strerror(errno) << " (" << errno << ")"); |
6de9e64b | 3446 | |
3447 | comm_close(fd); | |
3448 | ||
3449 | return; | |
3450 | } | |
3451 | ||
3452 | case SSL_ERROR_ZERO_RETURN: | |
bf8fe701 | 3453 | debugs(83, 1, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Closed by client"); |
6de9e64b | 3454 | comm_close(fd); |
3455 | return; | |
3456 | ||
62e76326 | 3457 | default: |
9e008dda AJ |
3458 | debugs(83, 1, "clientNegotiateSSL: Error negotiating SSL connection on FD " << |
3459 | fd << ": " << ERR_error_string(ERR_get_error(), NULL) << | |
3460 | " (" << ssl_error << "/" << ret << ")"); | |
62e76326 | 3461 | comm_close(fd); |
3462 | return; | |
3463 | } | |
3464 | ||
3465 | /* NOTREACHED */ | |
1f7c9178 | 3466 | } |
62e76326 | 3467 | |
6de9e64b | 3468 | if (SSL_session_reused(ssl)) { |
bf8fe701 | 3469 | debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl) << |
3470 | " reused on FD " << fd << " (" << fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << ")"); | |
6de9e64b | 3471 | } else { |
3472 | if (do_debug(83, 4)) { | |
3473 | /* Write out the SSL session details.. actually the call below, but | |
3474 | * OpenSSL headers do strange typecasts confusing GCC.. */ | |
3475 | /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */ | |
afdd443f | 3476 | #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L |
9f3de01a | 3477 | 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 | 3478 | |
0fd2205b | 3479 | #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1) |
2930f303 | 3480 | |
0fd2205b | 3481 | /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here. |
3482 | * This is caused by an unpredicatble gcc behaviour on a cast of the first argument | |
3483 | * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it, | |
3484 | * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1. | |
3485 | * Because there are two possible usable cast, if you get an error here, try the other | |
3486 | * commented line. */ | |
3487 | ||
3488 | PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); | |
3489 | /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */ | |
2930f303 | 3490 | |
0e33d58c | 3491 | #else |
3492 | ||
bf8fe701 | 3493 | debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." ); |
0fd2205b | 3494 | |
0e33d58c | 3495 | #endif |
6de9e64b | 3496 | /* Note: This does not automatically fflush the log file.. */ |
3497 | } | |
3498 | ||
bf8fe701 | 3499 | debugs(83, 2, "clientNegotiateSSL: New session " << |
3500 | SSL_get_session(ssl) << " on FD " << fd << " (" << | |
3501 | fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << | |
3502 | ")"); | |
6de9e64b | 3503 | } |
3504 | ||
bf8fe701 | 3505 | debugs(83, 3, "clientNegotiateSSL: FD " << fd << " negotiated cipher " << |
3506 | SSL_get_cipher(ssl)); | |
1f7c9178 | 3507 | |
6de9e64b | 3508 | client_cert = SSL_get_peer_certificate(ssl); |
62e76326 | 3509 | |
1f7c9178 | 3510 | if (client_cert != NULL) { |
bf8fe701 | 3511 | debugs(83, 3, "clientNegotiateSSL: FD " << fd << |
3512 | " client certificate: subject: " << | |
3513 | X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0)); | |
3514 | ||
3515 | debugs(83, 3, "clientNegotiateSSL: FD " << fd << | |
3516 | " client certificate: issuer: " << | |
3517 | X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0)); | |
1f7c9178 | 3518 | |
1f7c9178 | 3519 | |
62e76326 | 3520 | X509_free(client_cert); |
1f7c9178 | 3521 | } else { |
bf8fe701 | 3522 | debugs(83, 5, "clientNegotiateSSL: FD " << fd << |
3523 | " has no certificate."); | |
1f7c9178 | 3524 | } |
3525 | ||
a46d2c0e | 3526 | conn->readSomeData(); |
1f7c9178 | 3527 | } |
3528 | ||
379e8c1c | 3529 | /** |
ab2e0682 CT |
3530 | * If SSL_CTX is given, starts reading the SSL handshake. |
3531 | * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX. | |
379e8c1c AR |
3532 | */ |
3533 | static void | |
3534 | httpsEstablish(ConnStateData *connState, SSL_CTX *sslContext) | |
3535 | { | |
3536 | SSL *ssl = NULL; | |
3537 | assert(connState); | |
3538 | const Comm::ConnectionPointer &details = connState->clientConnection; | |
3539 | ||
3540 | if (sslContext && !(ssl = httpsCreate(details, sslContext))) | |
3541 | return; | |
3542 | ||
3543 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; | |
3544 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, | |
3545 | TimeoutDialer, connState, ConnStateData::requestTimeout); | |
3546 | commSetConnTimeout(details, Config.Timeout.request, timeoutCall); | |
3547 | ||
3548 | if (ssl) | |
3549 | Comm::SetSelect(details->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0); | |
3550 | else { | |
3551 | char buf[MAX_IPSTRLEN]; | |
3552 | debugs(33, 4, HERE << details << " try to generate a Dynamic SSL CTX"); | |
d7ce0bcd | 3553 | connState->switchToHttps(details->local.NtoA(buf, sizeof(buf)), details->local.GetPort()); |
379e8c1c AR |
3554 | } |
3555 | } | |
3556 | ||
3557 | /** | |
3558 | * A callback function to use with the ACLFilledChecklist callback. | |
3559 | * In the case of ACCES_ALLOWED answer initializes an ssl bumped connection, | |
3560 | * else revert the connection to tunnel mode. | |
3561 | */ | |
3562 | static void | |
3563 | httpsSslBumpAccessCheckDone(allow_t answer, void *data) | |
3564 | { | |
3565 | ConnStateData *connState = (ConnStateData *) data; | |
3566 | ||
3567 | //if connection closed/closing just return. | |
3568 | if (!connState->isOpen()) | |
3569 | return; | |
3570 | ||
3571 | if (answer == ACCESS_ALLOWED) { | |
3572 | debugs(33, 2, HERE << " sslBump done data: " << connState->clientConnection); | |
3573 | httpsEstablish(connState, NULL); | |
3574 | } else { | |
3575 | // fake a CONNECT request to force connState to tunnel | |
3576 | ||
ab2e0682 | 3577 | debugs(33, 2, HERE << " SslBump denied: " << connState->clientConnection << " revert to tunnel mode"); |
379e8c1c AR |
3578 | static char ip[MAX_IPSTRLEN]; |
3579 | static char reqStr[MAX_IPSTRLEN + 80]; | |
3580 | connState->clientConnection->local.NtoA(ip, sizeof(ip)); | |
ab2e0682 | 3581 | 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 |
3582 | bool ret = connState->handleReadData(reqStr, strlen(reqStr)); |
3583 | if (ret) | |
3584 | ret = connState->clientParseRequests(); | |
3585 | ||
3586 | if (!ret) { | |
3587 | debugs(33, 2, HERE << "Failed to start fake CONNECT request for ssl bumped connection: " << connState->clientConnection); | |
3588 | connState->clientConnection->close(); | |
3589 | } | |
3590 | } | |
3591 | } | |
3592 | ||
63be0a78 | 3593 | /** handle a new HTTPS connection */ |
1f7c9178 | 3594 | static void |
449f0115 | 3595 | httpsAccept(const CommAcceptCbParams ¶ms) |
1f7c9178 | 3596 | { |
859741ed | 3597 | http_port_list *s = (http_port_list *)params.data; |
c4b7a5a9 | 3598 | |
449f0115 | 3599 | if (params.flag != COMM_OK) { |
cbff89ba | 3600 | // Its possible the call was still queued when the client disconnected |
449f0115 | 3601 | debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno)); |
62e76326 | 3602 | return; |
c4b7a5a9 | 3603 | } |
62e76326 | 3604 | |
449f0115 AJ |
3605 | debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation."); |
3606 | fd_note(params.conn->fd, "client https connect"); | |
62e76326 | 3607 | |
859741ed AJ |
3608 | if (s->tcp_keepalive.enabled) { |
3609 | commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); | |
b2130d58 | 3610 | } |
3611 | ||
89aec9b6 | 3612 | incoming_sockets_accepted++; |
62e76326 | 3613 | |
89aec9b6 | 3614 | // Socket is ready, setup the connection manager to start using it |
859741ed | 3615 | ConnStateData *connState = connStateCreate(params.conn, s); |
62e76326 | 3616 | |
379e8c1c | 3617 | if (s->sslBump) { |
379e8c1c | 3618 | debugs(33, 5, "httpsAccept: accept transparent connection: " << params.conn); |
62e76326 | 3619 | |
379e8c1c AR |
3620 | if (!Config.accessList.ssl_bump) { |
3621 | httpsSslBumpAccessCheckDone(ACCESS_DENIED, connState); | |
3622 | return; | |
3623 | } | |
3624 | ||
3625 | // Create a fake HTTP request for ssl_bump ACL check, | |
3626 | // using tproxy-provided destination IP and port. | |
3627 | HttpRequest *request = new HttpRequest(); | |
3628 | static char ip[MAX_IPSTRLEN]; | |
d7ce0bcd | 3629 | assert(params.conn->flags & (COMM_TRANSPARENT | COMM_INTERCEPTION)); |
379e8c1c AR |
3630 | request->SetHost(params.conn->local.NtoA(ip, sizeof(ip))); |
3631 | request->port = params.conn->local.GetPort(); | |
3632 | request->myportname = s->name; | |
3633 | ||
3634 | ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL); | |
3635 | acl_checklist->src_addr = params.conn->remote; | |
3636 | acl_checklist->my_addr = s->s; | |
3637 | acl_checklist->nonBlockingCheck(httpsSslBumpAccessCheckDone, connState); | |
3638 | return; | |
3639 | } else { | |
3640 | SSL_CTX *sslContext = s->staticSslContext.get(); | |
3641 | httpsEstablish(connState, sslContext); | |
3642 | } | |
1f7c9178 | 3643 | } |
3644 | ||
95d2589c CT |
3645 | void |
3646 | ConnStateData::sslCrtdHandleReplyWrapper(void *data, char *reply) | |
ae7ff0b8 | 3647 | { |
95d2589c CT |
3648 | ConnStateData * state_data = (ConnStateData *)(data); |
3649 | state_data->sslCrtdHandleReply(reply); | |
3650 | } | |
ae7ff0b8 | 3651 | |
95d2589c CT |
3652 | void |
3653 | ConnStateData::sslCrtdHandleReply(const char * reply) | |
3654 | { | |
3655 | if (!reply) { | |
3656 | debugs(1, 1, HERE << "\"ssl_crtd\" helper return <NULL> reply"); | |
3657 | } else { | |
3658 | Ssl::CrtdMessage reply_message; | |
3659 | if (reply_message.parse(reply, strlen(reply)) != Ssl::CrtdMessage::OK) { | |
fb2178bb | 3660 | debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslConnectHostOrIp << " is incorrect"); |
95d2589c | 3661 | } else { |
419ac015 | 3662 | if (reply_message.getCode() != "OK") { |
fb2178bb | 3663 | debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply_message.getBody()); |
95d2589c | 3664 | } else { |
fb2178bb | 3665 | debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " was successfully recieved from ssl_crtd"); |
a594dbfa CT |
3666 | SSL_CTX *ctx = Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str()); |
3667 | getSslContextDone(ctx, true); | |
95d2589c CT |
3668 | return; |
3669 | } | |
3670 | } | |
3671 | } | |
3672 | getSslContextDone(NULL); | |
3673 | } | |
ae7ff0b8 | 3674 | |
06997a38 | 3675 | void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties &certProperties) |
fb2178bb | 3676 | { |
06997a38 | 3677 | certProperties.commonName = sslCommonName.defined() ? sslCommonName.termedBuf() : sslConnectHostOrIp.termedBuf(); |
fb2178bb CT |
3678 | |
3679 | // fake certificate adaptation requires bump-server-first mode | |
fd4624d7 | 3680 | if (!sslServerBump) |
fb2178bb CT |
3681 | return; |
3682 | ||
59a49556 CT |
3683 | // In the case of error while connecting to secure server, use a fake trusted certificate, |
3684 | // with no mimicked fields and no adaptation algorithms | |
fd4624d7 CT |
3685 | assert(sslServerBump->entry); |
3686 | if (sslServerBump->entry->isEmpty()) { | |
3687 | if (X509 *mimicCert = sslServerBump->serverCert.get()) | |
59a49556 CT |
3688 | certProperties.mimicCert.resetAndLock(mimicCert); |
3689 | ||
3690 | HttpRequest *fakeRequest = new HttpRequest(); | |
3691 | fakeRequest->SetHost(sslConnectHostOrIp.termedBuf()); | |
3692 | fakeRequest->port = clientConnection->local.GetPort(); | |
3693 | fakeRequest->protocol = AnyP::PROTO_HTTPS; | |
fb2178bb | 3694 | |
59a49556 CT |
3695 | ACLFilledChecklist checklist(NULL, fakeRequest, |
3696 | clientConnection != NULL ? clientConnection->rfc931 : dash_str); | |
3697 | checklist.conn(this); | |
3698 | checklist.src_addr = clientConnection->remote; | |
3699 | checklist.my_addr = clientConnection->local; | |
fd4624d7 | 3700 | checklist.sslErrorList = cbdataReference(sslServerBump->bumpSslErrorNoList); |
59a49556 CT |
3701 | |
3702 | for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) { | |
3703 | if (ca->aclList && checklist.fastCheck(ca->aclList) == ACCESS_ALLOWED) { | |
3704 | const char *alg = Ssl::CertAdaptAlgorithmStr[ca->alg]; | |
3705 | const char *param = ca->param; | |
fb2178bb | 3706 | |
59a49556 CT |
3707 | // if not param defined for Common Name adaptation use hostname from |
3708 | // the CONNECT request | |
3709 | if (ca->alg == Ssl::algSetCommonName && !certProperties.setCommonName) { | |
3710 | if (!param) | |
3711 | param = sslConnectHostOrIp.termedBuf(); | |
3712 | certProperties.commonName = param; | |
3713 | certProperties.setCommonName = true; | |
3714 | } | |
3715 | else if(ca->alg == Ssl::algSetValidAfter && !certProperties.setValidAfter) | |
3716 | certProperties.setValidAfter = true; | |
3717 | else if(ca->alg == Ssl::algSetValidBefore && !certProperties.setValidBefore) | |
3718 | certProperties.setValidBefore = true; | |
3719 | ||
3720 | assert(alg && param); | |
3721 | debugs(33, 5, HERE << "Matches certificate adaptation aglorithm: " << | |
3722 | alg << " param: " << param); | |
aebe6888 | 3723 | } |
fb2178bb | 3724 | } |
aebe6888 | 3725 | |
59a49556 CT |
3726 | certProperties.signAlgorithm = Ssl::algSignEnd; |
3727 | for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) { | |
3728 | if (sg->aclList && checklist.fastCheck(sg->aclList) == ACCESS_ALLOWED) { | |
3729 | certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg; | |
3730 | break; | |
3731 | } | |
aebe6888 | 3732 | } |
fd4624d7 | 3733 | } else {// if (!sslServerBump->entry->isEmpty()) |
59a49556 CT |
3734 | // Use trusted certificate for a Squid-generated error |
3735 | // or the user would have to add a security exception | |
3736 | // just to see the error page. We will close the connection | |
3737 | // so that the trust is not extended to non-Squid content. | |
3738 | certProperties.signAlgorithm = Ssl::algSignTrusted; | |
aebe6888 CT |
3739 | } |
3740 | ||
10d914f6 | 3741 | assert(certProperties.signAlgorithm != Ssl::algSignEnd); |
aebe6888 CT |
3742 | |
3743 | if (certProperties.signAlgorithm == Ssl::algSignUntrusted) { | |
f4e4d4d6 | 3744 | assert(port->untrustedSigningCert.get()); |
95588170 CT |
3745 | certProperties.signWithX509.resetAndLock(port->untrustedSigningCert.get()); |
3746 | certProperties.signWithPkey.resetAndLock(port->untrustedSignPkey.get()); | |
aebe6888 CT |
3747 | } |
3748 | else { | |
f4e4d4d6 CT |
3749 | assert(port->signingCert.get()); |
3750 | certProperties.signWithX509.resetAndLock(port->signingCert.get()); | |
aebe6888 CT |
3751 | |
3752 | if (port->signPkey.get()) | |
3753 | certProperties.signWithPkey.resetAndLock(port->signPkey.get()); | |
3754 | } | |
3755 | signAlgorithm = certProperties.signAlgorithm; | |
fb2178bb CT |
3756 | } |
3757 | ||
1ce2822d | 3758 | void |
95d2589c CT |
3759 | ConnStateData::getSslContextStart() |
3760 | { | |
fb2178bb | 3761 | if (port->generateHostCertificates) { |
aebe6888 | 3762 | Ssl::CertificateProperties certProperties; |
06997a38 CT |
3763 | buildSslCertGenerationParams(certProperties); |
3764 | sslBumpCertKey = certProperties.dbKey().c_str(); | |
fb2178bb CT |
3765 | assert(sslBumpCertKey.defined() && sslBumpCertKey[0] != '\0'); |
3766 | ||
aebe6888 | 3767 | debugs(33, 5, HERE << "Finding SSL certificate for " << sslBumpCertKey << " in cache"); |
95d2589c | 3768 | Ssl::LocalContextStorage & ssl_ctx_cache(Ssl::TheGlobalContextStorage.getLocalStorage(port->s)); |
fb2178bb | 3769 | SSL_CTX * dynCtx = ssl_ctx_cache.find(sslBumpCertKey.termedBuf()); |
95d2589c | 3770 | if (dynCtx) { |
fb2178bb | 3771 | debugs(33, 5, HERE << "SSL certificate for " << sslBumpCertKey << " have found in cache"); |
4ece76b2 | 3772 | if (Ssl::verifySslCertificate(dynCtx, certProperties)) { |
fb2178bb | 3773 | debugs(33, 5, HERE << "Cached SSL certificate for " << sslBumpCertKey << " is valid"); |
1ce2822d AR |
3774 | getSslContextDone(dynCtx); |
3775 | return; | |
95d2589c | 3776 | } else { |
fb2178bb CT |
3777 | debugs(33, 5, HERE << "Cached SSL certificate for " << sslBumpCertKey << " is out of date. Delete this certificate from cache"); |
3778 | ssl_ctx_cache.remove(sslBumpCertKey.termedBuf()); | |
95d2589c CT |
3779 | } |
3780 | } else { | |
fb2178bb | 3781 | debugs(33, 5, HERE << "SSL certificate for " << sslBumpCertKey << " haven't found in cache"); |
95d2589c CT |
3782 | } |
3783 | ||
b5faa519 | 3784 | #if USE_SSL_CRTD |
00fc192d | 3785 | try { |
aebe6888 | 3786 | debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName << " using ssl_crtd."); |
95d2589c CT |
3787 | Ssl::CrtdMessage request_message; |
3788 | request_message.setCode(Ssl::CrtdMessage::code_new_certificate); | |
06997a38 | 3789 | request_message.composeRequest(certProperties); |
fb2178bb | 3790 | debugs(33, 5, HERE << "SSL crtd request: " << request_message.compose().c_str()); |
95d2589c | 3791 | Ssl::Helper::GetInstance()->sslSubmit(request_message, sslCrtdHandleReplyWrapper, this); |
1ce2822d | 3792 | return; |
00fc192d AR |
3793 | } |
3794 | catch (const std::exception &e) { | |
3795 | debugs(33, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtd " << | |
3796 | "request for " << certProperties.commonName << | |
3797 | " certificate: " << e.what() << "; will now block to " << | |
3798 | "generate that certificate."); | |
3799 | // fall through to do blocking in-process generation. | |
3800 | } | |
3801 | #endif // USE_SSL_CRTD | |
3802 | ||
aebe6888 CT |
3803 | debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName); |
3804 | dynCtx = Ssl::generateSslContext(certProperties); | |
1ce2822d AR |
3805 | getSslContextDone(dynCtx, true); |
3806 | return; | |
95d2589c | 3807 | } |
1ce2822d | 3808 | getSslContextDone(NULL); |
95d2589c CT |
3809 | } |
3810 | ||
1ce2822d | 3811 | void |
95d2589c CT |
3812 | ConnStateData::getSslContextDone(SSL_CTX * sslContext, bool isNew) |
3813 | { | |
3814 | // Try to add generated ssl context to storage. | |
3815 | if (port->generateHostCertificates && isNew) { | |
a594dbfa | 3816 | |
aebe6888 CT |
3817 | if (signAlgorithm == Ssl::algSignTrusted) |
3818 | Ssl::addChainToSslContext(sslContext, port->certsToChain.get()); | |
3819 | //else it is self-signed or untrusted do not attrach any certificate | |
a594dbfa | 3820 | |
95d2589c | 3821 | Ssl::LocalContextStorage & ssl_ctx_cache(Ssl::TheGlobalContextStorage.getLocalStorage(port->s)); |
fb2178bb CT |
3822 | assert(sslBumpCertKey.defined() && sslBumpCertKey[0] != '\0'); |
3823 | if (sslContext) { | |
3824 | if (!ssl_ctx_cache.add(sslBumpCertKey.termedBuf(), sslContext)) { | |
95d2589c | 3825 | // If it is not in storage delete after using. Else storage deleted it. |
73c36fd9 | 3826 | fd_table[clientConnection->fd].dynamicSslContext = sslContext; |
95d2589c CT |
3827 | } |
3828 | } else { | |
fb2178bb | 3829 | debugs(33, 2, HERE << "Failed to generate SSL cert for " << sslConnectHostOrIp); |
95d2589c CT |
3830 | } |
3831 | } | |
3832 | ||
3833 | // If generated ssl context = NULL, try to use static ssl context. | |
3834 | if (!sslContext) { | |
3835 | if (!port->staticSslContext) { | |
73c36fd9 AJ |
3836 | debugs(83, 1, "Closing SSL " << clientConnection->remote << " as lacking SSL context"); |
3837 | clientConnection->close(); | |
1ce2822d | 3838 | return; |
95d2589c CT |
3839 | } else { |
3840 | debugs(33, 5, HERE << "Using static ssl context."); | |
3841 | sslContext = port->staticSslContext.get(); | |
3842 | } | |
3843 | } | |
ae7ff0b8 | 3844 | |
ae7ff0b8 | 3845 | SSL *ssl = NULL; |
73c36fd9 | 3846 | if (!(ssl = httpsCreate(clientConnection, sslContext))) |
1ce2822d | 3847 | return; |
ae7ff0b8 | 3848 | |
8d77a37c | 3849 | // commSetConnTimeout() was called for this request before we switched. |
ae7ff0b8 | 3850 | |
3851 | // Disable the client read handler until peer selection is complete | |
73c36fd9 AJ |
3852 | Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0); |
3853 | Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, clientNegotiateSSL, this, 0); | |
ae7ff0b8 | 3854 | switchedToHttps_ = true; |
ae7ff0b8 | 3855 | } |
3856 | ||
1ce2822d | 3857 | void |
d7ce0bcd | 3858 | ConnStateData::switchToHttps(const char *host, const int port) |
95d2589c CT |
3859 | { |
3860 | assert(!switchedToHttps_); | |
3861 | ||
fb2178bb CT |
3862 | sslConnectHostOrIp = host; |
3863 | sslCommonName = host; | |
95d2589c CT |
3864 | |
3865 | //HTTPMSGLOCK(currentobject->http->request); | |
3866 | assert(areAllContextsForThisConnection()); | |
3867 | freeAllContexts(); | |
3868 | //currentobject->connIsFinished(); | |
3869 | ||
d7ce0bcd AR |
3870 | /* careful: freeAllContexts() above frees request, host, etc. */ |
3871 | ||
83d4cd15 CT |
3872 | // We are going to read new request |
3873 | flags.readMore = true; | |
73c36fd9 | 3874 | debugs(33, 5, HERE << "converting " << clientConnection << " to SSL"); |
95d2589c | 3875 | |
d7ce0bcd | 3876 | const bool alwaysBumpServerFirst = true; |
2bd84e5f CT |
3877 | // If sslServerBump is set, then we have decided to deny CONNECT |
3878 | // and now want to switch to SSL to send the error to the client | |
3879 | // without even peeking at the origin server certificate. | |
3880 | if (alwaysBumpServerFirst && !sslServerBump) { | |
fd4624d7 CT |
3881 | HttpRequest *fakeRequest = new HttpRequest; |
3882 | fakeRequest->flags.sslPeek = 1; | |
3883 | fakeRequest->SetHost(sslConnectHostOrIp.termedBuf()); | |
3884 | fakeRequest->port = port; | |
3885 | fakeRequest->protocol = AnyP::PROTO_HTTPS; | |
3886 | fakeRequest->clientConnectionManager = this; | |
3887 | sslServerBump = new Ssl::ServerBump(fakeRequest); | |
3888 | ||
d7ce0bcd | 3889 | // will call httpsPeeked() with certificate and connection, eventually |
fd4624d7 | 3890 | FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request); |
d7ce0bcd AR |
3891 | return; |
3892 | } | |
3893 | ||
fb2178bb | 3894 | // otherwise, use sslConnectHostOrIp |
d7ce0bcd AR |
3895 | getSslContextStart(); |
3896 | } | |
3897 | ||
3898 | void | |
3899 | ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection) | |
3900 | { | |
fd4624d7 | 3901 | Must(sslServerBump != NULL); |
819c207f | 3902 | |
061bbdec CT |
3903 | if (Comm::IsConnOpen(serverConnection)) { |
3904 | SSL *ssl = fd_table[serverConnection->fd].ssl; | |
3905 | assert(ssl); | |
3906 | Ssl::X509_Pointer serverCert(SSL_get_peer_certificate(ssl)); | |
3907 | assert(serverCert.get() != NULL); | |
fb2178bb | 3908 | sslCommonName = Ssl::CommonHostName(serverCert.get()); |
59a49556 CT |
3909 | debugs(33, 5, HERE << "HTTPS server CN: " << sslCommonName << |
3910 | " bumped: " << *serverConnection); | |
061bbdec CT |
3911 | |
3912 | pinConnection(serverConnection, NULL, NULL, false); | |
3913 | ||
fb2178bb | 3914 | debugs(33, 5, HERE << "bumped HTTPS server: " << sslConnectHostOrIp); |
59a49556 | 3915 | } else { |
13858f50 | 3916 | debugs(33, 5, HERE << "Error while bumping: " << sslConnectHostOrIp); |
8499a1de CT |
3917 | Ip::Address intendedDest; |
3918 | intendedDest = sslConnectHostOrIp.termedBuf(); | |
3919 | // Squid serves its own error page and closes, so we want | |
3920 | // a CN that causes no additional browser errors. Possible | |
3921 | // only when bumping CONNECT which uses a host name. | |
3922 | if (intendedDest.IsAnyAddr()) | |
3923 | sslCommonName = sslConnectHostOrIp; | |
fd4624d7 CT |
3924 | else if (sslServerBump->serverCert.get()) |
3925 | sslCommonName = Ssl::CommonHostName(sslServerBump->serverCert.get()); | |
59a49556 | 3926 | } |
061bbdec | 3927 | |
1ce2822d | 3928 | getSslContextStart(); |
95d2589c CT |
3929 | } |
3930 | ||
1f7c9178 | 3931 | #endif /* USE_SSL */ |
3932 | ||
00516be1 AR |
3933 | /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed |
3934 | static bool | |
73c36fd9 | 3935 | OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType) |
00516be1 | 3936 | { |
73c36fd9 | 3937 | if (!Comm::IsConnOpen(c)) { |
00516be1 AR |
3938 | Must(NHttpSockets > 0); // we tried to open some |
3939 | --NHttpSockets; // there will be fewer sockets than planned | |
3940 | Must(HttpSockets[NHttpSockets] < 0); // no extra fds received | |
3941 | ||
3942 | if (!NHttpSockets) // we could not open any listen sockets at all | |
cbff89ba | 3943 | fatalf("Unable to open %s",FdNote(portType)); |
00516be1 AR |
3944 | |
3945 | return false; | |
3946 | } | |
3947 | return true; | |
3948 | } | |
3949 | ||
3950 | /// find any unused HttpSockets[] slot and store fd there or return false | |
3951 | static bool | |
e0d28505 | 3952 | AddOpenedHttpSocket(const Comm::ConnectionPointer &conn) |
00516be1 AR |
3953 | { |
3954 | bool found = false; | |
3955 | for (int i = 0; i < NHttpSockets && !found; i++) { | |
3956 | if ((found = HttpSockets[i] < 0)) | |
e0d28505 | 3957 | HttpSockets[i] = conn->fd; |
00516be1 AR |
3958 | } |
3959 | return found; | |
3960 | } | |
15df8349 | 3961 | |
d193a436 | 3962 | static void |
15df8349 | 3963 | clientHttpConnectionsOpen(void) |
3964 | { | |
cc192b50 | 3965 | http_port_list *s = NULL; |
62e76326 | 3966 | |
7e3ce7b9 | 3967 | for (s = Config.Sockaddr.http; s; s = s->next) { |
62e76326 | 3968 | if (MAXHTTPPORTS == NHttpSockets) { |
bf8fe701 | 3969 | debugs(1, 1, "WARNING: You have too many 'http_port' lines."); |
3970 | debugs(1, 1, " The limit is " << MAXHTTPPORTS); | |
62e76326 | 3971 | continue; |
3972 | } | |
3973 | ||
ae7ff0b8 | 3974 | #if USE_SSL |
3d61b18e | 3975 | if (s->sslBump && !Config.accessList.ssl_bump) { |
859741ed | 3976 | debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s->protocol << "_port " << s->s); |
3d61b18e AJ |
3977 | s->sslBump = 0; |
3978 | } | |
3979 | ||
3980 | if (s->sslBump && !s->staticSslContext && !s->generateHostCertificates) { | |
859741ed | 3981 | debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure."); |
ae7ff0b8 | 3982 | s->sslBump = 0; |
3983 | } | |
95d2589c | 3984 | if (s->sslBump) { |
95d2589c CT |
3985 | // Create ssl_ctx cache for this port. |
3986 | Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize); | |
3987 | } | |
ae7ff0b8 | 3988 | #endif |
3989 | ||
e0d28505 | 3990 | // Fill out a Comm::Connection which IPC will open as a listener for us |
8bbb16e3 | 3991 | // then pass back when active so we can start a TcpAcceptor subscription. |
e0d28505 AJ |
3992 | s->listenConn = new Comm::Connection; |
3993 | s->listenConn->local = s->s; | |
40d34a62 | 3994 | s->listenConn->flags = COMM_NONBLOCKING | (s->spoof_client_ip ? COMM_TRANSPARENT : 0) | (s->intercepted ? COMM_INTERCEPTION : 0); |
c303f6e3 | 3995 | |
cbff89ba AJ |
3996 | // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP |
3997 | typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall; | |
3998 | RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, s)); | |
3999 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
62e76326 | 4000 | |
cbff89ba | 4001 | AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened", |
8bbb16e3 AJ |
4002 | ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub)); |
4003 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall); | |
62e76326 | 4004 | |
cbff89ba | 4005 | HttpSockets[NHttpSockets++] = -1; // set in clientListenerConnectionOpened |
15df8349 | 4006 | } |
d193a436 | 4007 | } |
4008 | ||
4009 | #if USE_SSL | |
4010 | static void | |
4011 | clientHttpsConnectionsOpen(void) | |
4012 | { | |
859741ed | 4013 | http_port_list *s; |
62e76326 | 4014 | |
859741ed | 4015 | for (s = Config.Sockaddr.https; s; s = s->next) { |
62e76326 | 4016 | if (MAXHTTPPORTS == NHttpSockets) { |
ae7ff0b8 | 4017 | debugs(1, 1, "Ignoring 'https_port' lines exceeding the limit."); |
4018 | debugs(1, 1, "The limit is " << MAXHTTPPORTS << " HTTPS ports."); | |
62e76326 | 4019 | continue; |
4020 | } | |
4021 | ||
95d2589c | 4022 | if (!s->staticSslContext) { |
859741ed | 4023 | debugs(1, 1, "Ignoring https_port " << s->s << |
ae7ff0b8 | 4024 | " due to SSL initialization failure."); |
4025 | continue; | |
f9ad0106 | 4026 | } |
4027 | ||
d7ce0bcd AR |
4028 | // TODO: merge with similar code in clientHttpConnectionsOpen() |
4029 | if (s->sslBump && !Config.accessList.ssl_bump) { | |
03f00a11 | 4030 | debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s->protocol << "_port " << s->s); |
d7ce0bcd AR |
4031 | s->sslBump = 0; |
4032 | } | |
4033 | ||
4034 | if (s->sslBump && !s->staticSslContext && !s->generateHostCertificates) { | |
03f00a11 | 4035 | debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure."); |
d7ce0bcd AR |
4036 | s->sslBump = 0; |
4037 | } | |
4038 | ||
4039 | if (s->sslBump) { | |
4040 | // Create ssl_ctx cache for this port. | |
4041 | Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize); | |
4042 | } | |
4043 | ||
e0d28505 | 4044 | // Fill out a Comm::Connection which IPC will open as a listener for us |
859741ed AJ |
4045 | s->listenConn = new Comm::Connection; |
4046 | s->listenConn->local = s->s; | |
4047 | s->listenConn->flags = COMM_NONBLOCKING | (s->spoof_client_ip ? COMM_TRANSPARENT : 0) | | |
4048 | (s->intercepted ? COMM_INTERCEPTION : 0); | |
62e76326 | 4049 | |
cbff89ba AJ |
4050 | // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS |
4051 | typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall; | |
4052 | RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, s)); | |
4053 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
62e76326 | 4054 | |
cbff89ba | 4055 | AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened", |
8bbb16e3 | 4056 | ListeningStartedDialer(&clientListenerConnectionOpened, |
859741ed | 4057 | s, Ipc::fdnHttpsSocket, sub)); |
8bbb16e3 | 4058 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall); |
cbff89ba AJ |
4059 | HttpSockets[NHttpSockets++] = -1; |
4060 | } | |
d193a436 | 4061 | } |
d193a436 | 4062 | #endif |
4063 | ||
e0d28505 | 4064 | /// process clientHttpConnectionsOpen result |
00516be1 | 4065 | static void |
8bbb16e3 | 4066 | clientListenerConnectionOpened(http_port_list *s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub) |
00516be1 | 4067 | { |
8bbb16e3 | 4068 | if (!OpenedHttpSocket(s->listenConn, portTypeNote)) |
00516be1 | 4069 | return; |
62e76326 | 4070 | |
00516be1 | 4071 | Must(s); |
e0d28505 | 4072 | Must(Comm::IsConnOpen(s->listenConn)); |
62e76326 | 4073 | |
8bbb16e3 AJ |
4074 | // TCP: setup a job to handle accept() with subscribed handler |
4075 | AsyncJob::Start(new Comm::TcpAcceptor(s->listenConn, FdNote(portTypeNote), sub)); | |
4076 | ||
1b76e6c1 AJ |
4077 | debugs(1, 1, "Accepting " << |
4078 | (s->intercepted ? "NAT intercepted " : "") << | |
4079 | (s->spoof_client_ip ? "TPROXY spoofing " : "") << | |
4080 | (s->sslBump ? "SSL bumped " : "") << | |
4081 | (s->accel ? "reverse-proxy " : "") | |
8bbb16e3 AJ |
4082 | << FdNote(portTypeNote) << " connections at " |
4083 | << s->listenConn); | |
62e76326 | 4084 | |
e0d28505 | 4085 | Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for |
d193a436 | 4086 | } |
4087 | ||
d193a436 | 4088 | void |
4089 | clientOpenListenSockets(void) | |
4090 | { | |
4091 | clientHttpConnectionsOpen(); | |
4092 | #if USE_SSL | |
4093 | clientHttpsConnectionsOpen(); | |
1f7c9178 | 4094 | #endif |
62e76326 | 4095 | |
15df8349 | 4096 | if (NHttpSockets < 1) |
598c41da | 4097 | fatal("No HTTP or HTTPS ports configured"); |
15df8349 | 4098 | } |
edce4d98 | 4099 | |
c0fbae16 | 4100 | void |
4101 | clientHttpConnectionsClose(void) | |
4102 | { | |
04f55905 | 4103 | for (http_port_list *s = Config.Sockaddr.http; s; s = s->next) { |
00406b24 | 4104 | if (s->listenConn != NULL) { |
e0d28505 | 4105 | debugs(1, 1, "Closing HTTP port " << s->listenConn->local); |
00406b24 AJ |
4106 | s->listenConn->close(); |
4107 | s->listenConn = NULL; | |
04f55905 AJ |
4108 | } |
4109 | } | |
62e76326 | 4110 | |
04f55905 AJ |
4111 | #if USE_SSL |
4112 | for (http_port_list *s = Config.Sockaddr.https; s; s = s->next) { | |
00406b24 | 4113 | if (s->listenConn != NULL) { |
e0d28505 | 4114 | debugs(1, 1, "Closing HTTPS port " << s->listenConn->local); |
00406b24 AJ |
4115 | s->listenConn->close(); |
4116 | s->listenConn = NULL; | |
62e76326 | 4117 | } |
c0fbae16 | 4118 | } |
04f55905 AJ |
4119 | #endif |
4120 | ||
4121 | // TODO see if we can drop HttpSockets array entirely */ | |
4122 | for (int i = 0; i < NHttpSockets; i++) { | |
4123 | HttpSockets[i] = -1; | |
4124 | } | |
62e76326 | 4125 | |
c0fbae16 | 4126 | NHttpSockets = 0; |
4127 | } | |
f66a9ef4 | 4128 | |
4129 | int | |
190154cf | 4130 | varyEvaluateMatch(StoreEntry * entry, HttpRequest * request) |
f66a9ef4 | 4131 | { |
4132 | const char *vary = request->vary_headers; | |
a9925b40 | 4133 | int has_vary = entry->getReply()->header.has(HDR_VARY); |
f66a9ef4 | 4134 | #if X_ACCELERATOR_VARY |
62e76326 | 4135 | |
edce4d98 | 4136 | has_vary |= |
a9925b40 | 4137 | entry->getReply()->header.has(HDR_X_ACCELERATOR_VARY); |
f66a9ef4 | 4138 | #endif |
62e76326 | 4139 | |
f66a9ef4 | 4140 | if (!has_vary || !entry->mem_obj->vary_headers) { |
62e76326 | 4141 | if (vary) { |
4142 | /* Oops... something odd is going on here.. */ | |
9e008dda AJ |
4143 | debugs(33, 1, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" << |
4144 | entry->mem_obj->url << "' '" << vary << "'"); | |
62e76326 | 4145 | safe_free(request->vary_headers); |
4146 | return VARY_CANCEL; | |
4147 | } | |
4148 | ||
4149 | if (!has_vary) { | |
4150 | /* This is not a varying object */ | |
4151 | return VARY_NONE; | |
4152 | } | |
4153 | ||
4154 | /* virtual "vary" object found. Calculate the vary key and | |
4155 | * continue the search | |
4156 | */ | |
4157 | vary = httpMakeVaryMark(request, entry->getReply()); | |
4158 | ||
4159 | if (vary) { | |
4160 | request->vary_headers = xstrdup(vary); | |
4161 | return VARY_OTHER; | |
4162 | } else { | |
4163 | /* Ouch.. we cannot handle this kind of variance */ | |
4164 | /* XXX This cannot really happen, but just to be complete */ | |
4165 | return VARY_CANCEL; | |
4166 | } | |
f66a9ef4 | 4167 | } else { |
62e76326 | 4168 | if (!vary) { |
4169 | vary = httpMakeVaryMark(request, entry->getReply()); | |
4170 | ||
4171 | if (vary) | |
4172 | request->vary_headers = xstrdup(vary); | |
4173 | } | |
4174 | ||
4175 | if (!vary) { | |
4176 | /* Ouch.. we cannot handle this kind of variance */ | |
4177 | /* XXX This cannot really happen, but just to be complete */ | |
4178 | return VARY_CANCEL; | |
4179 | } else if (strcmp(vary, entry->mem_obj->vary_headers) == 0) { | |
4180 | return VARY_MATCH; | |
4181 | } else { | |
4182 | /* Oops.. we have already been here and still haven't | |
4183 | * found the requested variant. Bail out | |
4184 | */ | |
bf8fe701 | 4185 | debugs(33, 1, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" << |
9e008dda | 4186 | entry->mem_obj->url << "' '" << vary << "'"); |
62e76326 | 4187 | return VARY_CANCEL; |
4188 | } | |
f66a9ef4 | 4189 | } |
4190 | } | |
28d4805a | 4191 | |
c0941a6a | 4192 | ACLFilledChecklist * |
59a1efb2 | 4193 | clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http) |
28d4805a | 4194 | { |
1cf238db | 4195 | ConnStateData * conn = http->getConn(); |
c0941a6a | 4196 | ACLFilledChecklist *ch = new ACLFilledChecklist(acl, http->request, |
73c36fd9 | 4197 | cbdataReferenceValid(conn) && conn != NULL && conn->clientConnection != NULL ? conn->clientConnection->rfc931 : dash_str); |
28d4805a | 4198 | |
4199 | /* | |
4200 | * hack for ident ACL. It needs to get full addresses, and a place to store | |
4201 | * the ident result on persistent connections... | |
4202 | */ | |
4203 | /* connection oriented auth also needs these two lines for it's operation. */ | |
4204 | /* | |
4205 | * Internal requests do not have a connection reference, because: A) their | |
4206 | * byte count may be transformed before being applied to an outbound | |
4207 | * connection B) they are internal - any limiting on them should be done on | |
4208 | * the server end. | |
4209 | */ | |
62e76326 | 4210 | |
1cf238db | 4211 | if (conn != NULL) |
c0941a6a | 4212 | ch->conn(conn); /* unreferenced in FilledCheckList.cc */ |
28d4805a | 4213 | |
4214 | return ch; | |
4215 | } | |
a46d2c0e | 4216 | |
4217 | CBDATA_CLASS_INIT(ConnStateData); | |
4218 | ||
5c336a3b AJ |
4219 | ConnStateData::ConnStateData() : |
4220 | AsyncJob("ConnStateData"), | |
061bbdec | 4221 | #if USE_SSL |
cf6eb29e | 4222 | switchedToHttps_(false), |
fd4624d7 | 4223 | sslServerBump(NULL), |
061bbdec | 4224 | #endif |
cf6eb29e CT |
4225 | stoppedSending_(NULL), |
4226 | stoppedReceiving_(NULL) | |
b65351fa | 4227 | { |
d67acb4e AJ |
4228 | pinning.pinned = false; |
4229 | pinning.auth = false; | |
b65351fa | 4230 | } |
a46d2c0e | 4231 | |
4232 | bool | |
4233 | ConnStateData::transparent() const | |
4234 | { | |
40d34a62 | 4235 | return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION)); |
a46d2c0e | 4236 | } |
4237 | ||
4238 | bool | |
4239 | ConnStateData::reading() const | |
4240 | { | |
f84dd7eb | 4241 | return reader != NULL; |
a46d2c0e | 4242 | } |
4243 | ||
4244 | void | |
f84dd7eb | 4245 | ConnStateData::stopReading() |
a46d2c0e | 4246 | { |
f84dd7eb | 4247 | if (reading()) { |
73c36fd9 | 4248 | comm_read_cancel(clientConnection->fd, reader); |
f84dd7eb AR |
4249 | reader = NULL; |
4250 | } | |
a46d2c0e | 4251 | } |
4252 | ||
5f8252d2 | 4253 | |
4254 | BodyPipe::Pointer | |
3e62bd58 | 4255 | ConnStateData::expectRequestBody(int64_t size) |
5f8252d2 | 4256 | { |
4257 | bodyPipe = new BodyPipe(this); | |
39cb8c41 AR |
4258 | if (size >= 0) |
4259 | bodyPipe->setBodySize(size); | |
4260 | else | |
4261 | startDechunkingRequest(); | |
5f8252d2 | 4262 | return bodyPipe; |
4263 | } | |
4264 | ||
39cb8c41 AR |
4265 | int64_t |
4266 | ConnStateData::mayNeedToReadMoreBody() const | |
4267 | { | |
4268 | if (!bodyPipe) | |
4269 | return 0; // request without a body or read/produced all body bytes | |
4270 | ||
4271 | if (!bodyPipe->bodySizeKnown()) | |
4272 | return -1; // probably need to read more, but we cannot be sure | |
4273 | ||
4274 | const int64_t needToProduce = bodyPipe->unproducedSize(); | |
4275 | const int64_t haveAvailable = static_cast<int64_t>(in.notYetUsed); | |
4276 | ||
4277 | if (needToProduce <= haveAvailable) | |
4278 | return 0; // we have read what we need (but are waiting for pipe space) | |
4279 | ||
4280 | return needToProduce - haveAvailable; | |
4281 | } | |
4282 | ||
55e44db9 | 4283 | void |
cf6eb29e | 4284 | ConnStateData::stopReceiving(const char *error) |
55e44db9 | 4285 | { |
cf6eb29e CT |
4286 | debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error << |
4287 | "; old sending error: " << | |
4288 | (stoppedSending() ? stoppedSending_ : "none")); | |
5f8252d2 | 4289 | |
cf6eb29e CT |
4290 | if (const char *oldError = stoppedReceiving()) { |
4291 | debugs(33, 3, HERE << "already stopped receiving: " << oldError); | |
4292 | return; // nothing has changed as far as this connection is concerned | |
4293 | } | |
5f8252d2 | 4294 | |
cf6eb29e | 4295 | stoppedReceiving_ = error; |
5f8252d2 | 4296 | |
cf6eb29e CT |
4297 | if (const char *sendError = stoppedSending()) { |
4298 | debugs(33, 3, HERE << "closing because also stopped sending: " << sendError); | |
4299 | clientConnection->close(); | |
4300 | } | |
55e44db9 | 4301 | } |
4302 | ||
eb44b2d7 | 4303 | void |
e29ccb57 A |
4304 | ConnStateData::expectNoForwarding() |
4305 | { | |
eb44b2d7 CT |
4306 | if (bodyPipe != NULL) { |
4307 | debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status()); | |
4308 | bodyPipe->expectNoConsumption(); | |
4309 | } | |
4310 | } | |
4311 | ||
39cb8c41 | 4312 | /// initialize dechunking state |
3ff65596 | 4313 | void |
39cb8c41 | 4314 | ConnStateData::startDechunkingRequest() |
3ff65596 | 4315 | { |
39cb8c41 AR |
4316 | Must(bodyPipe != NULL); |
4317 | debugs(33, 5, HERE << "start dechunking" << bodyPipe->status()); | |
3ff65596 AR |
4318 | assert(!in.bodyParser); |
4319 | in.bodyParser = new ChunkedCodingParser; | |
3ff65596 AR |
4320 | } |
4321 | ||
39cb8c41 | 4322 | /// put parsed content into input buffer and clean up |
3ff65596 | 4323 | void |
39cb8c41 | 4324 | ConnStateData::finishDechunkingRequest(bool withSuccess) |
3ff65596 | 4325 | { |
39cb8c41 | 4326 | debugs(33, 5, HERE << "finish dechunking: " << withSuccess); |
3ff65596 | 4327 | |
39cb8c41 AR |
4328 | if (bodyPipe != NULL) { |
4329 | debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status()); | |
4330 | BodyPipe::Pointer myPipe = bodyPipe; | |
4331 | stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize() | |
4332 | Must(!bodyPipe); // we rely on it being nil after we are done with body | |
4333 | if (withSuccess) { | |
4334 | Must(myPipe->bodySizeKnown()); | |
4335 | ClientSocketContext::Pointer context = getCurrentContext(); | |
4336 | if (context != NULL && context->http && context->http->request) | |
4337 | context->http->request->setContentLength(myPipe->bodySize()); | |
4338 | } | |
3ff65596 | 4339 | } |
3ff65596 | 4340 | |
39cb8c41 AR |
4341 | delete in.bodyParser; |
4342 | in.bodyParser = NULL; | |
3ff65596 AR |
4343 | } |
4344 | ||
a46d2c0e | 4345 | char * |
4346 | ConnStateData::In::addressToReadInto() const | |
4347 | { | |
4348 | return buf + notYetUsed; | |
4349 | } | |
4350 | ||
3ff65596 | 4351 | ConnStateData::In::In() : bodyParser(NULL), |
39cb8c41 | 4352 | buf (NULL), notYetUsed (0), allocatedSize (0) |
a46d2c0e | 4353 | {} |
4354 | ||
4355 | ConnStateData::In::~In() | |
4356 | { | |
4357 | if (allocatedSize) | |
4358 | memFreeBuf(allocatedSize, buf); | |
39cb8c41 | 4359 | delete bodyParser; // TODO: pool |
a46d2c0e | 4360 | } |
d67acb4e | 4361 | |
655daa06 AR |
4362 | void |
4363 | ConnStateData::sendControlMsg(HttpControlMsg msg) | |
4364 | { | |
eedd4182 AR |
4365 | if (!isOpen()) { |
4366 | debugs(33, 3, HERE << "ignoring 1xx due to earlier closure"); | |
655daa06 AR |
4367 | return; |
4368 | } | |
4369 | ||
eedd4182 AR |
4370 | ClientSocketContext::Pointer context = getCurrentContext(); |
4371 | if (context != NULL) { | |
4372 | context->writeControlMsg(msg); // will call msg.cbSuccess | |
655daa06 AR |
4373 | return; |
4374 | } | |
4375 | ||
4376 | debugs(33, 3, HERE << " closing due to missing context for 1xx"); | |
73c36fd9 | 4377 | clientConnection->close(); |
655daa06 AR |
4378 | } |
4379 | ||
d7ce0bcd | 4380 | /// Our close handler called by Comm when the pinned connection is closed |
d67acb4e AJ |
4381 | void |
4382 | ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io) | |
4383 | { | |
85563fd9 AR |
4384 | // it might be possible for FwdState to repin a failed connection sooner |
4385 | // than this close callback is called for the failed connection | |
4386 | if (pinning.serverConnection == io.conn) { | |
4387 | pinning.closeHandler = NULL; // Comm unregisters handlers before calling | |
4388 | unpinConnection(); | |
4389 | } | |
d67acb4e AJ |
4390 | } |
4391 | ||
b1cf2350 | 4392 | void |
73c36fd9 | 4393 | ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, struct peer *aPeer, bool auth) |
9e008dda | 4394 | { |
d67acb4e AJ |
4395 | char desc[FD_DESC_SZ]; |
4396 | ||
73c36fd9 AJ |
4397 | if (Comm::IsConnOpen(pinning.serverConnection)) { |
4398 | if (pinning.serverConnection->fd == pinServer->fd) | |
e3a4aecc | 4399 | return; |
d7ce0bcd | 4400 | } |
9e008dda | 4401 | |
d7ce0bcd | 4402 | unpinConnection(); // closes pinned connection, if any, and resets fields. |
9e008dda | 4403 | |
73c36fd9 | 4404 | pinning.serverConnection = pinServer; |
d7ce0bcd | 4405 | |
85563fd9 AR |
4406 | debugs(33, 3, HERE << pinning.serverConnection); |
4407 | ||
d7ce0bcd AR |
4408 | // when pinning an SSL bumped connection, the request may be NULL |
4409 | const char *pinnedHost = "[unknown]"; | |
4410 | if (request) { | |
4411 | pinning.host = xstrdup(request->GetHost()); | |
4412 | pinning.port = request->port; | |
4413 | pinnedHost = pinning.host; | |
4414 | } else { | |
4415 | pinning.port = pinServer->remote.GetPort(); | |
4416 | } | |
d67acb4e | 4417 | pinning.pinned = true; |
8bcf08e0 FC |
4418 | if (aPeer) |
4419 | pinning.peer = cbdataReference(aPeer); | |
d67acb4e | 4420 | pinning.auth = auth; |
e3a4aecc AJ |
4421 | char stmp[MAX_IPSTRLEN]; |
4422 | snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)", | |
d7ce0bcd AR |
4423 | (auth || !aPeer) ? pinnedHost : aPeer->name, |
4424 | clientConnection->remote.ToURL(stmp,MAX_IPSTRLEN), | |
4425 | clientConnection->fd); | |
73c36fd9 | 4426 | fd_note(pinning.serverConnection->fd, desc); |
9e008dda | 4427 | |
d67acb4e | 4428 | typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer; |
4299f876 | 4429 | pinning.closeHandler = JobCallback(33, 5, |
4cb2536f | 4430 | Dialer, this, ConnStateData::clientPinnedConnectionClosed); |
85563fd9 AR |
4431 | // remember the pinned connection so that cb does not unpin a fresher one |
4432 | typedef CommCloseCbParams Params; | |
4433 | Params ¶ms = GetCommParams<Params>(pinning.closeHandler); | |
4434 | params.conn = pinning.serverConnection; | |
73c36fd9 | 4435 | comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler); |
d67acb4e AJ |
4436 | } |
4437 | ||
e3a4aecc | 4438 | const Comm::ConnectionPointer |
b1cf2350 | 4439 | ConnStateData::validatePinnedConnection(HttpRequest *request, const struct peer *aPeer) |
d67acb4e | 4440 | { |
85563fd9 AR |
4441 | debugs(33, 7, HERE << pinning.serverConnection); |
4442 | ||
d67acb4e | 4443 | bool valid = true; |
73c36fd9 | 4444 | if (!Comm::IsConnOpen(pinning.serverConnection)) |
e3a4aecc | 4445 | valid = false; |
d67acb4e | 4446 | if (pinning.auth && request && strcasecmp(pinning.host, request->GetHost()) != 0) { |
9e008dda | 4447 | valid = false; |
d67acb4e | 4448 | } |
9e008dda AJ |
4449 | if (request && pinning.port != request->port) { |
4450 | valid = false; | |
d67acb4e | 4451 | } |
9e008dda AJ |
4452 | if (pinning.peer && !cbdataReferenceValid(pinning.peer)) { |
4453 | valid = false; | |
d67acb4e | 4454 | } |
8bcf08e0 | 4455 | if (aPeer != pinning.peer) { |
9e008dda | 4456 | valid = false; |
d67acb4e AJ |
4457 | } |
4458 | ||
9e008dda | 4459 | if (!valid) { |
b1cf2350 | 4460 | /* The pinning info is not safe, remove any pinning info */ |
9e008dda | 4461 | unpinConnection(); |
d67acb4e AJ |
4462 | } |
4463 | ||
73c36fd9 | 4464 | return pinning.serverConnection; |
d67acb4e AJ |
4465 | } |
4466 | ||
b1cf2350 AJ |
4467 | void |
4468 | ConnStateData::unpinConnection() | |
d67acb4e | 4469 | { |
85563fd9 AR |
4470 | debugs(33, 3, HERE << pinning.serverConnection); |
4471 | ||
9e008dda AJ |
4472 | if (pinning.peer) |
4473 | cbdataReferenceDone(pinning.peer); | |
d67acb4e | 4474 | |
d7ce0bcd | 4475 | if (Comm::IsConnOpen(pinning.serverConnection)) { |
9e008dda | 4476 | if (pinning.closeHandler != NULL) { |
73c36fd9 | 4477 | comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler); |
9e008dda | 4478 | pinning.closeHandler = NULL; |
d67acb4e | 4479 | } |
b1cf2350 | 4480 | /// also close the server side socket, we should not use it for any future requests... |
d7ce0bcd | 4481 | // TODO: do not close if called from our close handler? |
1b76e6c1 | 4482 | pinning.serverConnection->close(); |
d7ce0bcd AR |
4483 | } |
4484 | ||
d67acb4e | 4485 | safe_free(pinning.host); |
e3a4aecc AJ |
4486 | |
4487 | /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host | |
4488 | * connection has gone away */ | |
d67acb4e | 4489 | } |