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