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