FTP.CPP 40 KB

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