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