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