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