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