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