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