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