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