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