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