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