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