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