| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848 |
- /*
- ** Command & Conquer Generals(tm)
- ** Copyright 2025 Electronic Arts Inc.
- **
- ** This program is free software: you can redistribute it and/or modify
- ** it under the terms of the GNU General Public License as published by
- ** the Free Software Foundation, either version 3 of the License, or
- ** (at your option) any later version.
- **
- ** This program is distributed in the hope that it will be useful,
- ** but WITHOUT ANY WARRANTY; without even the implied warranty of
- ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- ** GNU General Public License for more details.
- **
- ** You should have received a copy of the GNU General Public License
- ** along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- // ftp.cpp : Implementation of Cftp
- /*************************************************************************/
- /*_$ Include Files */
- /*************************************************************************/
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/timeb.h>
- #include <stdlib.h>
- #include <process.h>
- #include <sys/stat.h>
- #include <io.h>
- #include <time.h>
- #include "assert.h"
- #include "ftp.h"
- #include "winsock.h"
- #include <time.h>
- #include <direct.h>
- #include <errno.h>
- //#include "wlib/wstring.h"
- #include "DownloadDebug.h"
- // umm... what?? BGC 3/27/03
- //#ifndef _DEBUG
- //#define _DEBUG
- //#endif
- /*************************************************************************/
- /*_$ External References */
- /*************************************************************************/
- /*************************************************************************/
- /*_$ Private Datatypes */
- /*************************************************************************/
- /*************************************************************************/
- /*_$ Public Data */
- /*************************************************************************/
- /*************************************************************************/
- /*_$ Private Data */
- /*************************************************************************/
- //static HOSTENT gThreadHost;
- struct sockaddr_in gThreadAddress;
- static int gThreadFlag;
- /*************************************************************************/
- /*_$ Private Prototypes */
- /*************************************************************************/
- /*************************************************************************/
- /*_$ Private Macros */
- /*************************************************************************/
- /* Status flags */
- #define FTPSTAT_INIT 0
- #define FTPSTAT_CONNECTING 10
- #define FTPSTAT_WAITINGSERVEROK 15
- #define FTPSTAT_CONNECTED 20
- #define FTPSTAT_SENDINGUSER 30
- #define FTPSTAT_SENTUSER 40
- #define FTPSTAT_SENDINGPASS 50
- #define FTPSTAT_LOGGEDIN 60
- #define FTPSTAT_LOGGINGOFF 70
- #define FTPSTAT_SENDINGQUIT 80
- #define FTPSTAT_SENTQUIT 90
- #define FTPSTAT_FILEFOUND 100
- #define FTPSTAT_SENDINGCWD 110
- #define FTPSTAT_SENTCWD 120
- #define FTPSTAT_SENTPORT 130
- #define FTPSTAT_SENDINGLIST 140
- #define FTPSTAT_SENTLIST 150
- #define FTPSTAT_LISTDATAOPEN 160
- #define FTPSTAT_LISTDATARECVD 170
- #define FTPSTAT_FILEOPEN 180
- #define FTPSTAT_SENTFILEPORT 190
- #define FTPSTAT_SENDINGTYPE 200
- #define FTPSTAT_SENTTYPE 210
- #define FTPSTAT_SENDINGREST 220
- #define FTPSTAT_SENTREST 230
- #define FTPSTAT_SENDINGRETR 240
- #define FTPSTAT_SENTRETR 250
- #define FTPSTAT_FILEDATAOPEN 260
- #define FTPSTAT_FILEDATACLOSED 270
- #define FTPSTAT_TRANSFERREPLY 280
- // Utility functions
- bool Prepare_Directories(const char *rootdir, const char *filename);
- //
- // This is here as a hack...
- // Some firewalls break the TCP stack so non-blocking sockets don't work right...
- //
- static bool Use_Non_Blocking_Mode(void)
- {
- HKEY regKey;
- LONG regRetval;
- DWORD bufsiz=0;
- DWORD type=0;
- DWORD value=0;
- // Try and open the named key
- regRetval=RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Westwood\\Earth And Beyond Beta 2",0,KEY_READ,®Key);
- if (regRetval!=ERROR_SUCCESS)
- return(TRUE); // default TRUE
- // Fetch the flag
- bufsiz=sizeof(value);
- type=REG_DWORD;
- regRetval=RegQueryValueEx(regKey, "UseNonBlockingFTP", 0, &type, (BYTE*) &value, &bufsiz);
- RegCloseKey(regKey);
- if ((regRetval!=ERROR_SUCCESS) || (type != REG_DWORD))
- return(TRUE);
- return(bool(value));
- }
- /////////////////////////////////////////////////////////////////////////////
- // Cftp
- /*$_Function****************************************************************
- * $_Name :
- * Cftp::Cftp()
- *
- * $_Description :
- * Constructor for the ftp class - initialises more or less all data
- * members to zero.
- *
- * $_Parameters :
- * None.
- *
- * $_ReturnValue :
- * None.
- *
- ***************************************************************************/
- Cftp::Cftp()
- {
- ZeroStuff();
- }
- /*$_Function****************************************************************
- * $_Name :
- * Cftp::Cftp()
- *
- * $_Description :
- * Destructor for the ftp class - close sockets behind us as we leave.
- *
- * $_Parameters :
- * None.
- *
- * $_ReturnValue :
- * None.
- *
- ***************************************************************************/
- Cftp::~Cftp()
- {
- CloseSockets();
- if (m_pfLocalFile)
- {
- fclose(m_pfLocalFile);
- m_pfLocalFile = NULL;
- }
- }
- void Cftp::CloseSockets(void)
- {
- if( m_iDataSocket )
- {
- closesocket( m_iDataSocket );
- m_iDataSocket=0;
- }
- if( m_iCommandSocket )
- {
- closesocket( m_iCommandSocket );
- m_iCommandSocket=0;
- }
- }
- void Cftp::ZeroStuff(void)
- {
- m_iBytesRead = 0;
- m_iFileSize = 0;
- m_szRemoteFilePath[ 0 ] = (char)0;
- m_szRemoteFileName[ 0 ] = (char)0;
- m_szLocalFilePath[ 0 ] = (char)0;
- m_szLocalFileName[ 0 ] = (char)0;
- m_szServerName[ 0 ] = (char)0;
- m_szUserName[ 0 ] = (char)0;
- m_szPassword[ 0 ] = (char)0;
- m_iDataSocket = 0;
- m_iCommandSocket = 0;
- m_iFilePos = 0;
- m_iStatus = FTPSTAT_INIT;
- m_sendNewPortStatus = 0;
- m_pfLocalFile = NULL;
- m_findStart = 0;
- memset(&m_CommandSockAddr, 0, sizeof(m_CommandSockAddr));
- memset(&m_DataSockAddr, 0, sizeof(m_DataSockAddr));
- }
- DWORD WINAPI gethostbynameA( void * szName )
- {
- HOSTENT *he = gethostbyname( (const char *)szName );
- //////DBGMSG("Hostname copy start");
- if (he)
- memcpy((char *)&(gThreadAddress.sin_addr), he->h_addr, he->h_length );
- else
- memcpy((char *)&(gThreadAddress.sin_addr),"",strlen("")+1);
- /////DBGMSG("Hostname copy complete");
- gThreadFlag = 1;
- return 0;
- }
- int Cftp::AsyncGetHostByName(char * szName, struct sockaddr_in &address )
- {
- static int stat = 0;
- static unsigned long threadid;
- if( stat == 0 )
- {
- /* Kick off gethostname thread */
- gThreadFlag = 0;
- memset(&gThreadAddress,0,sizeof(gThreadAddress));
- if( CreateThread( NULL, 0, gethostbynameA, szName, 0, &threadid ) == NULL )
- {
- return( FTP_FAILED );
- }
- stat = 1;
- }
- if( stat == 1 )
- {
- if( gThreadFlag )
- {
- /* Thread finished */
- address = gThreadAddress;
- address.sin_family=AF_INET;
- stat = 0;
- return( FTP_SUCCEEDED );
- }
- }
- return( FTP_TRYING );
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::ConnectToServer(LPCSTR szServerName)
- *
- * $_Description :
- * Overloaded funciton that makes a connection to a server. Will probably
- * fail on (at least) the first call, as it may take a while for the server
- * to send it's "ready" reply.
- *
- * $_Parameters :
- * -> const char * szServerName
- * Optionally, the name of the server to connect to. This must be specified
- * in the first call to the function.
- *
- * $_ReturnValue :
- * FTP_TRYING until the connection has succeeded, then FTP_SUCCEEDED.
- * FTP_FAILED on error.
- *
- ***************************************************************************/
- HRESULT Cftp::ConnectToServer(LPCSTR szServerName)
- {
- struct sockaddr_in address;
- unsigned long uTemp;
- unsigned long serverIP;
- char buffer[ 256 ];
- int iReply, error;
- strncpy( m_szServerName, szServerName, 128 );
- if( m_iStatus == FTPSTAT_INIT )
- {
- /* Find the IP address of the server */
- serverIP = inet_addr( m_szServerName );
- memset( &m_CommandSockAddr, 0, sizeof( m_CommandSockAddr ) );
- m_CommandSockAddr.sin_family = AF_INET;
- if( serverIP == INADDR_NONE )
- {
- /* It's an FQDN - hopefully. */
- ////////DBGMSG("Async gethostbyname");
- if( AsyncGetHostByName( m_szServerName, address ) == FTP_TRYING )
- {
- return( FTP_TRYING );
- }
- //////DBGMSG("Got hostbyname");
- if( address.sin_addr.s_addr == 0 )
- {
- ///////DBGMSG("gethostbyname failed");
- return( FTP_FAILED );
- }
- m_CommandSockAddr=address;
- ///////memcpy( (char *)&(m_CommandSockAddr.sin_addr), he.h_addr, he.h_length );
- serverIP = m_CommandSockAddr.sin_addr.s_addr;
- //////DBGMSG("ServerIP = "<<serverIP);
- /////DBGMSG("Memcpy OK");
- }
- else
- {
- m_CommandSockAddr.sin_addr.s_addr = serverIP;
- }
- /* Set port number. */
- m_CommandSockAddr.sin_port = htons( 21 );
- /* Open a socket. */
- m_iCommandSocket = socket( AF_INET, SOCK_STREAM, 0 );
- if( m_iCommandSocket < 0 )
- {
- return( FTP_FAILED );
- }
- //////DBGMSG("Socket created");
- /* Set socket to non-blocking */
- uTemp = 1;
- if (Use_Non_Blocking_Mode()) {
- if( ioctlsocket( m_iCommandSocket, FIONBIO, &uTemp ) == SOCKET_ERROR )
- {
- return( FTP_FAILED );
- }
- }
- // Go ahead and advance the state....
- m_iStatus = FTPSTAT_CONNECTING;
- // Start the connection process....
- if( connect( m_iCommandSocket, (struct sockaddr *)&m_CommandSockAddr, sizeof( m_CommandSockAddr ) ) == -1 )
- {
- error = WSAGetLastError();
- if( ( error == WSAEWOULDBLOCK ) || ( error == WSAEINVAL ) || ( error == WSAEALREADY ) )
- {
- return( FTP_TRYING );
- }
- if( error != WSAEISCONN )
- {
- ////////DBGMSG("Connect failed");
- closesocket( m_iCommandSocket );
- return( FTP_FAILED );
- }
- }
- }
- if( m_iStatus == FTPSTAT_CONNECTING )
- {
- // Check to see if we're connected
- fd_set wset;
- fd_set eset;
- FD_ZERO(&wset);
- FD_ZERO(&eset);
- FD_SET(m_iCommandSocket,&wset);
- FD_SET(m_iCommandSocket,&eset);
- timeval tv;
- tv.tv_sec=0;
- tv.tv_usec=0;
- int retval=select(m_iCommandSocket+1,0,&wset,&eset,&tv);
- if (retval == 0) // not ready yet....
- return(FTP_TRYING);
- if (FD_ISSET(m_iCommandSocket, &eset)) {
- // OK, the exception flag is set, guess we couldn't connect....
- closesocket( m_iCommandSocket );
- return( FTP_FAILED );
- }
- if (FD_ISSET(m_iCommandSocket, &wset)) {
- // OK, the write flag is set, we're good to go...
- m_iStatus = FTPSTAT_WAITINGSERVEROK;
- }
- }
- if( m_iStatus == FTPSTAT_WAITINGSERVEROK )
- {
- iReply=0;
- if (RecvReply( buffer, 256, &iReply ) != FTP_SUCCEEDED)
- return(FTP_TRYING);
- if (iReply != FTPREPLY_SERVEROK)
- return(FTP_FAILED);
- m_iStatus = FTPSTAT_CONNECTED;
- return( FTP_SUCCEEDED );
- }
- return( FTP_FAILED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * STDMETHOD Cftp::LoginToServer( LPCSTR szUserName, LPCSTR szPassword )
- *
- * $_Description :
- * Logs into a server. ConnectToServer() must have succeeded before this
- * call is made.
- *
- * $_Parameters :
- * -> LPCSTR szUserName
- * The username under which to log in.
- *
- * -> LPCSTR szPassword
- * The password to use.
- *
- * $_ReturnValue :
- * FTP_TRYING until the login has succeeded, then FTP_SUCCEEDED.
- * FTP_FAILED on error.
- *
- ***************************************************************************/
- HRESULT Cftp::LoginToServer( LPCSTR szUserName, LPCSTR szPassword )
- {
- char command[ 256 ];
- int iReply;
- strncpy( m_szUserName, szUserName, 128 );
- strncpy( m_szPassword, szPassword, 128 );
- memset( command, 0, 256 );
- if( m_iStatus == FTPSTAT_CONNECTED )
- {
- sprintf( command, "USER %s\r\n", m_szUserName );
- if( SendCommand( command, 7 + strlen( m_szUserName ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGUSER;
- }
- if( m_iStatus == FTPSTAT_SENDINGUSER )
- {
- if(RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED )
- return( FTP_TRYING );
- if (iReply != FTPREPLY_PASSWORD)
- return( FTP_FAILED );
- m_iStatus = FTPSTAT_SENTUSER;
- }
- if( m_iStatus == FTPSTAT_SENTUSER )
- {
- sprintf( command, "PASS %s\r\n", m_szPassword );
- if( SendCommand( command, 7 + strlen( m_szPassword ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGPASS;
- }
- if( m_iStatus == FTPSTAT_SENDINGPASS )
- {
- if( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED )
- {
- return( FTP_TRYING );
- }
- if( iReply != FTPREPLY_LOGGEDIN )
- {
- if( iReply == FTPREPLY_CONTROLCLOSED )
- {
- return( FTP_FAILED );
- }
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_LOGGEDIN;
- return( FTP_SUCCEEDED );
- }
- return( FTP_FAILED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * STDMETHOD Cftp::LogoffFromServer( void )
- *
- * $_Description :
- * Logs off from a server. LoginToServer() must have succeeded before this
- * call is made.
- *
- * $_Parameters :
- * None.
- *
- * $_ReturnValue :
- * FTP_TRYING until the logoff has succeeded, then FTP_SUCCEEDED.
- * FTP_FAILED on error.
- *
- ***************************************************************************/
- HRESULT Cftp::LogoffFromServer( void )
- {
- char command[ 256 ];
- int iReply, iRetCode;
- memset( command, 0, 256 );
- switch( m_iStatus )
- {
- case FTPSTAT_LOGGINGOFF:
- if( SendCommand( "QUIT\r\n", 6 ) == FTP_SUCCEEDED )
- {
- m_iStatus = FTPSTAT_SENDINGQUIT;
- }
- else
- {
- return( FTP_FAILED );
- }
- case FTPSTAT_SENDINGQUIT:
- {
- char buf[ 50 ];
- if( ( iReply = RecvReply( buf, 50, &iRetCode ) ) == FTP_SUCCEEDED )
- {
- if( iRetCode == 221 )
- {
- //m_iStatus = FTPSTAT_SENTQUIT;
- //m_iStatus = FTPSTAT_INIT; // NAK
- CloseSockets();
- ZeroStuff();
- return( FTP_SUCCEEDED );
- }
- }
- else
- {
- if( iReply == FTP_FAILED )
- {
- return( FTP_FAILED );
- }
- return( FTP_TRYING );
- }
- }
- default:
- m_iStatus = FTPSTAT_LOGGINGOFF;
- return( FTP_TRYING );
- }
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::FindFile( LPCSTR szRemoteFileName, int * piSize )
- *
- * $_Description :
- * Locates a file on the remote server.
- *
- * $_Parameters :
- * -> LPCSTR szRemoteFileName
- * Full path and file name of the file to be downloaded.
- *
- * <- int * piSize
- * A pointer to an integer in which to return the size of the file, in bytes.
- *
- * $_ReturnValue :
- * FTP_SUCCEEDED on success. Otherwise FTP_TRYING, or FTP_FAILED on error.
- *
- * $_Warnings :
- * This function will continue to return FTP_TRYING if the file does not exist on
- * the server.
- *
- ***************************************************************************/
- HRESULT Cftp::FindFile( LPCSTR szRemoteFileName, int * piSize )
- {
- char command[ 256 ];
- static char listline[ 256 ];
- int i, iReply;
- char ext[ 10 ];
- if (m_findStart==0)
- m_findStart=time(NULL);
- if((time(NULL)-m_findStart) > 30) // try for 30 seconds
- {
- /////////DBGMSG("FindFile: Tried for too long");
- m_findStart=0;
- return( FTP_FAILED );
- }
- //strcpy(m_szRemoteFilePath, "/"); // start at home
- _splitpath( szRemoteFileName, NULL, m_szRemoteFilePath+strlen(m_szRemoteFilePath),
- m_szRemoteFileName, ext );
- strcat( m_szRemoteFileName, ext );
- for( i = 0; i < (int)strlen( m_szRemoteFilePath ); i++ )
- {
- if( m_szRemoteFilePath[ i ] == '\\' )
- {
- m_szRemoteFilePath[ i ] = '/';
- }
- }
- memset( command, 0, 256 );
- /* Change directory */
- if( ( m_iStatus == FTPSTAT_LOGGEDIN ) || ( m_iStatus == FTPSTAT_FILEFOUND ) )
- {
- sprintf( command, "CWD %s\r\n", m_szRemoteFilePath );
- if( SendCommand( command, 6 + strlen( m_szRemoteFilePath ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGCWD;
- }
- /* Get reply */
- if( m_iStatus == FTPSTAT_SENDINGCWD )
- {
- HRESULT reply=RecvReply( command, 256, &iReply );
- if ((reply == FTP_SUCCEEDED) && (iReply == 550)) {
- m_findStart=0;
- return(FTP_FAILED);
- }
- if( ( reply != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_CWDOK ) )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENTCWD;
- }
- /* Set up data connection port */
- if( m_iStatus == FTPSTAT_SENTCWD )
- {
- i = 0;
- while( SendNewPort() == FTP_TRYING )
- {
- i++;
- if( i == 1000 )
- {
- return( FTP_TRYING );
- }
- }
- m_iStatus = FTPSTAT_SENTPORT;
- }
- /* Get directory listing for file. */
- if( m_iStatus == FTPSTAT_SENTPORT )
- {
- sprintf( command, "LIST %s\r\n", m_szRemoteFileName );
- if( SendCommand( command, 7 + strlen( m_szRemoteFileName ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGLIST;
- }
- /* Get reply */
- if( m_iStatus == FTPSTAT_SENDINGLIST )
- {
- if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_OPENASCII ) )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENTLIST;
- }
- /* Open data connection */
- if( m_iStatus == FTPSTAT_SENTLIST )
- {
- i = OpenDataConnection();
- if( i != FTP_SUCCEEDED )
- {
- /////////DBGMSG("FindFile: OpenDataConnection failed: "<<i);
- m_findStart=0;
- return( i );
- }
- m_iStatus = FTPSTAT_LISTDATAOPEN;
- memset( listline, 0, 256 );
- }
- /* Get data */
- if( m_iStatus == FTPSTAT_LISTDATAOPEN )
- {
- RecvData( listline, 256 );
- if( strlen( listline ) == 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_LISTDATARECVD;
- }
- /* Wait for confirmation of end of data stream */
- if( m_iStatus == FTPSTAT_LISTDATARECVD )
- {
- if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_COMPLETE ) )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_FILEFOUND;
- }
- CloseDataConnection();
- m_findStart=0;
- /* Is the file there? */
- if( strncmp( listline, m_szRemoteFileName, sizeof( m_szRemoteFileName ) ) == 0 )
- {
- /* No */
- ////////DBGMSG("FindFile: File not in list: "<<listline);
- return( FTP_FAILED );
- }
- /* Yes - find out the size, in bytes */
- if( sscanf( &listline[ 32 ], " %d ", &i ) == 1 )
- {
- if( piSize != NULL )
- {
- *piSize = i;
- m_iFileSize = i;
- }
- return( FTP_SUCCEEDED );
- }
-
- ////////DBGMSG("Default fail case: "<<listline);
- return( FTP_FAILED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::SendCommand( LPCSTR pCommand, int iSize )
- *
- * $_Description :
- * Sends a command to the server. Commands are strings terminated with
- * "\r\n"
- *
- * $_Parameters :
- * LPCSTR pCommand
- * A pointer to a command
- *
- * int iSize
- * The size of the command in bytes.
- *
- * $_ReturnValue :
- * FTP_SUCCEEDED on success, or FTP_FAILED on error.
- *
- ***************************************************************************/
- HRESULT Cftp::SendCommand( LPCSTR pCommand, int iSize )
- {
- int i;
-
- i = send( m_iCommandSocket, pCommand, iSize, 0 );
- if( i > 0 )
- {
- #ifdef _DEBUG
- OutputDebugString( "-->" );
- OutputDebugString( pCommand );
- #endif
- return( FTP_SUCCEEDED );
- }
- else
- {
- return( FTP_FAILED );
- }
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode )
- *
- * $_Description :
- * Receives a reply from the server and extracts the numerical reply
- * code.
- *
- * $_Parameters :
- * -> LPCSTR pReplyBuffer
- * A buffer for the reply - must be specified and be at least 4 bytes in
- * length.
- *
- * -> iSize
- * The size of the reply buffer.
- *
- * <- piRetCode
- * A pointer to an integer to store the numeric return code for the message received.
- *
- * $_ReturnValue :
- * FTP_SUCCEEDED on success, FTP_FAILED otherwise.
- *
- ***************************************************************************/
- HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode )
- {
- int readval;
- char * pc = (char *)pReplyBuffer;
- while(1) {
- // Preview whats on the socket so we can make the decision if there is enough
- // there to use.
- readval = recv(m_iCommandSocket, pc, iSize-1, MSG_PEEK);
- pc[iSize-1]=0;
- if (readval > 0)
- pc[readval]=0;
- // Did the endpoint close?
- if (readval < 0) {
- if ((WSAGetLastError() == WSAECONNRESET ) || ((WSAGetLastError() == WSAENOTCONN)))
- readval=0;
- else {
- // nothing to read right now....
- return(FTP_TRYING);
- }
- }
- if (readval == 0) {
- // endpoint closed
- *piRetCode=FTPREPLY_CONTROLCLOSED;
- return(FTP_SUCCEEDED); // we succeeded in getting a reply
- }
- if (readval < 3) // minimal response
- return(FTP_TRYING);
- // Verify that this is a complete line, if not we will keep trying til
- // we have one.
- char *end=strstr(pc, "\r\n");
- if (end == 0)
- return(FTP_TRYING);
- // OK, we've got a line, pull it from the socket...
- recv(m_iCommandSocket, pc, end-pc+strlen("\r\n"), 0);
- #ifdef _DEBUG
- OutputDebugString( "<--" );
- OutputDebugString( pc );
- #endif
- // Is this an unrecognized command? It's probably in response to our BOGUSCOMMAND, ignore it.
- // If we got this for some other reason then this FTP server doesn't support our required command set.
- // If this were a general purpose FTP library we probably couldn't get away with this because it's pretty lame.
- const char *BOGUS_RESPONSE="500";
- if (_strnicmp(pc, BOGUS_RESPONSE, strlen(BOGUS_RESPONSE))==0)
- continue;
- // If the line starts with a non-digit then we ignore it...
- if (isdigit(pc[0])==0)
- continue;
- if (piRetCode)
- *piRetCode=atol(pc);
- return( FTP_SUCCEEDED );
- }
- }
- /*$_Function****************************************************************
- * $_Name :
- * unsigned long MyIPAddress( int sockfd )
- *
- * $_Description :
- * Finds the IP address of the local host.
- *
- * $_Parameters :
- * -> int sockfd
- * An optional socket descriptor - if this is given and the socket is connected
- * then the answer will guaranteed to be on the same interface as the connected
- * socket.
- *
- * $_ReturnValue :
- * A unsigned integer containing the IP address of the local host.
- *
- ***************************************************************************/
- unsigned long MyIPAddress( int sockfd )
- {
- int test = 99;
- int i;
- char pBuffer[ 256 ];
- char * pAddr;
- struct hostent * pHE;
- unsigned long ip;
- struct sockaddr_in sin;
- if( sockfd != -1 )
- {
- i = sizeof( sin );
- getsockname( sockfd, (struct sockaddr *)&sin, &i );
- ip = sin.sin_addr.S_un.S_addr;
- }
- else
- {
- /* Get this machine's name. */
- if( gethostname( pBuffer, 256 ) != 0 )
- {
- return( FTP_FAILED );
- }
- /* Look up the machine in "DNS" or whatever. */
- pHE = gethostbyname( pBuffer );
- if( pHE == NULL )
- {
- return( FTP_FAILED );
- }
- /* Find a good IP address. */
- ip = 0;
- i = 0;
-
- while( ( pAddr = pHE->h_addr_list[ i++ ] ) != NULL )
- {
- ip = *((unsigned long *)pAddr );
- if( ( ip != 0 ) && ( ip != inet_addr( "127.0.0.1" ) ) )
- {
- break;
- }
- else
- {
- ip = 0;
- }
- }
- }
- if( ip == 0 )
- {
- return( FTP_FAILED );
- }
- return( ip );
- }
- /*$_Function****************************************************************
- * $_Name :
- * int Cftp::SendNewPort( void )
- *
- * $_Description :
- * Sends a PORT command to the server specifying a new ephemeral port to
- * use for a data connection. Opens the port in the process.
- *
- * $_Parameters :
- * bool reset
- * Should be TRUE for the first attempt, FALSE subsequently.
- *
- * $_ReturnValue :
- * FTP_SUCCEEDED on success, FTP_FAILED on error, FTP_TRYING while
- * going through the stages.
- *
- ***************************************************************************/
- int Cftp::SendNewPort( void )
- {
- unsigned long uTemp;
- char command[ 256 ];
- int i, iReply;
- /* Open a socket */
- if( m_sendNewPortStatus == 0 )
- {
- m_iDataSocket = socket( AF_INET, SOCK_STREAM, 0 );
- if( m_iDataSocket < 0 )
- {
- return( FTP_FAILED );
- }
- /* Set socket to non-blocking */
- uTemp = 1;
- if (Use_Non_Blocking_Mode()) {
- if( ioctlsocket( m_iCommandSocket, FIONBIO, &uTemp ) == SOCKET_ERROR )
- {
- return( FTP_FAILED );
- }
- }
- memset( &m_DataSockAddr, 0, sizeof( m_DataSockAddr ) );
- m_DataSockAddr.sin_family = AF_INET;
- m_DataSockAddr.sin_addr.s_addr = htonl( INADDR_ANY );
- m_DataSockAddr.sin_port = 0; // Winsock fills in an ephemeral port during bind...
- if( bind( m_iDataSocket, (struct sockaddr *)&m_DataSockAddr, sizeof( m_DataSockAddr ) ) < 0 )
- {
- return( FTP_FAILED );
- }
- i = sizeof( m_DataSockAddr);
- getsockname( m_iDataSocket, (struct sockaddr *)&m_DataSockAddr, &i );
- listen( m_iDataSocket, 5 );
- // Set socket to non-blocking
- uTemp = 1;
- if (Use_Non_Blocking_Mode()) {
- if( ioctlsocket( m_iDataSocket, FIONBIO, &uTemp ) == SOCKET_ERROR )
- {
- return( FTP_FAILED );
- }
- }
- m_sendNewPortStatus = 1;
- }
- /* Send a port command. */
- if( m_sendNewPortStatus == 1 )
- {
- memset( command, 0, 256 );
- i = MyIPAddress( m_iCommandSocket );
- if( i == FTP_FAILED )
- {
- return( FTP_FAILED );
- }
- sprintf( command, "PORT %d,%d,%d,%d,%d,%d\r\n",
- i & 0xFF,
- ( i >> 8 ) & 0xFF,
- ( i >> 16 ) & 0xFF,
- ( i >> 24 ) & 0xFF,
- m_DataSockAddr.sin_port & 0xFF,
- m_DataSockAddr.sin_port >> 8 );
- if( SendCommand( command, strlen(command) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_sendNewPortStatus = 2;
- }
- /* Get reply */
- if( m_sendNewPortStatus == 2 )
- {
- if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_PORTOK ) )
- {
- return( FTP_TRYING );
- }
- m_sendNewPortStatus = 0;
- }
- return( FTP_SUCCEEDED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * int Cftp::OpenDataConnection()
- *
- * $_Description :
- * Opens the data connection to the server. Actually, the socket for the
- * data connection should have been opened by a call to SendNewPort before
- * this method is called - this just calls accept.
- *
- * $_Parameters :
- * None.
- *
- * $_ReturnValue :
- * FTP_SUCCEEDED on success, FTP_FAILED otherwise.
- *
- * $_Warnings :
- * This call may block.
- *
- ***************************************************************************/
- int Cftp::OpenDataConnection()
- {
- int iNewSocket;
- if( m_iDataSocket == 0 )
- {
- return( FTP_FAILED );
- }
- if( ( iNewSocket = accept( m_iDataSocket, NULL, 0 ) ) < 0 )
- {
- if( WSAGetLastError() != (WSAEWOULDBLOCK ) )
- {
- return( FTP_FAILED );
- }
- else
- {
- return( FTP_TRYING );
- }
- }
- m_iDataSocket = iNewSocket;
- return( FTP_SUCCEEDED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * void Cftp::CloseDataConnection()
- *
- * $_Description :
- * Closes the data connection.
- *
- * $_Parameters :
- * None.
- *
- * $_ReturnValue :
- * None.
- *
- ***************************************************************************/
- void Cftp::CloseDataConnection()
- {
- closesocket( m_iDataSocket );
- m_iDataSocket = 0;
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::DisconnectFromServer()
- *
- * $_Description :
- * Disconnects from the server.
- *
- * $_Parameters :
- * None.
- *
- * $_ReturnValue :
- * None.
- *
- ***************************************************************************/
- HRESULT Cftp::DisconnectFromServer()
- {
- // Make the download file read-only so it's still there the next time
- // we're run.
- closesocket( m_iCommandSocket );
- return( FTP_SUCCEEDED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * int Cftp::SendData( char * pData, int iSize )
- *
- * $_Description :
- * Sends data to the server.
- *
- * $_Parameters :
- * -> char * pData
- * A pointer to some data to be sent.
- *
- * -> int iSize
- * The size, in bytes, of the data.
- *
- * $_ReturnValue :
- * The number of bytes sent, or -1 on error.
- *
- ***************************************************************************/
- int Cftp::SendData( char * pData, int iSize )
- {
- return( send( m_iDataSocket, pData, iSize, 0 ) );
- }
- /*$_Function****************************************************************
- * $_Name :
- * int Cftp::RecvData( char * pData, int iSize )
- *
- * $_Description :
- * Receives data from the server.
- *
- * $_Parameters :
- * -> LPCSTR pData
- * A pointer to a buffer for the data to be received.
- *
- * -> int iSize
- * The size, in bytes, of the data buffer.
- *
- * $_ReturnValue :
- * The number of bytes received, or -1 on error.
- *
- ***************************************************************************/
- int Cftp::RecvData( char * pData, int iSize )
- {
- /***** testing...
- int readval = recv(m_iDataSocket, pData, iSize, MSG_PEEK);
- if (readval <= 0) // If there's nothing to read, don't read now...
- return(readval);
- ******/
- return( recv( m_iDataSocket, pData, iSize, 0 ) );
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead )
- *
- * $_Description :
- * Retrieves the next block of data from the remote file and writes it into
- * the local file. Deals with opening the local file and restarting a
- * failed transfer if FileRecoveryPosition() returns non-zero. To prevent
- * a restart after FileRecoveryPosition() returns non-zero, call
- * Cftp::RestartFrom() with 0 as the offset parameter.
- *
- * The file is initally written to a temporary file and then copied to the local
- * file name when the transfer is complete. If the transfer is halted, the
- * temporary file will be used as the starting point for subsequent retries.
- *
- * $_Parameters :
- * -> LPCSTR szLocalFileName
- * A pointer to a string containing the local file name for the transferred file.
- *
- * <- int * piTotalRead
- * A pointer to an integer in which to store the total number of bytes
- * transferred so far.
- *
- * $_ReturnValue :
- * FTP_TRYING while the transfer is in progress, FTP_SUCCEEDED on completion,
- * FTP_FAILED on error.
- *
- ***************************************************************************/
- HRESULT Cftp::GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead )
- {
- char command[ 256 ];
- int read, totread = 0;
- const int max_data_len=10240;
- char data[ max_data_len ];
- int res, iReply;
- char downloadfilename[256];
- GetDownloadFilename(szLocalFileName, downloadfilename);
- //char str[ 256 ];
- strncpy( m_szLocalFileName, szLocalFileName, 256 );
- // Open local file
- if( m_iStatus == FTPSTAT_FILEFOUND )
- {
- if( m_iFilePos == 0 )
- {
- if( ( m_pfLocalFile = fopen( downloadfilename, "wb" ) ) == NULL )
- {
- return( FTP_FAILED );
- }
- }
- else
- {
- if( ( m_pfLocalFile = fopen( downloadfilename, "ab" ) ) == NULL )
- {
- return( FTP_FAILED );
- }
- }
- m_iStatus = FTPSTAT_FILEOPEN;
- }
- // Send the PORT command
- if( m_iStatus == FTPSTAT_FILEOPEN )
- {
- if( SendNewPort() == FTP_SUCCEEDED )
- {
- m_iStatus = FTPSTAT_SENTFILEPORT;
- }
- else
- {
- return( FTP_TRYING );
- }
- }
- // Set type to BINARY
- if( m_iStatus == FTPSTAT_SENTFILEPORT )
- {
- sprintf( command, "TYPE I\r\n");
- if( SendCommand( command, strlen( command ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGTYPE;
- }
- /* Get reply */
- if( m_iStatus == FTPSTAT_SENDINGTYPE )
- {
- if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_TYPEOK ) )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENTTYPE;
- }
- // Send the RESTART command - if we are restarting a previous transfer.
- if( m_iStatus == FTPSTAT_SENTTYPE )
- {
- if( m_iFilePos == 0 )
- {
- m_iStatus = FTPSTAT_SENTREST;
- }
- else
- {
- sprintf( command, "REST %d\r\n", m_iFilePos );
- if( SendCommand( command, strlen( command ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGREST;
- }
- }
- /* Get reply */
- if( m_iStatus == FTPSTAT_SENDINGREST )
- {
- HRESULT res=RecvReply( command, 256, &iReply );
- if ((res == FTP_FAILED) || (iReply == 502)) // unsupported command
- {
- m_iFilePos=0;
- fclose(m_pfLocalFile);
- m_pfLocalFile = fopen( downloadfilename, "wb" );
- }
- else if( ( res != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_RESTARTOK ) )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENTREST;
- }
- // Send the RETR command
- if( m_iStatus == FTPSTAT_SENTREST )
- {
- sprintf( command, "RETR %s\r\n", m_szRemoteFileName );
- if( SendCommand( command, strlen( command ) ) < 0 )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENDINGRETR;
- }
- /* Get reply */
- if( m_iStatus == FTPSTAT_SENDINGRETR )
- {
- if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
- ( iReply != FTPREPLY_OPENBINARY ) )
- {
- return( FTP_TRYING );
- }
- m_iStatus = FTPSTAT_SENTRETR;
- }
- /* Open data connection */
- if( m_iStatus == FTPSTAT_SENTRETR )
- {
- res = OpenDataConnection();
- if( res != FTP_SUCCEEDED )
- {
- return( res );
- }
- m_iStatus = FTPSTAT_FILEDATAOPEN;
- }
- /* Get data */
- if( m_iStatus == FTPSTAT_FILEDATAOPEN )
- {
- do
- {
- read = RecvData( data, max_data_len );
- if( read > 0 )
- {
- fwrite( data, 1, read, m_pfLocalFile );
- totread += read;
- }
- }
- while( ( read > 0 ) && ( totread < (max_data_len * 20) ) ); // Don't read too much -
- // must not block for too long
- m_iFilePos += totread; // update read position
- if( piTotalRead != NULL )
- *piTotalRead = m_iFilePos;
- // look for all notices about endpoint closed...
- if (read < 0) {
- int wsa_err=WSAGetLastError();
- if ((wsa_err == WSAECONNRESET) || (wsa_err == WSAENOTCONN))
- read = 0; // just treat it as a close....
- }
- /* See if the download has finished */
- if( read == 0 )
- {
- // Data connection reset
- if( m_iFilePos != m_iFileSize ) {
- // Haven't got all the data
- return( FTP_FAILED );
- } else {
- // got all the data and the connection is closed so mark it so
- m_iStatus = FTPSTAT_FILEDATACLOSED;
- }
- } else {
- return( FTP_TRYING );
- }
- }
- // if we have gotten to here, we have all the data and the connection is
- // closed. The case where the connection was closed but we didn't get
- // everything is handled above.
- if( m_iStatus == FTPSTAT_FILEDATACLOSED ) {
- CloseDataConnection();
- fclose( m_pfLocalFile );
- m_pfLocalFile = NULL;
- /*
- * Move the file from the temporary download location to its
- * final resting place
- */
- char downloadfilename[256];
- GetDownloadFilename(m_szLocalFileName, downloadfilename);
- // Make sure the path exists for the new file
- char curdir[256];
- _getcwd(curdir,256);
- Prepare_Directories(curdir, m_szLocalFileName);
- DEBUG_LOG(("CWD: %s\n", curdir));
- if( rename( downloadfilename, m_szLocalFileName ) != 0 ) {
- DEBUG_LOG(("First rename of %s to %s failed with errno of %d\n", downloadfilename, m_szLocalFileName, errno));
- /* Error moving file - remove file that's already there and try again. */
- _chmod( m_szLocalFileName, _S_IWRITE | _S_IREAD); // make sure it's not readonly
- DEBUG_LOG(("_chmod of %s failed with errno of %d\n", m_szLocalFileName, errno));
- remove( m_szLocalFileName );
- DEBUG_LOG(("remove of %s failed with errno of %d\n", m_szLocalFileName, errno));
- if( rename( downloadfilename, m_szLocalFileName ) != 0 ) {
- DEBUG_LOG(("Second rename of %s to %s failed with errno of %d\n", downloadfilename, m_szLocalFileName, errno));
- return( FTP_FAILED );
- }
- }
- // Send a bogus command. If the firewall has closed our ftp command channel connection this
- // will allow us to detect it. (Obviously the data channel is closed or we wouldn't be here)
- // There are cases (firewall) where the connection will go away without having a close command
- // but writing to it will allow us to detect this case.
- // We will ignore the response because we don't know in which order the server will respond
- SendCommand("BOGUSCOMMAND\r\n", strlen("BOGUSCOMMAND\r\n"));
- OutputDebugString("File closed, waiting for response.\n");
- m_iStatus = FTPSTAT_TRANSFERREPLY;
- }
- if( m_iStatus == FTPSTAT_TRANSFERREPLY ) {
- iReply=0;
- // Get the file complete reply
- if (RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED )
- return(FTP_TRYING);
- if (iReply == FTPREPLY_CONTROLCLOSED) {
- m_iStatus = FTPSTAT_INIT;
- m_iFilePos=0;
- CloseSockets();
- } else {
- m_iStatus = FTPSTAT_LOGGEDIN;
- m_iFilePos=0;
- }
- return(FTP_SUCCEEDED);
- }
- return( FTP_FAILED );
- }
- /*$_Function****************************************************************
- * $_Name :
- * HRESULT Cftp::FileRecoveryPosition( LPCSTR szLocalFileName )
- *
- * $_Description :
- * Finds the size of the specified file. This size can be used
- *
- * $_Parameters :
- * char & szLocalFileName
- * The full path name of the local file.
- *
- * $_ReturnValue :
- * The size of that file on the local disk. 0 if the file does not exist.
- *
- ***************************************************************************/
- //
- // Do we have this file in the download directory? If so then it's a partial download.
- //
- //
- HRESULT Cftp::FileRecoveryPosition( LPCSTR szLocalFileName, LPCSTR szRegistryRoot )
- {
- char downloadfilename[256];
- GetDownloadFilename(szLocalFileName, downloadfilename);
- FILE *testfp = fopen( downloadfilename, "rb" );
- if( testfp == NULL )
- {
- m_iFilePos = 0;
- return 0;
- }
- fseek( testfp, 0, SEEK_END );
- m_iFilePos = ftell( testfp );
- fclose( testfp );
- return( m_iFilePos );
- }
- /*************8
- FILE * testfp;
- HKEY hkey;
- unsigned char regfilename[ 256 ];
- char regkey[ 512 ];
- unsigned long t1, t2;
- if( ( szRegistryRoot == NULL ) || ( szLocalFileName == NULL ) )
- {
- // Bail out
- return( 0 );
- }
- // Concatenate the registry key together
- strcpy( regkey, szRegistryRoot );
- if( regkey[ strlen( regkey ) - 1 ] != '\\' )
- {
- strcat( regkey, "\\Download" );
- }
- else
- {
- strcat( regkey, "Download" );
- }
- if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, (LPCTSTR)regkey,
- 0, KEY_ALL_ACCESS, &hkey ) != ERROR_SUCCESS )
- {
- // Key doesn't exist, create it
- if( RegCreateKey( HKEY_LOCAL_MACHINE, (LPCTSTR)regkey,
- &hkey ) != ERROR_SUCCESS )
- {
- // Error, bail out
- return( 0 );
- }
- RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 );
- RegCloseKey(hkey);
- return( 0 );
- }
- t2 = 256;
- if( RegQueryValueEx( hkey, (LPCTSTR)"File", 0, &t1, regfilename, &t2 ) != ERROR_SUCCESS )
- {
- RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 );
- RegCloseKey(hkey);
- return( 0 );
- }
- if( strcmp( szLocalFileName, (const char *)regfilename ) == 0 )
- {
- // File previously downloaded
- testfp = fopen( FTP_TEMPFILENAME, "rb" );
- if( testfp == NULL )
- {
- m_iFilePos = 0;
- RegCloseKey(hkey);
- return 0;
- }
- fseek( testfp, 0, SEEK_END );
- m_iFilePos = ftell( testfp );
- fclose( testfp );
- RegCloseKey(hkey);
- return( m_iFilePos );
- }
- // Download file doesn't exist
- RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 );
- RegCloseKey(hkey);
- // get rid of any temp downloads
- _unlink(FTP_TEMPFILENAME);
- return( 0 );
- }
- **************************************/
- //
- // convert a local name to a temp filename to use for downloading
- //
- void Cftp::GetDownloadFilename(const char *localname, char *downloadname)
- {
- char *name = strdup(localname);
- char *s = name;
- while (*s)
- {
- if (*s == '\\' || *s == '.' || *s == ' ')
- *s = '_';
- ++s;
- }
- sprintf(downloadname,"download\\%s_%d.tmp",name,m_iFileSize);
- free(name);
- /*
- Wstring name;
- name.set(localname);
- name.replace("\\","_");
- name.replace(".","_");
- name.replace(" ","_");
- sprintf(downloadname,"download\\%s_%d.tmp",name.get(),m_iFileSize);
- */
- return;
- }
- //
- // Build all the subdirectories for a given filename
- //
- bool Prepare_Directories(const char *rootdir, const char *filename)
- {
- char tempstr[256];
- char newdir[256];
- const char *cptr=filename;
- while(cptr=strchr(cptr,'\\'))
- {
- memset(tempstr,0,256);
- strncpy(tempstr,filename,cptr-filename);
- sprintf(newdir,"%s\\%s",rootdir, tempstr);
- if (!CreateDirectory(newdir, NULL))
- return false;
- //if ((_mkdir(newdir) == -1) && ((errno == ENOENT || errno==EACCES)))
- //return(false);
- cptr++;
- }
- return(true);
- }
|