TransferSocket.cpp 31 KB

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