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