1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/ftp.cpp
3 // Purpose: FTP protocol
4 // Author: Guilhem Lavaux
5 // Modified by: Mark Johnson, wxWindows@mj10777.de
6 // 20000917 : RmDir, GetLastResult, GetList
7 // Vadim Zeitlin (numerous fixes and rewrites to all part of the
8 // code, support ASCII/Binary modes, better error reporting, more
9 // robust Abort(), support for arbitrary FTP commands, ...)
10 // Randall Fox (support for active mode)
11 // Created: 07/07/1997
13 // Copyright: (c) 1997, 1998 Guilhem Lavaux
14 // (c) 1998-2004 wxWidgets team
15 // Licence: wxWindows licence
16 /////////////////////////////////////////////////////////////////////////////
18 // ============================================================================
20 // ============================================================================
22 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
23 #pragma implementation "ftp.h"
26 // ----------------------------------------------------------------------------
28 // ----------------------------------------------------------------------------
30 // For compilers that support precompilation, includes "wx.h".
31 #include "wx/wxprec.h"
37 #if wxUSE_PROTOCOL_FTP
41 #include "wx/string.h"
47 #include "wx/sckaddr.h"
48 #include "wx/socket.h"
50 #include "wx/sckstrm.h"
51 #include "wx/protocol/protocol.h"
52 #include "wx/protocol/ftp.h"
54 #if defined(__WXMAC__)
55 #include "wx/mac/macsock.h"
62 // ----------------------------------------------------------------------------
64 // ----------------------------------------------------------------------------
66 // the length of FTP status code (3 digits)
67 static const size_t LEN_CODE
= 3;
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 IMPLEMENT_DYNAMIC_CLASS(wxFTP
, wxProtocol
)
74 IMPLEMENT_PROTOCOL(wxFTP
, wxT("ftp"), wxT("ftp"), true)
76 // ============================================================================
78 // ============================================================================
80 // ----------------------------------------------------------------------------
81 // wxFTP constructor and destructor
82 // ----------------------------------------------------------------------------
86 m_lastError
= wxPROTO_NOERR
;
88 m_currentTransfermode
= NONE
;
90 m_user
= wxT("anonymous");
91 m_passwd
<< wxGetUserId() << wxT('@') << wxGetFullHostName();
94 SetFlags(wxSOCKET_NONE
);
96 SetDefaultTimeout(60); // Default is Sixty Seconds
97 m_bEncounteredError
= false;
104 // if we are streaming, this will issue
105 // an FTP ABORT command, to tell the server we are aborting
109 // now this issues a "QUIT" command to tell the server we are
113 // ----------------------------------------------------------------------------
114 // wxFTP connect and login methods
115 // ----------------------------------------------------------------------------
117 bool wxFTP::Connect(wxSockAddress
& addr
, bool WXUNUSED(wait
))
119 if ( !wxProtocol::Connect(addr
) )
121 m_lastError
= wxPROTO_NETERR
;
127 m_lastError
= wxPROTO_CONNERR
;
131 // we should have 220 welcome message
132 if ( !CheckResult('2') )
139 command
.Printf(wxT("USER %s"), m_user
.c_str());
140 char rc
= SendCommand(command
);
143 // 230 return: user accepted without password
153 command
.Printf(wxT("PASS %s"), m_passwd
.c_str());
154 if ( !CheckCommand(command
, '2') )
163 bool wxFTP::Connect(const wxString
& host
)
167 addr
.Service(wxT("ftp"));
169 return Connect(addr
);
176 m_lastError
= wxPROTO_STREAMING
;
182 if ( !CheckCommand(wxT("QUIT"), '2') )
184 wxLogDebug(_T("Failed to close connection gracefully."));
188 return wxSocketClient::Close();
191 // ============================================================================
193 // ============================================================================
195 // ----------------------------------------------------------------------------
196 // Send command to FTP server
197 // ----------------------------------------------------------------------------
199 char wxFTP::SendCommand(const wxString
& command
)
203 m_lastError
= wxPROTO_STREAMING
;
207 wxString tmp_str
= command
+ wxT("\r\n");
208 const wxWX2MBbuf tmp_buf
= tmp_str
.mb_str();
209 if ( Write(wxMBSTRINGCAST tmp_buf
, strlen(tmp_buf
)).Error())
211 m_lastError
= wxPROTO_NETERR
;
216 // don't show the passwords in the logs (even in debug ones)
217 wxString cmd
, password
;
218 if ( command
.Upper().StartsWith(_T("PASS "), &password
) )
220 cmd
<< _T("PASS ") << wxString(_T('*'), password
.length());
227 wxLogTrace(FTP_TRACE_MASK
, _T("==> %s"), cmd
.c_str());
228 #endif // __WXDEBUG__
233 // ----------------------------------------------------------------------------
234 // Recieve servers reply
235 // ----------------------------------------------------------------------------
237 char wxFTP::GetResult()
239 // if we've already had a read or write timeout error, the connection is
240 // probably toast, so don't bother, it just wastes the users time
241 if ( m_bEncounteredError
)
246 // m_lastResult will contain the entire server response, possibly on
248 m_lastResult
.clear();
250 // we handle multiline replies here according to RFC 959: it says that a
251 // reply may either be on 1 line of the form "xyz ..." or on several lines
252 // in whuch case it looks like
256 // and the intermeidate lines may start with xyz or not
257 bool badReply
= false;
258 bool firstLine
= true;
259 bool endOfReply
= false;
260 while ( !endOfReply
&& !badReply
)
263 m_lastError
= ReadLine(this,line
);
266 m_bEncounteredError
= true;
270 if ( !m_lastResult
.empty() )
272 // separate from last line
273 m_lastResult
+= _T('\n');
276 m_lastResult
+= line
;
278 // unless this is an intermediate line of a multiline reply, it must
279 // contain the code in the beginning and '-' or ' ' following it
280 if ( line
.Len() < LEN_CODE
+ 1 )
288 wxLogTrace(FTP_TRACE_MASK
, _T("<== %s %s"),
289 code
.c_str(), line
.c_str());
292 else // line has at least 4 chars
294 // this is the char which tells us what we're dealing with
295 wxChar chMarker
= line
.GetChar(LEN_CODE
);
299 code
= wxString(line
, LEN_CODE
);
300 wxLogTrace(FTP_TRACE_MASK
, _T("<== %s %s"),
301 code
.c_str(), line
.c_str() + LEN_CODE
+ 1);
318 else // subsequent line of multiline reply
320 if ( wxStrncmp(line
, code
, LEN_CODE
) == 0 )
322 if ( chMarker
== _T(' ') )
327 wxLogTrace(FTP_TRACE_MASK
, _T("<== %s %s"),
328 code
.c_str(), line
.c_str() + LEN_CODE
+ 1);
332 // just part of reply
333 wxLogTrace(FTP_TRACE_MASK
, _T("<== %s %s"),
334 code
.c_str(), line
.c_str());
342 wxLogDebug(_T("Broken FTP server: '%s' is not a valid reply."),
343 m_lastResult
.c_str());
345 m_lastError
= wxPROTO_PROTERR
;
350 // if we got here we must have a non empty code string
351 return (char)code
[0u];
354 // ----------------------------------------------------------------------------
355 // wxFTP simple commands
356 // ----------------------------------------------------------------------------
358 bool wxFTP::SetTransferMode(TransferMode transferMode
)
360 if ( transferMode
== m_currentTransfermode
)
367 switch ( transferMode
)
370 wxFAIL_MSG(_T("unknown FTP transfer mode"));
382 if ( !DoSimpleCommand(_T("TYPE"), mode
) )
384 wxLogError(_("Failed to set FTP transfer mode to %s."), (const wxChar
*)
385 (transferMode
== ASCII
? _("ASCII") : _("binary")));
390 // If we get here the operation has been succesfully completed
391 // Set the status-member
392 m_currentTransfermode
= transferMode
;
397 bool wxFTP::DoSimpleCommand(const wxChar
*command
, const wxString
& arg
)
399 wxString fullcmd
= command
;
402 fullcmd
<< _T(' ') << arg
;
405 if ( !CheckCommand(fullcmd
, '2') )
407 wxLogDebug(_T("FTP command '%s' failed."), fullcmd
.c_str());
415 bool wxFTP::ChDir(const wxString
& dir
)
417 // some servers might not understand ".." if they use different directory
418 // tree conventions, but they always understand CDUP - should we use it if
419 // dir == ".."? OTOH, do such servers (still) exist?
421 return DoSimpleCommand(_T("CWD"), dir
);
424 bool wxFTP::MkDir(const wxString
& dir
)
426 return DoSimpleCommand(_T("MKD"), dir
);
429 bool wxFTP::RmDir(const wxString
& dir
)
431 return DoSimpleCommand(_T("RMD"), dir
);
434 wxString
wxFTP::Pwd()
438 if ( CheckCommand(wxT("PWD"), '2') )
440 // the result is at least that long if CheckCommand() succeeded
441 const wxChar
*p
= m_lastResult
.c_str() + LEN_CODE
+ 1;
444 wxLogDebug(_T("Missing starting quote in reply for PWD: %s"), p
);
452 // check if the quote is doubled
454 if ( !*p
|| *p
!= _T('"') )
456 // no, this is the end
459 //else: yes, it is: this is an embedded quote in the
460 // filename, treat as normal char
468 wxLogDebug(_T("Missing ending quote in reply for PWD: %s"),
469 m_lastResult
.c_str() + LEN_CODE
+ 1);
475 wxLogDebug(_T("FTP PWD command failed."));
481 bool wxFTP::Rename(const wxString
& src
, const wxString
& dst
)
485 str
= wxT("RNFR ") + src
;
486 if ( !CheckCommand(str
, '3') )
489 str
= wxT("RNTO ") + dst
;
491 return CheckCommand(str
, '2');
494 bool wxFTP::RmFile(const wxString
& path
)
497 str
= wxT("DELE ") + path
;
499 return CheckCommand(str
, '2');
502 // ----------------------------------------------------------------------------
503 // wxFTP download and upload
504 // ----------------------------------------------------------------------------
506 class wxInputFTPStream
: public wxSocketInputStream
509 wxInputFTPStream(wxFTP
*ftp
, wxSocketBase
*sock
)
510 : wxSocketInputStream(*sock
)
513 // socket timeout automatically set in GetPort function
516 virtual ~wxInputFTPStream()
518 delete m_i_socket
; // keep at top
520 // when checking the result, the stream will
521 // almost always show an error, even if the file was
522 // properly transfered, thus, lets just grab the result
524 // we are looking for "226 transfer completed"
525 char code
= m_ftp
->GetResult();
528 // it was a good transfer.
530 m_ftp
->m_streaming
= false;
536 // the connection is probably toast. issue an abort, and
537 // then a close. there won't be any more waiting
538 // for this connection
543 // There was a problem with the transfer and the server
544 // has acknowledged it. If we issue an "ABORT" now, the user
545 // would get the "226" for the abort and think the xfer was
546 // complete, thus, don't do anything here, just return
551 DECLARE_NO_COPY_CLASS(wxInputFTPStream
)
554 class wxOutputFTPStream
: public wxSocketOutputStream
557 wxOutputFTPStream(wxFTP
*ftp_clt
, wxSocketBase
*sock
)
558 : wxSocketOutputStream(*sock
), m_ftp(ftp_clt
)
562 virtual ~wxOutputFTPStream(void)
566 // close data connection first, this will generate "transfer
571 m_ftp
->GetResult(); // save result so user can get to it
573 m_ftp
->m_streaming
= false;
577 // abort data connection first
580 // and close it after
587 DECLARE_NO_COPY_CLASS(wxOutputFTPStream
)
590 void wxFTP::SetDefaultTimeout(wxUint32 Value
)
592 m_uiDefaultTimeout
= Value
;
593 SetTimeout(Value
); // sets it for this socket
597 wxSocketBase
*wxFTP::GetPort()
600 PASSIVE: Client sends a "PASV" to the server. The server responds with
601 an address and port number which it will be listening on. Then
602 the client connects to the server at the specified address and
605 ACTIVE: Client sends the server a PORT command which includes an
606 address and port number which the client will be listening on.
607 The server then connects to the client at that address and
611 wxSocketBase
*socket
= m_bPassive
? GetPassivePort() : GetActivePort();
614 m_bEncounteredError
= true;
618 // Now set the time for the new socket to the default or user selected
620 socket
->SetTimeout(m_uiDefaultTimeout
);
625 wxSocketBase
*wxFTP::AcceptIfActive(wxSocketBase
*sock
)
630 // now wait for a connection from server
631 wxSocketServer
*sockSrv
= (wxSocketServer
*)sock
;
632 if ( !sockSrv
->WaitForAccept() )
634 m_lastError
= wxPROTO_CONNERR
;
635 wxLogError(_("Timeout while waiting for FTP server to connect, try passive mode."));
641 sock
= sockSrv
->Accept(true);
648 wxString
wxFTP::GetPortCmdArgument(wxIPV4address addrLocal
,
649 wxIPV4address addrNew
)
651 // Just fills in the return value with the local IP
652 // address of the current socket. Also it fill in the
653 // PORT which the client will be listening on
655 wxString addrIP
= addrLocal
.IPAddress();
656 int portNew
= addrNew
.Service();
658 // We need to break the PORT number in bytes
659 addrIP
.Replace(_T("."), _T(","));
661 << wxString::Format(_T("%d"), portNew
>> 8) << _T(',')
662 << wxString::Format(_T("%d"), portNew
& 0xff);
664 // Now we have a value like "10,0,0,1,5,23"
668 wxSocketBase
*wxFTP::GetActivePort()
670 // we need an address to listen on
671 wxIPV4address addrNew
, addrLocal
;
673 addrNew
.AnyAddress();
674 addrNew
.Service(0); // pick an open port number.
676 wxSocketServer
*sockSrv
= new wxSocketServer(addrNew
);
679 // We use Ok() here to see if everything is ok
680 m_lastError
= wxPROTO_PROTERR
;
685 //gets the new address, actually it is just the port number
686 sockSrv
->GetLocal(addrNew
);
688 // Now we create the argument of the PORT command, we send in both
689 // addresses because the addrNew has an IP of "0.0.0.0", so we need the
690 // value in addrLocal
691 wxString port
= GetPortCmdArgument(addrLocal
, addrNew
);
692 if ( !DoSimpleCommand(_T("PORT "), port
) )
694 m_lastError
= wxPROTO_PROTERR
;
696 wxLogError(_("The FTP server doesn't support the PORT command."));
700 sockSrv
->Notify(false); // Don't send any events
704 wxSocketBase
*wxFTP::GetPassivePort()
706 if ( !DoSimpleCommand(_T("PASV")) )
708 wxLogError(_("The FTP server doesn't support passive mode."));
712 const wxChar
*addrStart
= wxStrchr(m_lastResult
, _T('('));
713 const wxChar
*addrEnd
= addrStart
? wxStrchr(addrStart
, _T(')')) : NULL
;
716 m_lastError
= wxPROTO_PROTERR
;
721 // get the port number and address
723 wxString
straddr(addrStart
+ 1, addrEnd
);
724 wxSscanf(straddr
, wxT("%d,%d,%d,%d,%d,%d"),
725 &a
[2],&a
[3],&a
[4],&a
[5],&a
[0],&a
[1]);
727 wxUint32 hostaddr
= (wxUint16
)a
[2] << 24 |
728 (wxUint16
)a
[3] << 16 |
729 (wxUint16
)a
[4] << 8 |
731 wxUint16 port
= (wxUint16
)(a
[0] << 8 | a
[1]);
734 addr
.Hostname(hostaddr
);
737 wxSocketClient
*client
= new wxSocketClient();
738 if ( !client
->Connect(addr
) )
744 client
->Notify(false);
755 if ( !CheckCommand(wxT("ABOR"), '4') )
758 return CheckResult('2');
761 wxInputStream
*wxFTP::GetInputStream(const wxString
& path
)
763 if ( ( m_currentTransfermode
== NONE
) && !SetTransferMode(BINARY
) )
766 wxSocketBase
*sock
= GetPort();
770 m_lastError
= wxPROTO_NETERR
;
774 wxString tmp_str
= wxT("RETR ") + wxURI::Unescape(path
);
775 if ( !CheckCommand(tmp_str
, '1') )
778 sock
= AcceptIfActive(sock
);
782 sock
->SetFlags(wxSOCKET_WAITALL
);
786 wxInputFTPStream
*in_stream
= new wxInputFTPStream(this, sock
);
791 wxOutputStream
*wxFTP::GetOutputStream(const wxString
& path
)
793 if ( ( m_currentTransfermode
== NONE
) && !SetTransferMode(BINARY
) )
796 wxSocketBase
*sock
= GetPort();
798 wxString tmp_str
= wxT("STOR ") + path
;
799 if ( !CheckCommand(tmp_str
, '1') )
802 sock
= AcceptIfActive(sock
);
806 return new wxOutputFTPStream(this, sock
);
809 // ----------------------------------------------------------------------------
810 // FTP directory listing
811 // ----------------------------------------------------------------------------
813 bool wxFTP::GetList(wxArrayString
& files
,
814 const wxString
& wildcard
,
817 wxSocketBase
*sock
= GetPort();
821 // NLST : List of Filenames (including Directory's !)
822 // LIST : depending on BS of FTP-Server
823 // - Unix : result like "ls" command
824 // - Windows : like "dir" command
826 wxString
line(details
? _T("LIST") : _T("NLST"));
827 if ( !wildcard
.empty() )
829 line
<< _T(' ') << wildcard
;
832 if ( !CheckCommand(line
, '1') )
834 m_lastError
= wxPROTO_PROTERR
;
835 wxLogDebug(_T("FTP 'LIST' command returned unexpected result from server"));
840 sock
= AcceptIfActive(sock
);
845 while (ReadLine(sock
, line
) == wxPROTO_NOERR
)
852 // the file list should be terminated by "226 Transfer complete""
853 return CheckResult('2');
856 bool wxFTP::FileExists(const wxString
& fileName
)
858 // This function checks if the file specified in fileName exists in the
859 // current dir. It does so by simply doing an NLST (via GetList).
860 // If this succeeds (and the list is not empty) the file exists.
863 wxArrayString fileList
;
865 if ( GetList(fileList
, fileName
, false) )
867 // Some ftp-servers (Ipswitch WS_FTP Server 1.0.5 does this)
868 // displays this behaviour when queried on a non-existing file:
869 // NLST this_file_does_not_exist
870 // 150 Opening ASCII data connection for directory listing
871 // (no data transferred)
872 // 226 Transfer complete
873 // Here wxFTP::GetList(...) will succeed but it will return an empty
875 retval
= !fileList
.IsEmpty();
881 // ----------------------------------------------------------------------------
883 // ----------------------------------------------------------------------------
885 int wxFTP::GetFileSize(const wxString
& fileName
)
887 // return the filesize of the given file if possible
888 // return -1 otherwise (predominantly if file doesn't exist
893 // Check for existance of file via wxFTP::FileExists(...)
894 if ( FileExists(fileName
) )
898 // First try "SIZE" command using BINARY(IMAGE) transfermode
899 // Especially UNIX ftp-servers distinguish between the different
900 // transfermodes and reports different filesizes accordingly.
901 // The BINARY size is the interesting one: How much memory
902 // will we need to hold this file?
903 TransferMode oldTransfermode
= m_currentTransfermode
;
904 SetTransferMode(BINARY
);
905 command
<< _T("SIZE ") << fileName
;
907 bool ok
= CheckCommand(command
, '2');
911 // The answer should be one line: "213 <filesize>\n"
912 // 213 is File Status (STD9)
913 // "SIZE" is not described anywhere..? It works on most servers
915 if ( wxSscanf(GetLastResult().c_str(), _T("%i %i"),
916 &statuscode
, &filesize
) == 2 )
918 // We've gotten a good reply.
923 // Something bad happened.. A "2yz" reply with no size
929 // Set transfermode back to the original. Only the "SIZE"-command
930 // is dependant on transfermode
931 if ( oldTransfermode
!= NONE
)
933 SetTransferMode(oldTransfermode
);
936 // this is not a direct else clause.. The size command might return an
937 // invalid "2yz" reply
940 // The server didn't understand the "SIZE"-command or it
941 // returned an invalid reply.
942 // We now try to get details for the file with a "LIST"-command
943 // and then parse the output from there..
944 wxArrayString fileList
;
945 if ( GetList(fileList
, fileName
, true) )
947 if ( !fileList
.IsEmpty() )
949 // We _should_ only get one line in return, but just to be
950 // safe we run through the line(s) returned and look for a
951 // substring containing the name we are looking for. We
952 // stop the iteration at the first occurrence of the
953 // filename. The search is not case-sensitive.
954 bool foundIt
= false;
957 for ( i
= 0; !foundIt
&& i
< fileList
.Count(); i
++ )
959 foundIt
= fileList
[i
].Upper().Contains(fileName
.Upper());
964 // The index i points to the first occurrence of
965 // fileName in the array Now we have to find out what
966 // format the LIST has returned. There are two
967 // "schools": Unix-like
969 // '-rw-rw-rw- owner group size month day time filename'
973 // 'date size filename'
975 // check if the first character is '-'. This would
976 // indicate Unix-style (this also limits this function
977 // to searching for files, not directories)
978 if ( fileList
[i
].Mid(0, 1) == _T("-") )
981 if ( wxSscanf(fileList
[i
].c_str(),
982 _T("%*s %*s %*s %*s %i %*s %*s %*s %*s"),
985 // Hmm... Invalid response
986 wxLogTrace(FTP_TRACE_MASK
,
987 _T("Invalid LIST response"));
990 else // Windows-style response (?)
992 if ( wxSscanf(fileList
[i
].c_str(),
993 _T("%*s %*s %i %*s"),
996 // something bad happened..?
997 wxLogTrace(FTP_TRACE_MASK
,
998 _T("Invalid or unknown LIST response"));
1007 // filesize might still be -1 when exiting
1011 #endif // wxUSE_PROTOCOL_FTP