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