]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/clients/FtpClient.cc
2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 09 File Transfer Protocol (FTP) */
12 #include "acl/FilledChecklist.h"
13 #include "client_side.h"
14 #include "clients/FtpClient.h"
15 #include "comm/ConnOpener.h"
16 #include "comm/Read.h"
17 #include "comm/TcpAcceptor.h"
18 #include "comm/Write.h"
19 #include "errorpage.h"
21 #include "ftp/Parsing.h"
23 #include "SquidConfig.h"
24 #include "SquidString.h"
25 #include "StatCounters.h"
34 const char *const crlf
= "\r\n";
37 escapeIAC(const char *buf
)
41 unsigned const char *p
;
44 for (p
= (unsigned const char *)buf
, n
= 1; *p
; ++n
, ++p
)
48 ret
= (char *)xmalloc(n
);
50 for (p
= (unsigned const char *)buf
, r
=(unsigned char *)ret
; *p
; ++p
) {
62 assert((r
- (unsigned char *)ret
) == n
);
68 /// configures the channel with a descriptor and registers a close handler
70 Ftp::Channel::opened(const Comm::ConnectionPointer
&newConn
,
71 const AsyncCall::Pointer
&aCloser
)
73 assert(!Comm::IsConnOpen(conn
));
74 assert(closer
== NULL
);
76 assert(Comm::IsConnOpen(newConn
));
77 assert(aCloser
!= NULL
);
81 comm_add_close_handler(conn
->fd
, closer
);
84 /// planned close: removes the close handler and calls comm_close
88 // channels with active listeners will be closed when the listener handler dies.
89 if (Comm::IsConnOpen(conn
)) {
90 comm_remove_close_handler(conn
->fd
, closer
);
91 conn
->close(); // we do not expect to be called back
97 Ftp::Channel::forget()
99 if (Comm::IsConnOpen(conn
)) {
100 commUnsetConnTimeout(conn
);
101 comm_remove_close_handler(conn
->fd
, closer
);
107 Ftp::Channel::clear()
113 /* Ftp::CtrlChannel */
115 Ftp::CtrlChannel::CtrlChannel():
124 buf
= static_cast<char*>(memAllocBuf(4096, &size
));
127 Ftp::CtrlChannel::~CtrlChannel()
129 memFreeBuf(size
, buf
);
131 wordlistDestroy(&message
);
132 safe_free(last_command
);
133 safe_free(last_reply
);
136 /* Ftp::DataChannel */
138 Ftp::DataChannel::DataChannel():
146 Ftp::DataChannel::~DataChannel()
152 Ftp::DataChannel::addr(const Ip::Address
&import
)
154 static char addrBuf
[MAX_IPSTRLEN
];
155 import
.toStr(addrBuf
, sizeof(addrBuf
));
157 host
= xstrdup(addrBuf
);
158 port
= import
.port();
163 Ftp::Client::Client(FwdState
*fwdState
):
164 AsyncJob("Ftp::Client"),
171 shortenReadTimeout(false)
173 ++statCounter
.server
.all
.requests
;
174 ++statCounter
.server
.ftp
.requests
;
176 ctrl
.last_command
= xstrdup("Connect to server");
178 typedef CommCbMemFunT
<Client
, CommCloseCbParams
> Dialer
;
179 const AsyncCall::Pointer closer
= JobCallback(9, 5, Dialer
, this,
180 Ftp::Client::ctrlClosed
);
181 ctrl
.opened(fwdState
->serverConnection(), closer
);
184 Ftp::Client::~Client()
186 if (data
.opener
!= NULL
) {
187 data
.opener
->cancel("Ftp::Client destructed");
192 safe_free(old_request
);
193 safe_free(old_reply
);
194 fwd
= NULL
; // refcounted
200 scheduleReadControlReply(0);
204 Ftp::Client::initReadBuf()
206 if (data
.readBuf
== NULL
) {
207 data
.readBuf
= new MemBuf
;
208 data
.readBuf
->init(4096, SQUID_TCP_SO_RCVBUF
);
213 * Close the FTP server connection(s). Used by serverComplete().
216 Ftp::Client::closeServer()
218 if (Comm::IsConnOpen(ctrl
.conn
)) {
219 debugs(9, 3, "closing FTP server FD " << ctrl
.conn
->fd
<< ", this " << this);
220 fwd
->unregister(ctrl
.conn
);
224 if (Comm::IsConnOpen(data
.conn
)) {
225 debugs(9, 3, "closing FTP data FD " << data
.conn
->fd
<< ", this " << this);
229 debugs(9, 3, "FTP ctrl and data connections closed. this " << this);
233 * Did we close all FTP server connection(s)?
235 \retval true Both server control and data channels are closed. And not waiting for a new data connection to open.
236 \retval false Either control channel or data is still active.
239 Ftp::Client::doneWithServer() const
241 return !Comm::IsConnOpen(ctrl
.conn
) && !Comm::IsConnOpen(data
.conn
);
245 Ftp::Client::failed(err_type error
, int xerrno
, ErrorState
*err
)
247 debugs(9, 3, "entry-null=" << (entry
?entry
->isEmpty():0) << ", entry=" << entry
);
249 const char *command
, *reply
;
253 debugs(9, 6, "error=" << err
->type
<< ", code=" << xerrno
<<
254 ", status=" << err
->httpStatus
);
258 Http::StatusCode httpStatus
= failedHttpStatus(error
);
259 ftperr
= new ErrorState(error
, httpStatus
, fwd
->request
);
262 ftperr
->xerrno
= xerrno
;
264 ftperr
->ftp
.server_msg
= ctrl
.message
;
268 command
= old_request
;
270 command
= ctrl
.last_command
;
272 if (command
&& strncmp(command
, "PASS", 4) == 0)
273 command
= "PASS <yourpassword>";
278 reply
= ctrl
.last_reply
;
281 ftperr
->ftp
.request
= xstrdup(command
);
284 ftperr
->ftp
.reply
= xstrdup(reply
);
287 fwd
->request
->detailError(error
, xerrno
);
289 closeServer(); // we failed, so no serverComplete()
294 Ftp::Client::failedHttpStatus(err_type
&error
)
296 if (error
== ERR_NONE
)
297 error
= ERR_FTP_FAILURE
;
298 return error
== ERR_READ_TIMEOUT
? Http::scGatewayTimeout
:
304 * Looks like there are no longer anymore callers that set
305 * buffered_ok=1. Perhaps it can be removed at some point.
308 Ftp::Client::scheduleReadControlReply(int buffered_ok
)
310 debugs(9, 3, ctrl
.conn
);
312 if (buffered_ok
&& ctrl
.offset
> 0) {
313 /* We've already read some reply data */
314 handleControlReply();
317 * Cancel the timeout on the Data socket (if any) and
318 * establish one on the control socket.
320 if (Comm::IsConnOpen(data
.conn
)) {
321 commUnsetConnTimeout(data
.conn
);
324 const time_t tout
= shortenReadTimeout
?
325 min(Config
.Timeout
.connect
, Config
.Timeout
.read
):
327 shortenReadTimeout
= false; // we only need to do this once, after PASV
329 typedef CommCbMemFunT
<Client
, CommTimeoutCbParams
> TimeoutDialer
;
330 AsyncCall::Pointer timeoutCall
= JobCallback(9, 5, TimeoutDialer
, this, Ftp::Client::timeout
);
331 commSetConnTimeout(ctrl
.conn
, tout
, timeoutCall
);
333 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
334 AsyncCall::Pointer reader
= JobCallback(9, 5, Dialer
, this, Ftp::Client::readControlReply
);
335 comm_read(ctrl
.conn
, ctrl
.buf
+ ctrl
.offset
, ctrl
.size
- ctrl
.offset
, reader
);
340 Ftp::Client::readControlReply(const CommIoCbParams
&io
)
342 debugs(9, 3, "FD " << io
.fd
<< ", Read " << io
.size
<< " bytes");
345 statCounter
.server
.all
.kbytes_in
+= io
.size
;
346 statCounter
.server
.ftp
.kbytes_in
+= io
.size
;
349 if (io
.flag
== Comm::ERR_CLOSING
)
352 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
353 abortTransaction("entry aborted during control reply read");
357 assert(ctrl
.offset
< ctrl
.size
);
359 if (io
.flag
== Comm::OK
&& io
.size
> 0) {
360 fd_bytes(io
.fd
, io
.size
, FD_READ
);
363 if (io
.flag
!= Comm::OK
) {
364 debugs(50, ignoreErrno(io
.xerrno
) ? 3 : DBG_IMPORTANT
,
365 "FTP control reply read error: " << xstrerr(io
.xerrno
));
367 if (ignoreErrno(io
.xerrno
)) {
368 scheduleReadControlReply(0);
370 failed(ERR_READ_ERROR
, io
.xerrno
);
371 /* failed closes ctrl.conn and frees ftpState */
377 if (entry
->store_status
== STORE_PENDING
) {
378 failed(ERR_FTP_FAILURE
, 0);
379 /* failed closes ctrl.conn and frees ftpState */
383 /* XXX this may end up having to be serverComplete() .. */
384 abortTransaction("zero control reply read");
388 unsigned int len
=io
.size
+ ctrl
.offset
;
390 assert(len
<= ctrl
.size
);
391 if (Comm::IsConnOpen(ctrl
.conn
))
392 commUnsetConnTimeout(ctrl
.conn
); // we are done waiting for ctrl reply
393 handleControlReply();
397 Ftp::Client::handleControlReply()
399 debugs(9, 3, status());
401 size_t bytes_used
= 0;
402 wordlistDestroy(&ctrl
.message
);
404 if (!parseControlReply(bytes_used
)) {
405 /* didn't get complete reply yet */
407 if (ctrl
.offset
== ctrl
.size
) {
408 ctrl
.buf
= static_cast<char*>(memReallocBuf(ctrl
.buf
, ctrl
.size
<< 1, &ctrl
.size
));
411 scheduleReadControlReply(0);
415 assert(ctrl
.message
); // the entire FTP server response, line by line
416 assert(ctrl
.replycode
>= 0); // FTP status code (from the last line)
417 assert(ctrl
.last_reply
); // FTP reason (from the last line)
419 if (ctrl
.offset
== bytes_used
) {
423 /* Got some data past the complete reply */
424 assert(bytes_used
< ctrl
.offset
);
425 ctrl
.offset
-= bytes_used
;
426 memmove(ctrl
.buf
, ctrl
.buf
+ bytes_used
, ctrl
.offset
);
429 debugs(9, 3, "state=" << state
<< ", code=" << ctrl
.replycode
);
433 Ftp::Client::handlePasvReply(Ip::Address
&srvAddr
)
435 int code
= ctrl
.replycode
;
437 debugs(9, 3, status());
440 debugs(9, 2, "PASV not supported by remote end");
444 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
445 /* ANSI sez [^0-9] is undefined, it breaks on Watcom cc */
446 debugs(9, 5, "scanning: " << ctrl
.last_reply
);
448 buf
= ctrl
.last_reply
+ strcspn(ctrl
.last_reply
, "0123456789");
450 const char *forceIp
= Config
.Ftp
.sanitycheck
?
451 fd_table
[ctrl
.conn
->fd
].ipaddr
: NULL
;
452 if (!Ftp::ParseIpPort(buf
, forceIp
, srvAddr
)) {
453 debugs(9, DBG_IMPORTANT
, "Unsafe PASV reply from " <<
454 ctrl
.conn
->remote
<< ": " << ctrl
.last_reply
);
464 Ftp::Client::handleEpsvReply(Ip::Address
&remoteAddr
)
466 int code
= ctrl
.replycode
;
468 debugs(9, 3, status());
470 if (code
!= 229 && code
!= 522) {
472 /* handle broken servers (RFC 2428 says OK code for EPSV MUST be 229 not 200) */
473 /* vsftpd for one send '200 EPSV ALL ok.' without even port info.
474 * Its okay to re-send EPSV 1/2 but nothing else. */
475 debugs(9, DBG_IMPORTANT
, "Broken FTP Server at " << ctrl
.conn
->remote
<< ". Wrong accept code for EPSV");
477 debugs(9, 2, "EPSV not supported by remote end");
479 return sendPassive();
483 /* Peer responded with a list of supported methods:
484 * 522 Network protocol not supported, use (1)
485 * 522 Network protocol not supported, use (1,2)
486 * 522 Network protocol not supported, use (2)
487 * TODO: Handle the (1,2) case which may happen after EPSV ALL. Close
488 * data + control without self-destructing and re-open from scratch.
490 debugs(9, 5, "scanning: " << ctrl
.last_reply
);
491 buf
= ctrl
.last_reply
;
492 while (buf
!= NULL
&& *buf
!= '\0' && *buf
!= '\n' && *buf
!= '(')
494 if (buf
!= NULL
&& *buf
== '\n')
497 if (buf
== NULL
|| *buf
== '\0') {
498 /* handle broken server (RFC 2428 says MUST specify supported protocols in 522) */
499 debugs(9, DBG_IMPORTANT
, "Broken FTP Server at " << ctrl
.conn
->remote
<< ". 522 error missing protocol negotiation hints");
500 return sendPassive();
501 } else if (strcmp(buf
, "(1)") == 0) {
502 state
= SENT_EPSV_2
; /* simulate having sent and failed EPSV 2 */
503 return sendPassive();
504 } else if (strcmp(buf
, "(2)") == 0) {
505 if (Ip::EnableIpv6
) {
506 /* If server only supports EPSV 2 and we have already tried that. Go straight to EPRT */
507 if (state
== SENT_EPSV_2
) {
510 /* or try the next Passive mode down the chain. */
511 return sendPassive();
514 /* Server only accept EPSV in IPv6 traffic. */
515 state
= SENT_EPSV_1
; /* simulate having sent and failed EPSV 1 */
516 return sendPassive();
519 /* handle broken server (RFC 2428 says MUST specify supported protocols in 522) */
520 debugs(9, DBG_IMPORTANT
, "WARNING: Server at " << ctrl
.conn
->remote
<< " sent unknown protocol negotiation hint: " << buf
);
521 return sendPassive();
523 /* coverity[unreachable] */
524 /* safeguard against possible future bugs in above conditions */
525 failed(ERR_FTP_FAILURE
, 0);
529 /* 229 Entering Extended Passive Mode (|||port|) */
530 /* ANSI sez [^0-9] is undefined, it breaks on Watcom cc */
531 debugs(9, 5, "scanning: " << ctrl
.last_reply
);
533 buf
= ctrl
.last_reply
+ strcspn(ctrl
.last_reply
, "(");
537 int n
= sscanf(buf
, "(%c%c%c%hu%c)", &h1
, &h2
, &h3
, &port
, &h4
);
539 if (n
< 4 || h1
!= h2
|| h1
!= h3
|| h1
!= h4
) {
540 debugs(9, DBG_IMPORTANT
, "Invalid EPSV reply from " <<
541 ctrl
.conn
->remote
<< ": " <<
544 return sendPassive();
548 debugs(9, DBG_IMPORTANT
, "Unsafe EPSV reply from " <<
549 ctrl
.conn
->remote
<< ": " <<
552 return sendPassive();
555 if (Config
.Ftp
.sanitycheck
) {
557 debugs(9, DBG_IMPORTANT
, "Unsafe EPSV reply from " <<
558 ctrl
.conn
->remote
<< ": " <<
561 return sendPassive();
565 remoteAddr
= ctrl
.conn
->remote
;
566 remoteAddr
.port(port
);
567 data
.addr(remoteAddr
);
571 // FTP clients do not support EPRT and PORT commands yet.
572 // The Ftp::Client::sendEprt() will fail because of the unimplemented
573 // openListenSocket() or sendPort() methods
575 Ftp::Client::sendEprt()
577 if (!Config
.Ftp
.eprt
) {
578 /* Disabled. Switch immediately to attempting old PORT command. */
579 debugs(9, 3, "EPRT disabled by local administrator");
583 debugs(9, 3, status());
585 if (!openListenSocket()) {
586 failed(ERR_FTP_FAILURE
, 0);
590 debugs(9, 3, "Listening for FTP data connection with FD " << data
.conn
);
591 if (!Comm::IsConnOpen(data
.conn
)) {
592 // TODO: Set error message.
593 failed(ERR_FTP_FAILURE
, 0);
599 char buf
[MAX_IPSTRLEN
];
600 /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
601 /* Which can be used by EITHER protocol. */
602 debugs(9, 3, "Listening for FTP data connection on port" << comm_local_port(data
.conn
->fd
) << " or port?" << data
.conn
->local
.port());
603 mb
.appendf("EPRT |%d|%s|%d|%s",
604 ( data
.conn
->local
.isIPv6() ? 2 : 1 ),
605 data
.conn
->local
.toStr(buf
,MAX_IPSTRLEN
),
606 comm_local_port(data
.conn
->fd
), Ftp::crlf
);
609 writeCommand(mb
.content());
614 Ftp::Client::sendPort()
616 failed(ERR_FTP_FAILURE
, 0);
621 Ftp::Client::sendPassive()
623 debugs(9, 3, status());
626 * Checks for EPSV ALL special conditions:
627 * If enabled to be sent, squid MUST NOT request any other connect methods.
628 * If 'ALL' is sent and fails the entire FTP Session fails.
629 * NP: By my reading exact EPSV protocols maybe attempted, but only EPSV method. */
630 if (Config
.Ftp
.epsv_all
&& state
== SENT_EPSV_1
) {
631 // We are here because the last "EPSV 1" failed, but because of epsv_all
632 // no other method allowed.
633 debugs(9, DBG_IMPORTANT
, "FTP does not allow PASV method after 'EPSV ALL' has been sent.");
634 failed(ERR_FTP_FAILURE
, 0);
638 /// Closes any old FTP-Data connection which may exist. */
642 * Checks for previous EPSV/PASV failures on this server/session.
643 * Diverts to EPRT immediately if they are not working. */
644 if (!Config
.Ftp
.passive
|| state
== SENT_PASV
) {
652 * Send EPSV (ALL,2,1) or PASV on the control channel.
654 * - EPSV ALL is used if enabled.
655 * - EPSV 2 is used if ALL is disabled and IPv6 is available and ctrl channel is IPv6.
656 * - EPSV 1 is used if EPSV 2 (IPv6) fails or is not available or ctrl channel is IPv4.
657 * - PASV is used if EPSV 1 fails.
660 case SENT_EPSV_ALL
: /* EPSV ALL resulted in a bad response. Try ther EPSV methods. */
661 if (ctrl
.conn
->local
.isIPv6()) {
662 debugs(9, 5, "FTP Channel is IPv6 (" << ctrl
.conn
->remote
<< ") attempting EPSV 2 after EPSV ALL has failed.");
663 mb
.appendf("EPSV 2%s", Ftp::crlf
);
667 // else fall through to skip EPSV 2
669 case SENT_EPSV_2
: /* EPSV IPv6 failed. Try EPSV IPv4 */
670 if (ctrl
.conn
->local
.isIPv4()) {
671 debugs(9, 5, "FTP Channel is IPv4 (" << ctrl
.conn
->remote
<< ") attempting EPSV 1 after EPSV ALL has failed.");
672 mb
.appendf("EPSV 1%s", Ftp::crlf
);
675 } else if (Config
.Ftp
.epsv_all
) {
676 debugs(9, DBG_IMPORTANT
, "FTP does not allow PASV method after 'EPSV ALL' has been sent.");
677 failed(ERR_FTP_FAILURE
, 0);
680 // else fall through to skip EPSV 1
682 case SENT_EPSV_1
: /* EPSV options exhausted. Try PASV now. */
683 debugs(9, 5, "FTP Channel (" << ctrl
.conn
->remote
<< ") rejects EPSV connection attempts. Trying PASV instead.");
684 mb
.appendf("PASV%s", Ftp::crlf
);
690 if (Config
.accessList
.ftp_epsv
) {
691 ACLFilledChecklist
checklist(Config
.accessList
.ftp_epsv
, fwd
->request
, NULL
);
692 doEpsv
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
695 debugs(9, 5, "EPSV support manually disabled. Sending PASV for FTP Channel (" << ctrl
.conn
->remote
<<")");
696 mb
.appendf("PASV%s", Ftp::crlf
);
698 } else if (Config
.Ftp
.epsv_all
) {
699 debugs(9, 5, "EPSV ALL manually enabled. Attempting with FTP Channel (" << ctrl
.conn
->remote
<<")");
700 mb
.appendf("EPSV ALL%s", Ftp::crlf
);
701 state
= SENT_EPSV_ALL
;
703 if (ctrl
.conn
->local
.isIPv6()) {
704 debugs(9, 5, "FTP Channel (" << ctrl
.conn
->remote
<< "). Sending default EPSV 2");
705 mb
.appendf("EPSV 2%s", Ftp::crlf
);
708 if (ctrl
.conn
->local
.isIPv4()) {
709 debugs(9, 5, "Channel (" << ctrl
.conn
->remote
<<"). Sending default EPSV 1");
710 mb
.appendf("EPSV 1%s", Ftp::crlf
);
719 wordlistDestroy(&ctrl
.message
);
720 ctrl
.message
= NULL
; //No message to return to client.
721 ctrl
.offset
= 0; //reset readed response, to make room read the next response
723 writeCommand(mb
.content());
725 shortenReadTimeout
= true;
730 Ftp::Client::connectDataChannel()
732 safe_free(ctrl
.last_command
);
734 safe_free(ctrl
.last_reply
);
736 ctrl
.last_command
= xstrdup("Connect to server data port");
738 // Generate a new data channel descriptor to be opened.
739 Comm::ConnectionPointer conn
= new Comm::Connection
;
740 conn
->setAddrs(ctrl
.conn
->local
, data
.host
);
742 conn
->remote
.port(data
.port
);
743 conn
->tos
= ctrl
.conn
->tos
;
744 conn
->nfmark
= ctrl
.conn
->nfmark
;
746 debugs(9, 3, "connecting to " << conn
->remote
);
748 typedef CommCbMemFunT
<Client
, CommConnectCbParams
> Dialer
;
749 data
.opener
= JobCallback(9, 3, Dialer
, this, Ftp::Client::dataChannelConnected
);
750 Comm::ConnOpener
*cs
= new Comm::ConnOpener(conn
, data
.opener
, Config
.Timeout
.connect
);
751 cs
->setHost(data
.host
);
756 Ftp::Client::openListenSocket()
761 /// creates a data channel Comm close callback
763 Ftp::Client::dataCloser()
765 typedef CommCbMemFunT
<Client
, CommCloseCbParams
> Dialer
;
766 return JobCallback(9, 5, Dialer
, this, Ftp::Client::dataClosed
);
769 /// handler called by Comm when FTP data channel is closed unexpectedly
771 Ftp::Client::dataClosed(const CommCloseCbParams
&)
773 debugs(9, 4, status());
774 if (data
.listenConn
!= NULL
) {
775 data
.listenConn
->close();
776 data
.listenConn
= NULL
;
777 // NP clear() does the: data.fd = -1;
783 Ftp::Client::writeCommand(const char *buf
)
786 /* trace FTP protocol communications at level 2 */
787 debugs(9, 2, "ftp<< " << buf
);
789 if (Config
.Ftp
.telnet
)
790 ebuf
= escapeIAC(buf
);
794 safe_free(ctrl
.last_command
);
796 safe_free(ctrl
.last_reply
);
798 ctrl
.last_command
= ebuf
;
800 if (!Comm::IsConnOpen(ctrl
.conn
)) {
801 debugs(9, 2, "cannot send to closing ctrl " << ctrl
.conn
);
802 // TODO: assert(ctrl.closer != NULL);
806 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
807 AsyncCall::Pointer call
= JobCallback(9, 5, Dialer
, this,
808 Ftp::Client::writeCommandCallback
);
809 Comm::Write(ctrl
.conn
, ctrl
.last_command
, strlen(ctrl
.last_command
), call
, NULL
);
811 scheduleReadControlReply(0);
815 Ftp::Client::writeCommandCallback(const CommIoCbParams
&io
)
818 debugs(9, 5, "wrote " << io
.size
<< " bytes");
821 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
822 statCounter
.server
.all
.kbytes_out
+= io
.size
;
823 statCounter
.server
.ftp
.kbytes_out
+= io
.size
;
826 if (io
.flag
== Comm::ERR_CLOSING
)
830 debugs(9, DBG_IMPORTANT
, "FTP command write error: " << io
.conn
<< ": " << xstrerr(io
.xerrno
));
831 failed(ERR_WRITE_ERROR
, io
.xerrno
);
832 /* failed closes ctrl.conn and frees ftpState */
837 /// handler called by Comm when FTP control channel is closed unexpectedly
839 Ftp::Client::ctrlClosed(const CommCloseCbParams
&)
841 debugs(9, 4, status());
843 mustStop("Ftp::Client::ctrlClosed");
847 Ftp::Client::timeout(const CommTimeoutCbParams
&io
)
849 debugs(9, 4, io
.conn
<< ": '" << entry
->url() << "'" );
851 if (abortOnBadEntry("entry went bad while waiting for a timeout"))
854 failed(ERR_READ_TIMEOUT
, 0);
855 /* failed() closes ctrl.conn and frees ftpState */
858 const Comm::ConnectionPointer
&
859 Ftp::Client::dataConnection() const
865 Ftp::Client::maybeReadVirginBody()
868 if (!Comm::IsConnOpen(data
.conn
) || fd_table
[data
.conn
->fd
].closing())
871 if (data
.read_pending
)
876 const int read_sz
= replyBodySpace(*data
.readBuf
, 0);
878 debugs(9, 9, "FTP may read up to " << read_sz
<< " bytes");
880 if (read_sz
< 2) // see http.cc
883 data
.read_pending
= true;
885 typedef CommCbMemFunT
<Client
, CommTimeoutCbParams
> TimeoutDialer
;
886 AsyncCall::Pointer timeoutCall
= JobCallback(9, 5,
887 TimeoutDialer
, this, Ftp::Client::timeout
);
888 commSetConnTimeout(data
.conn
, Config
.Timeout
.read
, timeoutCall
);
890 debugs(9,5,"queueing read on FD " << data
.conn
->fd
);
892 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
893 entry
->delayAwareRead(data
.conn
, data
.readBuf
->space(), read_sz
,
894 JobCallback(9, 5, Dialer
, this, Ftp::Client::dataRead
));
898 Ftp::Client::dataRead(const CommIoCbParams
&io
)
903 data
.read_pending
= false;
905 debugs(9, 3, "FD " << io
.fd
<< " Read " << io
.size
<< " bytes");
908 statCounter
.server
.all
.kbytes_in
+= io
.size
;
909 statCounter
.server
.ftp
.kbytes_in
+= io
.size
;
912 if (io
.flag
== Comm::ERR_CLOSING
)
915 assert(io
.fd
== data
.conn
->fd
);
917 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
918 abortTransaction("entry aborted during dataRead");
922 if (io
.flag
== Comm::OK
&& io
.size
> 0) {
923 debugs(9, 5, "appended " << io
.size
<< " bytes to readBuf");
924 data
.readBuf
->appended(io
.size
);
926 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
927 delayId
.bytesIn(io
.size
);
929 ++ IOStats
.Ftp
.reads
;
931 for (j
= io
.size
- 1, bin
= 0; j
; ++bin
)
934 ++ IOStats
.Ftp
.read_hist
[bin
];
937 if (io
.flag
!= Comm::OK
) {
938 debugs(50, ignoreErrno(io
.xerrno
) ? 3 : DBG_IMPORTANT
,
939 "FTP data read error: " << xstrerr(io
.xerrno
));
941 if (ignoreErrno(io
.xerrno
)) {
942 maybeReadVirginBody();
944 failed(ERR_READ_ERROR
, 0);
945 /* failed closes ctrl.conn and frees ftpState */
948 } else if (io
.size
== 0) {
949 debugs(9, 3, "Calling dataComplete() because io.size == 0");
952 * Dangerous curves ahead. This call to dataComplete was
953 * calling scheduleReadControlReply, handleControlReply,
954 * and then ftpReadTransferDone. If ftpReadTransferDone
955 * gets unexpected status code, it closes down the control
956 * socket and our FtpStateData object gets destroyed. As
957 * a workaround we no longer set the 'buffered_ok' flag in
958 * the scheduleReadControlReply call.
967 Ftp::Client::dataComplete()
969 debugs(9, 3,status());
971 /* Connection closed; transfer done. */
973 /// Close data channel, if any, to conserve resources while we wait.
976 /* expect the "transfer complete" message on the control socket */
979 * Previously, this was the only place where we set the
980 * 'buffered_ok' flag when calling scheduleReadControlReply().
981 * It caused some problems if the FTP server returns an unexpected
982 * status code after the data command. FtpStateData was being
983 * deleted in the middle of dataRead().
985 /* AYJ: 2011-01-13: Bug 2581.
986 * 226 status is possibly waiting in the ctrl buffer.
987 * The connection will hang if we DONT send buffered_ok.
988 * This happens on all transfers which can be completly sent by the
989 * server before the 150 started status message is read in by Squid.
990 * ie all transfers of about one packet hang.
992 scheduleReadControlReply(1);
996 * Quickly abort the transaction
998 \todo destruction should be sufficient as the destructor should cleanup,
999 * including canceling close handlers
1002 Ftp::Client::abortTransaction(const char *reason
)
1004 debugs(9, 3, "aborting transaction for " << reason
<<
1005 "; FD " << (ctrl
.conn
!=NULL
?ctrl
.conn
->fd
:-1) << ", Data FD " << (data
.conn
!=NULL
?data
.conn
->fd
:-1) << ", this " << this);
1006 if (Comm::IsConnOpen(ctrl
.conn
)) {
1011 fwd
->handleUnregisteredServerEnd();
1012 mustStop("Ftp::Client::abortTransaction");
1016 * Cancel the timeout on the Control socket and establish one
1017 * on the data socket
1020 Ftp::Client::switchTimeoutToDataChannel()
1022 commUnsetConnTimeout(ctrl
.conn
);
1024 typedef CommCbMemFunT
<Client
, CommTimeoutCbParams
> TimeoutDialer
;
1025 AsyncCall::Pointer timeoutCall
= JobCallback(9, 5, TimeoutDialer
, this,
1026 Ftp::Client::timeout
);
1027 commSetConnTimeout(data
.conn
, Config
.Timeout
.read
, timeoutCall
);
1031 Ftp::Client::sentRequestBody(const CommIoCbParams
&io
)
1034 statCounter
.server
.ftp
.kbytes_out
+= io
.size
;
1035 ::Client::sentRequestBody(io
);
1039 * called after we wrote the last byte of the request body
1042 Ftp::Client::doneSendingRequestBody()
1044 ::Client::doneSendingRequestBody();
1045 debugs(9, 3, status());
1047 /* NP: RFC 959 3.3. DATA CONNECTION MANAGEMENT
1048 * if transfer type is 'stream' call dataComplete()
1049 * otherwise leave open. (reschedule control channel read?)
1053 /// Parses FTP server control response into ctrl structure fields,
1054 /// setting bytesUsed and returning true on success.
1056 Ftp::Client::parseControlReply(size_t &bytesUsed
)
1063 wordlist
*head
= NULL
;
1065 wordlist
**tail
= &head
;
1067 debugs(9, 3, status());
1069 * We need a NULL-terminated buffer for scanning, ick
1071 const size_t len
= ctrl
.offset
;
1072 sbuf
= (char *)xmalloc(len
+ 1);
1073 xstrncpy(sbuf
, ctrl
.buf
, len
+ 1);
1074 end
= sbuf
+ len
- 1;
1076 while (*end
!= '\r' && *end
!= '\n' && end
> sbuf
)
1079 usable
= end
- sbuf
;
1081 debugs(9, 3, "usable = " << usable
);
1084 debugs(9, 3, "didn't find end of line");
1089 debugs(9, 3, len
<< " bytes to play with");
1092 s
+= strspn(s
, crlf
);
1094 for (; s
< end
; s
+= strcspn(s
, crlf
), s
+= strspn(s
, crlf
)) {
1098 debugs(9, 5, "s = {" << s
<< "}");
1100 linelen
= strcspn(s
, crlf
) + 1;
1106 complete
= (*s
>= '0' && *s
<= '9' && *(s
+ 3) == ' ');
1108 list
= new wordlist();
1110 list
->key
= (char *)xmalloc(linelen
);
1112 xstrncpy(list
->key
, s
, linelen
);
1114 /* trace the FTP communication chat at level 2 */
1115 debugs(9, 2, "ftp>> " << list
->key
);
1118 // use list->key for last_reply because s contains the new line
1119 ctrl
.last_reply
= xstrdup(list
->key
+ 4);
1120 ctrl
.replycode
= atoi(list
->key
);
1128 bytesUsed
= static_cast<size_t>(s
- sbuf
);
1132 wordlistDestroy(&head
);
1136 ctrl
.message
= head
;
1137 assert(ctrl
.replycode
>= 0);
1138 assert(ctrl
.last_reply
);
1139 assert(ctrl
.message
);