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