]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side.cc
Second adaptation missing for CONNECTs
[thirdparty/squid.git] / src / client_side.cc
CommitLineData
dd11e0b7 1/*
4ac4a490 2 * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
dd11e0b7 3 *
bbc27441
AJ
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
dd11e0b7 7 */
f88bb09c 8
bbc27441
AJ
9/* DEBUG: section 33 Client-side Routines */
10
63be0a78 11/**
12 \defgroup ClientSide Client-Side Logics
13 *
d85b8894 14 \section cserrors Errors and client side
edce4d98 15 *
63be0a78 16 \par Problem the first:
17 * the store entry is no longer authoritative on the
edce4d98 18 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
19 * of client_side_reply.c.
20 * Problem the second: resources are wasted if we delay in cleaning up.
21 * Problem the third we can't depend on a connection close to clean up.
9e008dda 22 *
63be0a78 23 \par Nice thing the first:
9e008dda 24 * Any step in the stream can callback with data
edce4d98 25 * representing an error.
26 * Nice thing the second: once you stop requesting reads from upstream,
27 * upstream can be stopped too.
28 *
63be0a78 29 \par Solution #1:
30 * Error has a callback mechanism to hand over a membuf
9e008dda 31 * with the error content. The failing node pushes that back as the
edce4d98 32 * reply. Can this be generalised to reduce duplicate efforts?
33 * A: Possibly. For now, only one location uses this.
34 * How to deal with pre-stream errors?
35 * Tell client_side_reply that we *want* an error page before any
36 * stream calls occur. Then we simply read as normal.
63be0a78 37 *
38 *
d85b8894 39 \section pconn_logic Persistent connection logic:
63be0a78 40 *
41 \par
42 * requests (httpClientRequest structs) get added to the connection
43 * list, with the current one being chr
9e008dda 44 *
63be0a78 45 \par
46 * The request is *immediately* kicked off, and data flows through
47 * to clientSocketRecipient.
9e008dda 48 *
63be0a78 49 \par
50 * If the data that arrives at clientSocketRecipient is not for the current
51 * request, clientSocketRecipient simply returns, without requesting more
52 * data, or sending it.
53 *
54 \par
4a4fbcef 55 * ConnStateData::kick() will then detect the presence of data in
9e008dda 56 * the next ClientHttpRequest, and will send it, restablishing the
63be0a78 57 * data flow.
edce4d98 58 */
59
582c2af2 60#include "squid.h"
04f55905 61#include "acl/FilledChecklist.h"
65d448bc 62#include "anyp/PortCfg.h"
00406b24 63#include "base/Subscription.h"
d841c88d 64#include "base/TextException.h"
a011edee 65#include "CachePeer.h"
95e6d864 66#include "client_db.h"
602d9612 67#include "client_side.h"
04f55905
AJ
68#include "client_side_reply.h"
69#include "client_side_request.h"
70#include "ClientRequestContext.h"
c8be6d7b 71#include "clientStream.h"
c4b7a5a9 72#include "comm.h"
cfd66529 73#include "comm/Connection.h"
d841c88d 74#include "comm/Loops.h"
7e66d5e2 75#include "comm/Read.h"
cbff89ba 76#include "comm/TcpAcceptor.h"
582c2af2
FC
77#include "comm/Write.h"
78#include "CommCalls.h"
8eb0a7ee 79#include "errorpage.h"
c4ad1349 80#include "fd.h"
04f55905 81#include "fde.h"
95e6d864 82#include "fqdncache.h"
eb13c21e 83#include "FwdState.h"
67679543 84#include "globals.h"
24438ec5
AJ
85#include "helper.h"
86#include "helper/Reply.h"
5c0c642e 87#include "http.h"
c99510dd 88#include "http/one/RequestParser.h"
db1720f8 89#include "http/one/TeChunkedParser.h"
d3dddfb5 90#include "http/Stream.h"
25b6a907 91#include "HttpHdrContRange.h"
a5bac1d2 92#include "HttpHeaderTools.h"
528b2c61 93#include "HttpReply.h"
94#include "HttpRequest.h"
4daaf3cb
AJ
95#include "ident/Config.h"
96#include "ident/Ident.h"
308e60be 97#include "internal.h"
cbff89ba 98#include "ipc/FdNotes.h"
fe090a86 99#include "ipc/StartListening.h"
1c7ae5ff 100#include "log/access_log.h"
0eb49b6d 101#include "MemBuf.h"
04f55905 102#include "MemObject.h"
b6149797 103#include "mime_header.h"
b1cef121 104#include "parser/Tokenizer.h"
582c2af2 105#include "profiler/Profiler.h"
1fa9b1a7 106#include "rfc1738.h"
2bcab852 107#include "security/NegotiationHistory.h"
92ae4c86 108#include "servers/forward.h"
4d5904f7 109#include "SquidConfig.h"
582c2af2 110#include "SquidTime.h"
e1656dc4 111#include "StatCounters.h"
00a7574e 112#include "StatHist.h"
582c2af2
FC
113#include "Store.h"
114#include "TimeOrTag.h"
4e540555 115#include "tools.h"
b1bd952a 116#include "URL.h"
582c2af2
FC
117
118#if USE_AUTH
119#include "auth/UserRequest.h"
120#endif
121#if USE_DELAY_POOLS
122#include "ClientInfo.h"
b27668ec 123#include "MessageDelayPools.h"
582c2af2 124#endif
cb4f4424 125#if USE_OPENSSL
d620ae0e 126#include "ssl/bio.h"
95d2589c 127#include "ssl/context_storage.h"
602d9612 128#include "ssl/gadgets.h"
95d2589c 129#include "ssl/helper.h"
602d9612 130#include "ssl/ProxyCerts.h"
fd4624d7 131#include "ssl/ServerBump.h"
4db984be 132#include "ssl/support.h"
95d2589c 133#endif
95d2589c 134
ed6e9fb9
AJ
135// for tvSubUsec() which should be in SquidTime.h
136#include "util.h"
137
074d6a40
AJ
138#include <climits>
139#include <cmath>
95d2589c 140#include <limits>
95d2589c 141
5492ad1d 142#if LINGERING_CLOSE
143#define comm_close comm_lingering_close
144#endif
145
cbff89ba 146/// dials clientListenerConnectionOpened call
fe090a86
AR
147class ListeningStartedDialer: public CallDialer, public Ipc::StartListeningCb
148{
149public:
fa720bfb
AJ
150 typedef void (*Handler)(AnyP::PortCfgPointer &portCfg, const Ipc::FdNoteId note, const Subscription::Pointer &sub);
151 ListeningStartedDialer(Handler aHandler, AnyP::PortCfgPointer &aPortCfg, const Ipc::FdNoteId note, const Subscription::Pointer &aSub):
f53969cc 152 handler(aHandler), portCfg(aPortCfg), portTypeNote(note), sub(aSub) {}
fe090a86 153
5667a628
AR
154 virtual void print(std::ostream &os) const {
155 startPrint(os) <<
f53969cc 156 ", " << FdNote(portTypeNote) << " port=" << (void*)&portCfg << ')';
5667a628 157 }
fe090a86
AR
158
159 virtual bool canDial(AsyncCall &) const { return true; }
8bbb16e3 160 virtual void dial(AsyncCall &) { (handler)(portCfg, portTypeNote, sub); }
fe090a86
AR
161
162public:
163 Handler handler;
164
165private:
fa720bfb 166 AnyP::PortCfgPointer portCfg; ///< from HttpPortList
cbff89ba 167 Ipc::FdNoteId portTypeNote; ///< Type of IPC socket being opened
cbff89ba 168 Subscription::Pointer sub; ///< The handler to be subscribed for this connetion listener
fe090a86
AR
169};
170
fa720bfb 171static void clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub);
fe090a86 172
e0d28505 173static IOACB httpAccept;
cb4f4424 174#if USE_OPENSSL
e0d28505 175static IOACB httpsAccept;
40d34a62 176#endif
8d77a37c 177static CTCB clientLifetimeTimeout;
3898f57f 178#if USE_IDENT
05832ae1 179static IDCB clientIdentDone;
3898f57f 180#endif
190154cf 181static int clientIsContentLengthValid(HttpRequest * r);
47f6e231 182static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength);
50c09fc4 183
91369933
AJ
184static void clientUpdateStatHistCounters(const LogTags &logType, int svc_time);
185static void clientUpdateStatCounters(const LogTags &logType);
c8be6d7b 186static void clientUpdateHierCounters(HierarchyLogEntry *);
528b2c61 187static bool clientPingHasFinished(ping_data const *aPing);
41ebd397 188void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry::Pointer &);
d3dddfb5 189static void ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest, ConnStateData * conn);
c8be6d7b 190
84cc2635 191char *skipLeadingSpace(char *aString);
62e76326 192
edce4d98 193#if USE_IDENT
4d55827a 194static void
edce4d98 195clientIdentDone(const char *ident, void *data)
4d55827a 196{
cc59d02a 197 ConnStateData *conn = (ConnStateData *)data;
73c36fd9 198 xstrncpy(conn->clientConnection->rfc931, ident ? ident : dash_str, USER_IDENT_SZ);
e81957b7 199}
447e176b 200#endif
7a2f978b 201
c8be6d7b 202void
91369933 203clientUpdateStatCounters(const LogTags &logType)
a7c05555 204{
e4f1fdae 205 ++statCounter.client_http.requests;
62e76326 206
91369933 207 if (logType.isTcpHit())
e4f1fdae 208 ++statCounter.client_http.hits;
62e76326 209
91369933 210 if (logType.oldType == LOG_TCP_HIT)
e4f1fdae 211 ++statCounter.client_http.disk_hits;
91369933 212 else if (logType.oldType == LOG_TCP_MEM_HIT)
e4f1fdae 213 ++statCounter.client_http.mem_hits;
c8be6d7b 214}
215
216void
91369933 217clientUpdateStatHistCounters(const LogTags &logType, int svc_time)
c8be6d7b 218{
e8baef82 219 statCounter.client_http.allSvcTime.count(svc_time);
63be0a78 220 /**
ee1679df 221 * The idea here is not to be complete, but to get service times
222 * for only well-defined types. For example, we don't include
1d7ab0f4 223 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
ee1679df 224 * (we *tried* to validate it, but failed).
225 */
62e76326 226
91369933 227 switch (logType.oldType) {
62e76326 228
1d7ab0f4 229 case LOG_TCP_REFRESH_UNMODIFIED:
e8baef82 230 statCounter.client_http.nearHitSvcTime.count(svc_time);
62e76326 231 break;
232
787ea68c 233 case LOG_TCP_INM_HIT:
ee1679df 234 case LOG_TCP_IMS_HIT:
e8baef82 235 statCounter.client_http.nearMissSvcTime.count(svc_time);
62e76326 236 break;
237
ee1679df 238 case LOG_TCP_HIT:
62e76326 239
ee1679df 240 case LOG_TCP_MEM_HIT:
62e76326 241
b540e168 242 case LOG_TCP_OFFLINE_HIT:
e8baef82 243 statCounter.client_http.hitSvcTime.count(svc_time);
62e76326 244 break;
245
ee1679df 246 case LOG_TCP_MISS:
62e76326 247
ee1679df 248 case LOG_TCP_CLIENT_REFRESH_MISS:
e8baef82 249 statCounter.client_http.missSvcTime.count(svc_time);
62e76326 250 break;
251
ee1679df 252 default:
62e76326 253 /* make compiler warnings go away */
254 break;
ee1679df 255 }
c8be6d7b 256}
257
528b2c61 258bool
c8be6d7b 259clientPingHasFinished(ping_data const *aPing)
260{
261 if (0 != aPing->stop.tv_sec && 0 != aPing->start.tv_sec)
62e76326 262 return true;
263
528b2c61 264 return false;
c8be6d7b 265}
266
267void
268clientUpdateHierCounters(HierarchyLogEntry * someEntry)
269{
270 ping_data *i;
62e76326 271
c8547a11 272 switch (someEntry->code) {
273#if USE_CACHE_DIGESTS
62e76326 274
c8547a11 275 case CD_PARENT_HIT:
62e76326 276
a196e1e4 277 case CD_SIBLING_HIT:
95dc7ff4 278 ++ statCounter.cd.times_used;
62e76326 279 break;
c8547a11 280#endif
62e76326 281
c8547a11 282 case SIBLING_HIT:
62e76326 283
c8547a11 284 case PARENT_HIT:
62e76326 285
c8547a11 286 case FIRST_PARENT_MISS:
62e76326 287
c8547a11 288 case CLOSEST_PARENT_MISS:
95dc7ff4 289 ++ statCounter.icp.times_used;
62e76326 290 i = &someEntry->ping;
291
292 if (clientPingHasFinished(i))
e8baef82 293 statCounter.icp.querySvcTime.count(tvSubUsec(i->start, i->stop));
62e76326 294
295 if (i->timeout)
95dc7ff4 296 ++ statCounter.icp.query_timeouts;
62e76326 297
298 break;
299
c8547a11 300 case CLOSEST_PARENT:
62e76326 301
c8547a11 302 case CLOSEST_DIRECT:
95dc7ff4 303 ++ statCounter.netdb.times_used;
62e76326 304
305 break;
306
69c95dd3 307 default:
62e76326 308 break;
17b6e784 309 }
a7c05555 310}
311
528b2c61 312void
313ClientHttpRequest::updateCounters()
c8be6d7b 314{
528b2c61 315 clientUpdateStatCounters(logType);
62e76326 316
528b2c61 317 if (request->errType != ERR_NONE)
95dc7ff4 318 ++ statCounter.client_http.errors;
62e76326 319
528b2c61 320 clientUpdateStatHistCounters(logType,
af0ded40 321 tvSubMsec(al->cache.start_time, current_time));
62e76326 322
528b2c61 323 clientUpdateHierCounters(&request->hier);
c8be6d7b 324}
325
edce4d98 326void
41ebd397 327prepareLogWithRequestDetails(HttpRequest * request, AccessLogEntry::Pointer &aLogEntry)
7a2f978b 328{
c8be6d7b 329 assert(request);
41ebd397 330 assert(aLogEntry != NULL);
7684c4b1 331
332 if (Config.onoff.log_mime_hdrs) {
7684c4b1 333 MemBuf mb;
2fe7eff9 334 mb.init();
10201568 335 request->header.packInto(&mb);
105d1937
A
336 //This is the request after adaptation or redirection
337 aLogEntry->headers.adapted_request = xstrdup(mb.buf);
338
339 // the virgin request is saved to aLogEntry->request
340 if (aLogEntry->request) {
105d1937 341 mb.reset();
10201568 342 aLogEntry->request->header.packInto(&mb);
105d1937
A
343 aLogEntry->headers.request = xstrdup(mb.buf);
344 }
3ff65596 345
5038f9d8
AR
346#if USE_ADAPTATION
347 const Adaptation::History::Pointer ah = request->adaptLogHistory();
348 if (ah != NULL) {
5038f9d8 349 mb.reset();
10201568 350 ah->lastMeta.packInto(&mb);
99690f32 351 aLogEntry->adapt.last_meta = xstrdup(mb.buf);
5038f9d8 352 }
3ff65596
AR
353#endif
354
2fe7eff9 355 mb.clean();
7684c4b1 356 }
357
3ff65596 358#if ICAP_CLIENT
5038f9d8 359 const Adaptation::Icap::History::Pointer ih = request->icapHistory();
3ff65596 360 if (ih != NULL)
01bd87d8 361 ih->processingTime(aLogEntry->icap.processingTime);
3ff65596
AR
362#endif
363
c8be6d7b 364 aLogEntry->http.method = request->method;
365 aLogEntry->http.version = request->http_ver;
c8be6d7b 366 aLogEntry->hier = request->hier;
5b4117d8 367 aLogEntry->cache.extuser = request->extacl_user.termedBuf();
abb929f0 368
a119c6ad
AR
369 // Adapted request, if any, inherits and then collects all the stats, but
370 // the virgin request gets logged instead; copy the stats to log them.
371 // TODO: avoid losses by keeping these stats in a shared history object?
64b66b76 372 if (aLogEntry->request) {
a119c6ad 373 aLogEntry->request->dnsWait = request->dnsWait;
64b66b76
CT
374 aLogEntry->request->errType = request->errType;
375 aLogEntry->request->errDetail = request->errDetail;
376 }
c8be6d7b 377}
378
379void
528b2c61 380ClientHttpRequest::logRequest()
381{
91369933
AJ
382 if (!out.size && logType.oldType == LOG_TAG_NONE)
383 debugs(33, 5, "logging half-baked transaction: " << log_uri);
6fd1086a 384
41ebd397
CT
385 al->icp.opcode = ICP_INVALID;
386 al->url = log_uri;
387 debugs(33, 9, "clientLogRequest: al.url='" << al->url << "'");
62e76326 388
41ebd397 389 if (al->reply) {
9b769c67 390 al->http.code = al->reply->sline.status();
41ebd397 391 al->http.content_type = al->reply->content_type.termedBuf();
6fd1086a 392 } else if (loggingEntry() && loggingEntry()->mem_obj) {
9b769c67 393 al->http.code = loggingEntry()->mem_obj->getReply()->sline.status();
41ebd397 394 al->http.content_type = loggingEntry()->mem_obj->getReply()->content_type.termedBuf();
6fd1086a 395 }
5f8252d2 396
41ebd397 397 debugs(33, 9, "clientLogRequest: http.code='" << al->http.code << "'");
90a8964c 398
3a646078 399 if (loggingEntry() && loggingEntry()->mem_obj && loggingEntry()->objectLen() >= 0)
d6df21d2 400 al->cache.objectSize = loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
90a8964c 401
cc0ca3b9 402 al->http.clientRequestSz.header = req_sz;
bd59d61c
EB
403 // the virgin request is saved to al->request
404 if (al->request && al->request->body_pipe)
405 al->http.clientRequestSz.payloadData = al->request->body_pipe->producedSize();
cc0ca3b9 406 al->http.clientReplySz.header = out.headers_sz;
d6df21d2 407 // XXX: calculate without payload encoding or headers !!
cc0ca3b9 408 al->http.clientReplySz.payloadData = out.size - out.headers_sz; // pretend its all un-encoded data for now.
90a8964c 409
41ebd397 410 al->cache.highOffset = out.offset;
90a8964c 411
41ebd397 412 al->cache.code = logType;
62e76326 413
01bd87d8 414 tvSub(al->cache.trTime, al->cache.start_time, current_time);
62e76326 415
6fd1086a 416 if (request)
41ebd397 417 prepareLogWithRequestDetails(request, al);
62e76326 418
1b76e6c1 419 if (getConn() != NULL && getConn()->clientConnection != NULL && getConn()->clientConnection->rfc931[0])
41ebd397 420 al->cache.rfc931 = getConn()->clientConnection->rfc931;
62e76326 421
cb4f4424 422#if USE_OPENSSL && 0
62e76326 423
6fd1086a
AR
424 /* This is broken. Fails if the connection has been closed. Needs
425 * to snarf the ssl details some place earlier..
426 */
427 if (getConn() != NULL)
41ebd397 428 al->cache.ssluser = sslGetUserEmail(fd_table[getConn()->fd].ssl);
62e76326 429
a7ad6e4e 430#endif
62e76326 431
f8a2338f
AJ
432 /* Add notes (if we have a request to annotate) */
433 if (request) {
75d47340
CT
434 SBuf matched;
435 for (auto h: Config.notes) {
436 if (h->match(request, al->reply, NULL, matched)) {
437 request->notes()->add(h->key(), matched);
438 debugs(33, 3, h->key() << " " << matched);
f8a2338f 439 }
d7f4a0b7 440 }
75d47340
CT
441 // The al->notes and request->notes must point to the same object.
442 al->syncNotes(request);
d7f4a0b7
CT
443 }
444
8ebad780 445 ACLFilledChecklist checklist(NULL, request, NULL);
b248c2a3 446 if (al->reply) {
8ebad780
CT
447 checklist.reply = al->reply;
448 HTTPMSGLOCK(checklist.reply);
b248c2a3 449 }
62e76326 450
8ebad780 451 if (request) {
542e1a7a 452 HTTPMSGUNLOCK(al->adapted_request);
8ebad780
CT
453 al->adapted_request = request;
454 HTTPMSGLOCK(al->adapted_request);
455 }
456 accessLogLog(al, &checklist);
457
458 bool updatePerformanceCounters = true;
459 if (Config.accessList.stats_collection) {
460 ACLFilledChecklist statsCheck(Config.accessList.stats_collection, request, NULL);
461 if (al->reply) {
462 statsCheck.reply = al->reply;
463 HTTPMSGLOCK(statsCheck.reply);
b248c2a3 464 }
8ebad780
CT
465 updatePerformanceCounters = (statsCheck.fastCheck() == ACCESS_ALLOWED);
466 }
467
468 if (updatePerformanceCounters) {
2ae98e09
TH
469 if (request)
470 updateCounters();
7684c4b1 471
1b76e6c1
AJ
472 if (getConn() != NULL && getConn()->clientConnection != NULL)
473 clientdbUpdate(getConn()->clientConnection->remote, logType, AnyP::PROTO_HTTP, out.size);
7a2f978b 474 }
c8be6d7b 475}
476
477void
528b2c61 478ClientHttpRequest::freeResources()
c8be6d7b 479{
528b2c61 480 safe_free(uri);
481 safe_free(log_uri);
482 safe_free(redirect.location);
30abd221 483 range_iter.boundary.clean();
6dd9f4bd 484 HTTPMSGUNLOCK(request);
62e76326 485
528b2c61 486 if (client_stream.tail)
62e76326 487 clientStreamAbort((clientStreamNode *)client_stream.tail->data, this);
c8be6d7b 488}
489
490void
491httpRequestFree(void *data)
492{
59a1efb2 493 ClientHttpRequest *http = (ClientHttpRequest *)data;
c8be6d7b 494 assert(http != NULL);
528b2c61 495 delete http;
7a2f978b 496}
497
498/* This is a handler normally called by comm_close() */
ced8def3 499void ConnStateData::connStateClosed(const CommCloseCbParams &)
7a2f978b 500{
6e1d409c 501 deleteThis("ConnStateData::connStateClosed");
a46d2c0e 502}
62e76326 503
cc1e110a
AJ
504#if USE_AUTH
505void
506ConnStateData::setAuth(const Auth::UserRequest::Pointer &aur, const char *by)
507{
508 if (auth_ == NULL) {
509 if (aur != NULL) {
510 debugs(33, 2, "Adding connection-auth to " << clientConnection << " from " << by);
511 auth_ = aur;
512 }
513 return;
514 }
515
516 // clobered with self-pointer
517 // NP: something nasty is going on in Squid, but harmless.
518 if (aur == auth_) {
519 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection << " from " << by);
520 return;
521 }
522
523 /*
524 * Connection-auth relies on a single set of credentials being preserved
525 * for all requests on a connection once they have been setup.
526 * There are several things which need to happen to preserve security
527 * when connection-auth credentials change unexpectedly or are unset.
528 *
529 * 1) auth helper released from any active state
530 *
531 * They can only be reserved by a handshake process which this
532 * connection can now never complete.
533 * This prevents helpers hanging when their connections close.
534 *
535 * 2) pinning is expected to be removed and server conn closed
536 *
537 * The upstream link is authenticated with the same credentials.
538 * Expecting the same level of consistency we should have received.
539 * This prevents upstream being faced with multiple or missing
540 * credentials after authentication.
541 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
542 * we just trigger that cleanup here via comm_reset_close() or
543 * ConnStateData::stopReceiving()
544 *
545 * 3) the connection needs to close.
546 *
547 * This prevents attackers injecting requests into a connection,
548 * or gateways wrongly multiplexing users into a single connection.
549 *
550 * When credentials are missing closure needs to follow an auth
551 * challenge for best recovery by the client.
552 *
553 * When credentials change there is nothing we can do but abort as
554 * fast as possible. Sending TCP RST instead of an HTTP response
555 * is the best-case action.
556 */
557
558 // clobbered with nul-pointer
559 if (aur == NULL) {
560 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection << " due to connection-auth erase from " << by);
561 auth_->releaseAuthServer();
562 auth_ = NULL;
563 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
564 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
565 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
566 stopReceiving("connection-auth removed");
567 return;
568 }
569
570 // clobbered with alternative credentials
571 if (aur != auth_) {
572 debugs(33, 2, "ERROR: Closing " << clientConnection << " due to change of connection-auth from " << by);
573 auth_->releaseAuthServer();
574 auth_ = NULL;
575 // this is a fatal type of problem.
576 // Close the connection immediately with TCP RST to abort all traffic flow
577 comm_reset_close(clientConnection);
578 return;
579 }
580
581 /* NOT REACHABLE */
582}
583#endif
584
6e1d409c 585// cleans up before destructor is called
a2ac85d9 586void
6e1d409c 587ConnStateData::swanSong()
a46d2c0e 588{
73c36fd9 589 debugs(33, 2, HERE << clientConnection);
da6dbcd1
EB
590 checkLogging();
591
f35961af 592 flags.readMore = false;
f53969cc 593 clientdbEstablished(clientConnection->remote, -1); /* decrement */
43e45ea7 594 pipeline.terminateAll(0);
6e1d409c 595
89b1d7a2 596 unpinConnection(true);
e3a4aecc 597
fcc444e3 598 Server::swanSong(); // closes the client connection
d67acb4e 599
cc1e110a
AJ
600#if USE_AUTH
601 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
602 setAuth(NULL, "ConnStateData::SwanSong cleanup");
603#endif
604
6e1d409c 605 flags.swanSang = true;
a2ac85d9 606}
607
608bool
609ConnStateData::isOpen() const
610{
10b06767 611 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
73c36fd9
AJ
612 Comm::IsConnOpen(clientConnection) &&
613 !fd_table[clientConnection->fd].closing();
a2ac85d9 614}
615
616ConnStateData::~ConnStateData()
617{
73c36fd9 618 debugs(33, 3, HERE << clientConnection);
a2ac85d9 619
620 if (isOpen())
e0236918 621 debugs(33, DBG_IMPORTANT, "BUG: ConnStateData did not close " << clientConnection);
6e1d409c
AR
622
623 if (!flags.swanSang)
e0236918 624 debugs(33, DBG_IMPORTANT, "BUG: ConnStateData was not destroyed properly; " << clientConnection);
62e76326 625
279152e7
AJ
626 if (bodyPipe != NULL)
627 stopProducingFor(bodyPipe, false);
87f237a9 628
fcc444e3
AJ
629 delete bodyParser; // TODO: pool
630
cb4f4424 631#if USE_OPENSSL
fd4624d7 632 delete sslServerBump;
8a7fe008 633#endif
7a2f978b 634}
635
63be0a78 636/**
450fe1cb 637 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
c68e9c6b 638 * This is the client-side persistent connection flag. We need
639 * to set this relatively early in the request processing
640 * to handle hacks for broken servers and clients.
641 */
92ae4c86 642void
59a1efb2 643clientSetKeepaliveFlag(ClientHttpRequest * http)
c68e9c6b 644{
190154cf 645 HttpRequest *request = http->request;
f6329bc3 646
7f06a3d8
AJ
647 debugs(33, 3, "http_ver = " << request->http_ver);
648 debugs(33, 3, "method = " << request->method);
62e76326 649
4a1acc56 650 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
e857372a 651 request->flags.proxyKeepalive = request->persistent();
c68e9c6b 652}
653
3e42b356 654/// checks body length of non-chunked requests
31be8b80 655static int
190154cf 656clientIsContentLengthValid(HttpRequest * r)
31be8b80 657{
3e42b356
AR
658 // No Content-Length means this request just has no body, but conflicting
659 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
660 if (r->header.conflictingContentLength())
661 return 0;
662
914b89a2 663 switch (r->method.id()) {
62e76326 664
c2a7cefd 665 case Http::METHOD_GET:
62e76326 666
c2a7cefd 667 case Http::METHOD_HEAD:
62e76326 668 /* We do not want to see a request entity on GET/HEAD requests */
669 return (r->content_length <= 0 || Config.onoff.request_entities);
670
ffc128c4 671 default:
62e76326 672 /* For other types of requests we don't care */
673 return 1;
ffc128c4 674 }
62e76326 675
ffc128c4 676 /* NOT REACHED */
31be8b80 677}
678
c8be6d7b 679int
47f6e231 680clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength)
efd900cb 681{
c8be6d7b 682 if (Config.maxRequestBodySize &&
62e76326 683 bodyLength > Config.maxRequestBodySize)
f53969cc 684 return 1; /* too large */
62e76326 685
efd900cb 686 return 0;
687}
688
528b2c61 689bool
690ClientHttpRequest::multipartRangeRequest() const
691{
692 return request->multipartRangeRequest();
693}
694
4ad60609 695void
d6fdeb41 696clientPackTermBound(String boundary, MemBuf *mb)
528b2c61 697{
4391cd15 698 mb->appendf("\r\n--" SQUIDSTRINGPH "--\r\n", SQUIDSTRINGPRINT(boundary));
d6fdeb41 699 debugs(33, 6, "buf offset: " << mb->size);
528b2c61 700}
701
d6fdeb41 702void
a0c227a9 703clientPackRangeHdr(const HttpReplyPointer &rep, const HttpHdrRangeSpec * spec, String boundary, MemBuf * mb)
528b2c61 704{
75faaa7a 705 HttpHeader hdr(hoReply);
528b2c61 706 assert(rep);
707 assert(spec);
708
709 /* put boundary */
d6fdeb41 710 debugs(33, 5, "appending boundary: " << boundary);
528b2c61 711 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
4391cd15 712 mb->appendf("\r\n--" SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(boundary));
528b2c61 713
714 /* stuff the header with required entries and pack it */
62e76326 715
789217a2
FC
716 if (rep->header.has(Http::HdrType::CONTENT_TYPE))
717 hdr.putStr(Http::HdrType::CONTENT_TYPE, rep->header.getStr(Http::HdrType::CONTENT_TYPE));
62e76326 718
528b2c61 719 httpHeaderAddContRange(&hdr, *spec, rep->content_length);
62e76326 720
10201568 721 hdr.packInto(mb);
519e0948 722 hdr.clean();
528b2c61 723
724 /* append <crlf> (we packed a header, not a reply) */
10201568 725 mb->append("\r\n", 2);
528b2c61 726}
727
63be0a78 728/** returns expected content length for multi-range replies
528b2c61 729 * note: assumes that httpHdrRangeCanonize has already been called
730 * warning: assumes that HTTP headers for individual ranges at the
731 * time of the actuall assembly will be exactly the same as
732 * the headers when clientMRangeCLen() is called */
733int
734ClientHttpRequest::mRangeCLen()
c8be6d7b 735{
47f6e231 736 int64_t clen = 0;
c8be6d7b 737 MemBuf mb;
528b2c61 738
86a2f789 739 assert(memObject());
528b2c61 740
2fe7eff9 741 mb.init();
528b2c61 742 HttpHdrRange::iterator pos = request->range->begin();
62e76326 743
528b2c61 744 while (pos != request->range->end()) {
62e76326 745 /* account for headers for this range */
2fe7eff9 746 mb.reset();
86a2f789 747 clientPackRangeHdr(memObject()->getReply(),
62e76326 748 *pos, range_iter.boundary, &mb);
749 clen += mb.size;
528b2c61 750
62e76326 751 /* account for range content */
752 clen += (*pos)->length;
528b2c61 753
4a7a3d56 754 debugs(33, 6, "clientMRangeCLen: (clen += " << mb.size << " + " << (*pos)->length << ") == " << clen);
62e76326 755 ++pos;
528b2c61 756 }
62e76326 757
528b2c61 758 /* account for the terminating boundary */
2fe7eff9 759 mb.reset();
62e76326 760
528b2c61 761 clientPackTermBound(range_iter.boundary, &mb);
62e76326 762
528b2c61 763 clen += mb.size;
764
2fe7eff9 765 mb.clean();
62e76326 766
528b2c61 767 return clen;
768}
769
63be0a78 770/**
771 * generates a "unique" boundary string for multipart responses
528b2c61 772 * the caller is responsible for cleaning the string */
30abd221 773String
528b2c61 774ClientHttpRequest::rangeBoundaryStr() const
775{
528b2c61 776 const char *key;
7dbca7a4
AJ
777 String b(APP_FULLNAME);
778 b.append(":",1);
86a2f789 779 key = storeEntry()->getMD5Text();
528b2c61 780 b.append(key, strlen(key));
781 return b;
782}
783
63be0a78 784/**
7dc5f514 785 * Write a chunk of data to a client socket. If the reply is present,
786 * send the reply headers down the wire too, and clean them up when
787 * finished.
9e008dda 788 * Pre-condition:
edce4d98 789 * The request is one backed by a connection, not an internal request.
790 * data context is not NULL
791 * There are no more entries in the stream chain.
2246b732 792 */
92ae4c86 793void
59a1efb2 794clientSocketRecipient(clientStreamNode * node, ClientHttpRequest * http,
2324cda2 795 HttpReply * rep, StoreIOBuffer receivedData)
edce4d98 796{
51571330
AJ
797 // dont tryt to deliver if client already ABORTED
798 if (!http->getConn() || !cbdataReferenceValid(http->getConn()) || !Comm::IsConnOpen(http->getConn()->clientConnection))
799 return;
800
edce4d98 801 /* Test preconditions */
802 assert(node != NULL);
559da936 803 PROF_start(clientSocketRecipient);
62e76326 804 /* TODO: handle this rather than asserting
9e008dda
AJ
805 * - it should only ever happen if we cause an abort and
806 * the callback chain loops back to here, so we can simply return.
807 * However, that itself shouldn't happen, so it stays as an assert for now.
edce4d98 808 */
809 assert(cbdataReferenceValid(node));
edce4d98 810 assert(node->node.next == NULL);
d3dddfb5 811 Http::StreamPointer context = dynamic_cast<Http::Stream *>(node->data.getRaw());
94a396a3 812 assert(context != NULL);
5c336a3b 813
528b2c61 814 /* TODO: check offset is what we asked for */
62e76326 815
efd5e784
AJ
816 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
817 if (context != http->getConn()->pipeline.front())
2324cda2 818 context->deferRecipientForLater(node, rep, receivedData);
24e1fd72
CT
819 else if (http->getConn()->cbControlMsgSent) // 1xx to the user is pending
820 context->deferRecipientForLater(node, rep, receivedData);
92ae4c86
AR
821 else
822 http->getConn()->handleReply(rep, receivedData);
fc68f6b1 823
559da936 824 PROF_stop(clientSocketRecipient);
edce4d98 825}
826
63be0a78 827/**
828 * Called when a downstream node is no longer interested in
edce4d98 829 * our data. As we are a terminal node, this means on aborts
830 * only
831 */
832void
59a1efb2 833clientSocketDetach(clientStreamNode * node, ClientHttpRequest * http)
edce4d98 834{
edce4d98 835 /* Test preconditions */
836 assert(node != NULL);
62e76326 837 /* TODO: handle this rather than asserting
9e008dda
AJ
838 * - it should only ever happen if we cause an abort and
839 * the callback chain loops back to here, so we can simply return.
edce4d98 840 * However, that itself shouldn't happen, so it stays as an assert for now.
841 */
842 assert(cbdataReferenceValid(node));
843 /* Set null by ContextFree */
edce4d98 844 assert(node->node.next == NULL);
0655fa4d 845 /* this is the assert discussed above */
d3dddfb5 846 assert(NULL == dynamic_cast<Http::Stream *>(node->data.getRaw()));
edce4d98 847 /* We are only called when the client socket shutsdown.
848 * Tell the prev pipeline member we're finished
849 */
850 clientStreamDetach(node, http);
7a2f978b 851}
852
c8be6d7b 853void
a46d2c0e 854ConnStateData::readNextRequest()
c8be6d7b 855{
73c36fd9 856 debugs(33, 5, HERE << clientConnection << " reading next req");
bf8fe701 857
97b32442 858 fd_note(clientConnection->fd, "Idle client: Waiting for next request");
63be0a78 859 /**
5ddf7edc 860 * Set the timeout BEFORE calling readSomeData().
c8be6d7b 861 */
1cf238db 862 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876 863 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
4cb2536f 864 TimeoutDialer, this, ConnStateData::requestTimeout);
c5c06f02 865 commSetConnTimeout(clientConnection, clientConnection->timeLeft(idleTimeout()), timeoutCall);
1cf238db 866
a46d2c0e 867 readSomeData();
63be0a78 868 /** Please don't do anything with the FD past here! */
c8be6d7b 869}
870
09d3938c 871static void
d3dddfb5 872ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest, ConnStateData * conn)
c8be6d7b 873{
73c36fd9 874 debugs(33, 2, HERE << conn->clientConnection << " Sending next");
bf8fe701 875
63be0a78 876 /** If the client stream is waiting on a socket write to occur, then */
62e76326 877
c8be6d7b 878 if (deferredRequest->flags.deferred) {
63be0a78 879 /** NO data is allowed to have been sent. */
62e76326 880 assert(deferredRequest->http->out.size == 0);
63be0a78 881 /** defer now. */
62e76326 882 clientSocketRecipient(deferredRequest->deferredparams.node,
883 deferredRequest->http,
884 deferredRequest->deferredparams.rep,
885 deferredRequest->deferredparams.queuedBuffer);
c8be6d7b 886 }
62e76326 887
63be0a78 888 /** otherwise, the request is still active in a callbacksomewhere,
c8be6d7b 889 * and we are done
f4f278b5 890 */
f4f278b5 891}
892
0655fa4d 893void
f4a53cf7 894ConnStateData::kick()
1a92a1e2 895{
4a4fbcef
AJ
896 if (!Comm::IsConnOpen(clientConnection)) {
897 debugs(33, 2, clientConnection << " Connection was closed");
898 return;
899 }
0655fa4d 900
f4a53cf7
AJ
901 if (pinning.pinned && !Comm::IsConnOpen(pinning.serverConnection)) {
902 debugs(33, 2, clientConnection << " Connection was pinned but server side gone. Terminating client connection");
903 clientConnection->close();
d67acb4e
AJ
904 return;
905 }
906
cf6eb29e
CT
907 /** \par
908 * We are done with the response, and we are either still receiving request
909 * body (early response!) or have already stopped receiving anything.
910 *
911 * If we are still receiving, then clientParseRequest() below will fail.
912 * (XXX: but then we will call readNextRequest() which may succeed and
913 * execute a smuggled request as we are not done with the current request).
914 *
915 * If we stopped because we got everything, then try the next request.
916 *
917 * If we stopped receiving because of an error, then close now to avoid
918 * getting stuck and to prevent accidental request smuggling.
919 */
920
f4a53cf7
AJ
921 if (const char *reason = stoppedReceiving()) {
922 debugs(33, 3, "closing for earlier request error: " << reason);
923 clientConnection->close();
cf6eb29e
CT
924 return;
925 }
926
63be0a78 927 /** \par
f900210a 928 * Attempt to parse a request from the request buffer.
929 * If we've been fed a pipelined request it may already
930 * be in our read buffer.
931 *
63be0a78 932 \par
f900210a 933 * This needs to fall through - if we're unlucky and parse the _last_ request
934 * from our read buffer we may never re-register for another client read.
935 */
936
f4a53cf7
AJ
937 if (clientParseRequests()) {
938 debugs(33, 3, clientConnection << ": parsed next request from buffer");
f900210a 939 }
940
63be0a78 941 /** \par
f900210a 942 * Either we need to kick-start another read or, if we have
943 * a half-closed connection, kill it after the last request.
944 * This saves waiting for half-closed connections to finished being
945 * half-closed _AND_ then, sometimes, spending "Timeout" time in
946 * the keepalive "Waiting for next request" state.
947 */
f4a53cf7 948 if (commIsHalfClosed(clientConnection->fd) && pipeline.empty()) {
e500cc89 949 debugs(33, 3, "half-closed client with no pending requests, closing");
f4a53cf7 950 clientConnection->close();
f900210a 951 return;
952 }
953
63be0a78 954 /** \par
f900210a 955 * At this point we either have a parsed request (which we've
956 * kicked off the processing for) or not. If we have a deferred
957 * request (parsed but deferred for pipeling processing reasons)
958 * then look at processing it. If not, simply kickstart
959 * another read.
960 */
d3dddfb5 961 Http::StreamPointer deferredRequest = pipeline.front();
efd5e784 962 if (deferredRequest != nullptr) {
f4a53cf7
AJ
963 debugs(33, 3, clientConnection << ": calling PushDeferredIfNeeded");
964 ClientSocketContextPushDeferredIfNeeded(deferredRequest, this);
965 } else if (flags.readMore) {
966 debugs(33, 3, clientConnection << ": calling readNextRequest()");
967 readNextRequest();
f35961af
AR
968 } else {
969 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
f4a53cf7 970 debugs(33, DBG_IMPORTANT, MYNAME << "abandoning " << clientConnection);
f900210a 971 }
1a92a1e2 972}
973
cf6eb29e
CT
974void
975ConnStateData::stopSending(const char *error)
976{
977 debugs(33, 4, HERE << "sending error (" << clientConnection << "): " << error <<
978 "; old receiving error: " <<
979 (stoppedReceiving() ? stoppedReceiving_ : "none"));
fc68f6b1 980
cf6eb29e
CT
981 if (const char *oldError = stoppedSending()) {
982 debugs(33, 3, HERE << "already stopped sending: " << oldError);
983 return; // nothing has changed as far as this connection is concerned
984 }
985 stoppedSending_ = error;
fc68f6b1 986
cf6eb29e
CT
987 if (!stoppedReceiving()) {
988 if (const int64_t expecting = mayNeedToReadMoreBody()) {
989 debugs(33, 5, HERE << "must still read " << expecting <<
fcc444e3 990 " request body bytes with " << inBuf.length() << " unused");
cf6eb29e 991 return; // wait for the request receiver to finish reading
3b299123 992 }
55e44db9 993 }
994
cf6eb29e 995 clientConnection->close();
55e44db9 996}
997
0655fa4d 998void
21cd3227
AJ
999ConnStateData::afterClientWrite(size_t size)
1000{
1001 if (pipeline.empty())
1002 return;
1003
d6fdeb41
AJ
1004 auto ctx = pipeline.front();
1005 if (size) {
1006 statCounter.client_http.kbytes_out += size;
1007 if (ctx->http->logType.isTcpHit())
1008 statCounter.client_http.hit_kbytes_out += size;
7a2f978b 1009 }
d6fdeb41 1010 ctx->writeComplete(size);
7a2f978b 1011}
1012
d3dddfb5 1013Http::Stream *
eacfca83 1014ConnStateData::abortRequestParsing(const char *const uri)
038eb4ed 1015{
eacfca83 1016 ClientHttpRequest *http = new ClientHttpRequest(this);
fcc444e3 1017 http->req_sz = inBuf.length();
edce4d98 1018 http->uri = xstrdup(uri);
c4b7a5a9 1019 setLogUri (http, uri);
d3dddfb5 1020 auto *context = new Http::Stream(clientConnection, http);
942b1c39
AJ
1021 StoreIOBuffer tempBuffer;
1022 tempBuffer.data = context->reqbuf;
1023 tempBuffer.length = HTTP_REQBUF_SZ;
edce4d98 1024 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 1025 clientReplyStatus, new clientReplyContext(http), clientSocketRecipient,
942b1c39 1026 clientSocketDetach, context, tempBuffer);
edce4d98 1027 return context;
038eb4ed 1028}
1029
d442618d
AJ
1030void
1031ConnStateData::startShutdown()
1032{
1033 // RegisteredRunner API callback - Squid has been shut down
1034
1035 // if connection is idle terminate it now,
1036 // otherwise wait for grace period to end
e500cc89 1037 if (pipeline.empty())
d442618d
AJ
1038 endingShutdown();
1039}
1040
1041void
1042ConnStateData::endingShutdown()
1043{
1044 // RegisteredRunner API callback - Squid shutdown grace period is over
1045
1046 // force the client connection to close immediately
1047 // swanSong() in the close handler will cleanup.
1048 if (Comm::IsConnOpen(clientConnection))
1049 clientConnection->close();
d442618d
AJ
1050}
1051
c8be6d7b 1052char *
1053skipLeadingSpace(char *aString)
1054{
1055 char *result = aString;
62e76326 1056
c8be6d7b 1057 while (xisspace(*aString))
62e76326 1058 ++aString;
1059
c8be6d7b 1060 return result;
1061}
1062
63be0a78 1063/**
d4a04ed5 1064 * 'end' defaults to NULL for backwards compatibility
1065 * remove default value if we ever get rid of NULL-terminated
1066 * request buffers.
1067 */
1068const char *
1069findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end)
c8be6d7b 1070{
d4a04ed5 1071 if (NULL == end) {
1072 end = uriAndHTTPVersion + strcspn(uriAndHTTPVersion, "\r\n");
1073 assert(end);
1074 }
62e76326 1075
5e263176 1076 for (; end > uriAndHTTPVersion; --end) {
d4a04ed5 1077 if (*end == '\n' || *end == '\r')
62e76326 1078 continue;
1079
d4a04ed5 1080 if (xisspace(*end)) {
1081 if (strncasecmp(end + 1, "HTTP/", 5) == 0)
1082 return end + 1;
62e76326 1083 else
1084 break;
1085 }
c8be6d7b 1086 }
62e76326 1087
3f38a55e 1088 return NULL;
c8be6d7b 1089}
1090
c8be6d7b 1091void
727552f4 1092setLogUri(ClientHttpRequest * http, char const *uri, bool cleanUrl)
c8be6d7b 1093{
a46d0227 1094 safe_free(http->log_uri);
62e76326 1095
727552f4
CT
1096 if (!cleanUrl)
1097 // The uri is already clean just dump it.
62e76326 1098 http->log_uri = xstrndup(uri, MAX_URL);
727552f4 1099 else {
2bea559d
A
1100 int flags = 0;
1101 switch (Config.uri_whitespace) {
1102 case URI_WHITESPACE_ALLOW:
1103 flags |= RFC1738_ESCAPE_NOSPACE;
1104
1105 case URI_WHITESPACE_ENCODE:
1106 flags |= RFC1738_ESCAPE_UNESCAPED;
1107 http->log_uri = xstrndup(rfc1738_do_escape(uri, flags), MAX_URL);
1108 break;
727552f4 1109
2bea559d
A
1110 case URI_WHITESPACE_CHOP: {
1111 flags |= RFC1738_ESCAPE_NOSPACE;
1112 flags |= RFC1738_ESCAPE_UNESCAPED;
1113 http->log_uri = xstrndup(rfc1738_do_escape(uri, flags), MAX_URL);
1114 int pos = strcspn(http->log_uri, w_space);
1115 http->log_uri[pos] = '\0';
1116 }
1117 break;
1118
1119 case URI_WHITESPACE_DENY:
1120 case URI_WHITESPACE_STRIP:
1121 default: {
1122 const char *t;
1123 char *tmp_uri = static_cast<char*>(xmalloc(strlen(uri) + 1));
1124 char *q = tmp_uri;
1125 t = uri;
1126 while (*t) {
a38ec4b1
FC
1127 if (!xisspace(*t)) {
1128 *q = *t;
1129 ++q;
1130 }
95dc7ff4 1131 ++t;
727552f4 1132 }
2bea559d
A
1133 *q = '\0';
1134 http->log_uri = xstrndup(rfc1738_escape_unescaped(tmp_uri), MAX_URL);
1135 xfree(tmp_uri);
1136 }
1137 break;
1138 }
727552f4 1139 }
c8be6d7b 1140}
1141
3f38a55e 1142static void
9bafa70d 1143prepareAcceleratedURL(ConnStateData * conn, ClientHttpRequest *http, const Http1::RequestParserPointer &hp)
62e76326 1144{
3f38a55e 1145 int vhost = conn->port->vhost;
1146 int vport = conn->port->vport;
9ff1b8ca 1147 static char ipbuf[MAX_IPSTRLEN];
c8be6d7b 1148
be4d35dc 1149 http->flags.accel = true;
c8be6d7b 1150
3f38a55e 1151 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
c8be6d7b 1152
5f3cc9a2 1153 static const SBuf cache_object("cache_object://");
9bafa70d 1154 if (hp->requestUri().startsWith(cache_object))
34399323 1155 return; /* already in good shape */
1156
b1cef121 1157 // XXX: re-use proper URL parser for this
9bafa70d 1158 SBuf url = hp->requestUri(); // use full provided URI if we abort
b1cef121
AJ
1159 do { // use a loop so we can break out of it
1160 ::Parser::Tokenizer tok(url);
f9688132 1161 if (tok.skip('/')) // origin-form URL already.
b1cef121
AJ
1162 break;
1163
62e76326 1164 if (conn->port->vhost)
1165 return; /* already in good shape */
1166
b1cef121 1167 // skip the URI scheme
9bafa70d 1168 static const CharacterSet uriScheme = CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA + CharacterSet::DIGIT;
b1cef121 1169 static const SBuf uriSchemeEnd("://");
9bafa70d 1170 if (!tok.skipAll(uriScheme) || !tok.skip(uriSchemeEnd))
b1cef121 1171 break;
62e76326 1172
b1cef121
AJ
1173 // skip the authority segment
1174 // RFC 3986 complex nested ABNF for "authority" boils down to this:
1175 static const CharacterSet authority = CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
f53969cc 1176 CharacterSet::HEXDIG + CharacterSet::ALPHA + CharacterSet::DIGIT;
9bafa70d 1177 if (!tok.skipAll(authority))
b1cef121 1178 break;
62e76326 1179
63ccea28 1180 static const SBuf slashUri("/");
83e3a594 1181 const SBuf t = tok.remaining();
b1cef121 1182 if (t.isEmpty())
63ccea28 1183 url = slashUri;
b1cef121
AJ
1184 else if (t[0]=='/') // looks like path
1185 url = t;
1186 else if (t[0]=='?' || t[0]=='#') { // looks like query or fragment. fix '/'
63ccea28 1187 url = slashUri;
b1cef121
AJ
1188 url.append(t);
1189 } // else do nothing. invalid path
62e76326 1190
b1cef121 1191 } while(false);
62e76326 1192
b1cef121
AJ
1193#if SHOULD_REJECT_UNKNOWN_URLS
1194 // reject URI which are not well-formed even after the processing above
f9688132 1195 if (url.isEmpty() || url[0] != '/') {
f1d5359e 1196 hp->parseStatusCode = Http::scBadRequest;
943cdf6d 1197 return conn->abortRequestParsing("error:invalid-request");
3f38a55e 1198 }
b1cef121 1199#endif
3f38a55e 1200
5463e4b9 1201 if (vport < 0)
4dd643d5 1202 vport = http->getConn()->clientConnection->local.port();
5463e4b9 1203
ae7ff0b8 1204 const bool switchedToHttps = conn->switchedToHttps();
1205 const bool tryHostHeader = vhost || switchedToHttps;
9ff1b8ca 1206 char *host = NULL;
9bafa70d 1207 if (tryHostHeader && (host = hp->getHeaderField("Host"))) {
5463e4b9
AJ
1208 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host << " + vport=" << vport);
1209 char thost[256];
1210 if (vport > 0) {
1211 thost[0] = '\0';
1212 char *t = NULL;
1213 if (host[strlen(host)] != ']' && (t = strrchr(host,':')) != NULL) {
1214 strncpy(thost, host, (t-host));
1215 snprintf(thost+(t-host), sizeof(thost)-(t-host), ":%d", vport);
1216 host = thost;
1217 } else if (!t) {
1218 snprintf(thost, sizeof(thost), "%s:%d",host, vport);
1219 host = thost;
1220 }
1221 } // else nothing to alter port-wise.
9bafa70d 1222 const int url_sz = hp->requestUri().length() + 32 + Config.appendDomainLen + strlen(host);
62e76326 1223 http->uri = (char *)xcalloc(url_sz, 1);
d31d59d8
AJ
1224 const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image();
1225 snprintf(http->uri, url_sz, SQUIDSBUFPH "://%s" SQUIDSBUFPH, SQUIDSBUFPRINT(scheme), host, SQUIDSBUFPRINT(url));
b1cef121 1226 debugs(33, 5, "ACCEL VHOST REWRITE: " << http->uri);
5463e4b9
AJ
1227 } else if (conn->port->defaultsite /* && !vhost */) {
1228 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn->port->defaultsite << " + vport=" << vport);
9bafa70d 1229 const int url_sz = hp->requestUri().length() + 32 + Config.appendDomainLen +
f53969cc 1230 strlen(conn->port->defaultsite);
62e76326 1231 http->uri = (char *)xcalloc(url_sz, 1);
5463e4b9
AJ
1232 char vportStr[32];
1233 vportStr[0] = '\0';
1234 if (vport > 0) {
1235 snprintf(vportStr, sizeof(vportStr),":%d",vport);
1236 }
d31d59d8
AJ
1237 const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image();
1238 snprintf(http->uri, url_sz, SQUIDSBUFPH "://%s%s" SQUIDSBUFPH,
1239 SQUIDSBUFPRINT(scheme), conn->port->defaultsite, vportStr, SQUIDSBUFPRINT(url));
b1cef121 1240 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http->uri);
5463e4b9 1241 } else if (vport > 0 /* && (!vhost || no Host:) */) {
3cc0f4e7 1242 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport);
5463e4b9 1243 /* Put the local socket IP address as the hostname, with whatever vport we found */
9bafa70d 1244 const int url_sz = hp->requestUri().length() + 32 + Config.appendDomainLen;
62e76326 1245 http->uri = (char *)xcalloc(url_sz, 1);
4dd643d5 1246 http->getConn()->clientConnection->local.toHostStr(ipbuf,MAX_IPSTRLEN);
d31d59d8
AJ
1247 const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image();
1248 snprintf(http->uri, url_sz, SQUIDSBUFPH "://%s:%d" SQUIDSBUFPH,
1249 SQUIDSBUFPRINT(scheme), ipbuf, vport, SQUIDSBUFPRINT(url));
b1cef121 1250 debugs(33, 5, "ACCEL VPORT REWRITE: " << http->uri);
3f38a55e 1251 }
1252}
1253
1254static void
9bafa70d 1255prepareTransparentURL(ConnStateData * conn, ClientHttpRequest *http, const Http1::RequestParserPointer &hp)
62e76326 1256{
b47500dc 1257 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
9bafa70d 1258 if (!hp->requestUri().isEmpty() && hp->requestUri()[0] != '/')
62e76326 1259 return; /* already in good shape */
3f38a55e 1260
1261 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1262
9bafa70d
AJ
1263 if (const char *host = hp->getHeaderField("Host")) {
1264 const int url_sz = hp->requestUri().length() + 32 + Config.appendDomainLen +
f53969cc 1265 strlen(host);
62e76326 1266 http->uri = (char *)xcalloc(url_sz, 1);
d31d59d8
AJ
1267 const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image();
1268 snprintf(http->uri, url_sz, SQUIDSBUFPH "://%s" SQUIDSBUFPH,
1269 SQUIDSBUFPRINT(scheme), host, SQUIDSBUFPRINT(hp->requestUri()));
b47500dc 1270 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http->uri);
c8be6d7b 1271 } else {
62e76326 1272 /* Put the local socket IP address as the hostname. */
9bafa70d 1273 const int url_sz = hp->requestUri().length() + 32 + Config.appendDomainLen;
62e76326 1274 http->uri = (char *)xcalloc(url_sz, 1);
f9688132 1275 static char ipbuf[MAX_IPSTRLEN];
4dd643d5 1276 http->getConn()->clientConnection->local.toHostStr(ipbuf,MAX_IPSTRLEN);
d31d59d8
AJ
1277 const SBuf &scheme = AnyP::UriScheme(http->getConn()->transferProtocol.protocol).image();
1278 snprintf(http->uri, url_sz, SQUIDSBUFPH "://%s:%d" SQUIDSBUFPH,
1279 SQUIDSBUFPRINT(scheme),
9bafa70d 1280 ipbuf, http->getConn()->clientConnection->local.port(), SQUIDSBUFPRINT(hp->requestUri()));
b47500dc 1281 debugs(33, 5, "TRANSPARENT REWRITE: " << http->uri);
c8be6d7b 1282 }
c8be6d7b 1283}
1284
7830d88a 1285/** Parse an HTTP request
9e008dda 1286 *
7830d88a
FC
1287 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
1288 * to 1 if the request was correctly parsed.
1289 * \param[in] csd a ConnStateData. The caller must make sure it is not null
1b51ee7b 1290 * \param[in] hp an Http1::RequestParser
7830d88a
FC
1291 * \param[out] mehtod_p will be set as a side-effect of the parsing.
1292 * Pointed-to value will be set to Http::METHOD_NONE in case of
1293 * parsing failure
1294 * \param[out] http_ver will be set as a side-effect of the parsing
1295 * \return NULL on incomplete requests,
d3dddfb5 1296 * a Http::Stream on success or failure.
7a2f978b 1297 */
d3dddfb5 1298Http::Stream *
9bafa70d 1299parseHttpRequest(ConnStateData *csd, const Http1::RequestParserPointer &hp)
7a2f978b 1300{
87abd755
AJ
1301 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
1302 {
fcc444e3 1303 const bool parsedOk = hp->parse(csd->inBuf);
fc68f6b1 1304
36a9c964 1305 // sync the buffers after parsing.
fcc444e3 1306 csd->inBuf = hp->remaining();
7a4fa6a0 1307
9bafa70d 1308 if (hp->needsMoreData()) {
87abd755
AJ
1309 debugs(33, 5, "Incomplete request, waiting for end of request line");
1310 return NULL;
1311 }
fc68f6b1 1312
6b2b6cfe
CT
1313 if (csd->mayTunnelUnsupportedProto()) {
1314 csd->preservedClientData = hp->parsed();
1315 csd->preservedClientData.append(csd->inBuf);
1316 }
1317
016a316b 1318 if (!parsedOk) {
fc10bc7d
AR
1319 const bool tooBig =
1320 hp->parseStatusCode == Http::scRequestHeaderFieldsTooLarge ||
1321 hp->parseStatusCode == Http::scUriTooLong;
1322 auto result = csd->abortRequestParsing(
1323 tooBig ? "error:request-too-large" : "error:invalid-request");
1324 // assume that remaining leftovers belong to this bad request
e6a4c1b2
AJ
1325 if (!csd->inBuf.isEmpty())
1326 csd->consumeInput(csd->inBuf.length());
fc10bc7d 1327 return result;
016a316b 1328 }
84cc2635 1329 }
fc68f6b1 1330
6d0613b2
AJ
1331 /* We know the whole request is in parser now */
1332 debugs(11, 2, "HTTP Client " << csd->clientConnection);
1333 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
9bafa70d
AJ
1334 hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol() << "\n" <<
1335 hp->mimeHeader() <<
6d0613b2 1336 "\n----------");
fc68f6b1 1337
adf29627 1338 /* deny CONNECT via accelerated ports */
9bafa70d 1339 if (hp->method() == Http::METHOD_CONNECT && csd->port != NULL && csd->port->flags.accelSurrogate) {
4599cded 1340 debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << csd->transferProtocol << " Accelerator port " << csd->port->s.port());
9bafa70d 1341 debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
f1d5359e 1342 hp->parseStatusCode = Http::scMethodNotAllowed;
eacfca83 1343 return csd->abortRequestParsing("error:method-not-allowed");
adf29627
AJ
1344 }
1345
c27e1e37 1346 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
5de5c2d0
AJ
1347 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
1348 * If seen it signals a broken client or proxy has corrupted the traffic.
1349 */
1350 if (hp->method() == Http::METHOD_PRI && hp->messageProtocol() < Http::ProtocolVersion(2,0)) {
1351 debugs(33, DBG_IMPORTANT, "WARNING: PRI method received on " << csd->transferProtocol << " port " << csd->port->s.port());
1352 debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
093c6381 1353 hp->parseStatusCode = Http::scMethodNotAllowed;
5de5c2d0
AJ
1354 return csd->abortRequestParsing("error:method-not-allowed");
1355 }
1356
9bafa70d
AJ
1357 if (hp->method() == Http::METHOD_NONE) {
1358 debugs(33, DBG_IMPORTANT, "WARNING: Unsupported method: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
f1d5359e 1359 hp->parseStatusCode = Http::scMethodNotAllowed;
eacfca83 1360 return csd->abortRequestParsing("error:unsupported-request-method");
3f38a55e 1361 }
7a2f978b 1362
6d0613b2
AJ
1363 // Process headers after request line
1364 debugs(33, 3, "complete request received. " <<
9bafa70d
AJ
1365 "prefix_sz = " << hp->messageHeaderSize() <<
1366 ", request-line-size=" << hp->firstLineSize() <<
1367 ", mime-header-size=" << hp->headerBlockSize() <<
1368 ", mime header block:\n" << hp->mimeHeader() << "\n----------");
62e76326 1369
7a2f978b 1370 /* Ok, all headers are received */
9ff1b8ca
AJ
1371 ClientHttpRequest *http = new ClientHttpRequest(csd);
1372
9bafa70d 1373 http->req_sz = hp->messageHeaderSize();
d3dddfb5 1374 Http::Stream *result = new Http::Stream(csd->clientConnection, http);
62e76326 1375
942b1c39
AJ
1376 StoreIOBuffer tempBuffer;
1377 tempBuffer.data = result->reqbuf;
1378 tempBuffer.length = HTTP_REQBUF_SZ;
1379
0655fa4d 1380 ClientStreamData newServer = new clientReplyContext(http);
0655fa4d 1381 ClientStreamData newClient = result;
edce4d98 1382 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 1383 clientReplyStatus, newServer, clientSocketRecipient,
942b1c39 1384 clientSocketDetach, newClient, tempBuffer);
62e76326 1385
3ff65596 1386 /* set url */
450e09f9 1387 debugs(33,5, "Prepare absolute URL from " <<
2ee34428 1388 (csd->transparent()?"intercept":(csd->port->flags.accelSurrogate ? "accel":"")));
3f38a55e 1389 /* Rewrite the URL in transparent or accelerator mode */
89272111
AJ
1390 /* NP: there are several cases to traverse here:
1391 * - standard mode (forward proxy)
1392 * - transparent mode (TPROXY)
1393 * - transparent mode with failures
1394 * - intercept mode (NAT)
1395 * - intercept mode with failures
1396 * - accelerator mode (reverse proxy)
51b5dcf5 1397 * - internal relative-URL
89272111 1398 * - mixed combos of the above with internal URL
151ba0d4
AJ
1399 * - remote interception with PROXY protocol
1400 * - remote reverse-proxy with PROXY protocol
89272111 1401 */
be364179 1402 if (csd->transparent()) {
89272111 1403 /* intercept or transparent mode, properly working with no failures */
5f3cc9a2 1404 prepareTransparentURL(csd, http, hp);
89272111 1405
51b5dcf5 1406 } else if (internalCheck(hp->requestUri())) { // NP: only matches relative-URI
89272111 1407 /* internal URL mode */
2f2749d7 1408 /* prepend our name & port */
51b5dcf5 1409 http->uri = xstrdup(internalLocalUri(NULL, hp->requestUri()));
59c59acf
AJ
1410 // We just re-wrote the URL. Must replace the Host: header.
1411 // But have not parsed there yet!! flag for local-only handling.
be4d35dc 1412 http->flags.internal = true;
59c59acf 1413
6a25a046 1414 } else if (csd->port->flags.accelSurrogate || csd->switchedToHttps()) {
59c59acf 1415 /* accelerator mode */
5f3cc9a2 1416 prepareAcceleratedURL(csd, http, hp);
3f38a55e 1417 }
1418
1419 if (!http->uri) {
62e76326 1420 /* No special rewrites have been applied above, use the
1421 * requested url. may be rewritten later, so make extra room */
9bafa70d 1422 int url_sz = hp->requestUri().length() + Config.appendDomainLen + 5;
62e76326 1423 http->uri = (char *)xcalloc(url_sz, 1);
3f0e38d6 1424 SBufToCstring(http->uri, hp->requestUri());
3f38a55e 1425 }
62e76326 1426
c4b7a5a9 1427 result->flags.parsed_ok = 1;
c8be6d7b 1428 return result;
7a2f978b 1429}
1430
fcc444e3 1431bool
1cf238db 1432ConnStateData::connFinishedWithConn(int size)
c8be6d7b 1433{
1434 if (size == 0) {
e500cc89 1435 if (pipeline.empty() && inBuf.isEmpty()) {
62e76326 1436 /* no current or pending requests */
73c36fd9 1437 debugs(33, 4, HERE << clientConnection << " closed");
fcc444e3 1438 return true;
62e76326 1439 } else if (!Config.onoff.half_closed_clients) {
1440 /* admin doesn't want to support half-closed client sockets */
73c36fd9 1441 debugs(33, 3, HERE << clientConnection << " aborted (half_closed_clients disabled)");
08a175bb 1442 pipeline.terminateAll(0);
fcc444e3 1443 return true;
62e76326 1444 }
c8be6d7b 1445 }
62e76326 1446
fcc444e3 1447 return false;
c8be6d7b 1448}
1449
92ae4c86
AR
1450void
1451ConnStateData::consumeInput(const size_t byteCount)
1452{
fcc444e3
AJ
1453 assert(byteCount > 0 && byteCount <= inBuf.length());
1454 inBuf.consume(byteCount);
1455 debugs(33, 5, "inBuf has " << inBuf.length() << " unused bytes");
92ae4c86
AR
1456}
1457
1cf238db 1458void
f35961af 1459ConnStateData::clientAfterReadingRequests()
c4b7a5a9 1460{
39cb8c41 1461 // Were we expecting to read more request body from half-closed connection?
73c36fd9
AJ
1462 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection->fd)) {
1463 debugs(33, 3, HERE << "truncated body: closing half-closed " << clientConnection);
1464 clientConnection->close();
39cb8c41 1465 return;
c4b7a5a9 1466 }
1467
f35961af
AR
1468 if (flags.readMore)
1469 readSomeData();
c4b7a5a9 1470}
1471
84c77748
AR
1472void
1473ConnStateData::quitAfterError(HttpRequest *request)
1474{
1475 // From HTTP p.o.v., we do not have to close after every error detected
1476 // at the client-side, but many such errors do require closure and the
1477 // client-side code is bad at handling errors so we play it safe.
1478 if (request)
e857372a 1479 request->flags.proxyKeepalive = false;
84c77748
AR
1480 flags.readMore = false;
1481 debugs(33,4, HERE << "Will close after error: " << clientConnection);
1482}
1483
cb4f4424 1484#if USE_OPENSSL
d3dddfb5 1485bool ConnStateData::serveDelayedError(Http::Stream *context)
8eb0a7ee
CT
1486{
1487 ClientHttpRequest *http = context->http;
fd4624d7
CT
1488
1489 if (!sslServerBump)
8eb0a7ee
CT
1490 return false;
1491
fd4624d7 1492 assert(sslServerBump->entry);
7a957a93 1493 // Did we create an error entry while processing CONNECT?
fd4624d7 1494 if (!sslServerBump->entry->isEmpty()) {
84c77748
AR
1495 quitAfterError(http->request);
1496
7a957a93
AR
1497 // Get the saved error entry and send it to the client by replacing the
1498 // ClientHttpRequest store entry with it.
8eb0a7ee
CT
1499 clientStreamNode *node = context->getClientReplyContext();
1500 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
7a957a93
AR
1501 assert(repContext);
1502 debugs(33, 5, "Responding with delated error for " << http->uri);
f0baf149 1503 repContext->setReplyToStoreEntry(sslServerBump->entry, "delayed SslBump error");
7a957a93
AR
1504
1505 // save the original request for logging purposes
b248c2a3
AJ
1506 if (!context->http->al->request) {
1507 context->http->al->request = http->request;
1508 HTTPMSGLOCK(context->http->al->request);
1509 }
7a957a93
AR
1510
1511 // Get error details from the fake certificate-peeking request.
129fe2a1 1512 http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
8eb0a7ee 1513 context->pullData();
8eb0a7ee
CT
1514 return true;
1515 }
1516
7a957a93
AR
1517 // In bump-server-first mode, we have not necessarily seen the intended
1518 // server name at certificate-peeking time. Check for domain mismatch now,
1519 // when we can extract the intended name from the bumped HTTP request.
92e3827b 1520 if (const Security::CertPointer &srvCert = sslServerBump->serverCert) {
8eb0a7ee 1521 HttpRequest *request = http->request;
92e3827b 1522 if (!Ssl::checkX509ServerValidity(srvCert.get(), request->url.host())) {
7a957a93 1523 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
5c51bffb 1524 "does not match domainname " << request->url.host());
8eb0a7ee 1525
d4a56c34 1526 bool allowDomainMismatch = false;
638402dd
AJ
1527 if (Config.ssl_client.cert_error) {
1528 ACLFilledChecklist check(Config.ssl_client.cert_error, request, dash_str);
92e3827b 1529 check.sslErrors = new Security::CertErrors(Security::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH, srvCert));
d4a56c34 1530 allowDomainMismatch = (check.fastCheck() == ACCESS_ALLOWED);
638402dd
AJ
1531 delete check.sslErrors;
1532 check.sslErrors = NULL;
1533 }
8eb0a7ee 1534
7d82c5b8 1535 if (!allowDomainMismatch) {
84c77748
AR
1536 quitAfterError(request);
1537
8eb0a7ee
CT
1538 clientStreamNode *node = context->getClientReplyContext();
1539 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1540 assert (repContext);
1541
7a957a93 1542 // Fill the server IP and hostname for error page generation.
fd4624d7 1543 HttpRequest::Pointer const & peekerRequest = sslServerBump->request;
5c51bffb 1544 request->hier.note(peekerRequest->hier.tcpServer, request->url.host());
7a957a93 1545
8eb0a7ee 1546 // Create an error object and fill it
955394ce 1547 ErrorState *err = new ErrorState(ERR_SECURE_CONNECT_FAIL, Http::scServiceUnavailable, request);
8eb0a7ee 1548 err->src_addr = clientConnection->remote;
7a957a93
AR
1549 Ssl::ErrorDetail *errDetail = new Ssl::ErrorDetail(
1550 SQUID_X509_V_ERR_DOMAIN_MISMATCH,
92e3827b 1551 srvCert.get(), nullptr);
8eb0a7ee 1552 err->detail = errDetail;
7a957a93 1553 // Save the original request for logging purposes.
b248c2a3
AJ
1554 if (!context->http->al->request) {
1555 context->http->al->request = request;
1556 HTTPMSGLOCK(context->http->al->request);
1557 }
8eb0a7ee
CT
1558 repContext->setReplyToError(request->method, err);
1559 assert(context->http->out.offset == 0);
1560 context->pullData();
8eb0a7ee
CT
1561 return true;
1562 }
1563 }
1564 }
1565
1566 return false;
1567}
cb4f4424 1568#endif // USE_OPENSSL
8eb0a7ee 1569
3248e962
CT
1570/**
1571 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
1572 * or false otherwise
1573 */
1574bool
6b2b6cfe 1575clientTunnelOnError(ConnStateData *conn, Http::StreamPointer &context, HttpRequest::Pointer &request, const HttpRequestMethod& method, err_type requestError)
3248e962 1576{
6b2b6cfe
CT
1577 if (conn->mayTunnelUnsupportedProto()) {
1578 ACLFilledChecklist checklist(Config.accessList.on_unsupported_protocol, request.getRaw(), nullptr);
3248e962
CT
1579 checklist.requestErrorType = requestError;
1580 checklist.src_addr = conn->clientConnection->remote;
1581 checklist.my_addr = conn->clientConnection->local;
1582 checklist.conn(conn);
1583 allow_t answer = checklist.fastCheck();
1584 if (answer == ACCESS_ALLOWED && answer.kind == 1) {
1585 debugs(33, 3, "Request will be tunneled to server");
6400749d
AJ
1586 if (context) {
1587 assert(conn->pipeline.front() == context); // XXX: still assumes HTTP/1 semantics
6b2b6cfe 1588 context->finished(); // Will remove from conn->pipeline queue
6400749d 1589 }
3248e962 1590 Comm::SetSelect(conn->clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
6b2b6cfe 1591 return conn->initiateTunneledRequest(request, Http::METHOD_NONE, "unknown-protocol", conn->preservedClientData);
3248e962
CT
1592 } else {
1593 debugs(33, 3, "Continue with returning the error: " << requestError);
1594 }
1595 }
1596
3248e962
CT
1597 return false;
1598}
1599
ec69bdb2 1600void
28fd6d0b
AJ
1601clientProcessRequestFinished(ConnStateData *conn, const HttpRequest::Pointer &request)
1602{
1603 /*
1604 * DPW 2007-05-18
1605 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
1606 * to here because calling comm_reset_close() causes http to
48a37aee 1607 * be freed before accessing.
28fd6d0b
AJ
1608 */
1609 if (request != NULL && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) {
1610 debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection);
1611 conn->flags.readMore = false;
1612 comm_reset_close(conn->clientConnection);
1613 }
1614}
1615
9bafa70d 1616void
d3dddfb5 1617clientProcessRequest(ConnStateData *conn, const Http1::RequestParserPointer &hp, Http::Stream *context)
c4b7a5a9 1618{
59a1efb2 1619 ClientHttpRequest *http = context->http;
39cb8c41 1620 bool chunked = false;
e18b8316 1621 bool mustReplyToOptions = false;
3ff65596 1622 bool unsupportedTe = false;
39cb8c41 1623 bool expectBody = false;
5f8252d2 1624
ec69bdb2
CT
1625 // We already have the request parsed and checked, so we
1626 // only need to go through the final body/conn setup to doCallouts().
1627 assert(http->request);
1628 HttpRequest::Pointer request = http->request;
1629
92ae4c86 1630 // temporary hack to avoid splitting this huge function with sensitive code
f9688132 1631 const bool isFtp = !hp;
9bafa70d 1632
92ae4c86
AR
1633 // Some blobs below are still HTTP-specific, but we would have to rewrite
1634 // this entire function to remove them from the FTP code path. Connection
1635 // setup and body_pipe preparation blobs are needed for FTP.
1636
40d34a62
AJ
1637 request->clientConnectionManager = conn;
1638
c4b7a5a9 1639 request->flags.accelerated = http->flags.accel;
450fe1cb 1640 request->flags.sslBumped=conn->switchedToHttps();
450fe1cb 1641 request->flags.ignoreCc = conn->port->ignore_cc;
7fb65ee4 1642 // TODO: decouple http->flags.accel from request->flags.sslBumped
450fe1cb 1643 request->flags.noDirect = (request->flags.accelerated && !request->flags.sslBumped) ?
e4a14600 1644 !conn->port->allow_direct : 0;
63df1d28
AJ
1645 request->sources |= isFtp ? Http::Message::srcFtp :
1646 ((request->flags.sslBumped || conn->port->transport.protocol == AnyP::PROTO_HTTPS) ? Http::Message::srcHttps : Http::Message::srcHttp);
21512911
CT
1647#if USE_AUTH
1648 if (request->flags.sslBumped) {
cc1e110a
AJ
1649 if (conn->getAuth() != NULL)
1650 request->auth_user_request = conn->getAuth();
21512911
CT
1651 }
1652#endif
2ad20b4f
AJ
1653
1654 /** \par
1655 * If transparent or interception mode is working clone the transparent and interception flags
1656 * from the port settings to the request.
1657 */
40d34a62 1658 if (http->clientConnection != NULL) {
304a6180 1659 request->flags.intercepted = ((http->clientConnection->flags & COMM_INTERCEPTION) != 0);
0d901ef4 1660 request->flags.interceptTproxy = ((http->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
13edf4cc
AJ
1661 static const bool proxyProtocolPort = (conn->port != NULL) ? conn->port->flags.proxySurrogate : false;
1662 if (request->flags.interceptTproxy && !proxyProtocolPort) {
0d901ef4
SH
1663 if (Config.accessList.spoof_client_ip) {
1664 ACLFilledChecklist *checklist = clientAclChecklistCreate(Config.accessList.spoof_client_ip, http);
1665 request->flags.spoofClientIp = (checklist->fastCheck() == ACCESS_ALLOWED);
1666 delete checklist;
1667 } else
1668 request->flags.spoofClientIp = true;
1669 } else
1670 request->flags.spoofClientIp = false;
2ad20b4f 1671 }
fc68f6b1 1672
51b5dcf5 1673 if (internalCheck(request->url.path())) {
5c51bffb
AJ
1674 if (internalHostnameIs(request->url.host()) && request->url.port() == getMyPort()) {
1675 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true));
be4d35dc 1676 http->flags.internal = true;
51b5dcf5 1677 } else if (Config.onoff.global_internal_static && internalStaticCheck(request->url.path())) {
5c51bffb 1678 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (global_internal_static on)");
d31d59d8 1679 request->url.setScheme(AnyP::PROTO_HTTP, "http");
851feda6 1680 request->url.host(internalHostname());
5c51bffb 1681 request->url.port(getMyPort());
be4d35dc 1682 http->flags.internal = true;
4e3f4dc7 1683 } else
5c51bffb 1684 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (not this proxy)");
f024c970 1685 }
e72a0ec0 1686
c4b7a5a9 1687 request->flags.internal = http->flags.internal;
b248c2a3 1688 setLogUri (http, urlCanonicalClean(request.getRaw()));
922c2ced 1689 request->client_addr = conn->clientConnection->remote; // XXX: remove request->client_addr member.
3d674977 1690#if FOLLOW_X_FORWARDED_FOR
40d34a62 1691 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
922c2ced 1692 // not details about the TCP connection itself
73c36fd9 1693 request->indirect_client_addr = conn->clientConnection->remote;
3d674977 1694#endif /* FOLLOW_X_FORWARDED_FOR */
73c36fd9 1695 request->my_addr = conn->clientConnection->local;
35fb56c9 1696 request->myportname = conn->port->name;
9bafa70d
AJ
1697
1698 if (!isFtp) {
63df1d28 1699 // XXX: for non-HTTP messages instantiate a different Http::Message child type
9bafa70d
AJ
1700 // for now Squid only supports HTTP requests
1701 const AnyP::ProtocolVersion &http_ver = hp->messageProtocol();
1702 assert(request->http_ver.protocol == http_ver.protocol);
1703 request->http_ver.major = http_ver.major;
1704 request->http_ver.minor = http_ver.minor;
1705 }
62e76326 1706
9174ba3d
AJ
1707 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
1708 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
1709 request->clientConnectionManager = conn;
1710
39cb8c41
AR
1711 if (request->header.chunked()) {
1712 chunked = true;
789217a2
FC
1713 } else if (request->header.has(Http::HdrType::TRANSFER_ENCODING)) {
1714 const String te = request->header.getList(Http::HdrType::TRANSFER_ENCODING);
39cb8c41
AR
1715 // HTTP/1.1 requires chunking to be the last encoding if there is one
1716 unsupportedTe = te.size() && te != "identity";
1717 } // else implied identity coding
de48b288 1718
f9688132 1719 mustReplyToOptions = (request->method == Http::METHOD_OPTIONS) &&
789217a2 1720 (request->header.getInt64(Http::HdrType::MAX_FORWARDS) == 0);
b248c2a3 1721 if (!urlCheckRequest(request.getRaw()) || mustReplyToOptions || unsupportedTe) {
62e76326 1722 clientStreamNode *node = context->getClientReplyContext();
b248c2a3 1723 conn->quitAfterError(request.getRaw());
0655fa4d 1724 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1725 assert (repContext);
955394ce 1726 repContext->setReplyToError(ERR_UNSUP_REQ, Http::scNotImplemented, request->method, NULL,
b248c2a3 1727 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 1728 assert(context->http->out.offset == 0);
1729 context->pullData();
28fd6d0b
AJ
1730 clientProcessRequestFinished(conn, request);
1731 return;
c4b7a5a9 1732 }
1733
b248c2a3 1734 if (!chunked && !clientIsContentLengthValid(request.getRaw())) {
62e76326 1735 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 1736 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1737 assert (repContext);
b248c2a3 1738 conn->quitAfterError(request.getRaw());
0655fa4d 1739 repContext->setReplyToError(ERR_INVALID_REQ,
955394ce 1740 Http::scLengthRequired, request->method, NULL,
b248c2a3 1741 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 1742 assert(context->http->out.offset == 0);
1743 context->pullData();
28fd6d0b
AJ
1744 clientProcessRequestFinished(conn, request);
1745 return;
c4b7a5a9 1746 }
1747
92ae4c86 1748 clientSetKeepaliveFlag(http);
f35961af 1749 // Let tunneling code be fully responsible for CONNECT requests
c2a7cefd 1750 if (http->request->method == Http::METHOD_CONNECT) {
b66e0e86 1751 context->mayUseConnection(true);
f35961af
AR
1752 conn->flags.readMore = false;
1753 }
fc68f6b1 1754
cb4f4424 1755#if USE_OPENSSL
28fd6d0b 1756 if (conn->switchedToHttps() && conn->serveDelayedError(context)) {
28fd6d0b
AJ
1757 clientProcessRequestFinished(conn, request);
1758 return;
1759 }
061bbdec
CT
1760#endif
1761
b66e0e86 1762 /* Do we expect a request-body? */
39cb8c41
AR
1763 expectBody = chunked || request->content_length > 0;
1764 if (!context->mayUseConnection() && expectBody) {
1765 request->body_pipe = conn->expectRequestBody(
de48b288 1766 chunked ? -1 : request->content_length);
5f8252d2 1767
62e76326 1768 /* Is it too large? */
39cb8c41 1769 if (!chunked && // if chunked, we will check as we accumulate
de48b288 1770 clientIsRequestBodyTooLargeForPolicy(request->content_length)) {
62e76326 1771 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 1772 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1773 assert (repContext);
b248c2a3 1774 conn->quitAfterError(request.getRaw());
0655fa4d 1775 repContext->setReplyToError(ERR_TOO_BIG,
f11c8e2f 1776 Http::scPayloadTooLarge, Http::METHOD_NONE, NULL,
73c36fd9 1777 conn->clientConnection->remote, http->request, NULL, NULL);
62e76326 1778 assert(context->http->out.offset == 0);
1779 context->pullData();
28fd6d0b
AJ
1780 clientProcessRequestFinished(conn, request);
1781 return;
62e76326 1782 }
1783
92ae4c86 1784 if (!isFtp) {
a5d444a5
DK
1785 // We may stop producing, comm_close, and/or call setReplyToError()
1786 // below, so quit on errors to avoid http->doCallouts()
28fd6d0b
AJ
1787 if (!conn->handleRequestBodyData()) {
1788 clientProcessRequestFinished(conn, request);
1789 return;
1790 }
39cb8c41 1791
a5d444a5 1792 if (!request->body_pipe->productionEnded()) {
e7ce227f 1793 debugs(33, 5, "need more request body");
a5d444a5
DK
1794 context->mayUseConnection(true);
1795 assert(conn->flags.readMore);
1796 }
f35961af 1797 }
c4b7a5a9 1798 }
1799
de31d06f 1800 http->calloutContext = new ClientRequestContext(http);
1801
1802 http->doCallouts();
9e008dda 1803
28fd6d0b 1804 clientProcessRequestFinished(conn, request);
c4b7a5a9 1805}
1806
92ae4c86
AR
1807int
1808ConnStateData::pipelinePrefetchMax() const
1809{
efbea402
CT
1810 // TODO: Support pipelined requests through pinned connections.
1811 if (pinning.pinned)
1812 return 0;
92ae4c86
AR
1813 return Config.pipeline_max_prefetch;
1814}
1815
079a8480
AJ
1816/**
1817 * Limit the number of concurrent requests.
1818 * \return true when there are available position(s) in the pipeline queue for another request.
1819 * \return false when the pipeline queue is full or disabled.
1820 */
1821bool
1822ConnStateData::concurrentRequestQueueFilled() const
c4b7a5a9 1823{
e500cc89 1824 const int existingRequestCount = pipeline.count();
079a8480
AJ
1825
1826 // default to the configured pipeline size.
1827 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
0de57497 1828#if USE_OPENSSL
43b43c46 1829 const int internalRequest = (transparent() && sslBumpMode == Ssl::bumpSplice) ? 1 : 0;
0de57497 1830#else
06211564 1831 const int internalRequest = 0;
0de57497 1832#endif
43b43c46 1833 const int concurrentRequestLimit = pipelinePrefetchMax() + 1 + internalRequest;
62e76326 1834
079a8480
AJ
1835 // when queue filled already we cant add more.
1836 if (existingRequestCount >= concurrentRequestLimit) {
1837 debugs(33, 3, clientConnection << " max concurrent requests reached (" << concurrentRequestLimit << ")");
1838 debugs(33, 5, clientConnection << " deferring new request until one is done");
1839 return true;
c4b7a5a9 1840 }
62e76326 1841
079a8480 1842 return false;
c4b7a5a9 1843}
1844
00d0ce87 1845/**
d3d92daa 1846 * Perform proxy_protocol_access ACL tests on the client which
3bd97e7e
AJ
1847 * connected to PROXY protocol port to see if we trust the
1848 * sender enough to accept their PROXY header claim.
00d0ce87 1849 */
6658cc16 1850bool
00d0ce87
AJ
1851ConnStateData::proxyProtocolValidateClient()
1852{
d3d92daa
AJ
1853 if (!Config.accessList.proxyProtocol)
1854 return proxyProtocolError("PROXY client not permitted by default ACL");
1855
1856 ACLFilledChecklist ch(Config.accessList.proxyProtocol, NULL, clientConnection->rfc931);
00d0ce87
AJ
1857 ch.src_addr = clientConnection->remote;
1858 ch.my_addr = clientConnection->local;
6658cc16 1859 ch.conn(this);
00d0ce87 1860
3bd97e7e
AJ
1861 if (ch.fastCheck() != ACCESS_ALLOWED)
1862 return proxyProtocolError("PROXY client not permitted by ACLs");
1863
6658cc16 1864 return true;
00d0ce87
AJ
1865}
1866
1867/**
1868 * Perform cleanup on PROXY protocol errors.
1869 * If header parsing hits a fatal error terminate the connection,
1870 * otherwise wait for more data.
1871 */
1872bool
3bd97e7e 1873ConnStateData::proxyProtocolError(const char *msg)
00d0ce87 1874{
3c082dbe 1875 if (msg) {
70a16fea
AJ
1876 // This is important to know, but maybe not so much that flooding the log is okay.
1877#if QUIET_PROXY_PROTOCOL
1878 // display the first of every 32 occurances at level 1, the others at level 2.
1879 static uint8_t hide = 0;
1880 debugs(33, (hide++ % 32 == 0 ? DBG_IMPORTANT : 2), msg << " from " << clientConnection);
1881#else
1882 debugs(33, DBG_IMPORTANT, msg << " from " << clientConnection);
1883#endif
3bd97e7e 1884 mustStop(msg);
3c082dbe 1885 }
00d0ce87
AJ
1886 return false;
1887}
1888
3bd97e7e 1889/// magic octet prefix for PROXY protocol version 1
70a16fea 1890static const SBuf Proxy1p0magic("PROXY ", 6);
3bd97e7e
AJ
1891
1892/// magic octet prefix for PROXY protocol version 2
70a16fea 1893static const SBuf Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
3bd97e7e 1894
00d0ce87 1895/**
3bd97e7e
AJ
1896 * Test the connection read buffer for PROXY protocol header.
1897 * Version 1 and 2 header currently supported.
00d0ce87
AJ
1898 */
1899bool
3d74cb1f 1900ConnStateData::parseProxyProtocolHeader()
00d0ce87 1901{
00d0ce87 1902 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
cbae7ab9 1903
70a16fea 1904 // detect and parse PROXY/2.0 protocol header
fcc444e3 1905 if (inBuf.startsWith(Proxy2p0magic))
70a16fea 1906 return parseProxy2p0();
00d0ce87 1907
70a16fea 1908 // detect and parse PROXY/1.0 protocol header
fcc444e3 1909 if (inBuf.startsWith(Proxy1p0magic))
bd1be2ae 1910 return parseProxy1p0();
00d0ce87 1911
70a16fea 1912 // detect and terminate other protocols
fcc444e3 1913 if (inBuf.length() >= Proxy2p0magic.length()) {
70a16fea
AJ
1914 // PROXY/1.0 magic is shorter, so we know that
1915 // the input does not start with any PROXY magic
3bd97e7e
AJ
1916 return proxyProtocolError("PROXY protocol error: invalid header");
1917 }
00d0ce87 1918
3d74cb1f
AJ
1919 // TODO: detect short non-magic prefixes earlier to avoid
1920 // waiting for more data which may never come
1921
3bd97e7e
AJ
1922 // not enough bytes to parse yet.
1923 return false;
1924}
00d0ce87 1925
3bd97e7e
AJ
1926/// parse the PROXY/1.0 protocol header from the connection read buffer
1927bool
70a16fea 1928ConnStateData::parseProxy1p0()
3bd97e7e 1929{
fcc444e3 1930 ::Parser::Tokenizer tok(inBuf);
70a16fea 1931 tok.skip(Proxy1p0magic);
3bd97e7e 1932
154ea566
AJ
1933 // skip to first LF (assumes it is part of CRLF)
1934 static const CharacterSet lineContent = CharacterSet::LF.complement("non-LF");
1935 SBuf line;
1936 if (tok.prefix(line, lineContent, 107-Proxy1p0magic.length())) {
1937 if (tok.skip('\n')) {
1938 // found valid header
fcc444e3 1939 inBuf = tok.remaining();
154ea566
AJ
1940 needProxyProtocolHeader_ = false;
1941 // reset the tokenizer to work on found line only.
1942 tok.reset(line);
1943 } else
1944 return false; // no LF yet
1945
1946 } else // protocol error only if there are more than 107 bytes prefix header
fcc444e3 1947 return proxyProtocolError(inBuf.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL);
154ea566 1948
1689cdbc
AJ
1949 static const SBuf unknown("UNKNOWN"), tcpName("TCP");
1950 if (tok.skip(tcpName)) {
3bd97e7e 1951
1689cdbc
AJ
1952 // skip TCP/IP version number
1953 static const CharacterSet tcpVersions("TCP-version","46");
bd1be2ae 1954 if (!tok.skipOne(tcpVersions))
154ea566 1955 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
00d0ce87 1956
3bd97e7e
AJ
1957 // skip SP after protocol version
1958 if (!tok.skip(' '))
154ea566 1959 return proxyProtocolError("PROXY/1.0 error: missing SP");
00d0ce87 1960
3bd97e7e
AJ
1961 SBuf ipa, ipb;
1962 int64_t porta, portb;
1689cdbc
AJ
1963 static const CharacterSet ipChars = CharacterSet("IP Address",".:") + CharacterSet::HEXDIG;
1964
1965 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1966 // leave the LF until later.
1967 const bool correct = tok.prefix(ipa, ipChars) && tok.skip(' ') &&
1968 tok.prefix(ipb, ipChars) && tok.skip(' ') &&
1969 tok.int64(porta) && tok.skip(' ') &&
1970 tok.int64(portb) &&
1971 tok.skip('\r');
1972 if (!correct)
154ea566 1973 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
00d0ce87 1974
3bd97e7e
AJ
1975 // parse IP and port strings
1976 Ip::Address originalClient, originalDest;
00d0ce87 1977
3bd97e7e
AJ
1978 if (!originalClient.GetHostByName(ipa.c_str()))
1979 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
00d0ce87 1980
3bd97e7e
AJ
1981 if (!originalDest.GetHostByName(ipb.c_str()))
1982 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
00d0ce87 1983
3bd97e7e
AJ
1984 if (porta > 0 && porta <= 0xFFFF) // max uint16_t
1985 originalClient.port(static_cast<uint16_t>(porta));
1986 else
1987 return proxyProtocolError("PROXY/1.0 error: invalid src port");
cbae7ab9 1988
3bd97e7e
AJ
1989 if (portb > 0 && portb <= 0xFFFF) // max uint16_t
1990 originalDest.port(static_cast<uint16_t>(portb));
1991 else
1992 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
cbae7ab9 1993
3bd97e7e
AJ
1994 // we have original client and destination details now
1995 // replace the client connection values
1996 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection);
1997 clientConnection->local = originalDest;
1998 clientConnection->remote = originalClient;
65984b09
YW
1999 if ((clientConnection->flags & COMM_TRANSPARENT))
2000 clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP.
3bd97e7e 2001 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection);
3bd97e7e 2002 return true;
1689cdbc
AJ
2003
2004 } else if (tok.skip(unknown)) {
154ea566
AJ
2005 // found valid but unusable header
2006 return true;
1689cdbc
AJ
2007
2008 } else
154ea566 2009 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
cbae7ab9 2010
3bd97e7e
AJ
2011 return false;
2012}
cbae7ab9 2013
3bd97e7e
AJ
2014/// parse the PROXY/2.0 protocol header from the connection read buffer
2015bool
70a16fea 2016ConnStateData::parseProxy2p0()
3bd97e7e 2017{
1689cdbc 2018 static const SBuf::size_type prefixLen = Proxy2p0magic.length();
fcc444e3 2019 if (inBuf.length() < prefixLen + 4)
1689cdbc
AJ
2020 return false; // need more bytes
2021
fcc444e3 2022 if ((inBuf[prefixLen] & 0xF0) != 0x20) // version == 2 is mandatory
3bd97e7e 2023 return proxyProtocolError("PROXY/2.0 error: invalid version");
cbae7ab9 2024
fcc444e3 2025 const char command = (inBuf[prefixLen] & 0x0F);
3bd97e7e
AJ
2026 if ((command & 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2027 return proxyProtocolError("PROXY/2.0 error: invalid command");
cbae7ab9 2028
fcc444e3 2029 const char family = (inBuf[prefixLen+1] & 0xF0) >>4;
3bd97e7e
AJ
2030 if (family > 0x3) // values other than 0x0-0x3 are invalid
2031 return proxyProtocolError("PROXY/2.0 error: invalid family");
cbae7ab9 2032
fcc444e3 2033 const char proto = (inBuf[prefixLen+1] & 0x0F);
3bd97e7e
AJ
2034 if (proto > 0x2) // values other than 0x0-0x2 are invalid
2035 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
cbae7ab9 2036
fcc444e3 2037 const char *clen = inBuf.rawContent() + prefixLen + 2;
17954dbd
AJ
2038 uint16_t len;
2039 memcpy(&len, clen, sizeof(len));
2040 len = ntohs(len);
cbae7ab9 2041
fcc444e3 2042 if (inBuf.length() < prefixLen + 4 + len)
3bd97e7e 2043 return false; // need more bytes
cbae7ab9 2044
fcc444e3
AJ
2045 inBuf.consume(prefixLen + 4); // 4 being the extra bytes
2046 const SBuf extra = inBuf.consume(len);
3bd97e7e 2047 needProxyProtocolHeader_ = false; // found successfully
cbae7ab9 2048
3bd97e7e
AJ
2049 // LOCAL connections do nothing with the extras
2050 if (command == 0x00/* LOCAL*/)
cbae7ab9
AJ
2051 return true;
2052
1689cdbc 2053 union pax {
3bd97e7e
AJ
2054 struct { /* for TCP/UDP over IPv4, len = 12 */
2055 struct in_addr src_addr;
2056 struct in_addr dst_addr;
2057 uint16_t src_port;
2058 uint16_t dst_port;
2059 } ipv4_addr;
2060 struct { /* for TCP/UDP over IPv6, len = 36 */
bd1be2ae
A
2061 struct in6_addr src_addr;
2062 struct in6_addr dst_addr;
2063 uint16_t src_port;
2064 uint16_t dst_port;
3bd97e7e
AJ
2065 } ipv6_addr;
2066#if NOT_SUPPORTED
2067 struct { /* for AF_UNIX sockets, len = 216 */
bd1be2ae
A
2068 uint8_t src_addr[108];
2069 uint8_t dst_addr[108];
3bd97e7e
AJ
2070 } unix_addr;
2071#endif
1689cdbc 2072 };
3bd97e7e 2073
17954dbd
AJ
2074 pax ipu;
2075 memcpy(&ipu, extra.rawContent(), sizeof(pax));
3bd97e7e
AJ
2076
2077 // replace the client connection values
2078 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection);
bd1be2ae 2079 switch (family) {
3bd97e7e 2080 case 0x1: // IPv4
17954dbd
AJ
2081 clientConnection->local = ipu.ipv4_addr.dst_addr;
2082 clientConnection->local.port(ntohs(ipu.ipv4_addr.dst_port));
2083 clientConnection->remote = ipu.ipv4_addr.src_addr;
2084 clientConnection->remote.port(ntohs(ipu.ipv4_addr.src_port));
65984b09
YW
2085 if ((clientConnection->flags & COMM_TRANSPARENT))
2086 clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP.
3bd97e7e
AJ
2087 break;
2088 case 0x2: // IPv6
17954dbd
AJ
2089 clientConnection->local = ipu.ipv6_addr.dst_addr;
2090 clientConnection->local.port(ntohs(ipu.ipv6_addr.dst_port));
2091 clientConnection->remote = ipu.ipv6_addr.src_addr;
2092 clientConnection->remote.port(ntohs(ipu.ipv6_addr.src_port));
65984b09
YW
2093 if ((clientConnection->flags & COMM_TRANSPARENT))
2094 clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP.
3bd97e7e
AJ
2095 break;
2096 default: // do nothing
2097 break;
00d0ce87 2098 }
3bd97e7e 2099 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection);
3bd97e7e 2100 return true;
00d0ce87
AJ
2101}
2102
3248e962
CT
2103void
2104ConnStateData::receivedFirstByte()
2105{
2106 if (receivedFirstByte_)
2107 return;
2108
2109 receivedFirstByte_ = true;
2110 // Set timeout to Config.Timeout.request
2111 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
2112 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
2113 TimeoutDialer, this, ConnStateData::requestTimeout);
2114 commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall);
2115}
2116
63be0a78 2117/**
f900210a 2118 * Attempt to parse one or more requests from the input buffer.
eacfca83
AR
2119 * Returns true after completing parsing of at least one request [header]. That
2120 * includes cases where parsing ended with an error (e.g., a huge request).
f900210a 2121 */
4959e21e 2122bool
f35961af 2123ConnStateData::clientParseRequests()
f900210a 2124{
f900210a 2125 bool parsed_req = false;
2126
1b76e6c1 2127 debugs(33, 5, HERE << clientConnection << ": attempting to parse");
f900210a 2128
39cb8c41 2129 // Loop while we have read bytes that are not needed for producing the body
f35961af 2130 // On errors, bodyPipe may become nil, but readMore will be cleared
fcc444e3 2131 while (!inBuf.isEmpty() && !bodyPipe && flags.readMore) {
f900210a 2132
079a8480
AJ
2133 /* Limit the number of concurrent requests */
2134 if (concurrentRequestQueueFilled())
f900210a 2135 break;
f900210a 2136
00d0ce87 2137 // try to parse the PROXY protocol header magic bytes
42cbf844
AJ
2138 if (needProxyProtocolHeader_) {
2139 if (!parseProxyProtocolHeader())
2140 break;
2141
2142 // we have been waiting for PROXY to provide client-IP
2143 // for some lookups, ie rDNS and IDENT.
2144 whenClientIpKnown();
2145 }
00d0ce87 2146
6b2b6cfe 2147 if (Http::StreamPointer context = parseOneRequest()) {
eacfca83 2148 debugs(33, 5, clientConnection << ": done parsing a request");
f900210a 2149
8d77a37c 2150 AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout",
dc49061a 2151 CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http));
1b76e6c1 2152 commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall);
f900210a 2153
eacfca83
AR
2154 context->registerWithConn();
2155
9bafa70d 2156 processParsedRequest(context);
f900210a 2157
4959e21e 2158 parsed_req = true; // XXX: do we really need to parse everything right NOW ?
f900210a 2159
2160 if (context->mayUseConnection()) {
f35961af 2161 debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection");
f900210a 2162 break;
2163 }
eacfca83
AR
2164 } else {
2165 debugs(33, 5, clientConnection << ": not enough request data: " <<
fcc444e3
AJ
2166 inBuf.length() << " < " << Config.maxRequestHeaderSize);
2167 Must(inBuf.length() < Config.maxRequestHeaderSize);
eacfca83 2168 break;
f900210a 2169 }
39cb8c41 2170 }
fc68f6b1 2171
a5baffba 2172 /* XXX where to 'finish' the parsing pass? */
f900210a 2173 return parsed_req;
2174}
2175
1cf238db 2176void
fcc444e3 2177ConnStateData::afterClientRead()
c4b7a5a9 2178{
3cae14a6 2179#if USE_OPENSSL
d20cf186
AR
2180 if (parsingTlsHandshake) {
2181 parseTlsHandshake();
3cae14a6
CT
2182 return;
2183 }
2184#endif
d20cf186 2185
94439e4e 2186 /* Process next request */
e500cc89 2187 if (pipeline.empty())
fcc444e3 2188 fd_note(clientConnection->fd, "Reading next request");
c8be6d7b 2189
f35961af 2190 if (!clientParseRequests()) {
9e008dda
AJ
2191 if (!isOpen())
2192 return;
f900210a 2193 /*
2194 * If the client here is half closed and we failed
2195 * to parse a request, close the connection.
2196 * The above check with connFinishedWithConn() only
2197 * succeeds _if_ the buffer is empty which it won't
2198 * be if we have an incomplete request.
f4a53cf7 2199 * XXX: This duplicates ConnStateData::kick
f900210a 2200 */
e500cc89 2201 if (pipeline.empty() && commIsHalfClosed(clientConnection->fd)) {
fcc444e3 2202 debugs(33, 5, clientConnection << ": half-closed connection, no completed request parsed, connection closing.");
73c36fd9 2203 clientConnection->close();
ee6f0213 2204 return;
62e76326 2205 }
f900210a 2206 }
ee6f0213 2207
1cf238db 2208 if (!isOpen())
2e216b1d 2209 return;
2210
f35961af 2211 clientAfterReadingRequests();
94439e4e 2212}
2213
63be0a78 2214/**
2215 * called when new request data has been read from the socket
39cb8c41
AR
2216 *
2217 * \retval false called comm_close or setReplyToError (the caller should bail)
2218 * \retval true we did not call comm_close or setReplyToError
63be0a78 2219 */
39cb8c41 2220bool
7e66d5e2 2221ConnStateData::handleReadData()
94439e4e 2222{
5f8252d2 2223 // if we are reading a body, stuff data into the body pipe
2224 if (bodyPipe != NULL)
39cb8c41
AR
2225 return handleRequestBodyData();
2226 return true;
94439e4e 2227}
2228
63be0a78 2229/**
fcc444e3 2230 * called when new request body data has been buffered in inBuf
63be0a78 2231 * may close the connection if we were closing and piped everything out
39cb8c41
AR
2232 *
2233 * \retval false called comm_close or setReplyToError (the caller should bail)
2234 * \retval true we did not call comm_close or setReplyToError
63be0a78 2235 */
39cb8c41 2236bool
5f8252d2 2237ConnStateData::handleRequestBodyData()
94439e4e 2238{
5f8252d2 2239 assert(bodyPipe != NULL);
2240
fcc444e3 2241 if (bodyParser) { // chunked encoding
be29ee33 2242 if (const err_type error = handleChunkedRequestBody()) {
39cb8c41
AR
2243 abortChunkedRequestBody(error);
2244 return false;
3ff65596 2245 }
39cb8c41 2246 } else { // identity encoding
73c36fd9 2247 debugs(33,5, HERE << "handling plain request body for " << clientConnection);
fcc444e3 2248 const size_t putSize = bodyPipe->putMoreData(inBuf.c_str(), inBuf.length());
be29ee33
AJ
2249 if (putSize > 0)
2250 consumeInput(putSize);
2251
3ff65596
AR
2252 if (!bodyPipe->mayNeedMoreData()) {
2253 // BodyPipe will clear us automagically when we produced everything
2254 bodyPipe = NULL;
2255 }
2256 }
2257
3ff65596 2258 if (!bodyPipe) {
73c36fd9 2259 debugs(33,5, HERE << "produced entire request body for " << clientConnection);
62e76326 2260
cf6eb29e 2261 if (const char *reason = stoppedSending()) {
5f8252d2 2262 /* we've finished reading like good clients,
2263 * now do the close that initiateClose initiated.
5f8252d2 2264 */
cf6eb29e 2265 debugs(33, 3, HERE << "closing for earlier sending error: " << reason);
73c36fd9 2266 clientConnection->close();
39cb8c41
AR
2267 return false;
2268 }
2269 }
2270
2271 return true;
2272}
2273
2274/// parses available chunked encoded body bytes, checks size, returns errors
2275err_type
be29ee33 2276ConnStateData::handleChunkedRequestBody()
39cb8c41 2277{
fcc444e3 2278 debugs(33, 7, "chunked from " << clientConnection << ": " << inBuf.length());
39cb8c41
AR
2279
2280 try { // the parser will throw on errors
2281
fcc444e3 2282 if (inBuf.isEmpty()) // nothing to do
39cb8c41
AR
2283 return ERR_NONE;
2284
39cb8c41 2285 BodyPipeCheckout bpc(*bodyPipe);
fcc444e3
AJ
2286 bodyParser->setPayloadBuffer(&bpc.buf);
2287 const bool parsed = bodyParser->parse(inBuf);
2288 inBuf = bodyParser->remaining(); // sync buffers
39cb8c41 2289 bpc.checkIn();
39cb8c41
AR
2290
2291 // dechunk then check: the size limit applies to _dechunked_ content
2292 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize()))
2293 return ERR_TOO_BIG;
2294
2295 if (parsed) {
2296 finishDechunkingRequest(true);
2297 Must(!bodyPipe);
2298 return ERR_NONE; // nil bodyPipe implies body end for the caller
5f8252d2 2299 }
39cb8c41
AR
2300
2301 // if chunk parser needs data, then the body pipe must need it too
fcc444e3 2302 Must(!bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData());
39cb8c41
AR
2303
2304 // if parser needs more space and we can consume nothing, we will stall
fcc444e3 2305 Must(!bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent());
39cb8c41
AR
2306 } catch (...) { // TODO: be more specific
2307 debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status());
2308 return ERR_INVALID_REQ;
94439e4e 2309 }
39cb8c41
AR
2310
2311 debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status());
2312 return ERR_NONE;
2313}
2314
2315/// quit on errors related to chunked request body handling
2316void
2317ConnStateData::abortChunkedRequestBody(const err_type error)
2318{
2319 finishDechunkingRequest(false);
2320
2321 // XXX: The code below works if we fail during initial request parsing,
d5430dc8 2322 // but if we fail when the server connection is used already, the server may send
39cb8c41
AR
2323 // us its response too, causing various assertions. How to prevent that?
2324#if WE_KNOW_HOW_TO_SEND_ERRORS
d3dddfb5 2325 Http::StreamPointer context = pipeline.front();
39cb8c41
AR
2326 if (context != NULL && !context->http->out.offset) { // output nothing yet
2327 clientStreamNode *node = context->getClientReplyContext();
2328 clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw());
2329 assert(repContext);
955394ce 2330 const Http::StatusCode scode = (error == ERR_TOO_BIG) ?
f11c8e2f 2331 Http::scPayloadTooLarge : HTTP_BAD_REQUEST;
39cb8c41
AR
2332 repContext->setReplyToError(error, scode,
2333 repContext->http->request->method,
2334 repContext->http->uri,
a3c6762c 2335 CachePeer,
39cb8c41 2336 repContext->http->request,
fcc444e3 2337 inBuf, NULL);
39cb8c41
AR
2338 context->pullData();
2339 } else {
2340 // close or otherwise we may get stuck as nobody will notice the error?
73c36fd9 2341 comm_reset_close(clientConnection);
39cb8c41
AR
2342 }
2343#else
2344 debugs(33, 3, HERE << "aborting chunked request without error " << error);
73c36fd9 2345 comm_reset_close(clientConnection);
39cb8c41 2346#endif
f35961af 2347 flags.readMore = false;
5f8252d2 2348}
55e44db9 2349
5f8252d2 2350void
1cf238db 2351ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer )
5f8252d2 2352{
cf6eb29e
CT
2353 // request reader may get stuck waiting for space if nobody consumes body
2354 if (bodyPipe != NULL)
2355 bodyPipe->enableAutoConsumption();
2356
92ae4c86 2357 // kids extend
94439e4e 2358}
2359
63be0a78 2360/** general lifetime handler for HTTP requests */
1cf238db 2361void
2362ConnStateData::requestTimeout(const CommTimeoutCbParams &io)
7a2f978b 2363{
d5b97346
AJ
2364 if (!Comm::IsConnOpen(io.conn))
2365 return;
2366
6b2b6cfe
CT
2367 if (mayTunnelUnsupportedProto() && !receivedFirstByte_) {
2368 Http::StreamPointer context = pipeline.front();
2369 Must(context && context->http);
2370 HttpRequest::Pointer request = context->http->request;
2371 if (clientTunnelOnError(this, context, request, HttpRequestMethod(), ERR_REQUEST_START_TIMEOUT))
2372 return;
3248e962 2373 }
af57a2e3 2374 /*
62e76326 2375 * Just close the connection to not confuse browsers
6177a89f
HN
2376 * using persistent connections. Some browsers open
2377 * a connection and then do not use it until much
62e76326 2378 * later (presumeably because the request triggering
2379 * the open has already been completed on another
2380 * connection)
2381 */
1cf238db 2382 debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired.");
8d77a37c 2383 io.conn->close();
7a2f978b 2384}
2385
b5c39993 2386static void
8d77a37c 2387clientLifetimeTimeout(const CommTimeoutCbParams &io)
b5c39993 2388{
8d77a37c 2389 ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data);
cb61ec47
AJ
2390 debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout");
2391 debugs(33, DBG_IMPORTANT, "\t" << http->uri);
a981b360 2392 http->logType.err.timedout = true;
8d77a37c
AJ
2393 if (Comm::IsConnOpen(io.conn))
2394 io.conn->close();
b5c39993 2395}
2396
94bfd31f 2397ConnStateData::ConnStateData(const MasterXaction::Pointer &xact) :
f53969cc 2398 AsyncJob("ConnStateData"), // kids overwrite
fcc444e3
AJ
2399 Server(xact),
2400 bodyParser(nullptr),
cb4f4424 2401#if USE_OPENSSL
f53969cc 2402 sslBumpMode(Ssl::bumpEnd),
4579a6d0 2403#endif
f53969cc 2404 needProxyProtocolHeader_(false),
4579a6d0 2405#if USE_OPENSSL
f53969cc 2406 switchedToHttps_(false),
d20cf186 2407 parsingTlsHandshake(false),
f53969cc
SM
2408 sslServerBump(NULL),
2409 signAlgorithm(Ssl::algSignTrusted),
94bfd31f 2410#endif
f53969cc 2411 stoppedSending_(NULL),
fcc444e3 2412 stoppedReceiving_(NULL)
c8be6d7b 2413{
4579a6d0
AJ
2414 flags.readMore = true; // kids may overwrite
2415 flags.swanSang = false;
2416
94bfd31f
AJ
2417 pinning.host = NULL;
2418 pinning.port = -1;
2419 pinning.pinned = false;
2420 pinning.auth = false;
2421 pinning.zeroReply = false;
2422 pinning.peer = NULL;
2423
2424 // store the details required for creating more MasterXaction objects as new requests come in
94bfd31f
AJ
2425 log_addr = xact->tcpClient->remote;
2426 log_addr.applyMask(Config.Addrs.client_netmask);
d442618d
AJ
2427
2428 // register to receive notice of Squid signal events
2429 // which may affect long persisting client connections
b856803f 2430 registerRunner();
92ae4c86
AR
2431}
2432
2433void
2434ConnStateData::start()
2435{
2436 BodyProducer::start();
2437 HttpControlMsgSink::start();
2438
5529ca8a 2439 if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF &&
94bfd31f 2440 (transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) {
5529ca8a 2441#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2442 int i = IP_PMTUDISC_DONT;
b69e9ffa
AJ
2443 if (setsockopt(clientConnection->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof(i)) < 0) {
2444 int xerrno = errno;
2445 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection << " : " << xstrerr(xerrno));
2446 }
5529ca8a 2447#else
9bb67276 2448 static bool reported = false;
5529ca8a 2449
2450 if (!reported) {
9bb67276
AJ
2451 debugs(33, DBG_IMPORTANT, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2452 reported = true;
5529ca8a 2453 }
89aec9b6
AJ
2454#endif
2455 }
5529ca8a 2456
89aec9b6 2457 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
94bfd31f
AJ
2458 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, ConnStateData::connStateClosed);
2459 comm_add_close_handler(clientConnection->fd, call);
5529ca8a 2460
42cbf844
AJ
2461 needProxyProtocolHeader_ = port->flags.proxySurrogate;
2462 if (needProxyProtocolHeader_) {
2463 if (!proxyProtocolValidateClient()) // will close the connection on failure
2464 return;
2465 } else
2466 whenClientIpKnown();
2467
2468}
2469
2470void
2471ConnStateData::whenClientIpKnown()
2472{
89aec9b6 2473 if (Config.onoff.log_fqdn)
94bfd31f 2474 fqdncache_gethostbyaddr(clientConnection->remote, FQDN_LOOKUP_IF_MISS);
89aec9b6
AJ
2475
2476#if USE_IDENT
2477 if (Ident::TheConfig.identLookup) {
2478 ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL);
92ae4c86
AR
2479 identChecklist.src_addr = clientConnection->remote;
2480 identChecklist.my_addr = clientConnection->local;
2efeb0b7 2481 if (identChecklist.fastCheck() == ACCESS_ALLOWED)
92ae4c86 2482 Ident::Start(clientConnection, clientIdentDone, this);
89aec9b6 2483 }
5529ca8a 2484#endif
2485
94bfd31f 2486 clientdbEstablished(clientConnection->remote, 1);
5529ca8a 2487
9a0a18de 2488#if USE_DELAY_POOLS
92ae4c86 2489 fd_table[clientConnection->fd].clientInfo = NULL;
b4cd430a 2490
f33d34a8 2491 if (Config.onoff.client_db) {
b4cd430a
CT
2492 /* it was said several times that client write limiter does not work if client_db is disabled */
2493
b27668ec 2494 auto &pools = ClientDelayPools::Instance()->pools;
2efeb0b7 2495 ACLFilledChecklist ch(NULL, NULL, NULL);
b4cd430a 2496
2efeb0b7
AJ
2497 // TODO: we check early to limit error response bandwith but we
2498 // should recheck when we can honor delay_pool_uses_indirect
2499 // TODO: we should also pass the port details for myportname here.
92ae4c86
AR
2500 ch.src_addr = clientConnection->remote;
2501 ch.my_addr = clientConnection->local;
b4cd430a 2502
95dc7ff4 2503 for (unsigned int pool = 0; pool < pools.size(); ++pool) {
b4cd430a 2504
2efeb0b7 2505 /* pools require explicit 'allow' to assign a client into them */
b27668ec
EB
2506 if (pools[pool]->access) {
2507 ch.changeAcl(pools[pool]->access);
2efeb0b7
AJ
2508 allow_t answer = ch.fastCheck();
2509 if (answer == ACCESS_ALLOWED) {
2510
2511 /* request client information from db after we did all checks
2512 this will save hash lookup if client failed checks */
92ae4c86 2513 ClientInfo * cli = clientdbGetInfo(clientConnection->remote);
2efeb0b7
AJ
2514 assert(cli);
2515
2516 /* put client info in FDE */
92ae4c86 2517 fd_table[clientConnection->fd].clientInfo = cli;
2efeb0b7
AJ
2518
2519 /* setup write limiter for this request */
2520 const double burst = floor(0.5 +
b27668ec
EB
2521 (pools[pool]->highwatermark * Config.ClientDelay.initial)/100.0);
2522 cli->setWriteLimiter(pools[pool]->rate, burst, pools[pool]->highwatermark);
2efeb0b7
AJ
2523 break;
2524 } else {
2525 debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer);
2526 }
b4cd430a
CT
2527 }
2528 }
2529 }
2530#endif
92ae4c86
AR
2531
2532 // kids must extend to actually start doing something (e.g., reading)
7a2f978b 2533}
2534
e7ce227f 2535/** Handle a new connection on an HTTP socket. */
92ae4c86
AR
2536void
2537httpAccept(const CommAcceptCbParams &params)
6afea0a4
AR
2538{
2539 MasterXaction::Pointer xact = params.xaction;
2540 AnyP::PortCfgPointer s = xact->squidPort;
2541
2542 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2543
2544 if (params.flag != Comm::OK) {
2545 // Its possible the call was still queued when the client disconnected
e7ce227f 2546 debugs(33, 2, s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
6afea0a4
AR
2547 return;
2548 }
2549
e7ce227f 2550 debugs(33, 4, params.conn << ": accepted");
92ae4c86 2551 fd_note(params.conn->fd, "client http connect");
6afea0a4 2552
e7ce227f 2553 if (s->tcp_keepalive.enabled)
6afea0a4 2554 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
6afea0a4 2555
e7ce227f 2556 ++incoming_sockets_accepted;
6afea0a4
AR
2557
2558 // Socket is ready, setup the connection manager to start using it
5e77f674
AJ
2559 auto *srv = Http::NewServer(xact);
2560 AsyncJob::Start(srv); // usually async-calls readSomeData()
7a2f978b 2561}
2562
cb4f4424 2563#if USE_OPENSSL
86f77270 2564/// Create TLS connection structure and update fd_table
157c5ace 2565static bool
0476ec45 2566httpsCreate(const Comm::ConnectionPointer &conn, const Security::ContextPointer &ctx)
ae7ff0b8 2567{
86f77270 2568 if (Security::CreateServerSession(ctx, conn, "client https start")) {
ca2526bd 2569 debugs(33, 5, "will negotiate TLS on " << conn);
157c5ace 2570 return true;
ae7ff0b8 2571 }
2572
b3a8ae1b 2573 conn->close();
157c5ace 2574 return false;
ae7ff0b8 2575}
2576
3248e962 2577/**
44352c16 2578 *
3248e962
CT
2579 * \retval 1 on success
2580 * \retval 0 when needs more data
2581 * \retval -1 on error
2582 */
2583static int
d620ae0e 2584Squid_SSL_accept(ConnStateData *conn, PF *callback)
1f7c9178 2585{
d620ae0e 2586 int fd = conn->clientConnection->fd;
33cc0629 2587 auto ssl = fd_table[fd].ssl.get();
1f7c9178 2588 int ret;
2589
e9447f01 2590 errno = 0;
a7ad6e4e 2591 if ((ret = SSL_accept(ssl)) <= 0) {
f5518dca
AJ
2592 const int xerrno = errno;
2593 const int ssl_error = SSL_get_error(ssl, ret);
62e76326 2594
2595 switch (ssl_error) {
2596
2597 case SSL_ERROR_WANT_READ:
3cae14a6 2598 Comm::SetSelect(fd, COMM_SELECT_READ, callback, (callback != NULL ? conn : NULL), 0);
3248e962 2599 return 0;
62e76326 2600
2601 case SSL_ERROR_WANT_WRITE:
3cae14a6 2602 Comm::SetSelect(fd, COMM_SELECT_WRITE, callback, (callback != NULL ? conn : NULL), 0);
3248e962 2603 return 0;
62e76326 2604
6de9e64b 2605 case SSL_ERROR_SYSCALL:
6de9e64b 2606 if (ret == 0) {
d620ae0e 2607 debugs(83, 2, "Error negotiating SSL connection on FD " << fd << ": Aborted by client: " << ssl_error);
6de9e64b 2608 } else {
e9447f01 2609 debugs(83, (xerrno == ECONNRESET) ? 1 : 2, "Error negotiating SSL connection on FD " << fd << ": " <<
ea574635 2610 (xerrno == 0 ? Security::ErrorString(ssl_error) : xstrerr(xerrno)));
6de9e64b 2611 }
3248e962 2612 return -1;
6de9e64b 2613
2614 case SSL_ERROR_ZERO_RETURN:
d620ae0e 2615 debugs(83, DBG_IMPORTANT, "Error negotiating SSL connection on FD " << fd << ": Closed by client");
3248e962 2616 return -1;
6de9e64b 2617
62e76326 2618 default:
d620ae0e 2619 debugs(83, DBG_IMPORTANT, "Error negotiating SSL connection on FD " <<
ea574635 2620 fd << ": " << Security::ErrorString(ERR_get_error()) <<
9e008dda 2621 " (" << ssl_error << "/" << ret << ")");
3248e962 2622 return -1;
62e76326 2623 }
2624
2625 /* NOTREACHED */
1f7c9178 2626 }
3248e962 2627 return 1;
d620ae0e
CT
2628}
2629
2630/** negotiate an SSL connection */
2631static void
2632clientNegotiateSSL(int fd, void *data)
2633{
2634 ConnStateData *conn = (ConnStateData *)data;
3248e962
CT
2635 int ret;
2636 if ((ret = Squid_SSL_accept(conn, clientNegotiateSSL)) <= 0) {
2637 if (ret < 0) // An error
b54a7c5a 2638 conn->clientConnection->close();
d620ae0e 2639 return;
3248e962 2640 }
62e76326 2641
ad23e748
AJ
2642 Security::SessionPointer session(fd_table[fd].ssl);
2643 if (Security::SessionIsResumed(session)) {
2644 debugs(83, 2, "Session " << SSL_get_session(session.get()) <<
2645 " reused on FD " << fd << " (" << fd_table[fd].ipaddr <<
2646 ":" << (int)fd_table[fd].remote_port << ")");
6de9e64b 2647 } else {
014adac1 2648 if (Debug::Enabled(83, 4)) {
6de9e64b 2649 /* Write out the SSL session details.. actually the call below, but
2650 * OpenSSL headers do strange typecasts confusing GCC.. */
2651 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
afdd443f 2652#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
ad23e748
AJ
2653 PEM_ASN1_write(reinterpret_cast<i2d_of_void *>(i2d_SSL_SESSION),
2654 PEM_STRING_SSL_SESSION, debug_log,
bba00f17 2655 reinterpret_cast<char *>(SSL_get_session(session.get())),
ad23e748 2656 nullptr, nullptr, 0, nullptr, nullptr);
2930f303 2657
0fd2205b 2658#elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2930f303 2659
0fd2205b 2660 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
2661 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
2662 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
2663 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
2664 * Because there are two possible usable cast, if you get an error here, try the other
2665 * commented line. */
2666
ad23e748
AJ
2667 PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,
2668 debug_log,
bba00f17 2669 reinterpret_cast<char *>(SSL_get_session(session.get())),
ad23e748
AJ
2670 nullptr, nullptr, 0, nullptr, nullptr);
2671 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,
2672 debug_log,
bba00f17 2673 reinterpret_cast<char *>(SSL_get_session(session.get())),
ad23e748
AJ
2674 nullptr, nullptr, 0, nullptr, nullptr);
2675 */
0e33d58c 2676#else
ad23e748 2677 debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source.");
0fd2205b 2678
0e33d58c 2679#endif
6de9e64b 2680 /* Note: This does not automatically fflush the log file.. */
2681 }
2682
ad23e748
AJ
2683 debugs(83, 2, "New session " << SSL_get_session(session.get()) <<
2684 " on FD " << fd << " (" << fd_table[fd].ipaddr << ":" <<
2685 fd_table[fd].remote_port << ")");
6de9e64b 2686 }
2687
2bcab852 2688 // Connection established. Retrieve TLS connection parameters for logging.
ad23e748 2689 conn->clientConnection->tlsNegotiations()->retrieveNegotiatedInfo(session);
1f7c9178 2690
ad23e748 2691 X509 *client_cert = SSL_get_peer_certificate(session.get());
62e76326 2692
ad23e748
AJ
2693 if (client_cert) {
2694 debugs(83, 3, "FD " << fd << " client certificate: subject: " <<
bf8fe701 2695 X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0));
2696
ad23e748 2697 debugs(83, 3, "FD " << fd << " client certificate: issuer: " <<
bf8fe701 2698 X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0));
1f7c9178 2699
62e76326 2700 X509_free(client_cert);
1f7c9178 2701 } else {
ad23e748 2702 debugs(83, 5, "FD " << fd << " has no certificate.");
1f7c9178 2703 }
2704
a46d2c0e 2705 conn->readSomeData();
1f7c9178 2706}
2707
379e8c1c 2708/**
0476ec45
AJ
2709 * If Security::ContextPointer is given, starts reading the TLS handshake.
2710 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPointer.
379e8c1c
AR
2711 */
2712static void
0476ec45 2713httpsEstablish(ConnStateData *connState, const Security::ContextPointer &ctx)
379e8c1c 2714{
379e8c1c
AR
2715 assert(connState);
2716 const Comm::ConnectionPointer &details = connState->clientConnection;
2717
0476ec45 2718 if (!ctx || !httpsCreate(details, ctx))
379e8c1c
AR
2719 return;
2720
7a957a93
AR
2721 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
2722 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
87f237a9 2723 connState, ConnStateData::requestTimeout);
379e8c1c
AR
2724 commSetConnTimeout(details, Config.Timeout.request, timeoutCall);
2725
36048c42 2726 Comm::SetSelect(details->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0);
379e8c1c
AR
2727}
2728
2729/**
87f237a9 2730 * A callback function to use with the ACLFilledChecklist callback.
94bfd31f 2731 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
7a957a93 2732 * else reverts the connection to tunnel mode.
379e8c1c
AR
2733 */
2734static void
2735httpsSslBumpAccessCheckDone(allow_t answer, void *data)
2736{
2737 ConnStateData *connState = (ConnStateData *) data;
2738
7a957a93 2739 // if the connection is closed or closing, just return.
379e8c1c
AR
2740 if (!connState->isOpen())
2741 return;
2742
7a957a93 2743 // Require both a match and a positive bump mode to work around exceptional
caf3666d 2744 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
6b2b6cfe 2745 if (answer == ACCESS_ALLOWED && answer.kind != Ssl::bumpNone) {
e4f14091 2746 debugs(33, 2, "sslBump needed for " << connState->clientConnection << " method " << answer.kind);
08097970 2747 connState->sslBumpMode = static_cast<Ssl::BumpMode>(answer.kind);
379e8c1c 2748 } else {
08097970
AR
2749 debugs(33, 2, HERE << "sslBump not needed for " << connState->clientConnection);
2750 connState->sslBumpMode = Ssl::bumpNone;
9e104535 2751 }
efda53c5
CT
2752 if (!connState->fakeAConnectRequest("ssl-bump", connState->inBuf))
2753 connState->clientConnection->close();
a30b692c 2754}
379e8c1c 2755
63be0a78 2756/** handle a new HTTPS connection */
1f7c9178 2757static void
449f0115 2758httpsAccept(const CommAcceptCbParams &params)
1f7c9178 2759{
94bfd31f
AJ
2760 MasterXaction::Pointer xact = params.xaction;
2761 const AnyP::PortCfgPointer s = xact->squidPort;
2762
c0ff709f 2763 // NP: it is possible the port was reconfigured when the call or accept() was queued.
c4b7a5a9 2764
c8407295 2765 if (params.flag != Comm::OK) {
cbff89ba 2766 // Its possible the call was still queued when the client disconnected
449f0115 2767 debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
62e76326 2768 return;
c4b7a5a9 2769 }
62e76326 2770
449f0115
AJ
2771 debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation.");
2772 fd_note(params.conn->fd, "client https connect");
62e76326 2773
859741ed
AJ
2774 if (s->tcp_keepalive.enabled) {
2775 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
b2130d58 2776 }
95dc7ff4 2777 ++incoming_sockets_accepted;
62e76326 2778
89aec9b6 2779 // Socket is ready, setup the connection manager to start using it
5e77f674
AJ
2780 auto *srv = Https::NewServer(xact);
2781 AsyncJob::Start(srv); // usually async-calls postHttpsAccept()
92ae4c86 2782}
62e76326 2783
92ae4c86
AR
2784void
2785ConnStateData::postHttpsAccept()
2786{
b3cb9958 2787 if (port->flags.tunnelSslBumping) {
e7ce227f 2788 debugs(33, 5, "accept transparent connection: " << clientConnection);
62e76326 2789
379e8c1c 2790 if (!Config.accessList.ssl_bump) {
b3cb9958 2791 httpsSslBumpAccessCheckDone(ACCESS_DENIED, this);
379e8c1c
AR
2792 return;
2793 }
87f237a9 2794
379e8c1c 2795 // Create a fake HTTP request for ssl_bump ACL check,
38450a50 2796 // using tproxy/intercept provided destination IP and port.
379e8c1c
AR
2797 HttpRequest *request = new HttpRequest();
2798 static char ip[MAX_IPSTRLEN];
92ae4c86 2799 assert(clientConnection->flags & (COMM_TRANSPARENT | COMM_INTERCEPTION));
851feda6 2800 request->url.host(clientConnection->local.toStr(ip, sizeof(ip)));
5c51bffb 2801 request->url.port(clientConnection->local.port());
b3cb9958 2802 request->myportname = port->name;
87f237a9 2803
379e8c1c 2804 ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL);
92ae4c86 2805 acl_checklist->src_addr = clientConnection->remote;
b3cb9958 2806 acl_checklist->my_addr = port->s;
d4ddb3e6
CT
2807 // Build a local AccessLogEntry to allow requiresAle() acls work
2808 acl_checklist->al = new AccessLogEntry;
2809 acl_checklist->al->cache.start_time = current_time;
2810 acl_checklist->al->tcpClient = clientConnection;
2811 acl_checklist->al->cache.port = port;
2812 acl_checklist->al->cache.caddr = log_addr;
542e1a7a 2813 HTTPMSGUNLOCK(acl_checklist->al->request);
d4ddb3e6
CT
2814 acl_checklist->al->request = request;
2815 HTTPMSGLOCK(acl_checklist->al->request);
b3cb9958 2816 acl_checklist->nonBlockingCheck(httpsSslBumpAccessCheckDone, this);
379e8c1c
AR
2817 return;
2818 } else {
0476ec45 2819 httpsEstablish(this, port->secure.staticContext);
379e8c1c 2820 }
1f7c9178 2821}
2822
95d2589c 2823void
24438ec5 2824ConnStateData::sslCrtdHandleReplyWrapper(void *data, const Helper::Reply &reply)
ae7ff0b8 2825{
95d2589c
CT
2826 ConnStateData * state_data = (ConnStateData *)(data);
2827 state_data->sslCrtdHandleReply(reply);
2828}
ae7ff0b8 2829
95d2589c 2830void
24438ec5 2831ConnStateData::sslCrtdHandleReply(const Helper::Reply &reply)
95d2589c 2832{
b418d9c8
CT
2833 if (!isOpen()) {
2834 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply);
2835 return;
2836 }
2837
2428ce02 2838 if (reply.result == Helper::BrokenHelper) {
5955f162
AJ
2839 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply);
2840 } else if (!reply.other().hasContent()) {
2841 debugs(1, DBG_IMPORTANT, HERE << "\"ssl_crtd\" helper returned <NULL> reply.");
95d2589c 2842 } else {
ff2d7d92 2843 Ssl::CrtdMessage reply_message(Ssl::CrtdMessage::REPLY);
0272dd08 2844 if (reply_message.parse(reply.other().content(), reply.other().contentSize()) != Ssl::CrtdMessage::OK) {
fb2178bb 2845 debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslConnectHostOrIp << " is incorrect");
95d2589c 2846 } else {
2428ce02 2847 if (reply.result != Helper::Okay) {
fb2178bb 2848 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply_message.getBody());
95d2589c 2849 } else {
fb2178bb 2850 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " was successfully recieved from ssl_crtd");
a9c2dd2f 2851 if (sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare)) {
d620ae0e 2852 doPeekAndSpliceStep();
33cc0629 2853 auto ssl = fd_table[clientConnection->fd].ssl.get();
d620ae0e
CT
2854 bool ret = Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl, reply_message.getBody().c_str(), *port);
2855 if (!ret)
e4f14091 2856 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
d8f0ceab 2857
1c1fae0f 2858 Security::ContextPointer ctx(Security::GetFrom(fd_table[clientConnection->fd].ssl));
b23f5f9c 2859 Ssl::configureUnconfiguredSslContext(ctx, signAlgorithm, *port);
d620ae0e 2860 } else {
0476ec45 2861 Security::ContextPointer ctx(Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str(), *port));
d620ae0e
CT
2862 getSslContextDone(ctx, true);
2863 }
95d2589c
CT
2864 return;
2865 }
2866 }
2867 }
0476ec45
AJ
2868 Security::ContextPointer nil;
2869 getSslContextDone(nil);
95d2589c 2870}
ae7ff0b8 2871
06997a38 2872void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties &certProperties)
fb2178bb 2873{
69f69080 2874 certProperties.commonName = sslCommonName_.isEmpty() ? sslConnectHostOrIp.termedBuf() : sslCommonName_.c_str();
fb2178bb 2875
6b2b6cfe
CT
2876 const bool triedToConnect = sslServerBump && sslServerBump->entry;
2877 const bool connectedOK = triedToConnect && sslServerBump->entry->isEmpty();
2878 if (connectedOK) {
fd4624d7 2879 if (X509 *mimicCert = sslServerBump->serverCert.get())
59a49556
CT
2880 certProperties.mimicCert.resetAndLock(mimicCert);
2881
b248c2a3 2882 ACLFilledChecklist checklist(NULL, sslServerBump->request.getRaw(),
59a49556 2883 clientConnection != NULL ? clientConnection->rfc931 : dash_str);
088f0761 2884 checklist.sslErrors = cbdataReference(sslServerBump->sslErrors());
59a49556
CT
2885
2886 for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) {
7a957a93 2887 // If the algorithm already set, then ignore it.
a06042fa 2888 if ((ca->alg == Ssl::algSetCommonName && certProperties.setCommonName) ||
87f237a9
A
2889 (ca->alg == Ssl::algSetValidAfter && certProperties.setValidAfter) ||
2890 (ca->alg == Ssl::algSetValidBefore && certProperties.setValidBefore) )
a06042fa
CT
2891 continue;
2892
59a49556
CT
2893 if (ca->aclList && checklist.fastCheck(ca->aclList) == ACCESS_ALLOWED) {
2894 const char *alg = Ssl::CertAdaptAlgorithmStr[ca->alg];
2895 const char *param = ca->param;
87f237a9 2896
7a957a93
AR
2897 // For parameterless CN adaptation, use hostname from the
2898 // CONNECT request.
a06042fa 2899 if (ca->alg == Ssl::algSetCommonName) {
59a49556
CT
2900 if (!param)
2901 param = sslConnectHostOrIp.termedBuf();
2902 certProperties.commonName = param;
2903 certProperties.setCommonName = true;
87f237a9 2904 } else if (ca->alg == Ssl::algSetValidAfter)
59a49556 2905 certProperties.setValidAfter = true;
87f237a9 2906 else if (ca->alg == Ssl::algSetValidBefore)
59a49556
CT
2907 certProperties.setValidBefore = true;
2908
87f237a9 2909 debugs(33, 5, HERE << "Matches certificate adaptation aglorithm: " <<
8f9720ce 2910 alg << " param: " << (param ? param : "-"));
aebe6888 2911 }
fb2178bb 2912 }
aebe6888 2913
59a49556
CT
2914 certProperties.signAlgorithm = Ssl::algSignEnd;
2915 for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) {
2916 if (sg->aclList && checklist.fastCheck(sg->aclList) == ACCESS_ALLOWED) {
2917 certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg;
2918 break;
2919 }
aebe6888 2920 }
6b2b6cfe
CT
2921 } else {// did not try to connect (e.g. client-first) or failed to connect
2922 // In case of an error while connecting to the secure server, use a
2923 // trusted certificate, with no mimicked fields and no adaptation
2924 // algorithms. There is nothing we can mimic, so we want to minimize the
2925 // number of warnings the user will have to see to get to the error page.
2926 // We will close the connection, so that the trust is not extended to
2927 // non-Squid content.
59a49556 2928 certProperties.signAlgorithm = Ssl::algSignTrusted;
aebe6888
CT
2929 }
2930
10d914f6 2931 assert(certProperties.signAlgorithm != Ssl::algSignEnd);
aebe6888
CT
2932
2933 if (certProperties.signAlgorithm == Ssl::algSignUntrusted) {
f4e4d4d6 2934 assert(port->untrustedSigningCert.get());
95588170
CT
2935 certProperties.signWithX509.resetAndLock(port->untrustedSigningCert.get());
2936 certProperties.signWithPkey.resetAndLock(port->untrustedSignPkey.get());
87f237a9 2937 } else {
f4e4d4d6
CT
2938 assert(port->signingCert.get());
2939 certProperties.signWithX509.resetAndLock(port->signingCert.get());
aebe6888
CT
2940
2941 if (port->signPkey.get())
2942 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
2943 }
2944 signAlgorithm = certProperties.signAlgorithm;
3c26b00a
CT
2945
2946 certProperties.signHash = Ssl::DefaultSignHash;
fb2178bb
CT
2947}
2948
1ce2822d 2949void
95d2589c
CT
2950ConnStateData::getSslContextStart()
2951{
08a8a70b
AR
2952 // If we are called, then CONNECT has succeeded. Finalize it.
2953 if (auto xact = pipeline.front()) {
2954 if (xact->http && xact->http->request && xact->http->request->method == Http::METHOD_CONNECT)
2955 xact->finished();
2956 // cannot proceed with encryption if requests wait for plain responses
2957 Must(pipeline.empty());
2958 }
2959 /* careful: finished() above frees request, host, etc. */
129fe2a1 2960
fb2178bb 2961 if (port->generateHostCertificates) {
aebe6888 2962 Ssl::CertificateProperties certProperties;
06997a38
CT
2963 buildSslCertGenerationParams(certProperties);
2964 sslBumpCertKey = certProperties.dbKey().c_str();
b38b26cb 2965 assert(sslBumpCertKey.size() > 0 && sslBumpCertKey[0] != '\0');
fb2178bb 2966
d620ae0e 2967 // Disable caching for bumpPeekAndSplice mode
a9c2dd2f 2968 if (!(sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare))) {
e4f14091 2969 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey << " in cache");
31855516 2970 Ssl::LocalContextStorage * ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s);
3db3be00 2971 Security::ContextPointer *cachedCtx = ssl_ctx_cache ? ssl_ctx_cache->get(sslBumpCertKey.termedBuf()) : nullptr;
0476ec45 2972 if (cachedCtx) {
e4f14091 2973 debugs(33, 5, "SSL certificate for " << sslBumpCertKey << " found in cache");
b23f5f9c 2974 if (Ssl::verifySslCertificate(*cachedCtx, certProperties)) {
e4f14091 2975 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey << " is valid");
0476ec45 2976 getSslContextDone(*cachedCtx);
d620ae0e
CT
2977 return;
2978 } else {
e4f14091 2979 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey << " is out of date. Delete this certificate from cache");
31855516
CT
2980 if (ssl_ctx_cache)
2981 ssl_ctx_cache->del(sslBumpCertKey.termedBuf());
d620ae0e 2982 }
95d2589c 2983 } else {
e4f14091 2984 debugs(33, 5, "SSL certificate for " << sslBumpCertKey << " haven't found in cache");
95d2589c 2985 }
95d2589c
CT
2986 }
2987
b5faa519 2988#if USE_SSL_CRTD
00fc192d 2989 try {
87f237a9 2990 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName << " using ssl_crtd.");
ff2d7d92 2991 Ssl::CrtdMessage request_message(Ssl::CrtdMessage::REQUEST);
87f237a9
A
2992 request_message.setCode(Ssl::CrtdMessage::code_new_certificate);
2993 request_message.composeRequest(certProperties);
2994 debugs(33, 5, HERE << "SSL crtd request: " << request_message.compose().c_str());
2995 Ssl::Helper::GetInstance()->sslSubmit(request_message, sslCrtdHandleReplyWrapper, this);
2996 return;
2997 } catch (const std::exception &e) {
00fc192d
AR
2998 debugs(33, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtd " <<
2999 "request for " << certProperties.commonName <<
3000 " certificate: " << e.what() << "; will now block to " <<
3001 "generate that certificate.");
3002 // fall through to do blocking in-process generation.
3003 }
3004#endif // USE_SSL_CRTD
3005
aebe6888 3006 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName);
a9c2dd2f 3007 if (sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare)) {
d620ae0e 3008 doPeekAndSpliceStep();
33cc0629 3009 auto ssl = fd_table[clientConnection->fd].ssl.get();
d620ae0e 3010 if (!Ssl::configureSSL(ssl, certProperties, *port))
e4f14091 3011 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
d8f0ceab 3012
1c1fae0f 3013 Security::ContextPointer ctx(Security::GetFrom(fd_table[clientConnection->fd].ssl));
b23f5f9c 3014 Ssl::configureUnconfiguredSslContext(ctx, certProperties.signAlgorithm, *port);
d620ae0e 3015 } else {
0476ec45 3016 Security::ContextPointer dynCtx(Ssl::generateSslContext(certProperties, *port));
d620ae0e
CT
3017 getSslContextDone(dynCtx, true);
3018 }
1ce2822d 3019 return;
95d2589c 3020 }
0476ec45
AJ
3021
3022 Security::ContextPointer nil;
3023 getSslContextDone(nil);
95d2589c
CT
3024}
3025
1ce2822d 3026void
0476ec45 3027ConnStateData::getSslContextDone(Security::ContextPointer &ctx, bool isNew)
95d2589c
CT
3028{
3029 // Try to add generated ssl context to storage.
3030 if (port->generateHostCertificates && isNew) {
a594dbfa 3031
0476ec45 3032 if (ctx && (signAlgorithm == Ssl::algSignTrusted)) {
b23f5f9c 3033 Ssl::chainCertificatesToSSLContext(ctx, *port);
d8f0ceab
CT
3034 } else if (signAlgorithm == Ssl::algSignTrusted) {
3035 debugs(33, DBG_IMPORTANT, "WARNING: can not add signing certificate to SSL context chain because SSL context chain is invalid!");
a411d213 3036 }
aebe6888 3037 //else it is self-signed or untrusted do not attrach any certificate
a594dbfa 3038
9873e378 3039 Ssl::LocalContextStorage *ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s);
b38b26cb 3040 assert(sslBumpCertKey.size() > 0 && sslBumpCertKey[0] != '\0');
0476ec45
AJ
3041 if (ctx) {
3042 if (!ssl_ctx_cache || !ssl_ctx_cache->add(sslBumpCertKey.termedBuf(), new Security::ContextPointer(ctx))) {
95d2589c 3043 // If it is not in storage delete after using. Else storage deleted it.
0476ec45 3044 fd_table[clientConnection->fd].dynamicTlsContext = ctx;
95d2589c
CT
3045 }
3046 } else {
fb2178bb 3047 debugs(33, 2, HERE << "Failed to generate SSL cert for " << sslConnectHostOrIp);
95d2589c
CT
3048 }
3049 }
3050
3051 // If generated ssl context = NULL, try to use static ssl context.
0476ec45 3052 if (!ctx) {
80b5995a
AJ
3053 if (!port->secure.staticContext) {
3054 debugs(83, DBG_IMPORTANT, "Closing " << clientConnection->remote << " as lacking TLS context");
73c36fd9 3055 clientConnection->close();
1ce2822d 3056 return;
95d2589c 3057 } else {
80b5995a 3058 debugs(33, 5, "Using static TLS context.");
0476ec45 3059 ctx = port->secure.staticContext;
95d2589c
CT
3060 }
3061 }
ae7ff0b8 3062
0476ec45 3063 if (!httpsCreate(clientConnection, ctx))
1ce2822d 3064 return;
ae7ff0b8 3065
4e67d484
CT
3066 // bumped intercepted conns should already have Config.Timeout.request set
3067 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3068 // to make sure the connection does not get stuck on non-SSL clients.
3069 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3070 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
3899de60 3071 this, ConnStateData::requestTimeout);
4e67d484 3072 commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall);
ae7ff0b8 3073
ae7ff0b8 3074 switchedToHttps_ = true;
36698640
CT
3075
3076 auto ssl = fd_table[clientConnection->fd].ssl.get();
3077 BIO *b = SSL_get_rbio(ssl);
2a268a06 3078 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(BIO_get_data(b));
36698640
CT
3079 bio->setReadBufData(inBuf);
3080 inBuf.clear();
3081 clientNegotiateSSL(clientConnection->fd, this);
ae7ff0b8 3082}
3083
1ce2822d 3084void
caf3666d 3085ConnStateData::switchToHttps(HttpRequest *request, Ssl::BumpMode bumpServerMode)
95d2589c
CT
3086{
3087 assert(!switchedToHttps_);
3088
5c51bffb
AJ
3089 sslConnectHostOrIp = request->url.host();
3090 resetSslCommonName(request->url.host());
95d2589c 3091
83d4cd15
CT
3092 // We are going to read new request
3093 flags.readMore = true;
73c36fd9 3094 debugs(33, 5, HERE << "converting " << clientConnection << " to SSL");
95d2589c 3095
4599cded
AJ
3096 // keep version major.minor details the same.
3097 // but we are now performing the HTTPS handshake traffic
3098 transferProtocol.protocol = AnyP::PROTO_HTTPS;
3099
2bd84e5f
CT
3100 // If sslServerBump is set, then we have decided to deny CONNECT
3101 // and now want to switch to SSL to send the error to the client
3102 // without even peeking at the origin server certificate.
caf3666d 3103 if (bumpServerMode == Ssl::bumpServerFirst && !sslServerBump) {
e857372a 3104 request->flags.sslPeek = true;
65ba7f04 3105 sslServerBump = new Ssl::ServerBump(request);
e1f72a8b 3106 } else if (bumpServerMode == Ssl::bumpPeek || bumpServerMode == Ssl::bumpStare) {
d620ae0e 3107 request->flags.sslPeek = true;
5d65362c 3108 sslServerBump = new Ssl::ServerBump(request, NULL, bumpServerMode);
36698640 3109 }
3cae14a6 3110
36698640
CT
3111 // commSetConnTimeout() was called for this request before we switched.
3112 // Fix timeout to request_start_timeout
3113 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3114 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
fde0b2ca 3115 TimeoutDialer, this, ConnStateData::requestTimeout);
36698640
CT
3116 commSetConnTimeout(clientConnection, Config.Timeout.request_start_timeout, timeoutCall);
3117 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3118 // a bumbed "connect" request on non transparent port.
3119 receivedFirstByte_ = false;
3120 // Get more data to peek at Tls
d20cf186 3121 parsingTlsHandshake = true;
36698640
CT
3122 readSomeData();
3123}
3124
3125void
d20cf186 3126ConnStateData::parseTlsHandshake()
36698640 3127{
d20cf186
AR
3128 Must(parsingTlsHandshake);
3129
3130 assert(!inBuf.isEmpty());
36698640 3131 receivedFirstByte();
d20cf186
AR
3132 fd_note(clientConnection->fd, "Parsing TLS handshake");
3133
3134 bool unsupportedProtocol = false;
3135 try {
3136 if (!tlsParser.parseHello(inBuf)) {
3137 // need more data to finish parsing
3138 readSomeData();
3139 return;
3140 }
3141 }
3142 catch (const std::exception &ex) {
3143 debugs(83, 2, "error on FD " << clientConnection->fd << ": " << ex.what());
3144 unsupportedProtocol = true;
3145 }
36698640 3146
d20cf186 3147 parsingTlsHandshake = false;
36698640 3148
75f6c253
CT
3149 // client data may be needed for splicing and for
3150 // tunneling unsupportedProtocol after an error
3151 preservedClientData = inBuf;
6b2b6cfe 3152
d20cf186
AR
3153 // Even if the parser failed, each TLS detail should either be set
3154 // correctly or still be "unknown"; copying unknown detail is a no-op.
8d9e6d7f
CT
3155 Security::TlsDetails::Pointer const &details = tlsParser.details;
3156 clientConnection->tlsNegotiations()->retrieveParsedInfo(details);
3157 if (details && !details->serverName.isEmpty()) {
3158 resetSslCommonName(details->serverName.c_str());
3159 if (sslServerBump)
3160 sslServerBump->clientSni = details->serverName;
3161 }
36698640
CT
3162
3163 // We should disable read/write handlers
3164 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
3165 Comm::SetSelect(clientConnection->fd, COMM_SELECT_WRITE, NULL, NULL, 0);
3166
6b2b6cfe
CT
3167 if (unsupportedProtocol) {
3168 Http::StreamPointer context = pipeline.front();
3169 Must(context && context->http);
3170 HttpRequest::Pointer request = context->http->request;
3171 debugs(83, 5, "Got something other than TLS Client Hello. Cannot SslBump.");
3172 sslBumpMode = Ssl::bumpNone;
3173 if (!clientTunnelOnError(this, context, request, HttpRequestMethod(), ERR_PROTOCOL_UNKNOWN))
3174 clientConnection->close();
3175 return;
3176 }
3177
3178 if (!sslServerBump || sslServerBump->act.step1 == Ssl::bumpClientFirst) { // Either means client-first.
36698640 3179 getSslContextStart();
e1f72a8b 3180 return;
36698640
CT
3181 } else if (sslServerBump->act.step1 == Ssl::bumpServerFirst) {
3182 // will call httpsPeeked() with certificate and connection, eventually
3183 FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw());
3184 } else {
3185 Must(sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare);
6b2b6cfe 3186 startPeekAndSplice();
3248e962 3187 }
d620ae0e
CT
3188}
3189
5d65362c
CT
3190void httpsSslBumpStep2AccessCheckDone(allow_t answer, void *data)
3191{
3192 ConnStateData *connState = (ConnStateData *) data;
3193
3194 // if the connection is closed or closing, just return.
3195 if (!connState->isOpen())
3196 return;
3197
e4f14091 3198 debugs(33, 5, "Answer: " << answer << " kind:" << answer.kind);
a9c2dd2f
CT
3199 assert(connState->serverBump());
3200 Ssl::BumpMode bumpAction;
3201 if (answer == ACCESS_ALLOWED) {
640fe8fb 3202 bumpAction = (Ssl::BumpMode)answer.kind;
a9c2dd2f
CT
3203 } else
3204 bumpAction = Ssl::bumpSplice;
3205
3206 connState->serverBump()->act.step2 = bumpAction;
3207 connState->sslBumpMode = bumpAction;
3208
3209 if (bumpAction == Ssl::bumpTerminate) {
b54a7c5a 3210 connState->clientConnection->close();
a9c2dd2f 3211 } else if (bumpAction != Ssl::bumpSplice) {
6b2b6cfe 3212 connState->startPeekAndSplice();
efda53c5
CT
3213 } else if (!connState->splice())
3214 connState->clientConnection->close();
3248e962 3215}
5d65362c 3216
efda53c5 3217bool
3248e962
CT
3218ConnStateData::splice()
3219{
33cc0629 3220 // normally we can splice here, because we just got client hello message
2bcab852 3221
8abcff99 3222 if (fd_table[clientConnection->fd].ssl.get()) {
d9219c2b 3223 // Restore default read methods
3cae14a6
CT
3224 fd_table[clientConnection->fd].read_method = &default_read_method;
3225 fd_table[clientConnection->fd].write_method = &default_write_method;
3cae14a6 3226 }
3248e962 3227
6b2b6cfe
CT
3228 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3229 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3230 transferProtocol = Http::ProtocolVersion();
3231 assert(!pipeline.empty());
3232 Http::StreamPointer context = pipeline.front();
75f6c253
CT
3233 Must(context);
3234 Must(context->http);
6b2b6cfe 3235 ClientHttpRequest *http = context->http;
75f6c253
CT
3236 HttpRequest::Pointer request = http->request;
3237 context->finished();
3238 if (transparent()) {
3239 // For transparent connections, make a new fake CONNECT request, now
3240 // with SNI as target. doCallout() checks, adaptations may need that.
3241 return fakeAConnectRequest("splice", preservedClientData);
3242 } else {
3243 // For non transparent connections make a new tunneled CONNECT, which
3244 // also sets the HttpRequest::flags::forceTunnel flag to avoid
3245 // respond with "Connection Established" to the client.
3246 // This fake CONNECT request required to allow use of SNI in
3247 // doCallout() checks and adaptations.
3248 return initiateTunneledRequest(request, Http::METHOD_CONNECT, "splice", preservedClientData);
3249 }
5d65362c
CT
3250}
3251
d620ae0e 3252void
6b2b6cfe 3253ConnStateData::startPeekAndSplice()
d620ae0e 3254{
5d65362c
CT
3255 // This is the Step2 of the SSL bumping
3256 assert(sslServerBump);
d4ddb3e6 3257 Http::StreamPointer context = pipeline.front();
2f0d171f 3258 ClientHttpRequest *http = context ? context->http : nullptr;
d4ddb3e6 3259
5d65362c
CT
3260 if (sslServerBump->step == Ssl::bumpStep1) {
3261 sslServerBump->step = Ssl::bumpStep2;
3262 // Run a accessList check to check if want to splice or continue bumping
3263
2f0d171f
AJ
3264 ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, sslServerBump->request.getRaw(), nullptr);
3265 acl_checklist->al = http ? http->al : nullptr;
5d65362c
CT
3266 //acl_checklist->src_addr = params.conn->remote;
3267 //acl_checklist->my_addr = s->s;
640fe8fb
CT
3268 acl_checklist->banAction(allow_t(ACCESS_ALLOWED, Ssl::bumpNone));
3269 acl_checklist->banAction(allow_t(ACCESS_ALLOWED, Ssl::bumpClientFirst));
3270 acl_checklist->banAction(allow_t(ACCESS_ALLOWED, Ssl::bumpServerFirst));
5d65362c
CT
3271 acl_checklist->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone, this);
3272 return;
3273 }
3274
3cae14a6 3275 // will call httpsPeeked() with certificate and connection, eventually
0476ec45
AJ
3276 Security::ContextPointer unConfiguredCTX(Ssl::createSSLContext(port->signingCert, port->signPkey, *port));
3277 fd_table[clientConnection->fd].dynamicTlsContext = unConfiguredCTX;
3cae14a6
CT
3278
3279 if (!httpsCreate(clientConnection, unConfiguredCTX))
3280 return;
3281
3282 switchedToHttps_ = true;
3283
3284 auto ssl = fd_table[clientConnection->fd].ssl.get();
3285 BIO *b = SSL_get_rbio(ssl);
2a268a06 3286 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(BIO_get_data(b));
3cae14a6 3287 bio->setReadBufData(inBuf);
3cae14a6
CT
3288 bio->hold(true);
3289
fde0b2ca 3290 // Here squid should have all of the client hello message so the
3cae14a6
CT
3291 // Squid_SSL_accept should return 0;
3292 // This block exist only to force openSSL parse client hello and detect
3293 // ERR_SECURE_ACCEPT_FAIL error, which should be checked and splice if required.
3294 int ret = 0;
3295 if ((ret = Squid_SSL_accept(this, NULL)) < 0) {
3296 debugs(83, 2, "SSL_accept failed.");
2f0d171f 3297 HttpRequest::Pointer request(http ? http->request : nullptr);
6b2b6cfe 3298 if (!clientTunnelOnError(this, context, request, HttpRequestMethod(), ERR_SECURE_ACCEPT_FAIL))
3cae14a6
CT
3299 clientConnection->close();
3300 return;
3301 }
3302
56dacaca
CT
3303 // We need to reset inBuf here, to be used by incoming requests in the case
3304 // of SSL bump
8abcff99 3305 inBuf.clear();
3cae14a6
CT
3306
3307 debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! ");
d4ddb3e6 3308 FwdState::Start(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw(), http ? http->al : NULL);
d620ae0e
CT
3309}
3310
3311void
3312ConnStateData::doPeekAndSpliceStep()
3313{
33cc0629 3314 auto ssl = fd_table[clientConnection->fd].ssl.get();
d620ae0e
CT
3315 BIO *b = SSL_get_rbio(ssl);
3316 assert(b);
2a268a06 3317 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(BIO_get_data(b));
d620ae0e 3318
e4f14091 3319 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl));
d620ae0e
CT
3320 bio->hold(false);
3321
3322 Comm::SetSelect(clientConnection->fd, COMM_SELECT_WRITE, clientNegotiateSSL, this, 0);
3323 switchedToHttps_ = true;
3324}
3325
d7ce0bcd
AR
3326void
3327ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection)
3328{
fd4624d7 3329 Must(sslServerBump != NULL);
819c207f 3330
061bbdec 3331 if (Comm::IsConnOpen(serverConnection)) {
061bbdec
CT
3332 pinConnection(serverConnection, NULL, NULL, false);
3333
fb2178bb 3334 debugs(33, 5, HERE << "bumped HTTPS server: " << sslConnectHostOrIp);
59a49556 3335 } else {
13858f50 3336 debugs(33, 5, HERE << "Error while bumping: " << sslConnectHostOrIp);
129fe2a1
CT
3337
3338 // copy error detail from bump-server-first request to CONNECT request
baa6929f
AJ
3339 if (!pipeline.empty() && pipeline.front()->http != nullptr && pipeline.front()->http->request)
3340 pipeline.front()->http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
59a49556 3341 }
061bbdec 3342
1ce2822d 3343 getSslContextStart();
95d2589c
CT
3344}
3345
cb4f4424 3346#endif /* USE_OPENSSL */
1f7c9178 3347
efda53c5 3348bool
6b2b6cfe 3349ConnStateData::initiateTunneledRequest(HttpRequest::Pointer const &cause, Http::MethodType const method, const char *reason, const SBuf &payload)
0bd3c2a3
AJ
3350{
3351 // fake a CONNECT request to force connState to tunnel
e88bdb0e 3352 SBuf connectHost;
6b2b6cfe
CT
3353 unsigned short connectPort = 0;
3354
3355 if (pinning.serverConnection != nullptr) {
3356 static char ip[MAX_IPSTRLEN];
e9b219a0
TA
3357 pinning.serverConnection->remote.toHostStr(ip, sizeof(ip));
3358 connectHost.assign(ip);
6b2b6cfe
CT
3359 connectPort = pinning.serverConnection->remote.port();
3360 } else if (cause && cause->method == Http::METHOD_CONNECT) {
3361 // We are inside a (not fully established) CONNECT request
3362 connectHost = cause->url.host();
3363 connectPort = cause->url.port();
3364 } else {
3365 debugs(33, 2, "Not able to compute URL, abort request tunneling for " << reason);
3366 return false;
3367 }
3368
3369 debugs(33, 2, "Request tunneling for " << reason);
3370 ClientHttpRequest *http = buildFakeRequest(method, connectHost, connectPort, payload);
3371 HttpRequest::Pointer request = http->request;
3372 request->flags.forceTunnel = true;
3373 http->calloutContext = new ClientRequestContext(http);
3374 http->doCallouts();
3375 clientProcessRequestFinished(this, request);
3376 return true;
3377}
3378
3379bool
3380ConnStateData::fakeAConnectRequest(const char *reason, const SBuf &payload)
3381{
3382 debugs(33, 2, "fake a CONNECT request to force connState to tunnel for " << reason);
3383
3384 SBuf connectHost;
3385 assert(transparent());
3386 const unsigned short connectPort = clientConnection->local.port();
3387
65e0c910 3388#if USE_OPENSSL
6b2b6cfe 3389 if (serverBump() && !serverBump()->clientSni.isEmpty())
e88bdb0e 3390 connectHost.assign(serverBump()->clientSni);
6b2b6cfe 3391 else
65e0c910
CT
3392#endif
3393 {
e88bdb0e 3394 static char ip[MAX_IPSTRLEN];
e9b219a0
TA
3395 clientConnection->local.toHostStr(ip, sizeof(ip));
3396 connectHost.assign(ip);
0bd3c2a3 3397 }
6b2b6cfe
CT
3398
3399 ClientHttpRequest *http = buildFakeRequest(Http::METHOD_CONNECT, connectHost, connectPort, payload);
3400
3401 http->calloutContext = new ClientRequestContext(http);
3402 HttpRequest::Pointer request = http->request;
3403 http->doCallouts();
3404 clientProcessRequestFinished(this, request);
efda53c5 3405 return true;
0bd3c2a3
AJ
3406}
3407
6b2b6cfe
CT
3408ClientHttpRequest *
3409ConnStateData::buildFakeRequest(Http::MethodType const method, SBuf &useHost, unsigned short usePort, const SBuf &payload)
3410{
3411 ClientHttpRequest *http = new ClientHttpRequest(this);
3412 Http::Stream *stream = new Http::Stream(clientConnection, http);
3413
3414 StoreIOBuffer tempBuffer;
3415 tempBuffer.data = stream->reqbuf;
3416 tempBuffer.length = HTTP_REQBUF_SZ;
3417
3418 ClientStreamData newServer = new clientReplyContext(http);
3419 ClientStreamData newClient = stream;
3420 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
3421 clientReplyStatus, newServer, clientSocketRecipient,
3422 clientSocketDetach, newClient, tempBuffer);
3423
3424 http->uri = SBufToCstring(useHost);
3425 stream->flags.parsed_ok = 1; // Do we need it?
3426 stream->mayUseConnection(true);
aff439e0 3427
6b2b6cfe 3428 AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout",
aff439e0 3429 CommTimeoutCbPtrFun(clientLifetimeTimeout, stream->http));
6b2b6cfe
CT
3430 commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall);
3431
3432 stream->registerWithConn();
3433
3434 // Setup Http::Request object. Maybe should be replaced by a call to (modified)
3435 // clientProcessRequest
3436 HttpRequest::Pointer request = new HttpRequest();
3437 AnyP::ProtocolType proto = (method == Http::METHOD_NONE) ? AnyP::PROTO_AUTHORITY_FORM : AnyP::PROTO_HTTP;
3438 request->url.setScheme(proto, nullptr);
3439 request->method = method;
3440 request->url.host(useHost.c_str());
3441 request->url.port(usePort);
3442 http->request = request.getRaw();
3443 HTTPMSGLOCK(http->request);
3444
3445 request->clientConnectionManager = this;
3446
3447 if (proto == AnyP::PROTO_HTTP)
3448 request->header.putStr(Http::HOST, useHost.c_str());
3449 request->flags.intercepted = ((clientConnection->flags & COMM_INTERCEPTION) != 0);
3450 request->flags.interceptTproxy = ((clientConnection->flags & COMM_TRANSPARENT) != 0 );
63df1d28 3451 request->sources |= ((switchedToHttps() || port->transport.protocol == AnyP::PROTO_HTTPS) ? Http::Message::srcHttps : Http::Message::srcHttp);
6b2b6cfe
CT
3452#if USE_AUTH
3453 if (getAuth())
3454 request->auth_user_request = getAuth();
3455#endif
3456 request->client_addr = clientConnection->remote;
3457#if FOLLOW_X_FORWARDED_FOR
3458 request->indirect_client_addr = clientConnection->remote;
3459#endif /* FOLLOW_X_FORWARDED_FOR */
3460 request->my_addr = clientConnection->local;
3461 request->myportname = port->name;
3462
3463 inBuf = payload;
3464 flags.readMore = false;
3465
3466 setLogUri(http, urlCanonicalClean(request.getRaw()));
3467 return http;
3468}
3469
00516be1
AR
3470/// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3471static bool
73c36fd9 3472OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType)
00516be1 3473{
73c36fd9 3474 if (!Comm::IsConnOpen(c)) {
00516be1
AR
3475 Must(NHttpSockets > 0); // we tried to open some
3476 --NHttpSockets; // there will be fewer sockets than planned
3477 Must(HttpSockets[NHttpSockets] < 0); // no extra fds received
3478
3479 if (!NHttpSockets) // we could not open any listen sockets at all
cbff89ba 3480 fatalf("Unable to open %s",FdNote(portType));
00516be1
AR
3481
3482 return false;
3483 }
3484 return true;
3485}
3486
3487/// find any unused HttpSockets[] slot and store fd there or return false
3488static bool
e0d28505 3489AddOpenedHttpSocket(const Comm::ConnectionPointer &conn)
00516be1
AR
3490{
3491 bool found = false;
95dc7ff4 3492 for (int i = 0; i < NHttpSockets && !found; ++i) {
00516be1 3493 if ((found = HttpSockets[i] < 0))
e0d28505 3494 HttpSockets[i] = conn->fd;
00516be1
AR
3495 }
3496 return found;
3497}
15df8349 3498
d193a436 3499static void
15df8349 3500clientHttpConnectionsOpen(void)
3501{
fa720bfb 3502 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
d31d59d8 3503 const SBuf &scheme = AnyP::UriScheme(s->transport.protocol).image();
339e4d7a 3504
65d448bc 3505 if (MAXTCPLISTENPORTS == NHttpSockets) {
339e4d7a 3506 debugs(1, DBG_IMPORTANT, "WARNING: You have too many '" << scheme << "_port' lines.");
e0236918 3507 debugs(1, DBG_IMPORTANT, " The limit is " << MAXTCPLISTENPORTS << " HTTP ports.");
62e76326 3508 continue;
3509 }
3510
cb4f4424 3511#if USE_OPENSSL
6a25a046 3512 if (s->flags.tunnelSslBumping) {
339e4d7a
AJ
3513 if (!Config.accessList.ssl_bump) {
3514 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme << "_port " << s->s);
3515 s->flags.tunnelSslBumping = false;
3516 }
80b5995a 3517 if (!s->secure.staticContext && !s->generateHostCertificates) {
339e4d7a
AJ
3518 debugs(1, DBG_IMPORTANT, "Will not bump SSL at " << scheme << "_port " << s->s << " due to TLS initialization failure.");
3519 s->flags.tunnelSslBumping = false;
3520 if (s->transport.protocol == AnyP::PROTO_HTTP)
3521 s->secure.encryptTransport = false;
3522 }
3523 if (s->flags.tunnelSslBumping) {
3524 // Create ssl_ctx cache for this port.
3525 auto sz = s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize;
3526 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, sz);
3527 }
95d2589c 3528 }
ae7ff0b8 3529
80b5995a 3530 if (s->secure.encryptTransport && !s->secure.staticContext) {
339e4d7a
AJ
3531 debugs(1, DBG_CRITICAL, "ERROR: Ignoring " << scheme << "_port " << s->s << " due to TLS context initialization failure.");
3532 continue;
3533 }
188c0e31 3534#endif
339e4d7a 3535
e0d28505 3536 // Fill out a Comm::Connection which IPC will open as a listener for us
8bbb16e3 3537 // then pass back when active so we can start a TcpAcceptor subscription.
e0d28505
AJ
3538 s->listenConn = new Comm::Connection;
3539 s->listenConn->local = s->s;
c303f6e3 3540
339e4d7a
AJ
3541 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
3542 (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
62e76326 3543
339e4d7a
AJ
3544 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
3545 if (s->transport.protocol == AnyP::PROTO_HTTP) {
3546 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3547 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, CommAcceptCbParams(NULL)));
3548 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 3549
339e4d7a
AJ
3550 AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened",
3551 ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub));
3552 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall);
d193a436 3553
cb4f4424 3554#if USE_OPENSSL
339e4d7a
AJ
3555 } else if (s->transport.protocol == AnyP::PROTO_HTTPS) {
3556 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3557 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, CommAcceptCbParams(NULL)));
3558 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
3559
3560 AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened",
3561 ListeningStartedDialer(&clientListenerConnectionOpened,
3562 s, Ipc::fdnHttpsSocket, sub));
3563 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall);
3564#endif
d7ce0bcd
AR
3565 }
3566
339e4d7a 3567 HttpSockets[NHttpSockets] = -1; // set in clientListenerConnectionOpened
a38ec4b1 3568 ++NHttpSockets;
cbff89ba 3569 }
d193a436 3570}
d193a436 3571
92ae4c86 3572void
27c841f6
AR
3573clientStartListeningOn(AnyP::PortCfgPointer &port, const RefCount< CommCbFunPtrCallT<CommAcceptCbPtrFun> > &subCall, const Ipc::FdNoteId fdNote)
3574{
92ae4c86
AR
3575 // Fill out a Comm::Connection which IPC will open as a listener for us
3576 port->listenConn = new Comm::Connection;
3577 port->listenConn->local = port->s;
e7ce227f
AR
3578 port->listenConn->flags =
3579 COMM_NONBLOCKING |
3580 (port->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
3581 (port->flags.natIntercept ? COMM_INTERCEPTION : 0);
92ae4c86
AR
3582
3583 // route new connections to subCall
3584 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
3585 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
e7ce227f
AR
3586 AsyncCall::Pointer listenCall =
3587 asyncCall(33, 2, "clientListenerConnectionOpened",
3588 ListeningStartedDialer(&clientListenerConnectionOpened,
3589 port, fdNote, sub));
92ae4c86 3590 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, port->listenConn, fdNote, listenCall);
434a79b0 3591
92ae4c86
AR
3592 assert(NHttpSockets < MAXTCPLISTENPORTS);
3593 HttpSockets[NHttpSockets] = -1;
3594 ++NHttpSockets;
434a79b0
DK
3595}
3596
e0d28505 3597/// process clientHttpConnectionsOpen result
00516be1 3598static void
fa720bfb 3599clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub)
00516be1 3600{
fa720bfb
AJ
3601 Must(s != NULL);
3602
8bbb16e3 3603 if (!OpenedHttpSocket(s->listenConn, portTypeNote))
00516be1 3604 return;
62e76326 3605
e0d28505 3606 Must(Comm::IsConnOpen(s->listenConn));
62e76326 3607
8bbb16e3 3608 // TCP: setup a job to handle accept() with subscribed handler
fa720bfb 3609 AsyncJob::Start(new Comm::TcpAcceptor(s, FdNote(portTypeNote), sub));
8bbb16e3 3610
e0236918 3611 debugs(1, DBG_IMPORTANT, "Accepting " <<
6a25a046 3612 (s->flags.natIntercept ? "NAT intercepted " : "") <<
0d901ef4 3613 (s->flags.tproxyIntercept ? "TPROXY intercepted " : "") <<
6a25a046
FC
3614 (s->flags.tunnelSslBumping ? "SSL bumped " : "") <<
3615 (s->flags.accelSurrogate ? "reverse-proxy " : "")
8bbb16e3
AJ
3616 << FdNote(portTypeNote) << " connections at "
3617 << s->listenConn);
62e76326 3618
e0d28505 3619 Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for
d193a436 3620}
3621
d193a436 3622void
3623clientOpenListenSockets(void)
3624{
3625 clientHttpConnectionsOpen();
92ae4c86 3626 Ftp::StartListening();
62e76326 3627
15df8349 3628 if (NHttpSockets < 1)
e7ce227f 3629 fatal("No HTTP, HTTPS, or FTP ports configured");
15df8349 3630}
edce4d98 3631
c0fbae16 3632void
e7ce227f 3633clientConnectionsClose()
c0fbae16 3634{
fa720bfb 3635 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
00406b24 3636 if (s->listenConn != NULL) {
339e4d7a 3637 debugs(1, DBG_IMPORTANT, "Closing HTTP(S) port " << s->listenConn->local);
00406b24
AJ
3638 s->listenConn->close();
3639 s->listenConn = NULL;
04f55905
AJ
3640 }
3641 }
62e76326 3642
92ae4c86 3643 Ftp::StopListening();
434a79b0 3644
04f55905 3645 // TODO see if we can drop HttpSockets array entirely */
95dc7ff4 3646 for (int i = 0; i < NHttpSockets; ++i) {
04f55905
AJ
3647 HttpSockets[i] = -1;
3648 }
62e76326 3649
c0fbae16 3650 NHttpSockets = 0;
3651}
f66a9ef4 3652
3653int
190154cf 3654varyEvaluateMatch(StoreEntry * entry, HttpRequest * request)
f66a9ef4 3655{
90ab8f20 3656 SBuf vary(request->vary_headers);
789217a2 3657 int has_vary = entry->getReply()->header.has(Http::HdrType::VARY);
f66a9ef4 3658#if X_ACCELERATOR_VARY
62e76326 3659
edce4d98 3660 has_vary |=
789217a2 3661 entry->getReply()->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY);
f66a9ef4 3662#endif
62e76326 3663
90ab8f20
AJ
3664 if (!has_vary || entry->mem_obj->vary_headers.isEmpty()) {
3665 if (!vary.isEmpty()) {
62e76326 3666 /* Oops... something odd is going on here.. */
e0236918 3667 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
c877c0bc 3668 entry->mem_obj->urlXXX() << "' '" << vary << "'");
90ab8f20 3669 request->vary_headers.clear();
62e76326 3670 return VARY_CANCEL;
3671 }
3672
3673 if (!has_vary) {
3674 /* This is not a varying object */
3675 return VARY_NONE;
3676 }
3677
3678 /* virtual "vary" object found. Calculate the vary key and
3679 * continue the search
3680 */
3681 vary = httpMakeVaryMark(request, entry->getReply());
3682
90ab8f20
AJ
3683 if (!vary.isEmpty()) {
3684 request->vary_headers = vary;
62e76326 3685 return VARY_OTHER;
3686 } else {
3687 /* Ouch.. we cannot handle this kind of variance */
3688 /* XXX This cannot really happen, but just to be complete */
3689 return VARY_CANCEL;
3690 }
f66a9ef4 3691 } else {
90ab8f20 3692 if (vary.isEmpty()) {
62e76326 3693 vary = httpMakeVaryMark(request, entry->getReply());
3694
90ab8f20
AJ
3695 if (!vary.isEmpty())
3696 request->vary_headers = vary;
62e76326 3697 }
3698
90ab8f20 3699 if (vary.isEmpty()) {
62e76326 3700 /* Ouch.. we cannot handle this kind of variance */
3701 /* XXX This cannot really happen, but just to be complete */
3702 return VARY_CANCEL;
90ab8f20 3703 } else if (vary.cmp(entry->mem_obj->vary_headers) == 0) {
62e76326 3704 return VARY_MATCH;
3705 } else {
3706 /* Oops.. we have already been here and still haven't
3707 * found the requested variant. Bail out
3708 */
e0236918 3709 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
c877c0bc 3710 entry->mem_obj->urlXXX() << "' '" << vary << "'");
62e76326 3711 return VARY_CANCEL;
3712 }
f66a9ef4 3713 }
3714}
28d4805a 3715
c0941a6a 3716ACLFilledChecklist *
59a1efb2 3717clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http)
28d4805a 3718{
1cf238db 3719 ConnStateData * conn = http->getConn();
c0941a6a 3720 ACLFilledChecklist *ch = new ACLFilledChecklist(acl, http->request,
73c36fd9 3721 cbdataReferenceValid(conn) && conn != NULL && conn->clientConnection != NULL ? conn->clientConnection->rfc931 : dash_str);
d4806c91 3722 ch->al = http->al;
28d4805a 3723 /*
3724 * hack for ident ACL. It needs to get full addresses, and a place to store
3725 * the ident result on persistent connections...
3726 */
3727 /* connection oriented auth also needs these two lines for it's operation. */
28d4805a 3728 return ch;
3729}
a46d2c0e 3730
a46d2c0e 3731bool
3732ConnStateData::transparent() const
3733{
40d34a62 3734 return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION));
a46d2c0e 3735}
3736
5f8252d2 3737BodyPipe::Pointer
3e62bd58 3738ConnStateData::expectRequestBody(int64_t size)
5f8252d2 3739{
3740 bodyPipe = new BodyPipe(this);
39cb8c41
AR
3741 if (size >= 0)
3742 bodyPipe->setBodySize(size);
3743 else
3744 startDechunkingRequest();
5f8252d2 3745 return bodyPipe;
3746}
3747
39cb8c41
AR
3748int64_t
3749ConnStateData::mayNeedToReadMoreBody() const
3750{
3751 if (!bodyPipe)
3752 return 0; // request without a body or read/produced all body bytes
3753
3754 if (!bodyPipe->bodySizeKnown())
3755 return -1; // probably need to read more, but we cannot be sure
3756
3757 const int64_t needToProduce = bodyPipe->unproducedSize();
fcc444e3 3758 const int64_t haveAvailable = static_cast<int64_t>(inBuf.length());
39cb8c41
AR
3759
3760 if (needToProduce <= haveAvailable)
3761 return 0; // we have read what we need (but are waiting for pipe space)
3762
3763 return needToProduce - haveAvailable;
3764}
3765
55e44db9 3766void
cf6eb29e 3767ConnStateData::stopReceiving(const char *error)
55e44db9 3768{
cf6eb29e
CT
3769 debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error <<
3770 "; old sending error: " <<
3771 (stoppedSending() ? stoppedSending_ : "none"));
5f8252d2 3772
cf6eb29e
CT
3773 if (const char *oldError = stoppedReceiving()) {
3774 debugs(33, 3, HERE << "already stopped receiving: " << oldError);
3775 return; // nothing has changed as far as this connection is concerned
3776 }
5f8252d2 3777
cf6eb29e 3778 stoppedReceiving_ = error;
5f8252d2 3779
cf6eb29e
CT
3780 if (const char *sendError = stoppedSending()) {
3781 debugs(33, 3, HERE << "closing because also stopped sending: " << sendError);
3782 clientConnection->close();
3783 }
55e44db9 3784}
3785
eb44b2d7 3786void
e29ccb57
A
3787ConnStateData::expectNoForwarding()
3788{
eb44b2d7
CT
3789 if (bodyPipe != NULL) {
3790 debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status());
3791 bodyPipe->expectNoConsumption();
3792 }
3793}
3794
39cb8c41 3795/// initialize dechunking state
3ff65596 3796void
39cb8c41 3797ConnStateData::startDechunkingRequest()
3ff65596 3798{
39cb8c41
AR
3799 Must(bodyPipe != NULL);
3800 debugs(33, 5, HERE << "start dechunking" << bodyPipe->status());
fcc444e3
AJ
3801 assert(!bodyParser);
3802 bodyParser = new Http1::TeChunkedParser;
3ff65596
AR
3803}
3804
39cb8c41 3805/// put parsed content into input buffer and clean up
3ff65596 3806void
39cb8c41 3807ConnStateData::finishDechunkingRequest(bool withSuccess)
3ff65596 3808{
39cb8c41 3809 debugs(33, 5, HERE << "finish dechunking: " << withSuccess);
3ff65596 3810
39cb8c41
AR
3811 if (bodyPipe != NULL) {
3812 debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status());
3813 BodyPipe::Pointer myPipe = bodyPipe;
3814 stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize()
3815 Must(!bodyPipe); // we rely on it being nil after we are done with body
3816 if (withSuccess) {
3817 Must(myPipe->bodySizeKnown());
d3dddfb5 3818 Http::StreamPointer context = pipeline.front();
39cb8c41
AR
3819 if (context != NULL && context->http && context->http->request)
3820 context->http->request->setContentLength(myPipe->bodySize());
3821 }
3ff65596 3822 }
3ff65596 3823
fcc444e3
AJ
3824 delete bodyParser;
3825 bodyParser = NULL;
a46d2c0e 3826}
d67acb4e 3827
139a1d68 3828// XXX: this is an HTTP/1-only operation
655daa06
AR
3829void
3830ConnStateData::sendControlMsg(HttpControlMsg msg)
3831{
eedd4182
AR
3832 if (!isOpen()) {
3833 debugs(33, 3, HERE << "ignoring 1xx due to earlier closure");
655daa06
AR
3834 return;
3835 }
3836
84540b47 3837 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
139a1d68 3838 if (!pipeline.empty()) {
84540b47
AJ
3839 HttpReply::Pointer rep(msg.reply);
3840 Must(rep);
3841 // remember the callback
3842 cbControlMsgSent = msg.cbSuccess;
3843
3844 typedef CommCbMemFunT<HttpControlMsgSink, CommIoCbParams> Dialer;
3845 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, HttpControlMsgSink::wroteControlMsg);
3846
2f97ab10
CT
3847 if (!writeControlMsgAndCall(rep.getRaw(), call)) {
3848 // but still inform the caller (so it may resume its operation)
3849 doneWithControlMsg();
3850 }
655daa06
AR
3851 return;
3852 }
3853
3854 debugs(33, 3, HERE << " closing due to missing context for 1xx");
73c36fd9 3855 clientConnection->close();
655daa06
AR
3856}
3857
24e1fd72 3858void
2f97ab10 3859ConnStateData::doneWithControlMsg()
24e1fd72 3860{
2f97ab10 3861 HttpControlMsgSink::doneWithControlMsg();
24e1fd72
CT
3862
3863 if (Http::StreamPointer deferredRequest = pipeline.front()) {
3864 debugs(33, 3, clientConnection << ": calling PushDeferredIfNeeded after control msg wrote");
3865 ClientSocketContextPushDeferredIfNeeded(deferredRequest, this);
3866 }
3867}
3868
d7ce0bcd 3869/// Our close handler called by Comm when the pinned connection is closed
d67acb4e
AJ
3870void
3871ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io)
3872{
7a957a93
AR
3873 // FwdState might repin a failed connection sooner than this close
3874 // callback is called for the failed connection.
693cb033
CT
3875 assert(pinning.serverConnection == io.conn);
3876 pinning.closeHandler = NULL; // Comm unregisters handlers before calling
3877 const bool sawZeroReply = pinning.zeroReply; // reset when unpinning
b54a7c5a 3878 pinning.serverConnection->noteClosure();
89b1d7a2 3879 unpinConnection(false);
f8e4867b 3880
7ac40923 3881 if (sawZeroReply && clientConnection != NULL) {
693cb033
CT
3882 debugs(33, 3, "Closing client connection on pinned zero reply.");
3883 clientConnection->close();
85563fd9 3884 }
f8e4867b 3885
d67acb4e
AJ
3886}
3887
b1cf2350 3888void
f8e4867b 3889ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth, bool monitor)
9e008dda 3890{
e7ce227f 3891 if (!Comm::IsConnOpen(pinning.serverConnection) ||
27c841f6 3892 pinning.serverConnection->fd != pinServer->fd)
89b1d7a2 3893 pinNewConnection(pinServer, request, aPeer, auth);
d67acb4e 3894
f8e4867b
AR
3895 if (monitor)
3896 startPinnedConnectionMonitoring();
89b1d7a2 3897}
9e008dda 3898
89b1d7a2
AR
3899void
3900ConnStateData::pinNewConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth)
3901{
3902 unpinConnection(true); // closes pinned connection, if any, and resets fields
9e008dda 3903
73c36fd9 3904 pinning.serverConnection = pinServer;
d7ce0bcd 3905
85563fd9
AR
3906 debugs(33, 3, HERE << pinning.serverConnection);
3907
89b1d7a2
AR
3908 Must(pinning.serverConnection != NULL);
3909
d7ce0bcd
AR
3910 // when pinning an SSL bumped connection, the request may be NULL
3911 const char *pinnedHost = "[unknown]";
3912 if (request) {
5c51bffb
AJ
3913 pinning.host = xstrdup(request->url.host());
3914 pinning.port = request->url.port();
d7ce0bcd
AR
3915 pinnedHost = pinning.host;
3916 } else {
4dd643d5 3917 pinning.port = pinServer->remote.port();
d7ce0bcd 3918 }
d67acb4e 3919 pinning.pinned = true;
8bcf08e0
FC
3920 if (aPeer)
3921 pinning.peer = cbdataReference(aPeer);
d67acb4e 3922 pinning.auth = auth;
e3a4aecc 3923 char stmp[MAX_IPSTRLEN];
89b1d7a2 3924 char desc[FD_DESC_SZ];
e3a4aecc 3925 snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)",
d7ce0bcd 3926 (auth || !aPeer) ? pinnedHost : aPeer->name,
4dd643d5 3927 clientConnection->remote.toUrl(stmp,MAX_IPSTRLEN),
d7ce0bcd 3928 clientConnection->fd);
73c36fd9 3929 fd_note(pinning.serverConnection->fd, desc);
9e008dda 3930
d67acb4e 3931 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
4299f876 3932 pinning.closeHandler = JobCallback(33, 5,
4cb2536f 3933 Dialer, this, ConnStateData::clientPinnedConnectionClosed);
85563fd9
AR
3934 // remember the pinned connection so that cb does not unpin a fresher one
3935 typedef CommCloseCbParams Params;
3936 Params &params = GetCommParams<Params>(pinning.closeHandler);
3937 params.conn = pinning.serverConnection;
73c36fd9 3938 comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
7ac40923
AR
3939}
3940
e7ce227f
AR
3941/// [re]start monitoring pinned connection for peer closures so that we can
3942/// propagate them to an _idle_ client pinned to that peer
7ac40923
AR
3943void
3944ConnStateData::startPinnedConnectionMonitoring()
3945{
3946 if (pinning.readHandler != NULL)
3947 return; // already monitoring
3948
3949 typedef CommCbMemFunT<ConnStateData, CommIoCbParams> Dialer;
3950 pinning.readHandler = JobCallback(33, 3,
3951 Dialer, this, ConnStateData::clientPinnedConnectionRead);
7e66d5e2 3952 Comm::Read(pinning.serverConnection, pinning.readHandler);
7ac40923
AR
3953}
3954
3955void
3956ConnStateData::stopPinnedConnectionMonitoring()
3957{
3958 if (pinning.readHandler != NULL) {
7e66d5e2 3959 Comm::ReadCancel(pinning.serverConnection->fd, pinning.readHandler);
7ac40923
AR
3960 pinning.readHandler = NULL;
3961 }
3962}
3963
96aedee5
CT
3964#if USE_OPENSSL
3965bool
3966ConnStateData::handleIdleClientPinnedTlsRead()
3967{
3968 // A ready-for-reading connection means that the TLS server either closed
3969 // the connection, sent us some unexpected HTTP data, or started TLS
3970 // renegotiations. We should close the connection except for the last case.
3971
3972 Must(pinning.serverConnection != nullptr);
33cc0629 3973 auto ssl = fd_table[pinning.serverConnection->fd].ssl.get();
96aedee5
CT
3974 if (!ssl)
3975 return false;
3976
3977 char buf[1];
3978 const int readResult = SSL_read(ssl, buf, sizeof(buf));
3979
3980 if (readResult > 0 || SSL_pending(ssl) > 0) {
3981 debugs(83, 2, pinning.serverConnection << " TLS application data read");
3982 return false;
3983 }
3984
3985 switch(const int error = SSL_get_error(ssl, readResult)) {
3986 case SSL_ERROR_WANT_WRITE:
3987 debugs(83, DBG_IMPORTANT, pinning.serverConnection << " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
737ace5a 3988 // fall through to restart monitoring, for now
96aedee5
CT
3989 case SSL_ERROR_NONE:
3990 case SSL_ERROR_WANT_READ:
3991 startPinnedConnectionMonitoring();
3992 return true;
3993
3994 default:
3995 debugs(83, 2, pinning.serverConnection << " TLS error: " << error);
3996 return false;
3997 }
3998
3999 // not reached
4000 return true;
4001}
4002#endif
4003
7ac40923
AR
4004/// Our read handler called by Comm when the server either closes an idle pinned connection or
4005/// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4006void
4007ConnStateData::clientPinnedConnectionRead(const CommIoCbParams &io)
4008{
4009 pinning.readHandler = NULL; // Comm unregisters handlers before calling
4010
c8407295 4011 if (io.flag == Comm::ERR_CLOSING)
7ac40923
AR
4012 return; // close handler will clean up
4013
96aedee5
CT
4014 Must(pinning.serverConnection == io.conn);
4015
4016#if USE_OPENSSL
4017 if (handleIdleClientPinnedTlsRead())
4018 return;
4019#endif
4020
e500cc89 4021 const bool clientIsIdle = pipeline.empty();
7ac40923
AR
4022
4023 debugs(33, 3, "idle pinned " << pinning.serverConnection << " read " <<
4024 io.size << (clientIsIdle ? " with idle client" : ""));
4025
7ac40923
AR
4026 pinning.serverConnection->close();
4027
4028 // If we are still sending data to the client, do not close now. When we are done sending,
4a4fbcef 4029 // ConnStateData::kick() checks pinning.serverConnection and will close.
7ac40923
AR
4030 // However, if we are idle, then we must close to inform the idle client and minimize races.
4031 if (clientIsIdle && clientConnection != NULL)
4032 clientConnection->close();
d67acb4e
AJ
4033}
4034
e3a4aecc 4035const Comm::ConnectionPointer
a3c6762c 4036ConnStateData::validatePinnedConnection(HttpRequest *request, const CachePeer *aPeer)
d67acb4e 4037{
85563fd9
AR
4038 debugs(33, 7, HERE << pinning.serverConnection);
4039
d67acb4e 4040 bool valid = true;
73c36fd9 4041 if (!Comm::IsConnOpen(pinning.serverConnection))
e3a4aecc 4042 valid = false;
5c51bffb 4043 else if (pinning.auth && pinning.host && request && strcasecmp(pinning.host, request->url.host()) != 0)
9e008dda 4044 valid = false;
5c51bffb 4045 else if (request && pinning.port != request->url.port())
9e008dda 4046 valid = false;
6de3828e 4047 else if (pinning.peer && !cbdataReferenceValid(pinning.peer))
9e008dda 4048 valid = false;
6de3828e 4049 else if (aPeer != pinning.peer)
9e008dda 4050 valid = false;
d67acb4e 4051
9e008dda 4052 if (!valid) {
b1cf2350 4053 /* The pinning info is not safe, remove any pinning info */
89b1d7a2 4054 unpinConnection(true);
d67acb4e
AJ
4055 }
4056
73c36fd9 4057 return pinning.serverConnection;
d67acb4e
AJ
4058}
4059
89b1d7a2
AR
4060Comm::ConnectionPointer
4061ConnStateData::borrowPinnedConnection(HttpRequest *request, const CachePeer *aPeer)
4062{
4063 debugs(33, 7, pinning.serverConnection);
4064 if (validatePinnedConnection(request, aPeer) != NULL)
f8e4867b 4065 stopPinnedConnectionMonitoring();
89b1d7a2
AR
4066
4067 return pinning.serverConnection; // closed if validation failed
4068}
4069
b1cf2350 4070void
89b1d7a2 4071ConnStateData::unpinConnection(const bool andClose)
d67acb4e 4072{
85563fd9
AR
4073 debugs(33, 3, HERE << pinning.serverConnection);
4074
9e008dda
AJ
4075 if (pinning.peer)
4076 cbdataReferenceDone(pinning.peer);
d67acb4e 4077
d7ce0bcd 4078 if (Comm::IsConnOpen(pinning.serverConnection)) {
87f237a9
A
4079 if (pinning.closeHandler != NULL) {
4080 comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
4081 pinning.closeHandler = NULL;
4082 }
89b1d7a2 4083
f8e4867b 4084 stopPinnedConnectionMonitoring();
89b1d7a2
AR
4085
4086 // close the server side socket if requested
4087 if (andClose)
4088 pinning.serverConnection->close();
4089 pinning.serverConnection = NULL;
d67acb4e 4090 }
d7ce0bcd 4091
d67acb4e 4092 safe_free(pinning.host);
e3a4aecc 4093
693cb033
CT
4094 pinning.zeroReply = false;
4095
e3a4aecc
AJ
4096 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4097 * connection has gone away */
d67acb4e 4098}
44352c16 4099
da6dbcd1
EB
4100void
4101ConnStateData::checkLogging()
4102{
4103 // if we are parsing request body, its request is responsible for logging
4104 if (bodyPipe)
4105 return;
4106
4107 // a request currently using this connection is responsible for logging
4108 if (!pipeline.empty() && pipeline.back()->mayUseConnection())
4109 return;
4110
4111 /* Either we are waiting for the very first transaction, or
4112 * we are done with the Nth transaction and are waiting for N+1st.
4113 * XXX: We assume that if anything was added to inBuf, then it could
4114 * only be consumed by actions already covered by the above checks.
4115 */
4116
4117 // do not log connections that closed after a transaction (it is normal)
4118 // TODO: access_log needs ACLs to match received-no-bytes connections
6b2b6cfe 4119 if (pipeline.nrequests && inBuf.isEmpty())
da6dbcd1
EB
4120 return;
4121
4122 /* Create a temporary ClientHttpRequest object. Its destructor will log. */
4123 ClientHttpRequest http(this);
4124 http.req_sz = inBuf.length();
4125 char const *uri = "error:transaction-end-before-headers";
4126 http.uri = xstrdup(uri);
4127 setLogUri(&http, uri);
4128}
a6678149 4129
6b2b6cfe
CT
4130bool
4131ConnStateData::mayTunnelUnsupportedProto()
4132{
4133 return Config.accessList.on_unsupported_protocol
4134#if USE_OPENSSL
aff439e0
SM
4135 &&
4136 ((port->flags.isIntercepted() && port->flags.tunnelSslBumping)
4137 || (serverBump() && pinning.serverConnection))
6b2b6cfe 4138#endif
aff439e0 4139 ;
6b2b6cfe 4140}
aff439e0 4141
75d47340
CT
4142NotePairs::Pointer
4143ConnStateData::notes()
4144{
4145 if (!theNotes)
4146 theNotes = new NotePairs;
4147 return theNotes;
4148}
4149