TransferSocket.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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::OnAccept(int nErrorCode)
  336. {
  337. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnAccept(%d)"), nErrorCode);
  338. m_bListening=FALSE;
  339. CAsyncSocketEx tmp;
  340. Accept(tmp);
  341. SOCKET socket=tmp.Detach();
  342. CAsyncSocketEx::Close();
  343. Attach(socket);
  344. /* Set internal socket send buffer
  345. * this should fix the speed problems some users have reported
  346. */
  347. DWORD value;
  348. int len = sizeof(value);
  349. GetSockOpt(SO_SNDBUF, &value, &len);
  350. // MPEXT
  351. int sndbuf = COptions::GetOptionVal(OPTION_MPEXT_SNDBUF);
  352. if (value < sndbuf)
  353. {
  354. value = sndbuf;
  355. SetSockOpt(SO_SNDBUF, &value, sizeof(value));
  356. }
  357. if (m_nTransferState == STATE_STARTING)
  358. {
  359. m_nTransferState = STATE_STARTED;
  360. #ifndef MPEXT_NO_SSL
  361. if (m_pSslLayer)
  362. {
  363. AddLayer(m_pSslLayer);
  364. int res = m_pSslLayer->InitSSLConnection(true, m_pOwner->m_pSslLayer,
  365. COptions::GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  366. COptions::GetOptionVal(OPTION_MPEXT_MIN_TLS_VERSION),
  367. COptions::GetOptionVal(OPTION_MPEXT_MAX_TLS_VERSION));
  368. if (res == SSL_FAILURE_INITSSL)
  369. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  370. if (res)
  371. {
  372. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  373. return;
  374. }
  375. }
  376. #endif
  377. #ifndef MPEXT_NO_GSS
  378. if (m_pGssLayer)
  379. {
  380. AddLayer(m_pGssLayer);
  381. }
  382. #endif
  383. m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
  384. m_LastActiveTime = CTime::GetCurrentTime();
  385. }
  386. }
  387. void CTransferSocket::ConfigureSocket()
  388. {
  389. // Note that FileZilla re-enables Nagle's alg during TLS negotiation.
  390. // Following post claims that TCP_NODELAY
  391. // has to be set before connect()
  392. // http://stackoverflow.com/questions/22583941/what-is-the-workaround-for-tcp-delayed-acknowledgment/25871250#25871250
  393. int nodelay = COptions::GetOptionVal(OPTION_MPEXT_NODELAY);
  394. if (nodelay != 0)
  395. {
  396. BOOL bvalue = TRUE;
  397. SetSockOpt(TCP_NODELAY, &bvalue, sizeof(bvalue), IPPROTO_TCP);
  398. }
  399. CAsyncSocketEx::ConfigureSocket();
  400. }
  401. void CTransferSocket::OnConnect(int nErrorCode)
  402. {
  403. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnConnect(%d)"), nErrorCode);
  404. if (nErrorCode)
  405. {
  406. TCHAR buffer[1000];
  407. memset(buffer, 0, sizeof(buffer));
  408. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, nErrorCode, 0, buffer, 999, 0);
  409. CString str;
  410. str.Format(IDS_ERRORMSG_CANTOPENTRANSFERCHANNEL,buffer);
  411. str.Replace( _T("\n"), _T("\0") );
  412. str.Replace( _T("\r"), _T("\0") );
  413. m_pOwner->ShowStatus(str, FZ_LOG_ERROR);
  414. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  415. }
  416. else
  417. {
  418. /* Set internal socket send buffer
  419. * this should fix the speed problems some users have reported
  420. */
  421. DWORD value;
  422. int len = sizeof(value);
  423. GetSockOpt(SO_SNDBUF, &value, &len);
  424. // MPEXT
  425. int sndbuf = COptions::GetOptionVal(OPTION_MPEXT_SNDBUF);
  426. if (value < sndbuf)
  427. {
  428. value = sndbuf;
  429. SetSockOpt(SO_SNDBUF, &value, sizeof(value));
  430. }
  431. }
  432. if (m_nTransferState == STATE_WAITING)
  433. {
  434. // OnReceive (invoked by m_nNotifyWaiting including FD_READ)
  435. // will call back to OnConnected (as we won't be connected yet).
  436. // This is needed for file transfers only, where SetActive is
  437. // called only after 1xx response to RETR (and similar) arrives.
  438. // But we get FD_CONNECT earlier, hence we get to this branch.
  439. // With directory listing, SetActive is called before Connect,
  440. // so we are already STATE_STARTING on FD_CONNECT.
  441. // It should probably behave the same in both scenarios.
  442. m_nNotifyWaiting |= FD_READ;
  443. }
  444. else if (m_nTransferState == STATE_STARTING)
  445. {
  446. m_nTransferState = STATE_STARTED;
  447. m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
  448. m_LastActiveTime=CTime::GetCurrentTime();
  449. #ifndef MPEXT_NO_SSL
  450. if (m_pSslLayer)
  451. {
  452. AddLayer(m_pSslLayer);
  453. int res = m_pSslLayer->InitSSLConnection(true, m_pOwner->m_pSslLayer,
  454. COptions::GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  455. COptions::GetOptionVal(OPTION_MPEXT_MIN_TLS_VERSION),
  456. COptions::GetOptionVal(OPTION_MPEXT_MAX_TLS_VERSION));
  457. if (res == SSL_FAILURE_INITSSL)
  458. {
  459. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  460. }
  461. if (res)
  462. {
  463. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  464. return;
  465. }
  466. }
  467. #endif
  468. #ifndef MPEXT_NO_GSS
  469. if (m_pGssLayer)
  470. {
  471. AddLayer(m_pGssLayer);
  472. }
  473. #endif
  474. }
  475. }
  476. void CTransferSocket::OnClose(int nErrorCode)
  477. {
  478. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("OnClose(%d)"), nErrorCode);
  479. if (m_nTransferState == STATE_WAITING)
  480. {
  481. m_nNotifyWaiting |= FD_CLOSE;
  482. return;
  483. }
  484. OnReceive(0);
  485. CloseAndEnsureSendClose(0);
  486. }
  487. int CTransferSocket::CheckForTimeout(int delay)
  488. {
  489. UpdateStatusBar(false);
  490. if (!m_bCheckTimeout)
  491. {
  492. // we are closed, so make sure the FTP control socket is itself checking for
  493. // timeout as we are not
  494. return 0;
  495. }
  496. CTimeSpan span = CTime::GetCurrentTime()-m_LastActiveTime;
  497. if (span.GetTotalSeconds()>=delay)
  498. {
  499. m_pOwner->ShowStatus(IDS_ERRORMSG_TIMEOUT, FZ_LOG_ERROR);
  500. CloseAndEnsureSendClose(CSMODE_TRANSFERTIMEOUT);
  501. return 2;
  502. }
  503. return 1;
  504. }
  505. void CTransferSocket::SetActive()
  506. {
  507. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("SetActive()"));
  508. if (m_nTransferState == STATE_WAITING)
  509. m_nTransferState = STATE_STARTING;
  510. m_bCheckTimeout = TRUE;
  511. m_LastActiveTime = CTime::GetCurrentTime();
  512. if (m_nNotifyWaiting & FD_READ)
  513. OnReceive(0);
  514. if (m_nNotifyWaiting & FD_WRITE)
  515. OnSend(0);
  516. if (m_nNotifyWaiting & FD_CLOSE)
  517. OnClose(0);
  518. }
  519. void CTransferSocket::OnSend(int nErrorCode)
  520. {
  521. if (m_nTransferState == STATE_WAITING)
  522. {
  523. m_nNotifyWaiting |= FD_WRITE;
  524. return;
  525. }
  526. if (m_bSentClose)
  527. {
  528. return;
  529. }
  530. if (m_bListening)
  531. {
  532. return;
  533. }
  534. if (!(m_nMode&CSMODE_UPLOAD))
  535. {
  536. return;
  537. }
  538. if (m_nTransferState == STATE_STARTING)
  539. {
  540. OnConnect(0);
  541. }
  542. #ifndef MPEXT_NO_ZLIB
  543. if (m_useZlib)
  544. {
  545. if (!m_pBuffer)
  546. {
  547. m_pBuffer = new char[BUFSIZE];
  548. m_bufferpos = 0;
  549. m_zlibStream.next_out = (Bytef *)m_pBuffer;
  550. m_zlibStream.avail_out = BUFSIZE;
  551. }
  552. if (!m_pBuffer2)
  553. {
  554. m_pBuffer2 = new char[BUFSIZE];
  555. m_zlibStream.next_in = (Bytef *)m_pBuffer2;
  556. }
  557. bool beenWaiting = false;
  558. while (true)
  559. {
  560. int numsend;
  561. if (!m_zlibStream.avail_in)
  562. {
  563. if (m_pFile)
  564. {
  565. DWORD numread;
  566. numread = ReadDataFromFile(m_pBuffer2, BUFSIZE);
  567. if (numread < 0)
  568. {
  569. return;
  570. }
  571. m_transferdata.transferleft -= numread;
  572. m_zlibStream.next_in = (Bytef *)m_pBuffer2;
  573. m_zlibStream.avail_in = numread;
  574. if (numread < BUFSIZE)
  575. m_pFile = 0;
  576. }
  577. }
  578. if (!m_zlibStream.avail_out)
  579. {
  580. if (m_bufferpos >= BUFSIZE)
  581. {
  582. m_bufferpos = 0;
  583. m_zlibStream.next_out = (Bytef *)m_pBuffer;
  584. m_zlibStream.avail_out = BUFSIZE;
  585. }
  586. }
  587. int res = Z_OK;
  588. if (m_zlibStream.avail_out)
  589. {
  590. res = deflate(&m_zlibStream, m_pFile ? 0 : Z_FINISH);
  591. if (res != Z_OK && (!m_pFile && res != Z_STREAM_END))
  592. {
  593. m_pOwner->ShowStatus("Decompression error", FZ_LOG_ERROR);
  594. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  595. return;
  596. }
  597. }
  598. numsend = BUFSIZE;
  599. int len = BUFSIZE - m_bufferpos - m_zlibStream.avail_out;
  600. if (!len && !m_pFile)
  601. {
  602. break;
  603. }
  604. if (len < BUFSIZE)
  605. numsend = len;
  606. int nLimit = (int)m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
  607. if (nLimit != -1 && GetState() != closed && numsend > nLimit)
  608. numsend = nLimit;
  609. if (!numsend)
  610. {
  611. TriggerEvent(FD_WRITE);
  612. return;
  613. }
  614. int numsent = Send(m_pBuffer + m_bufferpos, numsend);
  615. if (numsent == SOCKET_ERROR)
  616. {
  617. int nError = GetLastError();
  618. if (nError == WSAENOTCONN)
  619. {
  620. //Not yet connected
  621. return;
  622. }
  623. #ifndef MPEXT_NO_SSL
  624. else if (m_pSslLayer && nError == WSAESHUTDOWN)
  625. {
  626. // Do nothing, wait for shutdown complete notification.
  627. return;
  628. }
  629. #endif
  630. else if (nError != WSAEWOULDBLOCK)
  631. {
  632. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  633. }
  634. UpdateStatusBar(false);
  635. return;
  636. }
  637. Transfered( numsent, CTime::GetCurrentTime());
  638. m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
  639. m_LastActiveTime = CTime::GetCurrentTime();
  640. UpdateSendLed();
  641. m_bufferpos += numsent;
  642. UpdateStatusBar(false);
  643. if (!m_zlibStream.avail_in && !m_pFile && m_zlibStream.avail_out &&
  644. m_zlibStream.avail_out + m_bufferpos == BUFSIZE && res == Z_STREAM_END)
  645. {
  646. CloseOnShutDownOrError(0);
  647. return;
  648. }
  649. //Check if there are other commands in the command queue.
  650. MSG msg;
  651. if (PeekMessage(&msg,0, 0, 0, PM_NOREMOVE))
  652. {
  653. TriggerEvent(FD_WRITE);
  654. return;
  655. }
  656. }
  657. }
  658. else
  659. #endif
  660. {
  661. if (!m_pFile)
  662. {
  663. return;
  664. }
  665. if (!m_pBuffer)
  666. m_pBuffer = new char[BUFSIZE];
  667. int numread;
  668. bool beenWaiting = false;
  669. _int64 currentBufferSize;
  670. if (GetState() != closed)
  671. currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
  672. else
  673. currentBufferSize = BUFSIZE;
  674. if (!currentBufferSize && !m_bufferpos)
  675. {
  676. // Not allowed to send yet, try later
  677. TriggerEvent(FD_WRITE);
  678. return;
  679. }
  680. else if (m_bufferpos < currentBufferSize)
  681. {
  682. numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
  683. if (numread < 0 )
  684. {
  685. return;
  686. }
  687. else if (!numread && !m_bufferpos)
  688. {
  689. CloseOnShutDownOrError(0);
  690. return;
  691. }
  692. }
  693. else
  694. numread = 0;
  695. ASSERT((numread+m_bufferpos) <= BUFSIZE);
  696. ASSERT(numread>=0);
  697. ASSERT(m_bufferpos>=0);
  698. if (numread+m_bufferpos <= 0)
  699. {
  700. CloseOnShutDownOrError(0);
  701. return;
  702. }
  703. int numsent = Send(m_pBuffer, numread + m_bufferpos);
  704. while (TRUE)
  705. {
  706. if (numsent != SOCKET_ERROR)
  707. {
  708. Transfered(numsent, CTime::GetCurrentTime());
  709. m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
  710. m_LastActiveTime = CTime::GetCurrentTime();
  711. UpdateSendLed();
  712. m_transferdata.transferleft -= numsent;
  713. }
  714. if (numsent==SOCKET_ERROR || !numsent)
  715. {
  716. int nError = GetLastError();
  717. if (nError == WSAENOTCONN)
  718. {
  719. //Not yet connected
  720. m_bufferpos += numread;
  721. return;
  722. }
  723. else if (nError == WSAEWOULDBLOCK)
  724. {
  725. m_bufferpos += numread;
  726. }
  727. #ifndef MPEXT_NO_SSL
  728. else if (m_pSslLayer && nError == WSAESHUTDOWN)
  729. {
  730. m_bufferpos += numread;
  731. // Do nothing, wait for shutdown complete notification.
  732. return;
  733. }
  734. #endif
  735. else
  736. {
  737. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  738. }
  739. UpdateStatusBar(false);
  740. return;
  741. }
  742. else
  743. {
  744. int pos = numread + m_bufferpos - numsent;
  745. if (pos < 0 || (numsent + pos) > BUFSIZE)
  746. {
  747. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Index out of range"));
  748. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  749. return;
  750. }
  751. else if (!pos && numread < (currentBufferSize-m_bufferpos) && m_bufferpos != currentBufferSize)
  752. {
  753. CloseOnShutDownOrError(0);
  754. return;
  755. }
  756. else if (!pos)
  757. {
  758. m_bufferpos = 0;
  759. }
  760. else
  761. {
  762. memmove(m_pBuffer, m_pBuffer+numsent, pos);
  763. m_bufferpos=pos;
  764. }
  765. }
  766. //Check if there are other commands in the command queue.
  767. MSG msg;
  768. if (PeekMessage(&msg, 0, m_nInternalMessageID, m_nInternalMessageID, PM_NOREMOVE))
  769. {
  770. //Send resume message
  771. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("Message waiting in queue, resuming later"));
  772. TriggerEvent(FD_WRITE);
  773. UpdateStatusBar(false);
  774. return;
  775. }
  776. UpdateStatusBar(false);
  777. if (GetState() != closed)
  778. currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
  779. else
  780. currentBufferSize = BUFSIZE;
  781. if (m_bufferpos < currentBufferSize)
  782. {
  783. numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
  784. if (numread < 0 )
  785. {
  786. return;
  787. }
  788. else if (!numread && !m_bufferpos)
  789. {
  790. CloseOnShutDownOrError(0);
  791. return;
  792. }
  793. }
  794. else
  795. {
  796. numread = 0;
  797. }
  798. if (!currentBufferSize && !m_bufferpos)
  799. {
  800. // Not allowed to send yet, try later
  801. TriggerEvent(FD_WRITE);
  802. return;
  803. }
  804. ASSERT(numread>=0);
  805. ASSERT(m_bufferpos>=0);
  806. numsent = Send(m_pBuffer, numread+m_bufferpos);
  807. }
  808. }
  809. }
  810. void CTransferSocket::UpdateStatusBar(bool forceUpdate)
  811. {
  812. if (m_nTransferState != STATE_STARTED)
  813. return;
  814. if (!forceUpdate)
  815. {
  816. //Don't flood the main window with messages
  817. //Else performance would be really low
  818. LARGE_INTEGER curtime;
  819. LARGE_INTEGER freq;
  820. QueryPerformanceFrequency(&freq);
  821. QueryPerformanceCounter(&curtime);
  822. if (((curtime.QuadPart-m_LastUpdateTime.QuadPart) < (freq.QuadPart/15) ) )
  823. return;
  824. m_LastUpdateTime = curtime;
  825. }
  826. //Update the statusbar
  827. CTimeSpan timespan=CTime::GetCurrentTime()-m_StartTime;
  828. int elapsed=(int)timespan.GetTotalSeconds();
  829. t_ffam_transferstatus *status=new t_ffam_transferstatus;
  830. status->bFileTransfer = m_nMode & (CSMODE_DOWNLOAD | CSMODE_UPLOAD);
  831. #ifdef MPEXT
  832. status->transfersize = m_transferdata.transfersize;
  833. #endif
  834. status->timeelapsed=elapsed;
  835. status->bytes=m_transferdata.transfersize-m_transferdata.transferleft;
  836. if (m_transferdata.transfersize>0 && !(m_nMode&CSMODE_LIST))
  837. {
  838. double leftmodifier=static_cast<double>(m_transferdata.transfersize-m_transferdata.nTransferStart-m_transferdata.transferleft);
  839. leftmodifier*=100;
  840. if (m_transferdata.transfersize-m_transferdata.nTransferStart)
  841. leftmodifier /= (m_transferdata.transfersize-m_transferdata.nTransferStart);
  842. else
  843. leftmodifier = 1;
  844. if (leftmodifier == 0)
  845. leftmodifier = 1;
  846. double leftmodifier2 = 100 - leftmodifier;
  847. int left=static_cast<int>((elapsed/leftmodifier)*leftmodifier2);
  848. double percent=100*static_cast<double>(m_transferdata.transfersize-m_transferdata.transferleft);
  849. percent/=m_transferdata.transfersize;
  850. status->percent=static_cast<int>(percent);
  851. if (status->percent>100)
  852. status->percent=100;
  853. if (left < 0)
  854. left = -1;
  855. status->timeleft=left;
  856. }
  857. else
  858. {
  859. status->percent=-1;
  860. status->timeleft=-1;
  861. }
  862. int count = 0;
  863. status->transferrate = 0;
  864. for ( int i = 0; i < SPEED_SECONDS; i++)
  865. {
  866. if ( m_UsedForTransfer[ i])
  867. {
  868. status->transferrate += m_Transfered[ i];
  869. count++;
  870. }
  871. }
  872. if ( count > 0)
  873. status->transferrate = status->transferrate / count;
  874. else if (m_Transfered[0])
  875. status->transferrate = m_Transfered[0];
  876. else
  877. status->timeleft=-1;
  878. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
  879. }
  880. void CTransferSocket::UpdateSendLed()
  881. {
  882. //Don't flood the main window with messages
  883. //Else performance would be really low
  884. LARGE_INTEGER curtime;
  885. LARGE_INTEGER freq;
  886. QueryPerformanceFrequency(&freq);
  887. QueryPerformanceCounter(&curtime);
  888. static LARGE_INTEGER oldtime={0};
  889. if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
  890. return;
  891. oldtime=curtime;
  892. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
  893. }
  894. void CTransferSocket::UpdateRecvLed()
  895. {
  896. //Don't flood the main window with messages
  897. //Else performance would be really low
  898. LARGE_INTEGER curtime;
  899. LARGE_INTEGER freq;
  900. QueryPerformanceFrequency(&freq);
  901. QueryPerformanceCounter(&curtime);
  902. static LARGE_INTEGER oldtime={0};
  903. if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
  904. return;
  905. oldtime=curtime;
  906. PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_RECV), 0);
  907. }
  908. BOOL CTransferSocket::Create(
  909. #ifndef MPEXT_NO_SSL
  910. BOOL bUseSsl
  911. #endif
  912. )
  913. {
  914. #ifndef MPEXT_NO_SSL
  915. if (bUseSsl)
  916. m_pSslLayer = new CAsyncSslSocketLayer;
  917. #endif
  918. if (!m_pOwner->m_CurrentServer.fwbypass)
  919. {
  920. int nProxyType = COptions::GetOptionVal(OPTION_PROXYTYPE);
  921. if (nProxyType != PROXYTYPE_NOPROXY)
  922. {
  923. USES_CONVERSION;
  924. m_pProxyLayer = new CAsyncProxySocketLayer;
  925. if (nProxyType == PROXYTYPE_SOCKS4)
  926. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
  927. else if (nProxyType == PROXYTYPE_SOCKS4A)
  928. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
  929. else if (nProxyType == PROXYTYPE_SOCKS5)
  930. if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
  931. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
  932. COptions::GetOptionVal(OPTION_PROXYPORT),
  933. T2CA(COptions::GetOption(OPTION_PROXYUSER)),
  934. T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
  935. else
  936. m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
  937. COptions::GetOptionVal(OPTION_PROXYPORT));
  938. else if (nProxyType == PROXYTYPE_HTTP11)
  939. if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
  940. m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), 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_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
  945. else
  946. ASSERT(FALSE);
  947. AddLayer(m_pProxyLayer);
  948. }
  949. }
  950. if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
  951. {
  952. if (!CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
  953. return FALSE;
  954. return TRUE;
  955. }
  956. else
  957. {
  958. int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
  959. int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
  960. if (min>=max)
  961. {
  962. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  963. return FALSE;
  964. }
  965. int startport=static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
  966. int port=startport;
  967. while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
  968. {
  969. port++;
  970. if (port>max)
  971. port=min;
  972. if (port==startport)
  973. {
  974. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  975. return FALSE;
  976. }
  977. }
  978. }
  979. return TRUE;
  980. }
  981. void CTransferSocket::Close()
  982. {
  983. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Close()"));
  984. m_bCheckTimeout = FALSE;
  985. CAsyncSocketEx::Close();
  986. }
  987. int CTransferSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  988. {
  989. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  990. {
  991. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  992. {
  993. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  994. {
  995. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  996. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  997. if (iter->pLayer == m_pProxyLayer)
  998. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Proxy layer changed state from %s to %s"), state2Desc, state1Desc);
  999. #ifndef MPEXT_NO_SSL
  1000. else if (iter->pLayer == m_pSslLayer)
  1001. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("TLS layer changed state from %s to %s"), state2Desc, state1Desc);
  1002. #endif
  1003. #ifndef MPEXT_NO_GSS
  1004. else if (iter->pLayer == m_pGssLayer)
  1005. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("GSS layer changed state from %s to %s"), state2Desc, state1Desc);
  1006. #endif
  1007. else
  1008. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %s to %s"), iter->pLayer, state2Desc, state1Desc);
  1009. }
  1010. }
  1011. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  1012. {
  1013. if (iter->pLayer == m_pProxyLayer)
  1014. {
  1015. switch (iter->nParam1)
  1016. {
  1017. case PROXYERROR_NOERROR:
  1018. m_pOwner->ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  1019. break;
  1020. case PROXYERROR_NOCONN:
  1021. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  1022. break;
  1023. case PROXYERROR_REQUESTFAILED:
  1024. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  1025. break;
  1026. case PROXYERROR_AUTHTYPEUNKNOWN:
  1027. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  1028. break;
  1029. case PROXYERROR_AUTHFAILED:
  1030. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  1031. break;
  1032. case PROXYERROR_AUTHNOLOGON:
  1033. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  1034. break;
  1035. case PROXYERROR_CANTRESOLVEHOST:
  1036. m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  1037. break;
  1038. default:
  1039. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error"));
  1040. }
  1041. }
  1042. #ifndef MPEXT_NO_SSL
  1043. else if (iter->pLayer == m_pSslLayer)
  1044. {
  1045. switch (iter->nParam1)
  1046. {
  1047. case SSL_INFO:
  1048. switch(iter->nParam2)
  1049. {
  1050. case SSL_INFO_SHUTDOWNCOMPLETE:
  1051. CloseAndEnsureSendClose(0);
  1052. break;
  1053. case SSL_INFO_ESTABLISHED:
  1054. m_pOwner->ShowStatus(IDS_STATUSMSG_SSLESTABLISHEDTRANSFER, FZ_LOG_STATUS);
  1055. TriggerEvent(FD_FORCEREAD);
  1056. break;
  1057. }
  1058. break;
  1059. case SSL_FAILURE:
  1060. switch (iter->nParam2)
  1061. {
  1062. case SSL_FAILURE_ESTABLISH:
  1063. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
  1064. break;
  1065. case SSL_FAILURE_INITSSL:
  1066. m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  1067. break;
  1068. }
  1069. EnsureSendClose(CSMODE_TRANSFERERROR);
  1070. break;
  1071. case SSL_VERIFY_CERT:
  1072. t_SslCertData data;
  1073. LPTSTR CertError = NULL;
  1074. if (m_pSslLayer->GetPeerCertificateData(data, CertError))
  1075. m_pSslLayer->SetNotifyReply(data.priv_data, SSL_VERIFY_CERT, 1);
  1076. else
  1077. {
  1078. CString str;
  1079. str.Format(TLS_CERT_DECODE_ERROR, CertError);
  1080. m_pOwner->ShowStatus(str, FZ_LOG_ERROR);
  1081. CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
  1082. }
  1083. break;
  1084. }
  1085. }
  1086. #endif
  1087. #ifndef MPEXT_NO_GSS
  1088. else if (iter->pLayer == m_pGssLayer)
  1089. {
  1090. USES_CONVERSION;
  1091. switch (iter->nParam1)
  1092. {
  1093. case GSS_INFO:
  1094. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  1095. break;
  1096. case GSS_ERROR:
  1097. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  1098. break;
  1099. case GSS_SHUTDOWN_COMPLETE:
  1100. CloseAndEnsureSendClose(0);
  1101. break;
  1102. }
  1103. }
  1104. #endif
  1105. }
  1106. delete [] iter->str;
  1107. }
  1108. return 0;
  1109. }
  1110. void CTransferSocket::Transfered(int count, CTime time)
  1111. {
  1112. CTimeSpan ts = time - m_TransferedFirst;
  1113. int diff = (int)ts.GetTotalSeconds();
  1114. if (diff < 0)
  1115. diff = 0;
  1116. if ( diff >= SPEED_SECONDS)
  1117. {
  1118. int move = diff - SPEED_SECONDS + 1;
  1119. int start = SPEED_SECONDS - move;
  1120. if ( start <= 0)
  1121. start = 0;
  1122. else
  1123. {
  1124. for ( int i = 0; i < SPEED_SECONDS - move; i++)
  1125. {
  1126. m_Transfered[ i] = m_Transfered[ i + move];
  1127. m_UsedForTransfer[ i] = m_UsedForTransfer[ i + move];
  1128. }
  1129. }
  1130. for ( int i = start; i < SPEED_SECONDS; i++)
  1131. {
  1132. m_Transfered[ i] = 0;
  1133. m_UsedForTransfer[ i] = false;
  1134. }
  1135. if (move >= SPEED_SECONDS)
  1136. {
  1137. m_TransferedFirst = time;
  1138. diff = 0;
  1139. }
  1140. else
  1141. {
  1142. m_TransferedFirst += CTimeSpan( move);
  1143. ts = time - m_TransferedFirst;
  1144. diff = (int)(ts.GetTotalSeconds() % 60);
  1145. }
  1146. }
  1147. m_Transfered[ diff] += count;
  1148. for ( int i = 0; i < diff - 1; i++)
  1149. m_UsedForTransfer[ i] = true;
  1150. }
  1151. #ifndef MPEXT_NO_GSS
  1152. void CTransferSocket::UseGSS(CAsyncGssSocketLayer *pGssLayer)
  1153. {
  1154. m_pGssLayer = new CAsyncGssSocketLayer;
  1155. m_pGssLayer->InitTransferChannel(pGssLayer);
  1156. }
  1157. #endif
  1158. #ifndef MPEXT_NO_ZLIB
  1159. bool CTransferSocket::InitZlib(int level)
  1160. {
  1161. int res;
  1162. if (m_nMode & CSMODE_UPLOAD)
  1163. res = deflateInit2(&m_zlibStream, level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
  1164. else
  1165. res = inflateInit2(&m_zlibStream, 15);
  1166. if (res == Z_OK)
  1167. m_useZlib = true;
  1168. return res == Z_OK;
  1169. }
  1170. #endif
  1171. int CTransferSocket::ReadDataFromFile(char *buffer, int len)
  1172. {
  1173. TRY
  1174. {
  1175. // Comparing to Filezilla 2, we do not do any translation locally,
  1176. // leaving it onto the server (what Filezilla 3 seems to do too)
  1177. const char Bom[3] = "\xEF\xBB\xBF";
  1178. int read = m_pFile->Read(buffer, len);
  1179. if (COptions::GetOptionVal(OPTION_MPEXT_REMOVE_BOM) &&
  1180. m_transferdata.bType && (read >= sizeof(Bom)) && (memcmp(buffer, Bom, sizeof(Bom)) == 0))
  1181. {
  1182. memcpy(buffer, buffer + sizeof(Bom), read - sizeof(Bom));
  1183. read -= sizeof(Bom);
  1184. int read2 = m_pFile->Read(buffer + read, sizeof(Bom));
  1185. if (read2 > 0)
  1186. {
  1187. read += read2;
  1188. }
  1189. }
  1190. return read;
  1191. }
  1192. CATCH_ALL(e)
  1193. {
  1194. TCHAR error[BUFSIZE];
  1195. if (e->GetErrorMessage(error, BUFSIZE))
  1196. m_pOwner->ShowStatus(error, FZ_LOG_ERROR);
  1197. CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
  1198. return -1;
  1199. }
  1200. END_CATCH_ALL;
  1201. }
  1202. void CTransferSocket::LogSocketMessage(int nMessageType, LPCTSTR pMsgFormat)
  1203. {
  1204. LogMessage(nMessageType, pMsgFormat);
  1205. }
  1206. void CTransferSocket::EnsureSendClose(int Mode)
  1207. {
  1208. if (!m_bSentClose)
  1209. {
  1210. if (Mode != 0)
  1211. {
  1212. m_nMode |= Mode;
  1213. }
  1214. m_bSentClose = TRUE;
  1215. VERIFY(m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode));
  1216. }
  1217. }
  1218. void CTransferSocket::CloseAndEnsureSendClose(int Mode)
  1219. {
  1220. Close();
  1221. EnsureSendClose(Mode);
  1222. }
  1223. void CTransferSocket::CloseOnShutDownOrError(int Mode)
  1224. {
  1225. if (ShutDown())
  1226. {
  1227. CloseAndEnsureSendClose(Mode);
  1228. }
  1229. else
  1230. {
  1231. int Error = GetLastError();
  1232. if (Error != WSAEWOULDBLOCK)
  1233. {
  1234. // Log always or only when (Mode & CSMODE_TRANSFERERROR)?
  1235. // Does it anyway make sense at all to call this with Mode == 0?
  1236. LogError(Error);
  1237. CloseAndEnsureSendClose(Mode);
  1238. }
  1239. }
  1240. }
  1241. void CTransferSocket::LogError(int Error)
  1242. {
  1243. wchar_t * Buffer;
  1244. int Len = FormatMessage(
  1245. FORMAT_MESSAGE_FROM_SYSTEM |
  1246. FORMAT_MESSAGE_IGNORE_INSERTS |
  1247. FORMAT_MESSAGE_ARGUMENT_ARRAY |
  1248. FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, Error, 0, (LPTSTR)&Buffer, 0, NULL);
  1249. if (Len > 0)
  1250. {
  1251. m_pOwner->ShowStatus(Buffer, FZ_LOG_ERROR);
  1252. LocalFree(Buffer);
  1253. }
  1254. }