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