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