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