]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/clients/FtpClient.cc
2 * Copyright (C) 1996-2014 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
)
247 debugs(9, 3, "entry-null=" << (entry
?entry
->isEmpty():0) << ", entry=" << entry
);
249 const char *command
, *reply
;
250 const Http::StatusCode httpStatus
= failedHttpStatus(error
);
251 ErrorState
*const ftperr
= new ErrorState(error
, httpStatus
, fwd
->request
);
252 ftperr
->xerrno
= xerrno
;
254 ftperr
->ftp
.server_msg
= ctrl
.message
;
258 command
= old_request
;
260 command
= ctrl
.last_command
;
262 if (command
&& strncmp(command
, "PASS", 4) == 0)
263 command
= "PASS <yourpassword>";
268 reply
= ctrl
.last_reply
;
271 ftperr
->ftp
.request
= xstrdup(command
);
274 ftperr
->ftp
.reply
= xstrdup(reply
);
276 fwd
->request
->detailError(error
, xerrno
);
279 closeServer(); // we failed, so no serverComplete()
283 Ftp::Client::failedHttpStatus(err_type
&error
)
285 if (error
== ERR_NONE
)
286 error
= ERR_FTP_FAILURE
;
287 return error
== ERR_READ_TIMEOUT
? Http::scGatewayTimeout
:
293 * Looks like there are no longer anymore callers that set
294 * buffered_ok=1. Perhaps it can be removed at some point.
297 Ftp::Client::scheduleReadControlReply(int buffered_ok
)
299 debugs(9, 3, ctrl
.conn
);
301 if (buffered_ok
&& ctrl
.offset
> 0) {
302 /* We've already read some reply data */
303 handleControlReply();
306 * Cancel the timeout on the Data socket (if any) and
307 * establish one on the control socket.
309 if (Comm::IsConnOpen(data
.conn
)) {
310 commUnsetConnTimeout(data
.conn
);
313 const time_t tout
= shortenReadTimeout
?
314 min(Config
.Timeout
.connect
, Config
.Timeout
.read
):
316 shortenReadTimeout
= false; // we only need to do this once, after PASV
318 typedef CommCbMemFunT
<Client
, CommTimeoutCbParams
> TimeoutDialer
;
319 AsyncCall::Pointer timeoutCall
= JobCallback(9, 5, TimeoutDialer
, this, Ftp::Client::timeout
);
320 commSetConnTimeout(ctrl
.conn
, tout
, timeoutCall
);
322 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
323 AsyncCall::Pointer reader
= JobCallback(9, 5, Dialer
, this, Ftp::Client::readControlReply
);
324 comm_read(ctrl
.conn
, ctrl
.buf
+ ctrl
.offset
, ctrl
.size
- ctrl
.offset
, reader
);
329 Ftp::Client::readControlReply(const CommIoCbParams
&io
)
331 debugs(9, 3, "FD " << io
.fd
<< ", Read " << io
.size
<< " bytes");
334 kb_incr(&(statCounter
.server
.all
.kbytes_in
), io
.size
);
335 kb_incr(&(statCounter
.server
.ftp
.kbytes_in
), io
.size
);
338 if (io
.flag
== Comm::ERR_CLOSING
)
341 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
342 abortTransaction("entry aborted during control reply read");
346 assert(ctrl
.offset
< ctrl
.size
);
348 if (io
.flag
== Comm::OK
&& io
.size
> 0) {
349 fd_bytes(io
.fd
, io
.size
, FD_READ
);
352 if (io
.flag
!= Comm::OK
) {
353 debugs(50, ignoreErrno(io
.xerrno
) ? 3 : DBG_IMPORTANT
,
354 "FTP control reply read error: " << xstrerr(io
.xerrno
));
356 if (ignoreErrno(io
.xerrno
)) {
357 scheduleReadControlReply(0);
359 failed(ERR_READ_ERROR
, io
.xerrno
);
360 /* failed closes ctrl.conn and frees ftpState */
366 if (entry
->store_status
== STORE_PENDING
) {
367 failed(ERR_FTP_FAILURE
, 0);
368 /* failed closes ctrl.conn and frees ftpState */
372 /* XXX this may end up having to be serverComplete() .. */
373 abortTransaction("zero control reply read");
377 unsigned int len
=io
.size
+ ctrl
.offset
;
379 assert(len
<= ctrl
.size
);
380 if (Comm::IsConnOpen(ctrl
.conn
))
381 commUnsetConnTimeout(ctrl
.conn
); // we are done waiting for ctrl reply
382 handleControlReply();
386 Ftp::Client::handleControlReply()
388 debugs(9, 3, status());
390 size_t bytes_used
= 0;
391 wordlistDestroy(&ctrl
.message
);
393 if (!parseControlReply(bytes_used
)) {
394 /* didn't get complete reply yet */
396 if (ctrl
.offset
== ctrl
.size
) {
397 ctrl
.buf
= static_cast<char*>(memReallocBuf(ctrl
.buf
, ctrl
.size
<< 1, &ctrl
.size
));
400 scheduleReadControlReply(0);
404 assert(ctrl
.message
); // the entire FTP server response, line by line
405 assert(ctrl
.replycode
>= 0); // FTP status code (from the last line)
406 assert(ctrl
.last_reply
); // FTP reason (from the last line)
408 if (ctrl
.offset
== bytes_used
) {
412 /* Got some data past the complete reply */
413 assert(bytes_used
< ctrl
.offset
);
414 ctrl
.offset
-= bytes_used
;
415 memmove(ctrl
.buf
, ctrl
.buf
+ bytes_used
, ctrl
.offset
);
418 debugs(9, 3, "state=" << state
<< ", code=" << ctrl
.replycode
);
422 Ftp::Client::handlePasvReply(Ip::Address
&srvAddr
)
424 int code
= ctrl
.replycode
;
426 debugs(9, 3, status());
429 debugs(9, 2, "PASV not supported by remote end");
433 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
434 /* ANSI sez [^0-9] is undefined, it breaks on Watcom cc */
435 debugs(9, 5, "scanning: " << ctrl
.last_reply
);
437 buf
= ctrl
.last_reply
+ strcspn(ctrl
.last_reply
, "0123456789");
439 const char *forceIp
= Config
.Ftp
.sanitycheck
?
440 fd_table
[ctrl
.conn
->fd
].ipaddr
: NULL
;
441 if (!Ftp::ParseIpPort(buf
, forceIp
, srvAddr
)) {
442 debugs(9, DBG_IMPORTANT
, "Unsafe PASV reply from " <<
443 ctrl
.conn
->remote
<< ": " << ctrl
.last_reply
);
453 Ftp::Client::handleEpsvReply(Ip::Address
&remoteAddr
)
455 int code
= ctrl
.replycode
;
457 debugs(9, 3, status());
459 if (code
!= 229 && code
!= 522) {
461 /* handle broken servers (RFC 2428 says OK code for EPSV MUST be 229 not 200) */
462 /* vsftpd for one send '200 EPSV ALL ok.' without even port info.
463 * Its okay to re-send EPSV 1/2 but nothing else. */
464 debugs(9, DBG_IMPORTANT
, "Broken FTP Server at " << ctrl
.conn
->remote
<< ". Wrong accept code for EPSV");
466 debugs(9, 2, "EPSV not supported by remote end");
468 return sendPassive();
472 /* Peer responded with a list of supported methods:
473 * 522 Network protocol not supported, use (1)
474 * 522 Network protocol not supported, use (1,2)
475 * 522 Network protocol not supported, use (2)
476 * TODO: Handle the (1,2) case which may happen after EPSV ALL. Close
477 * data + control without self-destructing and re-open from scratch.
479 debugs(9, 5, "scanning: " << ctrl
.last_reply
);
480 buf
= ctrl
.last_reply
;
481 while (buf
!= NULL
&& *buf
!= '\0' && *buf
!= '\n' && *buf
!= '(')
483 if (buf
!= NULL
&& *buf
== '\n')
486 if (buf
== NULL
|| *buf
== '\0') {
487 /* handle broken server (RFC 2428 says MUST specify supported protocols in 522) */
488 debugs(9, DBG_IMPORTANT
, "Broken FTP Server at " << ctrl
.conn
->remote
<< ". 522 error missing protocol negotiation hints");
489 return sendPassive();
490 } else if (strcmp(buf
, "(1)") == 0) {
491 state
= SENT_EPSV_2
; /* simulate having sent and failed EPSV 2 */
492 return sendPassive();
493 } else if (strcmp(buf
, "(2)") == 0) {
494 if (Ip::EnableIpv6
) {
495 /* If server only supports EPSV 2 and we have already tried that. Go straight to EPRT */
496 if (state
== SENT_EPSV_2
) {
499 /* or try the next Passive mode down the chain. */
500 return sendPassive();
503 /* Server only accept EPSV in IPv6 traffic. */
504 state
= SENT_EPSV_1
; /* simulate having sent and failed EPSV 1 */
505 return sendPassive();
508 /* handle broken server (RFC 2428 says MUST specify supported protocols in 522) */
509 debugs(9, DBG_IMPORTANT
, "WARNING: Server at " << ctrl
.conn
->remote
<< " sent unknown protocol negotiation hint: " << buf
);
510 return sendPassive();
512 failed(ERR_FTP_FAILURE
, 0);
516 /* 229 Entering Extended Passive Mode (|||port|) */
517 /* ANSI sez [^0-9] is undefined, it breaks on Watcom cc */
518 debugs(9, 5, "scanning: " << ctrl
.last_reply
);
520 buf
= ctrl
.last_reply
+ strcspn(ctrl
.last_reply
, "(");
524 int n
= sscanf(buf
, "(%c%c%c%hu%c)", &h1
, &h2
, &h3
, &port
, &h4
);
526 if (n
< 4 || h1
!= h2
|| h1
!= h3
|| h1
!= h4
) {
527 debugs(9, DBG_IMPORTANT
, "Invalid EPSV reply from " <<
528 ctrl
.conn
->remote
<< ": " <<
531 return sendPassive();
535 debugs(9, DBG_IMPORTANT
, "Unsafe EPSV reply from " <<
536 ctrl
.conn
->remote
<< ": " <<
539 return sendPassive();
542 if (Config
.Ftp
.sanitycheck
) {
544 debugs(9, DBG_IMPORTANT
, "Unsafe EPSV reply from " <<
545 ctrl
.conn
->remote
<< ": " <<
548 return sendPassive();
552 remoteAddr
= ctrl
.conn
->remote
;
553 remoteAddr
.port(port
);
554 data
.addr(remoteAddr
);
558 // FTP clients do not support EPRT and PORT commands yet.
559 // The Ftp::Client::sendEprt() will fail because of the unimplemented
560 // openListenSocket() or sendPort() methods
562 Ftp::Client::sendEprt()
564 if (!Config
.Ftp
.eprt
) {
565 /* Disabled. Switch immediately to attempting old PORT command. */
566 debugs(9, 3, "EPRT disabled by local administrator");
570 debugs(9, 3, status());
572 if (!openListenSocket()) {
573 failed(ERR_FTP_FAILURE
, 0);
577 debugs(9, 3, "Listening for FTP data connection with FD " << data
.conn
);
578 if (!Comm::IsConnOpen(data
.conn
)) {
579 // TODO: Set error message.
580 failed(ERR_FTP_FAILURE
, 0);
586 char buf
[MAX_IPSTRLEN
];
587 /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
588 /* Which can be used by EITHER protocol. */
589 debugs(9, 3, "Listening for FTP data connection on port" << comm_local_port(data
.conn
->fd
) << " or port?" << data
.conn
->local
.port());
590 mb
.Printf("EPRT |%d|%s|%d|%s",
591 ( data
.conn
->local
.isIPv6() ? 2 : 1 ),
592 data
.conn
->local
.toStr(buf
,MAX_IPSTRLEN
),
593 comm_local_port(data
.conn
->fd
), Ftp::crlf
);
596 writeCommand(mb
.content());
601 Ftp::Client::sendPort()
603 failed(ERR_FTP_FAILURE
, 0);
608 Ftp::Client::sendPassive()
610 debugs(9, 3, status());
613 * Checks for EPSV ALL special conditions:
614 * If enabled to be sent, squid MUST NOT request any other connect methods.
615 * If 'ALL' is sent and fails the entire FTP Session fails.
616 * NP: By my reading exact EPSV protocols maybe attempted, but only EPSV method. */
617 if (Config
.Ftp
.epsv_all
&& state
== SENT_EPSV_1
) {
618 // We are here because the last "EPSV 1" failed, but because of epsv_all
619 // no other method allowed.
620 debugs(9, DBG_IMPORTANT
, "FTP does not allow PASV method after 'EPSV ALL' has been sent.");
621 failed(ERR_FTP_FAILURE
, 0);
625 /// Closes any old FTP-Data connection which may exist. */
629 * Checks for previous EPSV/PASV failures on this server/session.
630 * Diverts to EPRT immediately if they are not working. */
631 if (!Config
.Ftp
.passive
|| state
== SENT_PASV
) {
639 * Send EPSV (ALL,2,1) or PASV on the control channel.
641 * - EPSV ALL is used if enabled.
642 * - EPSV 2 is used if ALL is disabled and IPv6 is available and ctrl channel is IPv6.
643 * - EPSV 1 is used if EPSV 2 (IPv6) fails or is not available or ctrl channel is IPv4.
644 * - PASV is used if EPSV 1 fails.
647 case SENT_EPSV_ALL
: /* EPSV ALL resulted in a bad response. Try ther EPSV methods. */
648 if (ctrl
.conn
->local
.isIPv6()) {
649 debugs(9, 5, "FTP Channel is IPv6 (" << ctrl
.conn
->remote
<< ") attempting EPSV 2 after EPSV ALL has failed.");
650 mb
.Printf("EPSV 2%s", Ftp::crlf
);
654 // else fall through to skip EPSV 2
656 case SENT_EPSV_2
: /* EPSV IPv6 failed. Try EPSV IPv4 */
657 if (ctrl
.conn
->local
.isIPv4()) {
658 debugs(9, 5, "FTP Channel is IPv4 (" << ctrl
.conn
->remote
<< ") attempting EPSV 1 after EPSV ALL has failed.");
659 mb
.Printf("EPSV 1%s", Ftp::crlf
);
662 } else if (Config
.Ftp
.epsv_all
) {
663 debugs(9, DBG_IMPORTANT
, "FTP does not allow PASV method after 'EPSV ALL' has been sent.");
664 failed(ERR_FTP_FAILURE
, 0);
667 // else fall through to skip EPSV 1
669 case SENT_EPSV_1
: /* EPSV options exhausted. Try PASV now. */
670 debugs(9, 5, "FTP Channel (" << ctrl
.conn
->remote
<< ") rejects EPSV connection attempts. Trying PASV instead.");
671 mb
.Printf("PASV%s", Ftp::crlf
);
677 if (Config
.accessList
.ftp_epsv
) {
678 ACLFilledChecklist
checklist(Config
.accessList
.ftp_epsv
, fwd
->request
, NULL
);
679 doEpsv
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
682 debugs(9, 5, "EPSV support manually disabled. Sending PASV for FTP Channel (" << ctrl
.conn
->remote
<<")");
683 mb
.Printf("PASV%s", Ftp::crlf
);
685 } else if (Config
.Ftp
.epsv_all
) {
686 debugs(9, 5, "EPSV ALL manually enabled. Attempting with FTP Channel (" << ctrl
.conn
->remote
<<")");
687 mb
.Printf("EPSV ALL%s", Ftp::crlf
);
688 state
= SENT_EPSV_ALL
;
690 if (ctrl
.conn
->local
.isIPv6()) {
691 debugs(9, 5, "FTP Channel (" << ctrl
.conn
->remote
<< "). Sending default EPSV 2");
692 mb
.Printf("EPSV 2%s", Ftp::crlf
);
695 if (ctrl
.conn
->local
.isIPv4()) {
696 debugs(9, 5, "Channel (" << ctrl
.conn
->remote
<<"). Sending default EPSV 1");
697 mb
.Printf("EPSV 1%s", Ftp::crlf
);
706 wordlistDestroy(&ctrl
.message
);
707 ctrl
.message
= NULL
; //No message to return to client.
708 ctrl
.offset
= 0; //reset readed response, to make room read the next response
710 writeCommand(mb
.content());
712 shortenReadTimeout
= true;
717 Ftp::Client::connectDataChannel()
719 safe_free(ctrl
.last_command
);
721 safe_free(ctrl
.last_reply
);
723 ctrl
.last_command
= xstrdup("Connect to server data port");
725 // Generate a new data channel descriptor to be opened.
726 Comm::ConnectionPointer conn
= new Comm::Connection
;
727 conn
->setAddrs(ctrl
.conn
->local
, data
.host
);
729 conn
->remote
.port(data
.port
);
730 conn
->tos
= ctrl
.conn
->tos
;
731 conn
->nfmark
= ctrl
.conn
->nfmark
;
733 debugs(9, 3, "connecting to " << conn
->remote
);
735 typedef CommCbMemFunT
<Client
, CommConnectCbParams
> Dialer
;
736 data
.opener
= JobCallback(9, 3, Dialer
, this, Ftp::Client::dataChannelConnected
);
737 Comm::ConnOpener
*cs
= new Comm::ConnOpener(conn
, data
.opener
, Config
.Timeout
.connect
);
738 cs
->setHost(data
.host
);
743 Ftp::Client::openListenSocket()
748 /// creates a data channel Comm close callback
750 Ftp::Client::dataCloser()
752 typedef CommCbMemFunT
<Client
, CommCloseCbParams
> Dialer
;
753 return JobCallback(9, 5, Dialer
, this, Ftp::Client::dataClosed
);
756 /// handler called by Comm when FTP data channel is closed unexpectedly
758 Ftp::Client::dataClosed(const CommCloseCbParams
&io
)
760 debugs(9, 4, status());
761 if (data
.listenConn
!= NULL
) {
762 data
.listenConn
->close();
763 data
.listenConn
= NULL
;
764 // NP clear() does the: data.fd = -1;
770 Ftp::Client::writeCommand(const char *buf
)
773 /* trace FTP protocol communications at level 2 */
774 debugs(9, 2, "ftp<< " << buf
);
776 if (Config
.Ftp
.telnet
)
777 ebuf
= escapeIAC(buf
);
781 safe_free(ctrl
.last_command
);
783 safe_free(ctrl
.last_reply
);
785 ctrl
.last_command
= ebuf
;
787 if (!Comm::IsConnOpen(ctrl
.conn
)) {
788 debugs(9, 2, "cannot send to closing ctrl " << ctrl
.conn
);
789 // TODO: assert(ctrl.closer != NULL);
793 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
794 AsyncCall::Pointer call
= JobCallback(9, 5, Dialer
, this,
795 Ftp::Client::writeCommandCallback
);
796 Comm::Write(ctrl
.conn
, ctrl
.last_command
, strlen(ctrl
.last_command
), call
, NULL
);
798 scheduleReadControlReply(0);
802 Ftp::Client::writeCommandCallback(const CommIoCbParams
&io
)
805 debugs(9, 5, "wrote " << io
.size
<< " bytes");
808 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
809 kb_incr(&(statCounter
.server
.all
.kbytes_out
), io
.size
);
810 kb_incr(&(statCounter
.server
.ftp
.kbytes_out
), io
.size
);
813 if (io
.flag
== Comm::ERR_CLOSING
)
817 debugs(9, DBG_IMPORTANT
, "FTP command write error: " << io
.conn
<< ": " << xstrerr(io
.xerrno
));
818 failed(ERR_WRITE_ERROR
, io
.xerrno
);
819 /* failed closes ctrl.conn and frees ftpState */
824 /// handler called by Comm when FTP control channel is closed unexpectedly
826 Ftp::Client::ctrlClosed(const CommCloseCbParams
&io
)
828 debugs(9, 4, status());
830 mustStop("Ftp::Client::ctrlClosed");
834 Ftp::Client::timeout(const CommTimeoutCbParams
&io
)
836 debugs(9, 4, io
.conn
<< ": '" << entry
->url() << "'" );
838 if (abortOnBadEntry("entry went bad while waiting for a timeout"))
841 failed(ERR_READ_TIMEOUT
, 0);
842 /* failed() closes ctrl.conn and frees ftpState */
845 const Comm::ConnectionPointer
&
846 Ftp::Client::dataConnection() const
852 Ftp::Client::maybeReadVirginBody()
855 if (!Comm::IsConnOpen(data
.conn
) || fd_table
[data
.conn
->fd
].closing())
858 if (data
.read_pending
)
863 const int read_sz
= replyBodySpace(*data
.readBuf
, 0);
865 debugs(9, 9, "FTP may read up to " << read_sz
<< " bytes");
867 if (read_sz
< 2) // see http.cc
870 data
.read_pending
= true;
872 typedef CommCbMemFunT
<Client
, CommTimeoutCbParams
> TimeoutDialer
;
873 AsyncCall::Pointer timeoutCall
= JobCallback(9, 5,
874 TimeoutDialer
, this, Ftp::Client::timeout
);
875 commSetConnTimeout(data
.conn
, Config
.Timeout
.read
, timeoutCall
);
877 debugs(9,5,"queueing read on FD " << data
.conn
->fd
);
879 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
880 entry
->delayAwareRead(data
.conn
, data
.readBuf
->space(), read_sz
,
881 JobCallback(9, 5, Dialer
, this, Ftp::Client::dataRead
));
885 Ftp::Client::dataRead(const CommIoCbParams
&io
)
890 data
.read_pending
= false;
892 debugs(9, 3, "FD " << io
.fd
<< " Read " << io
.size
<< " bytes");
895 kb_incr(&(statCounter
.server
.all
.kbytes_in
), io
.size
);
896 kb_incr(&(statCounter
.server
.ftp
.kbytes_in
), io
.size
);
899 if (io
.flag
== Comm::ERR_CLOSING
)
902 assert(io
.fd
== data
.conn
->fd
);
904 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
905 abortTransaction("entry aborted during dataRead");
909 if (io
.flag
== Comm::OK
&& io
.size
> 0) {
910 debugs(9, 5, "appended " << io
.size
<< " bytes to readBuf");
911 data
.readBuf
->appended(io
.size
);
913 DelayId delayId
= entry
->mem_obj
->mostBytesAllowed();
914 delayId
.bytesIn(io
.size
);
916 ++ IOStats
.Ftp
.reads
;
918 for (j
= io
.size
- 1, bin
= 0; j
; ++bin
)
921 ++ IOStats
.Ftp
.read_hist
[bin
];
924 if (io
.flag
!= Comm::OK
) {
925 debugs(50, ignoreErrno(io
.xerrno
) ? 3 : DBG_IMPORTANT
,
926 "FTP data read error: " << xstrerr(io
.xerrno
));
928 if (ignoreErrno(io
.xerrno
)) {
929 maybeReadVirginBody();
931 failed(ERR_READ_ERROR
, 0);
932 /* failed closes ctrl.conn and frees ftpState */
935 } else if (io
.size
== 0) {
936 debugs(9, 3, "Calling dataComplete() because io.size == 0");
939 * Dangerous curves ahead. This call to dataComplete was
940 * calling scheduleReadControlReply, handleControlReply,
941 * and then ftpReadTransferDone. If ftpReadTransferDone
942 * gets unexpected status code, it closes down the control
943 * socket and our FtpStateData object gets destroyed. As
944 * a workaround we no longer set the 'buffered_ok' flag in
945 * the scheduleReadControlReply call.
954 Ftp::Client::dataComplete()
956 debugs(9, 3,status());
958 /* Connection closed; transfer done. */
960 /// Close data channel, if any, to conserve resources while we wait.
963 /* expect the "transfer complete" message on the control socket */
966 * Previously, this was the only place where we set the
967 * 'buffered_ok' flag when calling scheduleReadControlReply().
968 * It caused some problems if the FTP server returns an unexpected
969 * status code after the data command. FtpStateData was being
970 * deleted in the middle of dataRead().
972 /* AYJ: 2011-01-13: Bug 2581.
973 * 226 status is possibly waiting in the ctrl buffer.
974 * The connection will hang if we DONT send buffered_ok.
975 * This happens on all transfers which can be completly sent by the
976 * server before the 150 started status message is read in by Squid.
977 * ie all transfers of about one packet hang.
979 scheduleReadControlReply(1);
983 * Quickly abort the transaction
985 \todo destruction should be sufficient as the destructor should cleanup,
986 * including canceling close handlers
989 Ftp::Client::abortTransaction(const char *reason
)
991 debugs(9, 3, "aborting transaction for " << reason
<<
992 "; FD " << (ctrl
.conn
!=NULL
?ctrl
.conn
->fd
:-1) << ", Data FD " << (data
.conn
!=NULL
?data
.conn
->fd
:-1) << ", this " << this);
993 if (Comm::IsConnOpen(ctrl
.conn
)) {
998 fwd
->handleUnregisteredServerEnd();
999 mustStop("Ftp::Client::abortTransaction");
1003 * Cancel the timeout on the Control socket and establish one
1004 * on the data socket
1007 Ftp::Client::switchTimeoutToDataChannel()
1009 commUnsetConnTimeout(ctrl
.conn
);
1011 typedef CommCbMemFunT
<Client
, CommTimeoutCbParams
> TimeoutDialer
;
1012 AsyncCall::Pointer timeoutCall
= JobCallback(9, 5, TimeoutDialer
, this,
1013 Ftp::Client::timeout
);
1014 commSetConnTimeout(data
.conn
, Config
.Timeout
.read
, timeoutCall
);
1018 Ftp::Client::sentRequestBody(const CommIoCbParams
&io
)
1021 kb_incr(&(statCounter
.server
.ftp
.kbytes_out
), io
.size
);
1022 ::Client::sentRequestBody(io
);
1026 * called after we wrote the last byte of the request body
1029 Ftp::Client::doneSendingRequestBody()
1031 ::Client::doneSendingRequestBody();
1032 debugs(9, 3, status());
1034 /* NP: RFC 959 3.3. DATA CONNECTION MANAGEMENT
1035 * if transfer type is 'stream' call dataComplete()
1036 * otherwise leave open. (reschedule control channel read?)
1040 /// Parses FTP server control response into ctrl structure fields,
1041 /// setting bytesUsed and returning true on success.
1043 Ftp::Client::parseControlReply(size_t &bytesUsed
)
1050 wordlist
*head
= NULL
;
1052 wordlist
**tail
= &head
;
1054 debugs(9, 3, status());
1056 * We need a NULL-terminated buffer for scanning, ick
1058 const size_t len
= ctrl
.offset
;
1059 sbuf
= (char *)xmalloc(len
+ 1);
1060 xstrncpy(sbuf
, ctrl
.buf
, len
+ 1);
1061 end
= sbuf
+ len
- 1;
1063 while (*end
!= '\r' && *end
!= '\n' && end
> sbuf
)
1066 usable
= end
- sbuf
;
1068 debugs(9, 3, "usable = " << usable
);
1071 debugs(9, 3, "didn't find end of line");
1076 debugs(9, 3, len
<< " bytes to play with");
1079 s
+= strspn(s
, crlf
);
1081 for (; s
< end
; s
+= strcspn(s
, crlf
), s
+= strspn(s
, crlf
)) {
1085 debugs(9, 5, "s = {" << s
<< "}");
1087 linelen
= strcspn(s
, crlf
) + 1;
1093 complete
= (*s
>= '0' && *s
<= '9' && *(s
+ 3) == ' ');
1095 list
= new wordlist();
1097 list
->key
= (char *)xmalloc(linelen
);
1099 xstrncpy(list
->key
, s
, linelen
);
1101 /* trace the FTP communication chat at level 2 */
1102 debugs(9, 2, "ftp>> " << list
->key
);
1105 // use list->key for last_reply because s contains the new line
1106 ctrl
.last_reply
= xstrdup(list
->key
+ 4);
1107 ctrl
.replycode
= atoi(list
->key
);
1115 bytesUsed
= static_cast<size_t>(s
- sbuf
);
1119 wordlistDestroy(&head
);
1123 ctrl
.message
= head
;
1124 assert(ctrl
.replycode
>= 0);
1125 assert(ctrl
.last_reply
);
1126 assert(ctrl
.message
);