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