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