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