FTP.CPP 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /*
  2. ** Command & Conquer Generals(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. // ftp.cpp : Implementation of Cftp
  19. /*************************************************************************/
  20. /*_$ Include Files */
  21. /*************************************************************************/
  22. #include <stdio.h>
  23. #include <sys/types.h>
  24. #include <sys/timeb.h>
  25. #include <stdlib.h>
  26. #include <process.h>
  27. #include <sys/stat.h>
  28. #include <io.h>
  29. #include <time.h>
  30. #include "assert.h"
  31. #include "ftp.h"
  32. #include "winsock.h"
  33. #include <time.h>
  34. #include <direct.h>
  35. #include <errno.h>
  36. //#include "wlib/wstring.h"
  37. #include "DownloadDebug.h"
  38. // umm... what?? BGC 3/27/03
  39. //#ifndef _DEBUG
  40. //#define _DEBUG
  41. //#endif
  42. /*************************************************************************/
  43. /*_$ External References */
  44. /*************************************************************************/
  45. /*************************************************************************/
  46. /*_$ Private Datatypes */
  47. /*************************************************************************/
  48. /*************************************************************************/
  49. /*_$ Public Data */
  50. /*************************************************************************/
  51. /*************************************************************************/
  52. /*_$ Private Data */
  53. /*************************************************************************/
  54. //static HOSTENT gThreadHost;
  55. struct sockaddr_in gThreadAddress;
  56. static int gThreadFlag;
  57. /*************************************************************************/
  58. /*_$ Private Prototypes */
  59. /*************************************************************************/
  60. /*************************************************************************/
  61. /*_$ Private Macros */
  62. /*************************************************************************/
  63. /* Status flags */
  64. #define FTPSTAT_INIT 0
  65. #define FTPSTAT_CONNECTING 10
  66. #define FTPSTAT_WAITINGSERVEROK 15
  67. #define FTPSTAT_CONNECTED 20
  68. #define FTPSTAT_SENDINGUSER 30
  69. #define FTPSTAT_SENTUSER 40
  70. #define FTPSTAT_SENDINGPASS 50
  71. #define FTPSTAT_LOGGEDIN 60
  72. #define FTPSTAT_LOGGINGOFF 70
  73. #define FTPSTAT_SENDINGQUIT 80
  74. #define FTPSTAT_SENTQUIT 90
  75. #define FTPSTAT_FILEFOUND 100
  76. #define FTPSTAT_SENDINGCWD 110
  77. #define FTPSTAT_SENTCWD 120
  78. #define FTPSTAT_SENTPORT 130
  79. #define FTPSTAT_SENDINGLIST 140
  80. #define FTPSTAT_SENTLIST 150
  81. #define FTPSTAT_LISTDATAOPEN 160
  82. #define FTPSTAT_LISTDATARECVD 170
  83. #define FTPSTAT_FILEOPEN 180
  84. #define FTPSTAT_SENTFILEPORT 190
  85. #define FTPSTAT_SENDINGTYPE 200
  86. #define FTPSTAT_SENTTYPE 210
  87. #define FTPSTAT_SENDINGREST 220
  88. #define FTPSTAT_SENTREST 230
  89. #define FTPSTAT_SENDINGRETR 240
  90. #define FTPSTAT_SENTRETR 250
  91. #define FTPSTAT_FILEDATAOPEN 260
  92. #define FTPSTAT_FILEDATACLOSED 270
  93. #define FTPSTAT_TRANSFERREPLY 280
  94. // Utility functions
  95. bool Prepare_Directories(const char *rootdir, const char *filename);
  96. //
  97. // This is here as a hack...
  98. // Some firewalls break the TCP stack so non-blocking sockets don't work right...
  99. //
  100. static bool Use_Non_Blocking_Mode(void)
  101. {
  102. HKEY regKey;
  103. LONG regRetval;
  104. DWORD bufsiz=0;
  105. DWORD type=0;
  106. DWORD value=0;
  107. // Try and open the named key
  108. regRetval=RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Westwood\\Earth And Beyond Beta 2",0,KEY_READ,&regKey);
  109. if (regRetval!=ERROR_SUCCESS)
  110. return(TRUE); // default TRUE
  111. // Fetch the flag
  112. bufsiz=sizeof(value);
  113. type=REG_DWORD;
  114. regRetval=RegQueryValueEx(regKey, "UseNonBlockingFTP", 0, &type, (BYTE*) &value, &bufsiz);
  115. RegCloseKey(regKey);
  116. if ((regRetval!=ERROR_SUCCESS) || (type != REG_DWORD))
  117. return(TRUE);
  118. return(bool(value));
  119. }
  120. /////////////////////////////////////////////////////////////////////////////
  121. // Cftp
  122. /*$_Function****************************************************************
  123. * $_Name :
  124. * Cftp::Cftp()
  125. *
  126. * $_Description :
  127. * Constructor for the ftp class - initialises more or less all data
  128. * members to zero.
  129. *
  130. * $_Parameters :
  131. * None.
  132. *
  133. * $_ReturnValue :
  134. * None.
  135. *
  136. ***************************************************************************/
  137. Cftp::Cftp()
  138. {
  139. ZeroStuff();
  140. }
  141. /*$_Function****************************************************************
  142. * $_Name :
  143. * Cftp::Cftp()
  144. *
  145. * $_Description :
  146. * Destructor for the ftp class - close sockets behind us as we leave.
  147. *
  148. * $_Parameters :
  149. * None.
  150. *
  151. * $_ReturnValue :
  152. * None.
  153. *
  154. ***************************************************************************/
  155. Cftp::~Cftp()
  156. {
  157. CloseSockets();
  158. if (m_pfLocalFile)
  159. {
  160. fclose(m_pfLocalFile);
  161. m_pfLocalFile = NULL;
  162. }
  163. }
  164. void Cftp::CloseSockets(void)
  165. {
  166. if( m_iDataSocket )
  167. {
  168. closesocket( m_iDataSocket );
  169. m_iDataSocket=0;
  170. }
  171. if( m_iCommandSocket )
  172. {
  173. closesocket( m_iCommandSocket );
  174. m_iCommandSocket=0;
  175. }
  176. }
  177. void Cftp::ZeroStuff(void)
  178. {
  179. m_iBytesRead = 0;
  180. m_iFileSize = 0;
  181. m_szRemoteFilePath[ 0 ] = (char)0;
  182. m_szRemoteFileName[ 0 ] = (char)0;
  183. m_szLocalFilePath[ 0 ] = (char)0;
  184. m_szLocalFileName[ 0 ] = (char)0;
  185. m_szServerName[ 0 ] = (char)0;
  186. m_szUserName[ 0 ] = (char)0;
  187. m_szPassword[ 0 ] = (char)0;
  188. m_iDataSocket = 0;
  189. m_iCommandSocket = 0;
  190. m_iFilePos = 0;
  191. m_iStatus = FTPSTAT_INIT;
  192. m_sendNewPortStatus = 0;
  193. m_pfLocalFile = NULL;
  194. m_findStart = 0;
  195. memset(&m_CommandSockAddr, 0, sizeof(m_CommandSockAddr));
  196. memset(&m_DataSockAddr, 0, sizeof(m_DataSockAddr));
  197. }
  198. DWORD WINAPI gethostbynameA( void * szName )
  199. {
  200. HOSTENT *he = gethostbyname( (const char *)szName );
  201. //////DBGMSG("Hostname copy start");
  202. if (he)
  203. memcpy((char *)&(gThreadAddress.sin_addr), he->h_addr, he->h_length );
  204. else
  205. memcpy((char *)&(gThreadAddress.sin_addr),"",strlen("")+1);
  206. /////DBGMSG("Hostname copy complete");
  207. gThreadFlag = 1;
  208. return 0;
  209. }
  210. int Cftp::AsyncGetHostByName(char * szName, struct sockaddr_in &address )
  211. {
  212. static int stat = 0;
  213. static unsigned long threadid;
  214. if( stat == 0 )
  215. {
  216. /* Kick off gethostname thread */
  217. gThreadFlag = 0;
  218. memset(&gThreadAddress,0,sizeof(gThreadAddress));
  219. if( CreateThread( NULL, 0, gethostbynameA, szName, 0, &threadid ) == NULL )
  220. {
  221. return( FTP_FAILED );
  222. }
  223. stat = 1;
  224. }
  225. if( stat == 1 )
  226. {
  227. if( gThreadFlag )
  228. {
  229. /* Thread finished */
  230. address = gThreadAddress;
  231. address.sin_family=AF_INET;
  232. stat = 0;
  233. return( FTP_SUCCEEDED );
  234. }
  235. }
  236. return( FTP_TRYING );
  237. }
  238. /*$_Function****************************************************************
  239. * $_Name :
  240. * HRESULT Cftp::ConnectToServer(LPCSTR szServerName)
  241. *
  242. * $_Description :
  243. * Overloaded funciton that makes a connection to a server. Will probably
  244. * fail on (at least) the first call, as it may take a while for the server
  245. * to send it's "ready" reply.
  246. *
  247. * $_Parameters :
  248. * -> const char * szServerName
  249. * Optionally, the name of the server to connect to. This must be specified
  250. * in the first call to the function.
  251. *
  252. * $_ReturnValue :
  253. * FTP_TRYING until the connection has succeeded, then FTP_SUCCEEDED.
  254. * FTP_FAILED on error.
  255. *
  256. ***************************************************************************/
  257. HRESULT Cftp::ConnectToServer(LPCSTR szServerName)
  258. {
  259. struct sockaddr_in address;
  260. unsigned long uTemp;
  261. unsigned long serverIP;
  262. char buffer[ 256 ];
  263. int iReply, error;
  264. strncpy( m_szServerName, szServerName, 128 );
  265. if( m_iStatus == FTPSTAT_INIT )
  266. {
  267. /* Find the IP address of the server */
  268. serverIP = inet_addr( m_szServerName );
  269. memset( &m_CommandSockAddr, 0, sizeof( m_CommandSockAddr ) );
  270. m_CommandSockAddr.sin_family = AF_INET;
  271. if( serverIP == INADDR_NONE )
  272. {
  273. /* It's an FQDN - hopefully. */
  274. ////////DBGMSG("Async gethostbyname");
  275. if( AsyncGetHostByName( m_szServerName, address ) == FTP_TRYING )
  276. {
  277. return( FTP_TRYING );
  278. }
  279. //////DBGMSG("Got hostbyname");
  280. if( address.sin_addr.s_addr == 0 )
  281. {
  282. ///////DBGMSG("gethostbyname failed");
  283. return( FTP_FAILED );
  284. }
  285. m_CommandSockAddr=address;
  286. ///////memcpy( (char *)&(m_CommandSockAddr.sin_addr), he.h_addr, he.h_length );
  287. serverIP = m_CommandSockAddr.sin_addr.s_addr;
  288. //////DBGMSG("ServerIP = "<<serverIP);
  289. /////DBGMSG("Memcpy OK");
  290. }
  291. else
  292. {
  293. m_CommandSockAddr.sin_addr.s_addr = serverIP;
  294. }
  295. /* Set port number. */
  296. m_CommandSockAddr.sin_port = htons( 21 );
  297. /* Open a socket. */
  298. m_iCommandSocket = socket( AF_INET, SOCK_STREAM, 0 );
  299. if( m_iCommandSocket < 0 )
  300. {
  301. return( FTP_FAILED );
  302. }
  303. //////DBGMSG("Socket created");
  304. /* Set socket to non-blocking */
  305. uTemp = 1;
  306. if (Use_Non_Blocking_Mode()) {
  307. if( ioctlsocket( m_iCommandSocket, FIONBIO, &uTemp ) == SOCKET_ERROR )
  308. {
  309. return( FTP_FAILED );
  310. }
  311. }
  312. // Go ahead and advance the state....
  313. m_iStatus = FTPSTAT_CONNECTING;
  314. // Start the connection process....
  315. if( connect( m_iCommandSocket, (struct sockaddr *)&m_CommandSockAddr, sizeof( m_CommandSockAddr ) ) == -1 )
  316. {
  317. error = WSAGetLastError();
  318. if( ( error == WSAEWOULDBLOCK ) || ( error == WSAEINVAL ) || ( error == WSAEALREADY ) )
  319. {
  320. return( FTP_TRYING );
  321. }
  322. if( error != WSAEISCONN )
  323. {
  324. ////////DBGMSG("Connect failed");
  325. closesocket( m_iCommandSocket );
  326. return( FTP_FAILED );
  327. }
  328. }
  329. }
  330. if( m_iStatus == FTPSTAT_CONNECTING )
  331. {
  332. // Check to see if we're connected
  333. fd_set wset;
  334. fd_set eset;
  335. FD_ZERO(&wset);
  336. FD_ZERO(&eset);
  337. FD_SET(m_iCommandSocket,&wset);
  338. FD_SET(m_iCommandSocket,&eset);
  339. timeval tv;
  340. tv.tv_sec=0;
  341. tv.tv_usec=0;
  342. int retval=select(m_iCommandSocket+1,0,&wset,&eset,&tv);
  343. if (retval == 0) // not ready yet....
  344. return(FTP_TRYING);
  345. if (FD_ISSET(m_iCommandSocket, &eset)) {
  346. // OK, the exception flag is set, guess we couldn't connect....
  347. closesocket( m_iCommandSocket );
  348. return( FTP_FAILED );
  349. }
  350. if (FD_ISSET(m_iCommandSocket, &wset)) {
  351. // OK, the write flag is set, we're good to go...
  352. m_iStatus = FTPSTAT_WAITINGSERVEROK;
  353. }
  354. }
  355. if( m_iStatus == FTPSTAT_WAITINGSERVEROK )
  356. {
  357. iReply=0;
  358. if (RecvReply( buffer, 256, &iReply ) != FTP_SUCCEEDED)
  359. return(FTP_TRYING);
  360. if (iReply != FTPREPLY_SERVEROK)
  361. return(FTP_FAILED);
  362. m_iStatus = FTPSTAT_CONNECTED;
  363. return( FTP_SUCCEEDED );
  364. }
  365. return( FTP_FAILED );
  366. }
  367. /*$_Function****************************************************************
  368. * $_Name :
  369. * STDMETHOD Cftp::LoginToServer( LPCSTR szUserName, LPCSTR szPassword )
  370. *
  371. * $_Description :
  372. * Logs into a server. ConnectToServer() must have succeeded before this
  373. * call is made.
  374. *
  375. * $_Parameters :
  376. * -> LPCSTR szUserName
  377. * The username under which to log in.
  378. *
  379. * -> LPCSTR szPassword
  380. * The password to use.
  381. *
  382. * $_ReturnValue :
  383. * FTP_TRYING until the login has succeeded, then FTP_SUCCEEDED.
  384. * FTP_FAILED on error.
  385. *
  386. ***************************************************************************/
  387. HRESULT Cftp::LoginToServer( LPCSTR szUserName, LPCSTR szPassword )
  388. {
  389. char command[ 256 ];
  390. int iReply;
  391. strncpy( m_szUserName, szUserName, 128 );
  392. strncpy( m_szPassword, szPassword, 128 );
  393. memset( command, 0, 256 );
  394. if( m_iStatus == FTPSTAT_CONNECTED )
  395. {
  396. sprintf( command, "USER %s\r\n", m_szUserName );
  397. if( SendCommand( command, 7 + strlen( m_szUserName ) ) < 0 )
  398. {
  399. return( FTP_TRYING );
  400. }
  401. m_iStatus = FTPSTAT_SENDINGUSER;
  402. }
  403. if( m_iStatus == FTPSTAT_SENDINGUSER )
  404. {
  405. if(RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED )
  406. return( FTP_TRYING );
  407. if (iReply != FTPREPLY_PASSWORD)
  408. return( FTP_FAILED );
  409. m_iStatus = FTPSTAT_SENTUSER;
  410. }
  411. if( m_iStatus == FTPSTAT_SENTUSER )
  412. {
  413. sprintf( command, "PASS %s\r\n", m_szPassword );
  414. if( SendCommand( command, 7 + strlen( m_szPassword ) ) < 0 )
  415. {
  416. return( FTP_TRYING );
  417. }
  418. m_iStatus = FTPSTAT_SENDINGPASS;
  419. }
  420. if( m_iStatus == FTPSTAT_SENDINGPASS )
  421. {
  422. if( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED )
  423. {
  424. return( FTP_TRYING );
  425. }
  426. if( iReply != FTPREPLY_LOGGEDIN )
  427. {
  428. if( iReply == FTPREPLY_CONTROLCLOSED )
  429. {
  430. return( FTP_FAILED );
  431. }
  432. return( FTP_TRYING );
  433. }
  434. m_iStatus = FTPSTAT_LOGGEDIN;
  435. return( FTP_SUCCEEDED );
  436. }
  437. return( FTP_FAILED );
  438. }
  439. /*$_Function****************************************************************
  440. * $_Name :
  441. * STDMETHOD Cftp::LogoffFromServer( void )
  442. *
  443. * $_Description :
  444. * Logs off from a server. LoginToServer() must have succeeded before this
  445. * call is made.
  446. *
  447. * $_Parameters :
  448. * None.
  449. *
  450. * $_ReturnValue :
  451. * FTP_TRYING until the logoff has succeeded, then FTP_SUCCEEDED.
  452. * FTP_FAILED on error.
  453. *
  454. ***************************************************************************/
  455. HRESULT Cftp::LogoffFromServer( void )
  456. {
  457. char command[ 256 ];
  458. int iReply, iRetCode;
  459. memset( command, 0, 256 );
  460. switch( m_iStatus )
  461. {
  462. case FTPSTAT_LOGGINGOFF:
  463. if( SendCommand( "QUIT\r\n", 6 ) == FTP_SUCCEEDED )
  464. {
  465. m_iStatus = FTPSTAT_SENDINGQUIT;
  466. }
  467. else
  468. {
  469. return( FTP_FAILED );
  470. }
  471. case FTPSTAT_SENDINGQUIT:
  472. {
  473. char buf[ 50 ];
  474. if( ( iReply = RecvReply( buf, 50, &iRetCode ) ) == FTP_SUCCEEDED )
  475. {
  476. if( iRetCode == 221 )
  477. {
  478. //m_iStatus = FTPSTAT_SENTQUIT;
  479. //m_iStatus = FTPSTAT_INIT; // NAK
  480. CloseSockets();
  481. ZeroStuff();
  482. return( FTP_SUCCEEDED );
  483. }
  484. }
  485. else
  486. {
  487. if( iReply == FTP_FAILED )
  488. {
  489. return( FTP_FAILED );
  490. }
  491. return( FTP_TRYING );
  492. }
  493. }
  494. default:
  495. m_iStatus = FTPSTAT_LOGGINGOFF;
  496. return( FTP_TRYING );
  497. }
  498. }
  499. /*$_Function****************************************************************
  500. * $_Name :
  501. * HRESULT Cftp::FindFile( LPCSTR szRemoteFileName, int * piSize )
  502. *
  503. * $_Description :
  504. * Locates a file on the remote server.
  505. *
  506. * $_Parameters :
  507. * -> LPCSTR szRemoteFileName
  508. * Full path and file name of the file to be downloaded.
  509. *
  510. * <- int * piSize
  511. * A pointer to an integer in which to return the size of the file, in bytes.
  512. *
  513. * $_ReturnValue :
  514. * FTP_SUCCEEDED on success. Otherwise FTP_TRYING, or FTP_FAILED on error.
  515. *
  516. * $_Warnings :
  517. * This function will continue to return FTP_TRYING if the file does not exist on
  518. * the server.
  519. *
  520. ***************************************************************************/
  521. HRESULT Cftp::FindFile( LPCSTR szRemoteFileName, int * piSize )
  522. {
  523. char command[ 256 ];
  524. static char listline[ 256 ];
  525. int i, iReply;
  526. char ext[ 10 ];
  527. if (m_findStart==0)
  528. m_findStart=time(NULL);
  529. if((time(NULL)-m_findStart) > 30) // try for 30 seconds
  530. {
  531. /////////DBGMSG("FindFile: Tried for too long");
  532. m_findStart=0;
  533. return( FTP_FAILED );
  534. }
  535. //strcpy(m_szRemoteFilePath, "/"); // start at home
  536. _splitpath( szRemoteFileName, NULL, m_szRemoteFilePath+strlen(m_szRemoteFilePath),
  537. m_szRemoteFileName, ext );
  538. strcat( m_szRemoteFileName, ext );
  539. for( i = 0; i < (int)strlen( m_szRemoteFilePath ); i++ )
  540. {
  541. if( m_szRemoteFilePath[ i ] == '\\' )
  542. {
  543. m_szRemoteFilePath[ i ] = '/';
  544. }
  545. }
  546. memset( command, 0, 256 );
  547. /* Change directory */
  548. if( ( m_iStatus == FTPSTAT_LOGGEDIN ) || ( m_iStatus == FTPSTAT_FILEFOUND ) )
  549. {
  550. sprintf( command, "CWD %s\r\n", m_szRemoteFilePath );
  551. if( SendCommand( command, 6 + strlen( m_szRemoteFilePath ) ) < 0 )
  552. {
  553. return( FTP_TRYING );
  554. }
  555. m_iStatus = FTPSTAT_SENDINGCWD;
  556. }
  557. /* Get reply */
  558. if( m_iStatus == FTPSTAT_SENDINGCWD )
  559. {
  560. HRESULT reply=RecvReply( command, 256, &iReply );
  561. if ((reply == FTP_SUCCEEDED) && (iReply == 550)) {
  562. m_findStart=0;
  563. return(FTP_FAILED);
  564. }
  565. if( ( reply != FTP_SUCCEEDED ) ||
  566. ( iReply != FTPREPLY_CWDOK ) )
  567. {
  568. return( FTP_TRYING );
  569. }
  570. m_iStatus = FTPSTAT_SENTCWD;
  571. }
  572. /* Set up data connection port */
  573. if( m_iStatus == FTPSTAT_SENTCWD )
  574. {
  575. i = 0;
  576. while( SendNewPort() == FTP_TRYING )
  577. {
  578. i++;
  579. if( i == 1000 )
  580. {
  581. return( FTP_TRYING );
  582. }
  583. }
  584. m_iStatus = FTPSTAT_SENTPORT;
  585. }
  586. /* Get directory listing for file. */
  587. if( m_iStatus == FTPSTAT_SENTPORT )
  588. {
  589. sprintf( command, "LIST %s\r\n", m_szRemoteFileName );
  590. if( SendCommand( command, 7 + strlen( m_szRemoteFileName ) ) < 0 )
  591. {
  592. return( FTP_TRYING );
  593. }
  594. m_iStatus = FTPSTAT_SENDINGLIST;
  595. }
  596. /* Get reply */
  597. if( m_iStatus == FTPSTAT_SENDINGLIST )
  598. {
  599. if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
  600. ( iReply != FTPREPLY_OPENASCII ) )
  601. {
  602. return( FTP_TRYING );
  603. }
  604. m_iStatus = FTPSTAT_SENTLIST;
  605. }
  606. /* Open data connection */
  607. if( m_iStatus == FTPSTAT_SENTLIST )
  608. {
  609. i = OpenDataConnection();
  610. if( i != FTP_SUCCEEDED )
  611. {
  612. /////////DBGMSG("FindFile: OpenDataConnection failed: "<<i);
  613. m_findStart=0;
  614. return( i );
  615. }
  616. m_iStatus = FTPSTAT_LISTDATAOPEN;
  617. memset( listline, 0, 256 );
  618. }
  619. /* Get data */
  620. if( m_iStatus == FTPSTAT_LISTDATAOPEN )
  621. {
  622. RecvData( listline, 256 );
  623. if( strlen( listline ) == 0 )
  624. {
  625. return( FTP_TRYING );
  626. }
  627. m_iStatus = FTPSTAT_LISTDATARECVD;
  628. }
  629. /* Wait for confirmation of end of data stream */
  630. if( m_iStatus == FTPSTAT_LISTDATARECVD )
  631. {
  632. if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
  633. ( iReply != FTPREPLY_COMPLETE ) )
  634. {
  635. return( FTP_TRYING );
  636. }
  637. m_iStatus = FTPSTAT_FILEFOUND;
  638. }
  639. CloseDataConnection();
  640. m_findStart=0;
  641. /* Is the file there? */
  642. if( strncmp( listline, m_szRemoteFileName, sizeof( m_szRemoteFileName ) ) == 0 )
  643. {
  644. /* No */
  645. ////////DBGMSG("FindFile: File not in list: "<<listline);
  646. return( FTP_FAILED );
  647. }
  648. /* Yes - find out the size, in bytes */
  649. if( sscanf( &listline[ 32 ], " %d ", &i ) == 1 )
  650. {
  651. if( piSize != NULL )
  652. {
  653. *piSize = i;
  654. m_iFileSize = i;
  655. }
  656. return( FTP_SUCCEEDED );
  657. }
  658. ////////DBGMSG("Default fail case: "<<listline);
  659. return( FTP_FAILED );
  660. }
  661. /*$_Function****************************************************************
  662. * $_Name :
  663. * HRESULT Cftp::SendCommand( LPCSTR pCommand, int iSize )
  664. *
  665. * $_Description :
  666. * Sends a command to the server. Commands are strings terminated with
  667. * "\r\n"
  668. *
  669. * $_Parameters :
  670. * LPCSTR pCommand
  671. * A pointer to a command
  672. *
  673. * int iSize
  674. * The size of the command in bytes.
  675. *
  676. * $_ReturnValue :
  677. * FTP_SUCCEEDED on success, or FTP_FAILED on error.
  678. *
  679. ***************************************************************************/
  680. HRESULT Cftp::SendCommand( LPCSTR pCommand, int iSize )
  681. {
  682. int i;
  683. i = send( m_iCommandSocket, pCommand, iSize, 0 );
  684. if( i > 0 )
  685. {
  686. #ifdef _DEBUG
  687. OutputDebugString( "-->" );
  688. OutputDebugString( pCommand );
  689. #endif
  690. return( FTP_SUCCEEDED );
  691. }
  692. else
  693. {
  694. return( FTP_FAILED );
  695. }
  696. }
  697. /*$_Function****************************************************************
  698. * $_Name :
  699. * HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode )
  700. *
  701. * $_Description :
  702. * Receives a reply from the server and extracts the numerical reply
  703. * code.
  704. *
  705. * $_Parameters :
  706. * -> LPCSTR pReplyBuffer
  707. * A buffer for the reply - must be specified and be at least 4 bytes in
  708. * length.
  709. *
  710. * -> iSize
  711. * The size of the reply buffer.
  712. *
  713. * <- piRetCode
  714. * A pointer to an integer to store the numeric return code for the message received.
  715. *
  716. * $_ReturnValue :
  717. * FTP_SUCCEEDED on success, FTP_FAILED otherwise.
  718. *
  719. ***************************************************************************/
  720. HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode )
  721. {
  722. int readval;
  723. char * pc = (char *)pReplyBuffer;
  724. while(1) {
  725. // Preview whats on the socket so we can make the decision if there is enough
  726. // there to use.
  727. readval = recv(m_iCommandSocket, pc, iSize-1, MSG_PEEK);
  728. pc[iSize-1]=0;
  729. if (readval > 0)
  730. pc[readval]=0;
  731. // Did the endpoint close?
  732. if (readval < 0) {
  733. if ((WSAGetLastError() == WSAECONNRESET ) || ((WSAGetLastError() == WSAENOTCONN)))
  734. readval=0;
  735. else {
  736. // nothing to read right now....
  737. return(FTP_TRYING);
  738. }
  739. }
  740. if (readval == 0) {
  741. // endpoint closed
  742. *piRetCode=FTPREPLY_CONTROLCLOSED;
  743. return(FTP_SUCCEEDED); // we succeeded in getting a reply
  744. }
  745. if (readval < 3) // minimal response
  746. return(FTP_TRYING);
  747. // Verify that this is a complete line, if not we will keep trying til
  748. // we have one.
  749. char *end=strstr(pc, "\r\n");
  750. if (end == 0)
  751. return(FTP_TRYING);
  752. // OK, we've got a line, pull it from the socket...
  753. recv(m_iCommandSocket, pc, end-pc+strlen("\r\n"), 0);
  754. #ifdef _DEBUG
  755. OutputDebugString( "<--" );
  756. OutputDebugString( pc );
  757. #endif
  758. // Is this an unrecognized command? It's probably in response to our BOGUSCOMMAND, ignore it.
  759. // If we got this for some other reason then this FTP server doesn't support our required command set.
  760. // If this were a general purpose FTP library we probably couldn't get away with this because it's pretty lame.
  761. const char *BOGUS_RESPONSE="500";
  762. if (_strnicmp(pc, BOGUS_RESPONSE, strlen(BOGUS_RESPONSE))==0)
  763. continue;
  764. // If the line starts with a non-digit then we ignore it...
  765. if (isdigit(pc[0])==0)
  766. continue;
  767. if (piRetCode)
  768. *piRetCode=atol(pc);
  769. return( FTP_SUCCEEDED );
  770. }
  771. }
  772. /*$_Function****************************************************************
  773. * $_Name :
  774. * unsigned long MyIPAddress( int sockfd )
  775. *
  776. * $_Description :
  777. * Finds the IP address of the local host.
  778. *
  779. * $_Parameters :
  780. * -> int sockfd
  781. * An optional socket descriptor - if this is given and the socket is connected
  782. * then the answer will guaranteed to be on the same interface as the connected
  783. * socket.
  784. *
  785. * $_ReturnValue :
  786. * A unsigned integer containing the IP address of the local host.
  787. *
  788. ***************************************************************************/
  789. unsigned long MyIPAddress( int sockfd )
  790. {
  791. int test = 99;
  792. int i;
  793. char pBuffer[ 256 ];
  794. char * pAddr;
  795. struct hostent * pHE;
  796. unsigned long ip;
  797. struct sockaddr_in sin;
  798. if( sockfd != -1 )
  799. {
  800. i = sizeof( sin );
  801. getsockname( sockfd, (struct sockaddr *)&sin, &i );
  802. ip = sin.sin_addr.S_un.S_addr;
  803. }
  804. else
  805. {
  806. /* Get this machine's name. */
  807. if( gethostname( pBuffer, 256 ) != 0 )
  808. {
  809. return( FTP_FAILED );
  810. }
  811. /* Look up the machine in "DNS" or whatever. */
  812. pHE = gethostbyname( pBuffer );
  813. if( pHE == NULL )
  814. {
  815. return( FTP_FAILED );
  816. }
  817. /* Find a good IP address. */
  818. ip = 0;
  819. i = 0;
  820. while( ( pAddr = pHE->h_addr_list[ i++ ] ) != NULL )
  821. {
  822. ip = *((unsigned long *)pAddr );
  823. if( ( ip != 0 ) && ( ip != inet_addr( "127.0.0.1" ) ) )
  824. {
  825. break;
  826. }
  827. else
  828. {
  829. ip = 0;
  830. }
  831. }
  832. }
  833. if( ip == 0 )
  834. {
  835. return( FTP_FAILED );
  836. }
  837. return( ip );
  838. }
  839. /*$_Function****************************************************************
  840. * $_Name :
  841. * int Cftp::SendNewPort( void )
  842. *
  843. * $_Description :
  844. * Sends a PORT command to the server specifying a new ephemeral port to
  845. * use for a data connection. Opens the port in the process.
  846. *
  847. * $_Parameters :
  848. * bool reset
  849. * Should be TRUE for the first attempt, FALSE subsequently.
  850. *
  851. * $_ReturnValue :
  852. * FTP_SUCCEEDED on success, FTP_FAILED on error, FTP_TRYING while
  853. * going through the stages.
  854. *
  855. ***************************************************************************/
  856. int Cftp::SendNewPort( void )
  857. {
  858. unsigned long uTemp;
  859. char command[ 256 ];
  860. int i, iReply;
  861. /* Open a socket */
  862. if( m_sendNewPortStatus == 0 )
  863. {
  864. m_iDataSocket = socket( AF_INET, SOCK_STREAM, 0 );
  865. if( m_iDataSocket < 0 )
  866. {
  867. return( FTP_FAILED );
  868. }
  869. /* Set socket to non-blocking */
  870. uTemp = 1;
  871. if (Use_Non_Blocking_Mode()) {
  872. if( ioctlsocket( m_iCommandSocket, FIONBIO, &uTemp ) == SOCKET_ERROR )
  873. {
  874. return( FTP_FAILED );
  875. }
  876. }
  877. memset( &m_DataSockAddr, 0, sizeof( m_DataSockAddr ) );
  878. m_DataSockAddr.sin_family = AF_INET;
  879. m_DataSockAddr.sin_addr.s_addr = htonl( INADDR_ANY );
  880. m_DataSockAddr.sin_port = 0; // Winsock fills in an ephemeral port during bind...
  881. if( bind( m_iDataSocket, (struct sockaddr *)&m_DataSockAddr, sizeof( m_DataSockAddr ) ) < 0 )
  882. {
  883. return( FTP_FAILED );
  884. }
  885. i = sizeof( m_DataSockAddr);
  886. getsockname( m_iDataSocket, (struct sockaddr *)&m_DataSockAddr, &i );
  887. listen( m_iDataSocket, 5 );
  888. // Set socket to non-blocking
  889. uTemp = 1;
  890. if (Use_Non_Blocking_Mode()) {
  891. if( ioctlsocket( m_iDataSocket, FIONBIO, &uTemp ) == SOCKET_ERROR )
  892. {
  893. return( FTP_FAILED );
  894. }
  895. }
  896. m_sendNewPortStatus = 1;
  897. }
  898. /* Send a port command. */
  899. if( m_sendNewPortStatus == 1 )
  900. {
  901. memset( command, 0, 256 );
  902. i = MyIPAddress( m_iCommandSocket );
  903. if( i == FTP_FAILED )
  904. {
  905. return( FTP_FAILED );
  906. }
  907. sprintf( command, "PORT %d,%d,%d,%d,%d,%d\r\n",
  908. i & 0xFF,
  909. ( i >> 8 ) & 0xFF,
  910. ( i >> 16 ) & 0xFF,
  911. ( i >> 24 ) & 0xFF,
  912. m_DataSockAddr.sin_port & 0xFF,
  913. m_DataSockAddr.sin_port >> 8 );
  914. if( SendCommand( command, strlen(command) ) < 0 )
  915. {
  916. return( FTP_TRYING );
  917. }
  918. m_sendNewPortStatus = 2;
  919. }
  920. /* Get reply */
  921. if( m_sendNewPortStatus == 2 )
  922. {
  923. if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
  924. ( iReply != FTPREPLY_PORTOK ) )
  925. {
  926. return( FTP_TRYING );
  927. }
  928. m_sendNewPortStatus = 0;
  929. }
  930. return( FTP_SUCCEEDED );
  931. }
  932. /*$_Function****************************************************************
  933. * $_Name :
  934. * int Cftp::OpenDataConnection()
  935. *
  936. * $_Description :
  937. * Opens the data connection to the server. Actually, the socket for the
  938. * data connection should have been opened by a call to SendNewPort before
  939. * this method is called - this just calls accept.
  940. *
  941. * $_Parameters :
  942. * None.
  943. *
  944. * $_ReturnValue :
  945. * FTP_SUCCEEDED on success, FTP_FAILED otherwise.
  946. *
  947. * $_Warnings :
  948. * This call may block.
  949. *
  950. ***************************************************************************/
  951. int Cftp::OpenDataConnection()
  952. {
  953. int iNewSocket;
  954. if( m_iDataSocket == 0 )
  955. {
  956. return( FTP_FAILED );
  957. }
  958. if( ( iNewSocket = accept( m_iDataSocket, NULL, 0 ) ) < 0 )
  959. {
  960. if( WSAGetLastError() != (WSAEWOULDBLOCK ) )
  961. {
  962. return( FTP_FAILED );
  963. }
  964. else
  965. {
  966. return( FTP_TRYING );
  967. }
  968. }
  969. m_iDataSocket = iNewSocket;
  970. return( FTP_SUCCEEDED );
  971. }
  972. /*$_Function****************************************************************
  973. * $_Name :
  974. * void Cftp::CloseDataConnection()
  975. *
  976. * $_Description :
  977. * Closes the data connection.
  978. *
  979. * $_Parameters :
  980. * None.
  981. *
  982. * $_ReturnValue :
  983. * None.
  984. *
  985. ***************************************************************************/
  986. void Cftp::CloseDataConnection()
  987. {
  988. closesocket( m_iDataSocket );
  989. m_iDataSocket = 0;
  990. }
  991. /*$_Function****************************************************************
  992. * $_Name :
  993. * HRESULT Cftp::DisconnectFromServer()
  994. *
  995. * $_Description :
  996. * Disconnects from the server.
  997. *
  998. * $_Parameters :
  999. * None.
  1000. *
  1001. * $_ReturnValue :
  1002. * None.
  1003. *
  1004. ***************************************************************************/
  1005. HRESULT Cftp::DisconnectFromServer()
  1006. {
  1007. // Make the download file read-only so it's still there the next time
  1008. // we're run.
  1009. closesocket( m_iCommandSocket );
  1010. return( FTP_SUCCEEDED );
  1011. }
  1012. /*$_Function****************************************************************
  1013. * $_Name :
  1014. * int Cftp::SendData( char * pData, int iSize )
  1015. *
  1016. * $_Description :
  1017. * Sends data to the server.
  1018. *
  1019. * $_Parameters :
  1020. * -> char * pData
  1021. * A pointer to some data to be sent.
  1022. *
  1023. * -> int iSize
  1024. * The size, in bytes, of the data.
  1025. *
  1026. * $_ReturnValue :
  1027. * The number of bytes sent, or -1 on error.
  1028. *
  1029. ***************************************************************************/
  1030. int Cftp::SendData( char * pData, int iSize )
  1031. {
  1032. return( send( m_iDataSocket, pData, iSize, 0 ) );
  1033. }
  1034. /*$_Function****************************************************************
  1035. * $_Name :
  1036. * int Cftp::RecvData( char * pData, int iSize )
  1037. *
  1038. * $_Description :
  1039. * Receives data from the server.
  1040. *
  1041. * $_Parameters :
  1042. * -> LPCSTR pData
  1043. * A pointer to a buffer for the data to be received.
  1044. *
  1045. * -> int iSize
  1046. * The size, in bytes, of the data buffer.
  1047. *
  1048. * $_ReturnValue :
  1049. * The number of bytes received, or -1 on error.
  1050. *
  1051. ***************************************************************************/
  1052. int Cftp::RecvData( char * pData, int iSize )
  1053. {
  1054. /***** testing...
  1055. int readval = recv(m_iDataSocket, pData, iSize, MSG_PEEK);
  1056. if (readval <= 0) // If there's nothing to read, don't read now...
  1057. return(readval);
  1058. ******/
  1059. return( recv( m_iDataSocket, pData, iSize, 0 ) );
  1060. }
  1061. /*$_Function****************************************************************
  1062. * $_Name :
  1063. * HRESULT Cftp::GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead )
  1064. *
  1065. * $_Description :
  1066. * Retrieves the next block of data from the remote file and writes it into
  1067. * the local file. Deals with opening the local file and restarting a
  1068. * failed transfer if FileRecoveryPosition() returns non-zero. To prevent
  1069. * a restart after FileRecoveryPosition() returns non-zero, call
  1070. * Cftp::RestartFrom() with 0 as the offset parameter.
  1071. *
  1072. * The file is initally written to a temporary file and then copied to the local
  1073. * file name when the transfer is complete. If the transfer is halted, the
  1074. * temporary file will be used as the starting point for subsequent retries.
  1075. *
  1076. * $_Parameters :
  1077. * -> LPCSTR szLocalFileName
  1078. * A pointer to a string containing the local file name for the transferred file.
  1079. *
  1080. * <- int * piTotalRead
  1081. * A pointer to an integer in which to store the total number of bytes
  1082. * transferred so far.
  1083. *
  1084. * $_ReturnValue :
  1085. * FTP_TRYING while the transfer is in progress, FTP_SUCCEEDED on completion,
  1086. * FTP_FAILED on error.
  1087. *
  1088. ***************************************************************************/
  1089. HRESULT Cftp::GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead )
  1090. {
  1091. char command[ 256 ];
  1092. int read, totread = 0;
  1093. const int max_data_len=10240;
  1094. char data[ max_data_len ];
  1095. int res, iReply;
  1096. char downloadfilename[256];
  1097. GetDownloadFilename(szLocalFileName, downloadfilename);
  1098. //char str[ 256 ];
  1099. strncpy( m_szLocalFileName, szLocalFileName, 256 );
  1100. // Open local file
  1101. if( m_iStatus == FTPSTAT_FILEFOUND )
  1102. {
  1103. if( m_iFilePos == 0 )
  1104. {
  1105. if( ( m_pfLocalFile = fopen( downloadfilename, "wb" ) ) == NULL )
  1106. {
  1107. return( FTP_FAILED );
  1108. }
  1109. }
  1110. else
  1111. {
  1112. if( ( m_pfLocalFile = fopen( downloadfilename, "ab" ) ) == NULL )
  1113. {
  1114. return( FTP_FAILED );
  1115. }
  1116. }
  1117. m_iStatus = FTPSTAT_FILEOPEN;
  1118. }
  1119. // Send the PORT command
  1120. if( m_iStatus == FTPSTAT_FILEOPEN )
  1121. {
  1122. if( SendNewPort() == FTP_SUCCEEDED )
  1123. {
  1124. m_iStatus = FTPSTAT_SENTFILEPORT;
  1125. }
  1126. else
  1127. {
  1128. return( FTP_TRYING );
  1129. }
  1130. }
  1131. // Set type to BINARY
  1132. if( m_iStatus == FTPSTAT_SENTFILEPORT )
  1133. {
  1134. sprintf( command, "TYPE I\r\n");
  1135. if( SendCommand( command, strlen( command ) ) < 0 )
  1136. {
  1137. return( FTP_TRYING );
  1138. }
  1139. m_iStatus = FTPSTAT_SENDINGTYPE;
  1140. }
  1141. /* Get reply */
  1142. if( m_iStatus == FTPSTAT_SENDINGTYPE )
  1143. {
  1144. if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
  1145. ( iReply != FTPREPLY_TYPEOK ) )
  1146. {
  1147. return( FTP_TRYING );
  1148. }
  1149. m_iStatus = FTPSTAT_SENTTYPE;
  1150. }
  1151. // Send the RESTART command - if we are restarting a previous transfer.
  1152. if( m_iStatus == FTPSTAT_SENTTYPE )
  1153. {
  1154. if( m_iFilePos == 0 )
  1155. {
  1156. m_iStatus = FTPSTAT_SENTREST;
  1157. }
  1158. else
  1159. {
  1160. sprintf( command, "REST %d\r\n", m_iFilePos );
  1161. if( SendCommand( command, strlen( command ) ) < 0 )
  1162. {
  1163. return( FTP_TRYING );
  1164. }
  1165. m_iStatus = FTPSTAT_SENDINGREST;
  1166. }
  1167. }
  1168. /* Get reply */
  1169. if( m_iStatus == FTPSTAT_SENDINGREST )
  1170. {
  1171. HRESULT res=RecvReply( command, 256, &iReply );
  1172. if ((res == FTP_FAILED) || (iReply == 502)) // unsupported command
  1173. {
  1174. m_iFilePos=0;
  1175. fclose(m_pfLocalFile);
  1176. m_pfLocalFile = fopen( downloadfilename, "wb" );
  1177. }
  1178. else if( ( res != FTP_SUCCEEDED ) ||
  1179. ( iReply != FTPREPLY_RESTARTOK ) )
  1180. {
  1181. return( FTP_TRYING );
  1182. }
  1183. m_iStatus = FTPSTAT_SENTREST;
  1184. }
  1185. // Send the RETR command
  1186. if( m_iStatus == FTPSTAT_SENTREST )
  1187. {
  1188. sprintf( command, "RETR %s\r\n", m_szRemoteFileName );
  1189. if( SendCommand( command, strlen( command ) ) < 0 )
  1190. {
  1191. return( FTP_TRYING );
  1192. }
  1193. m_iStatus = FTPSTAT_SENDINGRETR;
  1194. }
  1195. /* Get reply */
  1196. if( m_iStatus == FTPSTAT_SENDINGRETR )
  1197. {
  1198. if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) ||
  1199. ( iReply != FTPREPLY_OPENBINARY ) )
  1200. {
  1201. return( FTP_TRYING );
  1202. }
  1203. m_iStatus = FTPSTAT_SENTRETR;
  1204. }
  1205. /* Open data connection */
  1206. if( m_iStatus == FTPSTAT_SENTRETR )
  1207. {
  1208. res = OpenDataConnection();
  1209. if( res != FTP_SUCCEEDED )
  1210. {
  1211. return( res );
  1212. }
  1213. m_iStatus = FTPSTAT_FILEDATAOPEN;
  1214. }
  1215. /* Get data */
  1216. if( m_iStatus == FTPSTAT_FILEDATAOPEN )
  1217. {
  1218. do
  1219. {
  1220. read = RecvData( data, max_data_len );
  1221. if( read > 0 )
  1222. {
  1223. fwrite( data, 1, read, m_pfLocalFile );
  1224. totread += read;
  1225. }
  1226. }
  1227. while( ( read > 0 ) && ( totread < (max_data_len * 20) ) ); // Don't read too much -
  1228. // must not block for too long
  1229. m_iFilePos += totread; // update read position
  1230. if( piTotalRead != NULL )
  1231. *piTotalRead = m_iFilePos;
  1232. // look for all notices about endpoint closed...
  1233. if (read < 0) {
  1234. int wsa_err=WSAGetLastError();
  1235. if ((wsa_err == WSAECONNRESET) || (wsa_err == WSAENOTCONN))
  1236. read = 0; // just treat it as a close....
  1237. }
  1238. /* See if the download has finished */
  1239. if( read == 0 )
  1240. {
  1241. // Data connection reset
  1242. if( m_iFilePos != m_iFileSize ) {
  1243. // Haven't got all the data
  1244. return( FTP_FAILED );
  1245. } else {
  1246. // got all the data and the connection is closed so mark it so
  1247. m_iStatus = FTPSTAT_FILEDATACLOSED;
  1248. }
  1249. } else {
  1250. return( FTP_TRYING );
  1251. }
  1252. }
  1253. // if we have gotten to here, we have all the data and the connection is
  1254. // closed. The case where the connection was closed but we didn't get
  1255. // everything is handled above.
  1256. if( m_iStatus == FTPSTAT_FILEDATACLOSED ) {
  1257. CloseDataConnection();
  1258. fclose( m_pfLocalFile );
  1259. m_pfLocalFile = NULL;
  1260. /*
  1261. * Move the file from the temporary download location to its
  1262. * final resting place
  1263. */
  1264. char downloadfilename[256];
  1265. GetDownloadFilename(m_szLocalFileName, downloadfilename);
  1266. // Make sure the path exists for the new file
  1267. char curdir[256];
  1268. _getcwd(curdir,256);
  1269. Prepare_Directories(curdir, m_szLocalFileName);
  1270. DEBUG_LOG(("CWD: %s\n", curdir));
  1271. if( rename( downloadfilename, m_szLocalFileName ) != 0 ) {
  1272. DEBUG_LOG(("First rename of %s to %s failed with errno of %d\n", downloadfilename, m_szLocalFileName, errno));
  1273. /* Error moving file - remove file that's already there and try again. */
  1274. _chmod( m_szLocalFileName, _S_IWRITE | _S_IREAD); // make sure it's not readonly
  1275. DEBUG_LOG(("_chmod of %s failed with errno of %d\n", m_szLocalFileName, errno));
  1276. remove( m_szLocalFileName );
  1277. DEBUG_LOG(("remove of %s failed with errno of %d\n", m_szLocalFileName, errno));
  1278. if( rename( downloadfilename, m_szLocalFileName ) != 0 ) {
  1279. DEBUG_LOG(("Second rename of %s to %s failed with errno of %d\n", downloadfilename, m_szLocalFileName, errno));
  1280. return( FTP_FAILED );
  1281. }
  1282. }
  1283. // Send a bogus command. If the firewall has closed our ftp command channel connection this
  1284. // will allow us to detect it. (Obviously the data channel is closed or we wouldn't be here)
  1285. // There are cases (firewall) where the connection will go away without having a close command
  1286. // but writing to it will allow us to detect this case.
  1287. // We will ignore the response because we don't know in which order the server will respond
  1288. SendCommand("BOGUSCOMMAND\r\n", strlen("BOGUSCOMMAND\r\n"));
  1289. OutputDebugString("File closed, waiting for response.\n");
  1290. m_iStatus = FTPSTAT_TRANSFERREPLY;
  1291. }
  1292. if( m_iStatus == FTPSTAT_TRANSFERREPLY ) {
  1293. iReply=0;
  1294. // Get the file complete reply
  1295. if (RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED )
  1296. return(FTP_TRYING);
  1297. if (iReply == FTPREPLY_CONTROLCLOSED) {
  1298. m_iStatus = FTPSTAT_INIT;
  1299. m_iFilePos=0;
  1300. CloseSockets();
  1301. } else {
  1302. m_iStatus = FTPSTAT_LOGGEDIN;
  1303. m_iFilePos=0;
  1304. }
  1305. return(FTP_SUCCEEDED);
  1306. }
  1307. return( FTP_FAILED );
  1308. }
  1309. /*$_Function****************************************************************
  1310. * $_Name :
  1311. * HRESULT Cftp::FileRecoveryPosition( LPCSTR szLocalFileName )
  1312. *
  1313. * $_Description :
  1314. * Finds the size of the specified file. This size can be used
  1315. *
  1316. * $_Parameters :
  1317. * char & szLocalFileName
  1318. * The full path name of the local file.
  1319. *
  1320. * $_ReturnValue :
  1321. * The size of that file on the local disk. 0 if the file does not exist.
  1322. *
  1323. ***************************************************************************/
  1324. //
  1325. // Do we have this file in the download directory? If so then it's a partial download.
  1326. //
  1327. //
  1328. HRESULT Cftp::FileRecoveryPosition( LPCSTR szLocalFileName, LPCSTR szRegistryRoot )
  1329. {
  1330. char downloadfilename[256];
  1331. GetDownloadFilename(szLocalFileName, downloadfilename);
  1332. FILE *testfp = fopen( downloadfilename, "rb" );
  1333. if( testfp == NULL )
  1334. {
  1335. m_iFilePos = 0;
  1336. return 0;
  1337. }
  1338. fseek( testfp, 0, SEEK_END );
  1339. m_iFilePos = ftell( testfp );
  1340. fclose( testfp );
  1341. return( m_iFilePos );
  1342. }
  1343. /*************8
  1344. FILE * testfp;
  1345. HKEY hkey;
  1346. unsigned char regfilename[ 256 ];
  1347. char regkey[ 512 ];
  1348. unsigned long t1, t2;
  1349. if( ( szRegistryRoot == NULL ) || ( szLocalFileName == NULL ) )
  1350. {
  1351. // Bail out
  1352. return( 0 );
  1353. }
  1354. // Concatenate the registry key together
  1355. strcpy( regkey, szRegistryRoot );
  1356. if( regkey[ strlen( regkey ) - 1 ] != '\\' )
  1357. {
  1358. strcat( regkey, "\\Download" );
  1359. }
  1360. else
  1361. {
  1362. strcat( regkey, "Download" );
  1363. }
  1364. if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, (LPCTSTR)regkey,
  1365. 0, KEY_ALL_ACCESS, &hkey ) != ERROR_SUCCESS )
  1366. {
  1367. // Key doesn't exist, create it
  1368. if( RegCreateKey( HKEY_LOCAL_MACHINE, (LPCTSTR)regkey,
  1369. &hkey ) != ERROR_SUCCESS )
  1370. {
  1371. // Error, bail out
  1372. return( 0 );
  1373. }
  1374. RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 );
  1375. RegCloseKey(hkey);
  1376. return( 0 );
  1377. }
  1378. t2 = 256;
  1379. if( RegQueryValueEx( hkey, (LPCTSTR)"File", 0, &t1, regfilename, &t2 ) != ERROR_SUCCESS )
  1380. {
  1381. RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 );
  1382. RegCloseKey(hkey);
  1383. return( 0 );
  1384. }
  1385. if( strcmp( szLocalFileName, (const char *)regfilename ) == 0 )
  1386. {
  1387. // File previously downloaded
  1388. testfp = fopen( FTP_TEMPFILENAME, "rb" );
  1389. if( testfp == NULL )
  1390. {
  1391. m_iFilePos = 0;
  1392. RegCloseKey(hkey);
  1393. return 0;
  1394. }
  1395. fseek( testfp, 0, SEEK_END );
  1396. m_iFilePos = ftell( testfp );
  1397. fclose( testfp );
  1398. RegCloseKey(hkey);
  1399. return( m_iFilePos );
  1400. }
  1401. // Download file doesn't exist
  1402. RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 );
  1403. RegCloseKey(hkey);
  1404. // get rid of any temp downloads
  1405. _unlink(FTP_TEMPFILENAME);
  1406. return( 0 );
  1407. }
  1408. **************************************/
  1409. //
  1410. // convert a local name to a temp filename to use for downloading
  1411. //
  1412. void Cftp::GetDownloadFilename(const char *localname, char *downloadname)
  1413. {
  1414. char *name = strdup(localname);
  1415. char *s = name;
  1416. while (*s)
  1417. {
  1418. if (*s == '\\' || *s == '.' || *s == ' ')
  1419. *s = '_';
  1420. ++s;
  1421. }
  1422. sprintf(downloadname,"download\\%s_%d.tmp",name,m_iFileSize);
  1423. free(name);
  1424. /*
  1425. Wstring name;
  1426. name.set(localname);
  1427. name.replace("\\","_");
  1428. name.replace(".","_");
  1429. name.replace(" ","_");
  1430. sprintf(downloadname,"download\\%s_%d.tmp",name.get(),m_iFileSize);
  1431. */
  1432. return;
  1433. }
  1434. //
  1435. // Build all the subdirectories for a given filename
  1436. //
  1437. bool Prepare_Directories(const char *rootdir, const char *filename)
  1438. {
  1439. char tempstr[256];
  1440. char newdir[256];
  1441. const char *cptr=filename;
  1442. while(cptr=strchr(cptr,'\\'))
  1443. {
  1444. memset(tempstr,0,256);
  1445. strncpy(tempstr,filename,cptr-filename);
  1446. sprintf(newdir,"%s\\%s",rootdir, tempstr);
  1447. if (!CreateDirectory(newdir, NULL))
  1448. return false;
  1449. //if ((_mkdir(newdir) == -1) && ((errno == ENOENT || errno==EACCES)))
  1450. //return(false);
  1451. cptr++;
  1452. }
  1453. return(true);
  1454. }