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