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