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