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