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