ControlSocket.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. // ControlSocket.cpp: Implementierung der Klasse CControlSocket.
  15. //
  16. //////////////////////////////////////////////////////////////////////
  17. #include "stdafx.h"
  18. #include "ControlSocket.h"
  19. #include "mainthread.h"
  20. #include "AsyncProxySocketLayer.h"
  21. #ifndef MPEXT_NO_SSL
  22. #include "AsyncSslSocketLayer.h"
  23. #endif
  24. #ifndef MPEXT_NO_GSS
  25. #include "AsyncGssSocketLayer.h"
  26. #endif
  27. #ifndef MPEXT_NO_SPEED_LIM_RULES
  28. #include "SpeedLimit.h"
  29. #endif
  30. #ifndef MPEXT
  31. #include <idna.h>
  32. #endif
  33. #ifdef _DEBUG
  34. #undef THIS_FILE
  35. static char THIS_FILE[]=__FILE__;
  36. #define new DEBUG_NEW
  37. #endif
  38. #ifndef MPEXT
  39. std::list<CControlSocket::t_ActiveList> CControlSocket::m_InstanceList[2];
  40. #else
  41. // explicit initialization prevents an assertion in borland's compiler
  42. std::list<CControlSocket::t_ActiveList> CControlSocket::m_InstanceList[2] =
  43. {std::list<CControlSocket::t_ActiveList>(), std::list<CControlSocket::t_ActiveList>()};
  44. #endif
  45. CTime CControlSocket::m_CurrentTransferTime[2] = { CTime::GetCurrentTime(), CTime::GetCurrentTime() };
  46. _int64 CControlSocket::m_CurrentTransferLimit[2] = {0, 0};
  47. CCriticalSection CControlSocket::m_SpeedLimitSync;
  48. //////////////////////////////////////////////////////////////////////
  49. // Konstruktion/Destruktion
  50. //////////////////////////////////////////////////////////////////////
  51. CControlSocket::CControlSocket(CMainThread *pMainThread, CFileZillaTools * pTools)
  52. {
  53. ASSERT(pMainThread);
  54. m_pOwner=pMainThread;
  55. m_pTools=pTools;
  56. m_Operation.nOpMode=0;
  57. m_Operation.nOpState=-1;
  58. m_Operation.pData=0;
  59. m_pProxyLayer = NULL;
  60. #ifndef MPEXT_NO_SSL
  61. m_pSslLayer = NULL;
  62. #endif
  63. #ifndef MPEXT_NO_GSS
  64. m_pGssLayer = NULL;
  65. #endif
  66. m_pDirectoryListing=0;
  67. #ifndef MPEXT_NO_IDENT
  68. m_pIdentControl=0;
  69. #endif
  70. }
  71. CControlSocket::~CControlSocket()
  72. {
  73. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("~CControlSocket()"));
  74. Close();
  75. }
  76. /////////////////////////////////////////////////////////////////////////////
  77. // Member-Funktion CControlSocket
  78. #define CONNECT_INIT -1
  79. #ifndef MPEXT_NO_GSS
  80. #define CONNECT_GSS -3
  81. #endif
  82. #ifndef MPEXT_NO_SSL
  83. #define CONNECT_SSL_INIT -6
  84. #define CONNECT_SSL_NEGOTIATE -5
  85. #define CONNECT_SSL_WAITDONE -4
  86. #endif
  87. void CControlSocket::ShowStatus(UINT nID, int type) const
  88. {
  89. CString str;
  90. str.LoadString(nID);
  91. ShowStatus(str, type);
  92. }
  93. void CControlSocket::ShowStatus(CString status, int type) const
  94. {
  95. if (!COptions::GetOptionVal(OPTION_MPEXT_LOG_SENSITIVE))
  96. {
  97. if ( status.Left(5)==_T("PASS ") )
  98. {
  99. int len=status.GetLength()-5;
  100. status=_T("PASS ");
  101. for (int i=0;i<len;i++)
  102. status+=_MPT("*");
  103. }
  104. else if ( status.Left(5)==_T("ACCT ") )
  105. {
  106. int len=status.GetLength()-5;
  107. status=_T("ACCT ");
  108. for (int i=0;i<len;i++)
  109. status+=_MPT("*");
  110. }
  111. }
  112. LogMessageRaw(type, (LPCTSTR)status);
  113. }
  114. void CControlSocket::ShowTimeoutError(UINT nID) const
  115. {
  116. CString str1;
  117. str1.LoadString(IDS_ERRORMSG_TIMEOUT);
  118. CString str2;
  119. str2.LoadString(nID);
  120. CString message;
  121. message.Format(L"%s (%s)", str1, str2);
  122. ShowStatus(message, FZ_LOG_ERROR);
  123. }
  124. t_server CControlSocket::GetCurrentServer()
  125. {
  126. return m_CurrentServer;
  127. }
  128. void CControlSocket::Close()
  129. {
  130. #ifndef MPEXT_NO_IDENT
  131. if(m_pIdentControl)
  132. delete m_pIdentControl;
  133. m_pIdentControl=0;
  134. #endif
  135. if (m_pDirectoryListing)
  136. {
  137. delete m_pDirectoryListing;
  138. }
  139. m_pDirectoryListing=0;
  140. CAsyncSocketEx::Close();
  141. delete m_pProxyLayer;
  142. m_pProxyLayer = NULL;
  143. #ifndef MPEXT_NO_SSL
  144. delete m_pSslLayer;
  145. m_pSslLayer = NULL;
  146. #endif
  147. #ifndef MPEXT_NO_GSS
  148. delete m_pGssLayer;
  149. m_pGssLayer = NULL;
  150. #endif
  151. RemoveActiveTransfer();
  152. }
  153. BOOL CControlSocket::Connect(CString hostAddress, UINT nHostPort)
  154. {
  155. hostAddress = ConvertDomainName(hostAddress);
  156. //Don't resolve host asynchronously when using proxies
  157. if (m_pProxyLayer)
  158. {
  159. //If using proxies, we can't use ident -> won't be reachable from outside
  160. return CAsyncSocketEx::Connect(hostAddress, nHostPort);
  161. }
  162. BOOL res = CAsyncSocketEx::Connect(hostAddress, nHostPort);
  163. int nLastError = WSAGetLastError();
  164. if (res || nLastError==WSAEWOULDBLOCK)
  165. {
  166. #ifndef MPEXT_NO_IDENT
  167. if (COptions::GetOptionVal(OPTION_IDENT))
  168. m_pIdentControl = new CIdentServerControl(this);
  169. #endif
  170. WSASetLastError(nLastError);
  171. }
  172. return res;
  173. }
  174. void CControlSocket::SetDirectoryListing(t_directory *pDirectory, bool bSetWorkingDir /*=true*/)
  175. {
  176. if (m_pDirectoryListing)
  177. delete m_pDirectoryListing;
  178. m_CurrentServer=pDirectory->server;
  179. m_pDirectoryListing=new t_directory;
  180. *m_pDirectoryListing=*pDirectory;
  181. if (bSetWorkingDir)
  182. m_pOwner->SetWorkingDir(pDirectory);
  183. }
  184. int CControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  185. {
  186. USES_CONVERSION;
  187. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  188. {
  189. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  190. {
  191. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  192. {
  193. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  194. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  195. if (iter->pLayer == m_pProxyLayer)
  196. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Proxy layer changed state from %s to %s"), state2Desc, state1Desc);
  197. #ifndef MPEXT_NO_GSS
  198. else if (iter->pLayer == m_pGssLayer)
  199. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pGssLayer changed state from %s to %s"), state2Desc, state1Desc);
  200. #endif
  201. else
  202. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %s to %s"), iter->pLayer, state2Desc, state1Desc);
  203. }
  204. }
  205. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  206. {
  207. if (iter->pLayer == m_pProxyLayer)
  208. {
  209. switch (iter->nParam1)
  210. {
  211. case PROXYERROR_NOERROR:
  212. ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  213. break;
  214. case PROXYERROR_NOCONN:
  215. ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  216. break;
  217. case PROXYERROR_REQUESTFAILED:
  218. ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  219. if (iter->str)
  220. ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
  221. break;
  222. case PROXYERROR_AUTHTYPEUNKNOWN:
  223. ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  224. break;
  225. case PROXYERROR_AUTHFAILED:
  226. ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  227. break;
  228. case PROXYERROR_AUTHNOLOGON:
  229. ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  230. break;
  231. case PROXYERROR_CANTRESOLVEHOST:
  232. ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  233. break;
  234. default:
  235. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error") );
  236. }
  237. }
  238. #ifndef MPEXT_NO_GSS
  239. else if (iter->pLayer == m_pGssLayer)
  240. {
  241. switch (iter->nParam1)
  242. {
  243. case GSS_INFO:
  244. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  245. break;
  246. case GSS_ERROR:
  247. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  248. break;
  249. case GSS_COMMAND:
  250. ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
  251. break;
  252. case GSS_REPLY:
  253. ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
  254. break;
  255. }
  256. }
  257. #endif
  258. }
  259. delete [] iter->str;
  260. }
  261. return 1;
  262. }
  263. #ifndef MPEXT_NO_SPEED_LIM_RULES
  264. _int64 CControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue, SPEEDLIMITSLIST &list)
  265. #else
  266. _int64 CControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue)
  267. #endif
  268. {
  269. int type = COptions::GetOptionVal(valType);
  270. if ( type == 1)
  271. return ( _int64)COptions::GetOptionVal(valValue) * 1024;
  272. #ifndef MPEXT_NO_SPEED_LIM_RULES
  273. if ( type == 2)
  274. {
  275. CSingleLock lock(&COptions::m_Sync, TRUE);
  276. for ( unsigned int i = 0; i < list.size(); i++)
  277. {
  278. if ( list[ i]->IsItActive(time) && list[i]->m_Speed)
  279. return list[ i]->m_Speed * 1024;
  280. }
  281. }
  282. #endif
  283. return ( _int64)1000000000000; //I hope that when there will be something with 1000GB/s then I'll change it :)
  284. }
  285. _int64 CControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  286. {
  287. if (direction == download)
  288. #ifndef MPEXT_NO_SPEED_LIM_RULES
  289. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE, COptions::m_DownloadSpeedLimits);
  290. #else
  291. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE);
  292. #endif
  293. else
  294. #ifndef MPEXT_NO_SPEED_LIM_RULES
  295. return GetSpeedLimit( time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE, COptions::m_UploadSpeedLimits);
  296. #else
  297. return GetSpeedLimit( time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE);
  298. #endif
  299. return ( _int64)1000000000000;
  300. }
  301. _int64 CControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction, int nBufSize)
  302. {
  303. beenWaiting = false;
  304. CTime nowTime = CTime::GetCurrentTime();
  305. _int64 ableToRead = BUFSIZE;
  306. if ( nowTime == curTime)
  307. {
  308. ableToRead = iter->nBytesAvailable;
  309. if (ableToRead <= 0)
  310. {
  311. // we should wait till next second
  312. nowTime = CTime::GetCurrentTime();
  313. while (nowTime == curTime && !iter->nBytesAvailable)
  314. {
  315. if (beenWaiting)
  316. {
  317. //Check if there are other commands in the command queue.
  318. MSG msg;
  319. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  320. {
  321. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Message waiting in queue, resuming later"));
  322. return 0;
  323. }
  324. }
  325. m_SpeedLimitSync.Unlock();
  326. Sleep(100);
  327. m_SpeedLimitSync.Lock();
  328. nowTime = CTime::GetCurrentTime();
  329. beenWaiting = true;
  330. // Since we didn't hold the critical section for some time, we have to renew the iterator
  331. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  332. if (iter->pOwner == this)
  333. break;
  334. if (iter == m_InstanceList[direction].end())
  335. return 0;
  336. }
  337. }
  338. ableToRead = iter->nBytesAvailable;
  339. }
  340. if (nowTime != curTime)
  341. {
  342. if (ableToRead > 0)
  343. ableToRead = 0;
  344. curLimit = GetSpeedLimit(direction, curTime);
  345. __int64 nMax = curLimit / m_InstanceList[direction].size();
  346. _int64 nLeft = 0;
  347. int nCount = 0;
  348. std::list<t_ActiveList>::iterator iter2;
  349. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  350. {
  351. if (iter2->nBytesAvailable>0)
  352. {
  353. nLeft += iter2->nBytesAvailable;
  354. iter2->nBytesTransferred = 1;
  355. }
  356. else
  357. {
  358. nCount++;
  359. iter2->nBytesTransferred = 0;
  360. }
  361. iter2->nBytesAvailable = nMax;
  362. }
  363. if (nLeft && nCount)
  364. {
  365. nMax = nLeft / nCount;
  366. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  367. {
  368. if (!iter2->nBytesTransferred)
  369. iter2->nBytesAvailable += nMax;
  370. else
  371. iter2->nBytesTransferred = 0;
  372. }
  373. }
  374. ableToRead = iter->nBytesAvailable;
  375. }
  376. curTime = nowTime;
  377. if (!nBufSize)
  378. nBufSize = BUFSIZE;
  379. if (ableToRead > nBufSize)
  380. ableToRead = nBufSize;
  381. return ableToRead;
  382. }
  383. _int64 CControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting, int nBufSize)
  384. {
  385. m_SpeedLimitSync.Lock();
  386. std::list<t_ActiveList>::iterator iter;
  387. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  388. if (iter->pOwner == this)
  389. break;
  390. if (iter == m_InstanceList[direction].end())
  391. {
  392. t_ActiveList item;
  393. #ifdef MPEXT
  394. CTime time = CTime::GetCurrentTime();
  395. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  396. #else
  397. item.nBytesAvailable = GetSpeedLimit(direction, CTime::GetCurrentTime()) / (m_InstanceList[direction].size() + 1);
  398. #endif
  399. item.nBytesTransferred = 0;
  400. item.pOwner = this;
  401. m_InstanceList[direction].push_back(item);
  402. iter = m_InstanceList[direction].end();
  403. iter--;
  404. }
  405. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction, nBufSize);
  406. m_SpeedLimitSync.Unlock();
  407. return limit;
  408. }
  409. BOOL CControlSocket::RemoveActiveTransfer()
  410. {
  411. BOOL bFound = FALSE;
  412. m_SpeedLimitSync.Lock();
  413. std::list<t_ActiveList>::iterator iter;
  414. for (int i = 0; i < 2; i++)
  415. {
  416. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  417. if (iter->pOwner == this)
  418. {
  419. m_InstanceList[i].erase(iter);
  420. bFound = TRUE;
  421. break;
  422. }
  423. }
  424. m_SpeedLimitSync.Unlock();
  425. return bFound;
  426. }
  427. BOOL CControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  428. {
  429. m_SpeedLimitSync.Lock();
  430. std::list<t_ActiveList>::iterator iter;
  431. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  432. if (iter->pOwner == this)
  433. {
  434. if (iter->nBytesAvailable > nBytesTransferred)
  435. iter->nBytesAvailable -= nBytesTransferred;
  436. else
  437. iter->nBytesAvailable = 0;
  438. iter->nBytesTransferred += nBytesTransferred;
  439. m_SpeedLimitSync.Unlock();
  440. return TRUE;
  441. }
  442. m_SpeedLimitSync.Unlock();
  443. return FALSE;
  444. }
  445. CString CControlSocket::ConvertDomainName(CString domain)
  446. {
  447. USES_CONVERSION;
  448. LPCWSTR buffer = T2CW(domain);
  449. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  450. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  451. {
  452. delete [] utf8;
  453. LogMessage(FZ_LOG_WARNING, _T("Could not convert domain name"));
  454. return domain;
  455. }
  456. char *output = 0;
  457. #ifdef MPEXT
  458. output = strdup(utf8);
  459. #else
  460. if (idna_to_ascii_8z(utf8, &output, IDNA_ALLOW_UNASSIGNED))
  461. {
  462. delete [] utf8;
  463. LogMessage(FZ_LOG_WARNING, _T("Could not convert domain name"));
  464. return domain;
  465. }
  466. #endif
  467. delete [] utf8;
  468. CString result = A2T(output);
  469. free(output);
  470. return result;
  471. }
  472. void CControlSocket::LogSocketMessage(int nMessageType, LPCTSTR pMsgFormat)
  473. {
  474. LogMessage(nMessageType, pMsgFormat);
  475. }
  476. bool CControlSocket::LoggingSocketMessage(int nMessageType)
  477. {
  478. return LoggingMessageType(nMessageType);
  479. }