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