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