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