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