TransferSocket.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. // FileZilla - a Windows ftp client
  2. // Copyright (C) 2002-2004 - Tim Kosse <[email protected]>
  3. // This program is free software; you can redistribute it and/or
  4. // modify it under the terms of the GNU General Public License
  5. // as published by the Free Software Foundation; either version 2
  6. // of the License, or (at your option) any later version.
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU General Public License for more details.
  11. // You should have received a copy of the GNU General Public License
  12. // along with this program; if not, write to the Free Software
  13. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  14. // TransferSocket.cpp: Implementierungsdatei
  15. //
  16. #include "stdafx.h"
  17. #ifndef MPEXT
  18. #include "filezilla.h"
  19. #endif
  20. #include "TransferSocket.h"
  21. #include "mainthread.h"
  22. #include "AsyncProxySocketLayer.h"
  23. #ifndef MPEXT_NO_GSS
  24. #include "AsyncGssSocketLayer.h"
  25. #endif
  26. #ifdef _DEBUG
  27. #define new DEBUG_NEW
  28. #undef THIS_FILE
  29. static char THIS_FILE[] = __FILE__;
  30. #endif
  31. #define BUFSIZE 16384
  32. #define STATE_WAITING 0
  33. #define STATE_STARTING 1
  34. #define STATE_STARTED 2
  35. /////////////////////////////////////////////////////////////////////////////
  36. // CTransferSocket
  37. CTransferSocket::CTransferSocket(CFtpControlSocket *pOwner, int nMode)
  38. {
  39. ASSERT(pOwner);
  40. InitLog(pOwner);
  41. m_pOwner = pOwner;
  42. m_nMode = nMode;
  43. m_nTransferState = STATE_WAITING;
  44. m_bCheckTimeout = FALSE;
  45. m_pBuffer = 0;
  46. #ifndef MPEXT_NO_ZLIB
  47. m_pBuffer2 = 0;
  48. #endif
  49. m_bufferpos = 0;
  50. m_pFile = 0;
  51. m_bListening = FALSE;
  52. m_bSentClose = FALSE;
  53. m_nInternalMessageID = 0;
  54. m_transferdata.transfersize = 0;
  55. m_transferdata.transferleft = 0;
  56. m_transferdata.nTransferStart = 0;
  57. m_nNotifyWaiting = 0;
  58. m_bShutDown = FALSE;
  59. UpdateStatusBar(true);
  60. for (int i = 0; i < SPEED_SECONDS; i++)
  61. {
  62. m_Transfered[i] = 0;
  63. m_UsedForTransfer[i] = 0;
  64. }
  65. m_pProxyLayer = NULL;
  66. #ifndef MPEXT_NO_SSL
  67. m_pSslLayer = NULL;
  68. #endif
  69. #ifndef MPEXT_NO_GSS
  70. m_pGssLayer = NULL;
  71. #endif
  72. if (m_nMode & CSMODE_LIST)
  73. {
  74. m_pListResult = new CFtpListResult(pOwner->m_CurrentServer, &pOwner->m_bUTF8);
  75. m_pListResult->InitLog(this);
  76. }
  77. else
  78. m_pListResult = 0;
  79. m_LastUpdateTime.QuadPart = 0;
  80. #ifndef MPEXT_NO_ZLIB
  81. memset(&m_zlibStream, 0, sizeof(m_zlibStream));
  82. m_useZlib = false;
  83. #endif
  84. }
  85. CTransferSocket::~CTransferSocket()
  86. {
  87. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("~CTransferSocket()"));
  88. delete [] m_pBuffer;
  89. #ifndef MPEXT_NO_ZLIB
  90. delete [] m_pBuffer2;
  91. #endif
  92. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), 0);
  93. Close();
  94. RemoveAllLayers();
  95. delete m_pProxyLayer;
  96. #ifndef MPEXT_NO_SSL
  97. delete m_pSslLayer;
  98. #endif
  99. #ifndef MPEXT_NO_GSS
  100. delete m_pGssLayer;
  101. #endif
  102. m_pOwner->RemoveActiveTransfer();
  103. delete m_pListResult;
  104. #ifndef MPEXT_NO_ZLIB
  105. if (m_useZlib)
  106. {
  107. if (m_nMode & CSMODE_UPLOAD)
  108. deflateEnd(&m_zlibStream);
  109. else
  110. inflateEnd(&m_zlibStream);
  111. }
  112. #endif
  113. }
  114. /////////////////////////////////////////////////////////////////////////////
  115. // Member-Funktion CTransferSocket
  116. void CTransferSocket::OnReceive(int nErrorCode)
  117. {
  118. if (GetState() != connected && GetState() != attached && GetState() != closed)
  119. return;
  120. if (m_nTransferState == STATE_WAITING)
  121. {
  122. m_nNotifyWaiting |= FD_READ;
  123. return;
  124. }
  125. if (m_bSentClose)
  126. return;
  127. if (m_bListening)
  128. return;
  129. if (m_nMode&CSMODE_LIST)
  130. {
  131. if (m_nTransferState == STATE_STARTING)
  132. OnConnect(0);
  133. char *buffer = new char[BUFSIZE];
  134. int numread = CAsyncSocketEx::Receive(buffer, BUFSIZE);
  135. if (numread != SOCKET_ERROR && numread)
  136. {
  137. m_LastActiveTime = CTime::GetCurrentTime();
  138. UpdateRecvLed();
  139. #ifndef MPEXT_NO_ZLIB
  140. if (m_useZlib)
  141. {
  142. m_zlibStream.next_in = (Bytef *)buffer;
  143. m_zlibStream.avail_in = numread;
  144. char *out = new char[BUFSIZE];
  145. m_zlibStream.next_out = (Bytef *)out;
  146. m_zlibStream.avail_out = BUFSIZE;
  147. int res = inflate(&m_zlibStream, 0);
  148. while (res == Z_OK)
  149. {
  150. m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
  151. out = new char[BUFSIZE];
  152. m_zlibStream.next_out = (Bytef *)out;
  153. m_zlibStream.avail_out = BUFSIZE;
  154. res = inflate(&m_zlibStream, 0);
  155. }
  156. delete [] buffer;
  157. if (res == Z_STREAM_END)
  158. m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
  159. else if (res != Z_OK && res != Z_BUF_ERROR)
  160. {
  161. delete [] out;
  162. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  163. return;
  164. }
  165. else
  166. delete [] out;
  167. }
  168. else
  169. #endif
  170. m_pListResult->AddData(buffer, numread);
  171. m_transferdata.transfersize += numread;
  172. CTimeSpan timespan = CTime::GetCurrentTime() - m_StartTime;
  173. int elapsed = (int)timespan.GetTotalSeconds();
  174. //TODO
  175. //There are servers which report the total number of
  176. //bytes in the list response message, but yet it is not supported by FZ.
  177. /*double leftmodifier=(transfersize-transferstart-transferleft);
  178. leftmodifier*=100;
  179. leftmodifier/=(transfersize-transferstart);
  180. if (leftmodifier==0)
  181. leftmodifier=1;
  182. double leftmodifier2=100-leftmodifier;
  183. int left=(int)((elapsed/leftmodifier)*leftmodifier2);
  184. int percent=MulDiv(100,transfersize-transferleft,transfersize);*/
  185. int transferrate=static_cast<int>( (elapsed && m_transferdata.transfersize)?m_transferdata.transfersize/elapsed:0 );
  186. t_ffam_transferstatus *status = new t_ffam_transferstatus;
  187. status->bFileTransfer = FALSE;
  188. #ifdef MPEXT
  189. status->transfersize = -1;
  190. #endif
  191. status->bytes = m_transferdata.transfersize;
  192. status->percent = -1;
  193. status->timeelapsed = elapsed;
  194. status->timeleft = -1;
  195. status->transferrate = transferrate;
  196. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
  197. }
  198. else
  199. delete [] buffer;
  200. if (!numread)
  201. {
  202. CloseAndEnsureSendClose(0);
  203. }
  204. if (numread == SOCKET_ERROR)
  205. {
  206. int nError = GetLastError();
  207. if (nError == WSAENOTCONN)
  208. {
  209. //Not yet connected
  210. return;
  211. }
  212. #ifndef MPEXT_NO_SSL
  213. else if (m_pSslLayer && nError == WSAESHUTDOWN)
  214. {
  215. // Do nothing, wait for shutdown complete notification.
  216. return;
  217. }
  218. #endif
  219. else if (nError != WSAEWOULDBLOCK)
  220. {
  221. LogError(nError);
  222. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  223. }
  224. }
  225. }
  226. else if (m_nMode & CSMODE_DOWNLOAD)
  227. {
  228. if (m_nTransferState == STATE_STARTING)
  229. OnConnect(0);
  230. bool beenWaiting = false;
  231. _int64 ableToRead;
  232. if (GetState() != closed)
  233. ableToRead = m_pOwner->GetAbleToTransferSize(CControlSocket::download, beenWaiting);
  234. else
  235. ableToRead = BUFSIZE;
  236. if (!beenWaiting)
  237. ASSERT(ableToRead);
  238. else if (!ableToRead)
  239. {
  240. TriggerEvent(FD_READ);
  241. return;
  242. }
  243. if (!m_pBuffer)
  244. m_pBuffer = new char[BUFSIZE];
  245. int numread = CAsyncSocketEx::Receive(m_pBuffer, static_cast<int>(ableToRead));
  246. if (numread!=SOCKET_ERROR)
  247. {
  248. Transfered( numread, CTime::GetCurrentTime());
  249. m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::download, numread);
  250. }
  251. if (!numread)
  252. {
  253. CloseAndEnsureSendClose(0);
  254. return;
  255. }
  256. if (numread == SOCKET_ERROR)
  257. {
  258. int nError = GetLastError();
  259. if (nError == WSAENOTCONN)
  260. {
  261. //Not yet connected
  262. return;
  263. }
  264. #ifndef MPEXT_NO_SSL
  265. else if (m_pSslLayer && nError == WSAESHUTDOWN)
  266. {
  267. // Do nothing, wait for shutdown complete notification.
  268. return;
  269. }
  270. #endif
  271. else if (nError != WSAEWOULDBLOCK)
  272. {
  273. LogError(nError);
  274. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  275. }
  276. UpdateStatusBar(false);
  277. return;
  278. }
  279. int written = 0;
  280. m_LastActiveTime = CTime::GetCurrentTime();
  281. UpdateRecvLed();
  282. TRY
  283. {
  284. #ifndef MPEXT_NO_ZLIB
  285. if (m_useZlib)
  286. {
  287. if (!m_pBuffer2)
  288. m_pBuffer2 = new char[BUFSIZE];
  289. m_zlibStream.next_in = (Bytef *)m_pBuffer;
  290. m_zlibStream.avail_in = numread;
  291. m_zlibStream.next_out = (Bytef *)m_pBuffer2;
  292. m_zlibStream.avail_out = BUFSIZE;
  293. int res = inflate(&m_zlibStream, 0);
  294. while (res == Z_OK)
  295. {
  296. m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
  297. written += BUFSIZE - m_zlibStream.avail_out;
  298. m_zlibStream.next_out = (Bytef *)m_pBuffer2;
  299. m_zlibStream.avail_out = BUFSIZE;
  300. res = inflate(&m_zlibStream, 0);
  301. }
  302. if (res == Z_STREAM_END)
  303. {
  304. m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
  305. written += BUFSIZE - m_zlibStream.avail_out;
  306. }
  307. else if (res != Z_OK && res != Z_BUF_ERROR)
  308. {
  309. m_pOwner->ShowStatus(L"Compression error", FZ_LOG_ERROR);
  310. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  311. return;
  312. }
  313. }
  314. else
  315. #endif
  316. {
  317. m_pFile->Write(m_pBuffer, numread);
  318. written = numread;
  319. }
  320. }
  321. CATCH(CFileException,e)
  322. {
  323. LPTSTR msg = new TCHAR[BUFSIZE];
  324. if (e->GetErrorMessage(msg, BUFSIZE))
  325. m_pOwner->ShowStatus(msg, FZ_LOG_ERROR);
  326. delete [] msg;
  327. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  328. return;
  329. }
  330. END_CATCH;
  331. m_transferdata.transferleft -= written;
  332. UpdateStatusBar(false);
  333. }
  334. }
  335. void CTransferSocket::SetBuffers()
  336. {
  337. /* Set internal socket send buffer
  338. * this should fix the speed problems some users have reported
  339. */
  340. DWORD value = 0;
  341. int len = sizeof(value);
  342. GetSockOpt(SO_SNDBUF, &value, &len);
  343. // MPEXT
  344. int sndbuf = COptions::GetOptionVal(OPTION_MPEXT_SNDBUF);
  345. if (value < sndbuf)
  346. {
  347. value = sndbuf;
  348. SetSockOpt(SO_SNDBUF, &value, sizeof(value));
  349. }
  350. // For now we increase receive buffer, whenever send buffer is set.
  351. // The size is not configurable. The constant taken from FZ.
  352. if (sndbuf > 0)
  353. {
  354. value = 0;
  355. len = sizeof(value);
  356. GetSockOpt(SO_RCVBUF, &value, &len);
  357. int rcvbuf = 4 * 1024 * 1024;
  358. if (value < rcvbuf)
  359. {
  360. value = rcvbuf;
  361. SetSockOpt(SO_RCVBUF, &value, sizeof(value));
  362. }
  363. }
  364. }
  365. void CTransferSocket::OnAccept(int nErrorCode)
  366. {
  367. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnAccept(%d)"), nErrorCode);
  368. m_bListening=FALSE;
  369. CAsyncSocketEx tmp;
  370. Accept(tmp);
  371. SOCKET socket=tmp.Detach();
  372. CAsyncSocketEx::Close();
  373. Attach(socket);
  374. SetBuffers();
  375. if (m_nTransferState == STATE_STARTING)
  376. {
  377. m_nTransferState = STATE_STARTED;
  378. #ifndef MPEXT_NO_SSL
  379. if (m_pSslLayer)
  380. {
  381. AddLayer(m_pSslLayer);
  382. int res = m_pSslLayer->InitSSLConnection(true, m_pOwner->m_pSslLayer,
  383. COptions::GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  384. COptions::GetOptionVal(OPTION_MPEXT_MIN_TLS_VERSION),
  385. COptions::GetOptionVal(OPTION_MPEXT_MAX_TLS_VERSION));
  386. if (res == SSL_FAILURE_INITSSL)
  387. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  388. if (res)
  389. {
  390. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  391. return;
  392. }
  393. }
  394. #endif
  395. #ifndef MPEXT_NO_GSS
  396. if (m_pGssLayer)
  397. {
  398. AddLayer(m_pGssLayer);
  399. }
  400. #endif
  401. m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
  402. m_LastActiveTime = CTime::GetCurrentTime();
  403. }
  404. }
  405. void CTransferSocket::ConfigureSocket()
  406. {
  407. // Note that FileZilla re-enables Nagle's alg during TLS negotiation.
  408. // Following post claims that TCP_NODELAY
  409. // has to be set before connect()
  410. // http://stackoverflow.com/questions/22583941/what-is-the-workaround-for-tcp-delayed-acknowledgment/25871250#25871250
  411. int nodelay = COptions::GetOptionVal(OPTION_MPEXT_NODELAY);
  412. if (nodelay != 0)
  413. {
  414. BOOL bvalue = TRUE;
  415. SetSockOpt(TCP_NODELAY, &bvalue, sizeof(bvalue), IPPROTO_TCP);
  416. }
  417. CAsyncSocketEx::ConfigureSocket();
  418. }
  419. void CTransferSocket::OnConnect(int nErrorCode)
  420. {
  421. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnConnect(%d)"), nErrorCode);
  422. if (nErrorCode)
  423. {
  424. TCHAR buffer[1000];
  425. memset(buffer, 0, sizeof(buffer));
  426. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, nErrorCode, 0, buffer, 999, 0);
  427. CString str;
  428. str.Format(IDS_ERRORMSG_CANTOPENTRANSFERCHANNEL,buffer);
  429. str.Replace( _T("\n"), _T("\0") );
  430. str.Replace( _T("\r"), _T("\0") );
  431. m_pOwner->ShowStatus(str, FZ_LOG_ERROR);
  432. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  433. }
  434. else
  435. {
  436. SetBuffers();
  437. m_pOwner->ShowStatus(L"Data connection opened", FZ_LOG_INFO);
  438. }
  439. if (m_nTransferState == STATE_WAITING)
  440. {
  441. // OnReceive (invoked by m_nNotifyWaiting including FD_READ)
  442. // will call back to OnConnected (as we won't be connected yet).
  443. // This is needed for file transfers only, where SetActive is
  444. // called only after 1xx response to RETR (and similar) arrives.
  445. // But we get FD_CONNECT earlier, hence we get to this branch.
  446. // With directory listing, SetActive is called before Connect,
  447. // so we are already STATE_STARTING on FD_CONNECT.
  448. // It should probably behave the same in both scenarios.
  449. m_nNotifyWaiting |= FD_READ;
  450. }
  451. else if (m_nTransferState == STATE_STARTING)
  452. {
  453. m_nTransferState = STATE_STARTED;
  454. m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
  455. m_LastActiveTime=CTime::GetCurrentTime();
  456. #ifndef MPEXT_NO_SSL
  457. if (m_pSslLayer)
  458. {
  459. AddLayer(m_pSslLayer);
  460. int res = m_pSslLayer->InitSSLConnection(true, m_pOwner->m_pSslLayer,
  461. COptions::GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  462. COptions::GetOptionVal(OPTION_MPEXT_MIN_TLS_VERSION),
  463. COptions::GetOptionVal(OPTION_MPEXT_MAX_TLS_VERSION));
  464. if (res == SSL_FAILURE_INITSSL)
  465. {
  466. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  467. }
  468. if (res)
  469. {
  470. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  471. return;
  472. }
  473. }
  474. #endif
  475. #ifndef MPEXT_NO_GSS
  476. if (m_pGssLayer)
  477. {
  478. AddLayer(m_pGssLayer);
  479. }
  480. #endif
  481. }
  482. }
  483. void CTransferSocket::OnClose(int nErrorCode)
  484. {
  485. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("OnClose(%d)"), nErrorCode);
  486. if (m_nTransferState == STATE_WAITING)
  487. {
  488. m_nNotifyWaiting |= FD_CLOSE;
  489. return;
  490. }
  491. m_pOwner->ShowStatus(L"Data connection closed", FZ_LOG_INFO);
  492. OnReceive(0);
  493. CloseAndEnsureSendClose(0);
  494. }
  495. int CTransferSocket::CheckForTimeout(int delay)
  496. {
  497. UpdateStatusBar(false);
  498. if (!m_bCheckTimeout)
  499. {
  500. // we are closed, so make sure the FTP control socket is itself checking for
  501. // timeout as we are not
  502. return 0;
  503. }
  504. CTimeSpan span = CTime::GetCurrentTime()-m_LastActiveTime;
  505. if (span.GetTotalSeconds()>=delay)
  506. {
  507. m_pOwner->ShowTimeoutError(IDS_DATA_CONNECTION);
  508. CloseAndEnsureSendClose(CSMODE_TRANSFERTIMEOUT);
  509. return 2;
  510. }
  511. return 1;
  512. }
  513. void CTransferSocket::SetActive()
  514. {
  515. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("SetActive()"));
  516. if (m_nTransferState == STATE_WAITING)
  517. m_nTransferState = STATE_STARTING;
  518. m_bCheckTimeout = TRUE;
  519. m_LastActiveTime = CTime::GetCurrentTime();
  520. if (m_nNotifyWaiting & FD_READ)
  521. OnReceive(0);
  522. if (m_nNotifyWaiting & FD_WRITE)
  523. OnSend(0);
  524. if (m_nNotifyWaiting & FD_CLOSE)
  525. OnClose(0);
  526. }
  527. void CTransferSocket::OnSend(int nErrorCode)
  528. {
  529. if (m_nTransferState == STATE_WAITING)
  530. {
  531. m_nNotifyWaiting |= FD_WRITE;
  532. return;
  533. }
  534. if (m_bSentClose)
  535. {
  536. return;
  537. }
  538. if (m_bListening)
  539. {
  540. return;
  541. }
  542. if (!(m_nMode&CSMODE_UPLOAD))
  543. {
  544. return;
  545. }
  546. if (m_nTransferState == STATE_STARTING)
  547. {
  548. OnConnect(0);
  549. }
  550. #ifndef MPEXT_NO_ZLIB
  551. if (m_useZlib)
  552. {
  553. if (!m_pBuffer)
  554. {
  555. m_pBuffer = new char[BUFSIZE];
  556. m_bufferpos = 0;
  557. m_zlibStream.next_out = (Bytef *)m_pBuffer;
  558. m_zlibStream.avail_out = BUFSIZE;
  559. }
  560. if (!m_pBuffer2)
  561. {
  562. m_pBuffer2 = new char[BUFSIZE];
  563. m_zlibStream.next_in = (Bytef *)m_pBuffer2;
  564. }
  565. bool beenWaiting = false;
  566. while (true)
  567. {
  568. int numsend;
  569. if (!m_zlibStream.avail_in)
  570. {
  571. if (m_pFile)
  572. {
  573. DWORD numread;
  574. numread = ReadDataFromFile(m_pBuffer2, BUFSIZE);
  575. if (numread < 0)
  576. {
  577. return;
  578. }
  579. m_transferdata.transferleft -= numread;
  580. m_zlibStream.next_in = (Bytef *)m_pBuffer2;
  581. m_zlibStream.avail_in = numread;
  582. if (numread < BUFSIZE)
  583. m_pFile = 0;
  584. }
  585. }
  586. if (!m_zlibStream.avail_out)
  587. {
  588. if (m_bufferpos >= BUFSIZE)
  589. {
  590. m_bufferpos = 0;
  591. m_zlibStream.next_out = (Bytef *)m_pBuffer;
  592. m_zlibStream.avail_out = BUFSIZE;
  593. }
  594. }
  595. int res = Z_OK;
  596. if (m_zlibStream.avail_out)
  597. {
  598. res = deflate(&m_zlibStream, m_pFile ? 0 : Z_FINISH);
  599. if (res != Z_OK && (!m_pFile && res != Z_STREAM_END))
  600. {
  601. m_pOwner->ShowStatus("Decompression error", FZ_LOG_ERROR);
  602. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  603. return;
  604. }
  605. }
  606. numsend = BUFSIZE;
  607. int len = BUFSIZE - m_bufferpos - m_zlibStream.avail_out;
  608. if (!len && !m_pFile)
  609. {
  610. break;
  611. }
  612. if (len < BUFSIZE)
  613. numsend = len;
  614. int nLimit = (int)m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
  615. if (nLimit != -1 && GetState() != closed && numsend > nLimit)
  616. numsend = nLimit;
  617. if (!numsend)
  618. {
  619. TriggerEvent(FD_WRITE);
  620. return;
  621. }
  622. int numsent = Send(m_pBuffer + m_bufferpos, numsend);
  623. if (numsent == SOCKET_ERROR)
  624. {
  625. int nError = GetLastError();
  626. if (nError == WSAENOTCONN)
  627. {
  628. //Not yet connected
  629. return;
  630. }
  631. #ifndef MPEXT_NO_SSL
  632. else if (m_pSslLayer && nError == WSAESHUTDOWN)
  633. {
  634. // Do nothing, wait for shutdown complete notification.
  635. return;
  636. }
  637. #endif
  638. else if (nError != WSAEWOULDBLOCK)
  639. {
  640. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  641. }
  642. UpdateStatusBar(false);
  643. return;
  644. }
  645. Transfered( numsent, CTime::GetCurrentTime());
  646. m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
  647. m_LastActiveTime = CTime::GetCurrentTime();
  648. UpdateSendLed();
  649. m_bufferpos += numsent;
  650. UpdateStatusBar(false);
  651. if (!m_zlibStream.avail_in && !m_pFile && m_zlibStream.avail_out &&
  652. m_zlibStream.avail_out + m_bufferpos == BUFSIZE && res == Z_STREAM_END)
  653. {
  654. CloseOnShutDownOrError(0);
  655. return;
  656. }
  657. //Check if there are other commands in the command queue.
  658. MSG msg;
  659. if (PeekMessage(&msg,0, 0, 0, PM_NOREMOVE))
  660. {
  661. TriggerEvent(FD_WRITE);
  662. return;
  663. }
  664. }
  665. }
  666. else
  667. #endif
  668. {
  669. if (!m_pFile)
  670. {
  671. return;
  672. }
  673. if (!m_pBuffer)
  674. m_pBuffer = new char[BUFSIZE];
  675. int numread;
  676. bool beenWaiting = false;
  677. _int64 currentBufferSize;
  678. if (GetState() != closed)
  679. currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
  680. else
  681. currentBufferSize = BUFSIZE;
  682. if (!currentBufferSize && !m_bufferpos)
  683. {
  684. // Not allowed to send yet, try later
  685. TriggerEvent(FD_WRITE);
  686. return;
  687. }
  688. else if (m_bufferpos < currentBufferSize)
  689. {
  690. numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
  691. if (numread < 0 )
  692. {
  693. return;
  694. }
  695. else if (!numread && !m_bufferpos)
  696. {
  697. CloseOnShutDownOrError(0);
  698. return;
  699. }
  700. }
  701. else
  702. numread = 0;
  703. ASSERT((numread+m_bufferpos) <= BUFSIZE);
  704. ASSERT(numread>=0);
  705. ASSERT(m_bufferpos>=0);
  706. if (numread+m_bufferpos <= 0)
  707. {
  708. CloseOnShutDownOrError(0);
  709. return;
  710. }
  711. int numsent = Send(m_pBuffer, numread + m_bufferpos);
  712. while (TRUE)
  713. {
  714. if (numsent != SOCKET_ERROR)
  715. {
  716. Transfered(numsent, CTime::GetCurrentTime());
  717. m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
  718. m_LastActiveTime = CTime::GetCurrentTime();
  719. UpdateSendLed();
  720. m_transferdata.transferleft -= numsent;
  721. }
  722. if (numsent==SOCKET_ERROR || !numsent)
  723. {
  724. int nError = GetLastError();
  725. if (nError == WSAENOTCONN)
  726. {
  727. //Not yet connected
  728. m_bufferpos += numread;
  729. return;
  730. }
  731. else if (nError == WSAEWOULDBLOCK)
  732. {
  733. m_bufferpos += numread;
  734. }
  735. #ifndef MPEXT_NO_SSL
  736. else if (m_pSslLayer && nError == WSAESHUTDOWN)
  737. {
  738. m_bufferpos += numread;
  739. // Do nothing, wait for shutdown complete notification.
  740. return;
  741. }
  742. #endif
  743. else
  744. {
  745. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  746. }
  747. UpdateStatusBar(false);
  748. return;
  749. }
  750. else
  751. {
  752. int pos = numread + m_bufferpos - numsent;
  753. if (pos < 0 || (numsent + pos) > BUFSIZE)
  754. {
  755. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Index out of range"));
  756. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  757. return;
  758. }
  759. else if (!pos && numread < (currentBufferSize-m_bufferpos) && m_bufferpos != currentBufferSize)
  760. {
  761. CloseOnShutDownOrError(0);
  762. return;
  763. }
  764. else if (!pos)
  765. {
  766. m_bufferpos = 0;
  767. }
  768. else
  769. {
  770. memmove(m_pBuffer, m_pBuffer+numsent, pos);
  771. m_bufferpos=pos;
  772. }
  773. }
  774. //Check if there are other commands in the command queue.
  775. MSG msg;
  776. if (PeekMessage(&msg, 0, m_nInternalMessageID, m_nInternalMessageID, PM_NOREMOVE))
  777. {
  778. //Send resume message
  779. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("Message waiting in queue, resuming later"));
  780. TriggerEvent(FD_WRITE);
  781. UpdateStatusBar(false);
  782. return;
  783. }
  784. UpdateStatusBar(false);
  785. if (GetState() != closed)
  786. currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
  787. else
  788. currentBufferSize = BUFSIZE;
  789. if (m_bufferpos < currentBufferSize)
  790. {
  791. numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
  792. if (numread < 0 )
  793. {
  794. return;
  795. }
  796. else if (!numread && !m_bufferpos)
  797. {
  798. CloseOnShutDownOrError(0);
  799. return;
  800. }
  801. }
  802. else
  803. {
  804. numread = 0;
  805. }
  806. if (!currentBufferSize && !m_bufferpos)
  807. {
  808. // Not allowed to send yet, try later
  809. TriggerEvent(FD_WRITE);
  810. return;
  811. }
  812. ASSERT(numread>=0);
  813. ASSERT(m_bufferpos>=0);
  814. numsent = Send(m_pBuffer, numread+m_bufferpos);
  815. }
  816. }
  817. }
  818. void CTransferSocket::UpdateStatusBar(bool forceUpdate)
  819. {
  820. if (m_nTransferState != STATE_STARTED)
  821. return;
  822. if (!forceUpdate)
  823. {
  824. //Don't flood the main window with messages
  825. //Else performance would be really low
  826. LARGE_INTEGER curtime;
  827. LARGE_INTEGER freq;
  828. QueryPerformanceFrequency(&freq);
  829. QueryPerformanceCounter(&curtime);
  830. if (((curtime.QuadPart-m_LastUpdateTime.QuadPart) < (freq.QuadPart/15) ) )
  831. return;
  832. m_LastUpdateTime = curtime;
  833. }
  834. //Update the statusbar
  835. CTimeSpan timespan=CTime::GetCurrentTime()-m_StartTime;
  836. int elapsed=(int)timespan.GetTotalSeconds();
  837. t_ffam_transferstatus *status=new t_ffam_transferstatus;
  838. status->bFileTransfer = m_nMode & (CSMODE_DOWNLOAD | CSMODE_UPLOAD);
  839. #ifdef MPEXT
  840. status->transfersize = m_transferdata.transfersize;
  841. #endif
  842. status->timeelapsed=elapsed;
  843. status->bytes=m_transferdata.transfersize-m_transferdata.transferleft;
  844. if (m_transferdata.transfersize>0 && !(m_nMode&CSMODE_LIST))
  845. {
  846. double leftmodifier=static_cast<double>(m_transferdata.transfersize-m_transferdata.nTransferStart-m_transferdata.transferleft);
  847. leftmodifier*=100;
  848. if (m_transferdata.transfersize-m_transferdata.nTransferStart)
  849. leftmodifier /= (m_transferdata.transfersize-m_transferdata.nTransferStart);
  850. else
  851. leftmodifier = 1;
  852. if (leftmodifier == 0)
  853. leftmodifier = 1;
  854. double leftmodifier2 = 100 - leftmodifier;
  855. int left=static_cast<int>((elapsed/leftmodifier)*leftmodifier2);
  856. double percent=100*static_cast<double>(m_transferdata.transfersize-m_transferdata.transferleft);
  857. percent/=m_transferdata.transfersize;
  858. status->percent=static_cast<int>(percent);
  859. if (status->percent>100)
  860. status->percent=100;
  861. if (left < 0)
  862. left = -1;
  863. status->timeleft=left;
  864. }
  865. else
  866. {
  867. status->percent=-1;
  868. status->timeleft=-1;
  869. }
  870. int count = 0;
  871. status->transferrate = 0;
  872. for ( int i = 0; i < SPEED_SECONDS; i++)
  873. {
  874. if ( m_UsedForTransfer[ i])
  875. {
  876. status->transferrate += m_Transfered[ i];
  877. count++;
  878. }
  879. }
  880. if ( count > 0)
  881. status->transferrate = status->transferrate / count;
  882. else if (m_Transfered[0])
  883. status->transferrate = m_Transfered[0];
  884. else
  885. status->timeleft=-1;
  886. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
  887. }
  888. void CTransferSocket::UpdateSendLed()
  889. {
  890. //Don't flood the main window with messages
  891. //Else performance would be really low
  892. LARGE_INTEGER curtime;
  893. LARGE_INTEGER freq;
  894. QueryPerformanceFrequency(&freq);
  895. QueryPerformanceCounter(&curtime);
  896. static LARGE_INTEGER oldtime={0};
  897. if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
  898. return;
  899. oldtime=curtime;
  900. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
  901. }
  902. void CTransferSocket::UpdateRecvLed()
  903. {
  904. //Don't flood the main window with messages
  905. //Else performance would be really low
  906. LARGE_INTEGER curtime;
  907. LARGE_INTEGER freq;
  908. QueryPerformanceFrequency(&freq);
  909. QueryPerformanceCounter(&curtime);
  910. static LARGE_INTEGER oldtime={0};
  911. if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
  912. return;
  913. oldtime=curtime;
  914. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_RECV), 0);
  915. }
  916. BOOL CTransferSocket::Create(
  917. #ifndef MPEXT_NO_SSL
  918. BOOL bUseSsl
  919. #endif
  920. )
  921. {
  922. #ifndef MPEXT_NO_SSL
  923. if (bUseSsl)
  924. m_pSslLayer = new CAsyncSslSocketLayer;
  925. #endif
  926. if (!m_pOwner->m_CurrentServer.fwbypass)
  927. {
  928. int nProxyType = COptions::GetOptionVal(OPTION_PROXYTYPE);
  929. if (nProxyType != PROXYTYPE_NOPROXY)
  930. {
  931. USES_CONVERSION;
  932. m_pProxyLayer = new CAsyncProxySocketLayer;
  933. if (nProxyType == PROXYTYPE_SOCKS4)
  934. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
  935. else if (nProxyType == PROXYTYPE_SOCKS4A)
  936. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
  937. else if (nProxyType == PROXYTYPE_SOCKS5)
  938. if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
  939. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
  940. COptions::GetOptionVal(OPTION_PROXYPORT),
  941. T2CA(COptions::GetOption(OPTION_PROXYUSER)),
  942. T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
  943. else
  944. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
  945. COptions::GetOptionVal(OPTION_PROXYPORT));
  946. else if (nProxyType == PROXYTYPE_HTTP11)
  947. if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
  948. m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT),
  949. T2CA(COptions::GetOption(OPTION_PROXYUSER)),
  950. T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
  951. else
  952. m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
  953. else
  954. ASSERT(FALSE);
  955. AddLayer(m_pProxyLayer);
  956. }
  957. }
  958. if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
  959. {
  960. if (!CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
  961. return FALSE;
  962. return TRUE;
  963. }
  964. else
  965. {
  966. int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
  967. int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
  968. if (min>=max)
  969. {
  970. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  971. return FALSE;
  972. }
  973. int startport=static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
  974. int port=startport;
  975. while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
  976. {
  977. port++;
  978. if (port>max)
  979. port=min;
  980. if (port==startport)
  981. {
  982. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  983. return FALSE;
  984. }
  985. }
  986. }
  987. return TRUE;
  988. }
  989. void CTransferSocket::Close()
  990. {
  991. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Close()"));
  992. m_bCheckTimeout = FALSE;
  993. CAsyncSocketEx::Close();
  994. }
  995. int CTransferSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  996. {
  997. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  998. {
  999. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  1000. {
  1001. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  1002. {
  1003. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  1004. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  1005. if (iter->pLayer == m_pProxyLayer)
  1006. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Proxy layer changed state from %s to %s"), state2Desc, state1Desc);
  1007. #ifndef MPEXT_NO_SSL
  1008. else if (iter->pLayer == m_pSslLayer)
  1009. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("TLS layer changed state from %s to %s"), state2Desc, state1Desc);
  1010. #endif
  1011. #ifndef MPEXT_NO_GSS
  1012. else if (iter->pLayer == m_pGssLayer)
  1013. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("GSS layer changed state from %s to %s"), state2Desc, state1Desc);
  1014. #endif
  1015. else
  1016. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %s to %s"), iter->pLayer, state2Desc, state1Desc);
  1017. }
  1018. }
  1019. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  1020. {
  1021. if (iter->pLayer == m_pProxyLayer)
  1022. {
  1023. switch (iter->nParam1)
  1024. {
  1025. case PROXYERROR_NOERROR:
  1026. m_pOwner->ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  1027. break;
  1028. case PROXYERROR_NOCONN:
  1029. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  1030. break;
  1031. case PROXYERROR_REQUESTFAILED:
  1032. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  1033. break;
  1034. case PROXYERROR_AUTHTYPEUNKNOWN:
  1035. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  1036. break;
  1037. case PROXYERROR_AUTHFAILED:
  1038. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  1039. break;
  1040. case PROXYERROR_AUTHNOLOGON:
  1041. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  1042. break;
  1043. case PROXYERROR_CANTRESOLVEHOST:
  1044. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  1045. break;
  1046. default:
  1047. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error"));
  1048. }
  1049. }
  1050. #ifndef MPEXT_NO_SSL
  1051. else if (iter->pLayer == m_pSslLayer)
  1052. {
  1053. switch (iter->nParam1)
  1054. {
  1055. case SSL_INFO:
  1056. switch(iter->nParam2)
  1057. {
  1058. case SSL_INFO_SHUTDOWNCOMPLETE:
  1059. CloseAndEnsureSendClose(0);
  1060. break;
  1061. case SSL_INFO_ESTABLISHED:
  1062. m_pOwner->ShowStatus(IDS_STATUSMSG_SSLESTABLISHEDTRANSFER, FZ_LOG_STATUS);
  1063. TriggerEvent(FD_FORCEREAD);
  1064. break;
  1065. }
  1066. break;
  1067. case SSL_FAILURE:
  1068. switch (iter->nParam2)
  1069. {
  1070. case SSL_FAILURE_ESTABLISH:
  1071. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
  1072. break;
  1073. case SSL_FAILURE_INITSSL:
  1074. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  1075. break;
  1076. }
  1077. EnsureSendClose(CSMODE_TRANSFERERROR);
  1078. break;
  1079. case SSL_VERIFY_CERT:
  1080. t_SslCertData data;
  1081. LPTSTR CertError = NULL;
  1082. if (m_pSslLayer->GetPeerCertificateData(data, CertError))
  1083. m_pSslLayer->SetNotifyReply(data.priv_data, SSL_VERIFY_CERT, 1);
  1084. else
  1085. {
  1086. CString str;
  1087. str.Format(TLS_CERT_DECODE_ERROR, CertError);
  1088. m_pOwner->ShowStatus(str, FZ_LOG_ERROR);
  1089. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  1090. }
  1091. break;
  1092. }
  1093. }
  1094. #endif
  1095. #ifndef MPEXT_NO_GSS
  1096. else if (iter->pLayer == m_pGssLayer)
  1097. {
  1098. USES_CONVERSION;
  1099. switch (iter->nParam1)
  1100. {
  1101. case GSS_INFO:
  1102. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  1103. break;
  1104. case GSS_ERROR:
  1105. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  1106. break;
  1107. case GSS_SHUTDOWN_COMPLETE:
  1108. CloseAndEnsureSendClose(0);
  1109. break;
  1110. }
  1111. }
  1112. #endif
  1113. }
  1114. delete [] iter->str;
  1115. }
  1116. return 0;
  1117. }
  1118. void CTransferSocket::Transfered(int count, CTime time)
  1119. {
  1120. CTimeSpan ts = time - m_TransferedFirst;
  1121. int diff = (int)ts.GetTotalSeconds();
  1122. if (diff < 0)
  1123. diff = 0;
  1124. if ( diff >= SPEED_SECONDS)
  1125. {
  1126. int move = diff - SPEED_SECONDS + 1;
  1127. int start = SPEED_SECONDS - move;
  1128. if ( start <= 0)
  1129. start = 0;
  1130. else
  1131. {
  1132. for ( int i = 0; i < SPEED_SECONDS - move; i++)
  1133. {
  1134. m_Transfered[ i] = m_Transfered[ i + move];
  1135. m_UsedForTransfer[ i] = m_UsedForTransfer[ i + move];
  1136. }
  1137. }
  1138. for ( int i = start; i < SPEED_SECONDS; i++)
  1139. {
  1140. m_Transfered[ i] = 0;
  1141. m_UsedForTransfer[ i] = false;
  1142. }
  1143. if (move >= SPEED_SECONDS)
  1144. {
  1145. m_TransferedFirst = time;
  1146. diff = 0;
  1147. }
  1148. else
  1149. {
  1150. m_TransferedFirst += CTimeSpan( move);
  1151. ts = time - m_TransferedFirst;
  1152. diff = (int)(ts.GetTotalSeconds() % 60);
  1153. }
  1154. }
  1155. m_Transfered[ diff] += count;
  1156. for ( int i = 0; i < diff - 1; i++)
  1157. m_UsedForTransfer[ i] = true;
  1158. }
  1159. #ifndef MPEXT_NO_GSS
  1160. void CTransferSocket::UseGSS(CAsyncGssSocketLayer *pGssLayer)
  1161. {
  1162. m_pGssLayer = new CAsyncGssSocketLayer;
  1163. m_pGssLayer->InitTransferChannel(pGssLayer);
  1164. }
  1165. #endif
  1166. #ifndef MPEXT_NO_ZLIB
  1167. bool CTransferSocket::InitZlib(int level)
  1168. {
  1169. int res;
  1170. if (m_nMode & CSMODE_UPLOAD)
  1171. res = deflateInit2(&m_zlibStream, level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
  1172. else
  1173. res = inflateInit2(&m_zlibStream, 15);
  1174. if (res == Z_OK)
  1175. m_useZlib = true;
  1176. return res == Z_OK;
  1177. }
  1178. #endif
  1179. int CTransferSocket::ReadDataFromFile(char *buffer, int len)
  1180. {
  1181. TRY
  1182. {
  1183. // Comparing to Filezilla 2, we do not do any translation locally,
  1184. // leaving it onto the server (what Filezilla 3 seems to do too)
  1185. const char Bom[3] = "\xEF\xBB\xBF";
  1186. int read = m_pFile->Read(buffer, len);
  1187. if (COptions::GetOptionVal(OPTION_MPEXT_REMOVE_BOM) &&
  1188. m_transferdata.bType && (read >= sizeof(Bom)) && (memcmp(buffer, Bom, sizeof(Bom)) == 0))
  1189. {
  1190. memcpy(buffer, buffer + sizeof(Bom), read - sizeof(Bom));
  1191. read -= sizeof(Bom);
  1192. int read2 = m_pFile->Read(buffer + read, sizeof(Bom));
  1193. if (read2 > 0)
  1194. {
  1195. read += read2;
  1196. }
  1197. }
  1198. return read;
  1199. }
  1200. CATCH_ALL(e)
  1201. {
  1202. TCHAR error[BUFSIZE];
  1203. if (e->GetErrorMessage(error, BUFSIZE))
  1204. m_pOwner->ShowStatus(error, FZ_LOG_ERROR);
  1205. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  1206. return -1;
  1207. }
  1208. END_CATCH_ALL;
  1209. }
  1210. void CTransferSocket::LogSocketMessage(int nMessageType, LPCTSTR pMsgFormat)
  1211. {
  1212. LogMessage(nMessageType, pMsgFormat);
  1213. }
  1214. void CTransferSocket::EnsureSendClose(int Mode)
  1215. {
  1216. if (!m_bSentClose)
  1217. {
  1218. if (Mode != 0)
  1219. {
  1220. m_nMode |= Mode;
  1221. }
  1222. m_bSentClose = TRUE;
  1223. VERIFY(m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode));
  1224. }
  1225. }
  1226. void CTransferSocket::CloseAndEnsureSendClose(int Mode)
  1227. {
  1228. Close();
  1229. EnsureSendClose(Mode);
  1230. }
  1231. void CTransferSocket::CloseOnShutDownOrError(int Mode)
  1232. {
  1233. if (ShutDown())
  1234. {
  1235. CloseAndEnsureSendClose(Mode);
  1236. }
  1237. else
  1238. {
  1239. int Error = GetLastError();
  1240. if (Error != WSAEWOULDBLOCK)
  1241. {
  1242. // Log always or only when (Mode & CSMODE_TRANSFERERROR)?
  1243. // Does it anyway make sense at all to call this with Mode == 0?
  1244. LogError(Error);
  1245. CloseAndEnsureSendClose(Mode);
  1246. }
  1247. }
  1248. }
  1249. void CTransferSocket::LogError(int Error)
  1250. {
  1251. wchar_t * Buffer;
  1252. int Len = FormatMessage(
  1253. FORMAT_MESSAGE_FROM_SYSTEM |
  1254. FORMAT_MESSAGE_IGNORE_INSERTS |
  1255. FORMAT_MESSAGE_ARGUMENT_ARRAY |
  1256. FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, Error, 0, (LPTSTR)&Buffer, 0, NULL);
  1257. if (Len > 0)
  1258. {
  1259. m_pOwner->ShowStatus(Buffer, FZ_LOG_ERROR);
  1260. LocalFree(Buffer);
  1261. }
  1262. }