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