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