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