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