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