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