ControlSocket.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 ( status.Left(5)==_T("PASS ") )
  96. {
  97. int len=status.GetLength()-5;
  98. status=_T("PASS ");
  99. for (int i=0;i<len;i++)
  100. status+=_MPT("*");
  101. }
  102. else if ( status.Left(5)==_T("ACCT ") )
  103. {
  104. int len=status.GetLength()-5;
  105. status=_T("ACCT ");
  106. for (int i=0;i<len;i++)
  107. status+=_MPT("*");
  108. }
  109. LogMessageRaw(type, (LPCTSTR)status);
  110. }
  111. t_server CControlSocket::GetCurrentServer()
  112. {
  113. return m_CurrentServer;
  114. }
  115. void CControlSocket::Close()
  116. {
  117. #ifndef MPEXT_NO_IDENT
  118. if(m_pIdentControl)
  119. delete m_pIdentControl;
  120. m_pIdentControl=0;
  121. #endif
  122. if (m_pDirectoryListing)
  123. {
  124. delete m_pDirectoryListing;
  125. }
  126. m_pDirectoryListing=0;
  127. CAsyncSocketEx::Close();
  128. delete m_pProxyLayer;
  129. m_pProxyLayer = NULL;
  130. #ifndef MPEXT_NO_SSL
  131. delete m_pSslLayer;
  132. m_pSslLayer = NULL;
  133. #endif
  134. #ifndef MPEXT_NO_GSS
  135. delete m_pGssLayer;
  136. m_pGssLayer = NULL;
  137. #endif
  138. RemoveActiveTransfer();
  139. }
  140. BOOL CControlSocket::Connect(CString hostAddress, UINT nHostPort)
  141. {
  142. hostAddress = ConvertDomainName(hostAddress);
  143. //Don't resolve host asynchronously when using proxies
  144. if (m_pProxyLayer)
  145. {
  146. //If using proxies, we can't use ident -> won't be reachable from outside
  147. return CAsyncSocketEx::Connect(hostAddress, nHostPort);
  148. }
  149. BOOL res = CAsyncSocketEx::Connect(hostAddress, nHostPort);
  150. int nLastError = WSAGetLastError();
  151. if (res || nLastError==WSAEWOULDBLOCK)
  152. {
  153. #ifndef MPEXT_NO_IDENT
  154. if (COptions::GetOptionVal(OPTION_IDENT))
  155. m_pIdentControl = new CIdentServerControl(this);
  156. #endif
  157. WSASetLastError(nLastError);
  158. }
  159. return res;
  160. }
  161. void CControlSocket::SetDirectoryListing(t_directory *pDirectory, bool bSetWorkingDir /*=true*/)
  162. {
  163. if (m_pDirectoryListing)
  164. delete m_pDirectoryListing;
  165. m_CurrentServer=pDirectory->server;
  166. m_pDirectoryListing=new t_directory;
  167. *m_pDirectoryListing=*pDirectory;
  168. if (bSetWorkingDir)
  169. m_pOwner->SetWorkingDir(pDirectory);
  170. }
  171. int CControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  172. {
  173. USES_CONVERSION;
  174. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  175. {
  176. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  177. {
  178. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  179. {
  180. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  181. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  182. if (iter->pLayer == m_pProxyLayer)
  183. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Proxy layer changed state from %s to %s"), state2Desc, state1Desc);
  184. #ifndef MPEXT_NO_GSS
  185. else if (iter->pLayer == m_pGssLayer)
  186. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pGssLayer changed state from %s to %s"), state2Desc, state1Desc);
  187. #endif
  188. else
  189. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %s to %s"), iter->pLayer, state2Desc, state1Desc);
  190. }
  191. }
  192. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  193. {
  194. if (iter->pLayer == m_pProxyLayer)
  195. {
  196. switch (iter->nParam1)
  197. {
  198. case PROXYERROR_NOCONN:
  199. ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  200. break;
  201. case PROXYERROR_REQUESTFAILED:
  202. ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  203. if (iter->str)
  204. ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
  205. break;
  206. case PROXYERROR_AUTHTYPEUNKNOWN:
  207. ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  208. break;
  209. case PROXYERROR_AUTHFAILED:
  210. ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  211. break;
  212. case PROXYERROR_AUTHNOLOGON:
  213. ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  214. break;
  215. case PROXYERROR_CANTRESOLVEHOST:
  216. ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  217. break;
  218. default:
  219. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error") );
  220. }
  221. }
  222. #ifndef MPEXT_NO_GSS
  223. else if (iter->pLayer == m_pGssLayer)
  224. {
  225. switch (iter->nParam1)
  226. {
  227. case GSS_INFO:
  228. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  229. break;
  230. case GSS_ERROR:
  231. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  232. break;
  233. case GSS_COMMAND:
  234. ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
  235. break;
  236. case GSS_REPLY:
  237. ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
  238. break;
  239. }
  240. }
  241. #endif
  242. }
  243. delete [] iter->str;
  244. }
  245. return 1;
  246. }
  247. #ifndef MPEXT_NO_SPEED_LIM_RULES
  248. _int64 CControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue, SPEEDLIMITSLIST &list)
  249. #else
  250. _int64 CControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue)
  251. #endif
  252. {
  253. int type = COptions::GetOptionVal(valType);
  254. if ( type == 1)
  255. return ( _int64)COptions::GetOptionVal(valValue) * 1024;
  256. #ifndef MPEXT_NO_SPEED_LIM_RULES
  257. if ( type == 2)
  258. {
  259. CSingleLock lock(&COptions::m_Sync, TRUE);
  260. for ( unsigned int i = 0; i < list.size(); i++)
  261. {
  262. if ( list[ i]->IsItActive(time) && list[i]->m_Speed)
  263. return list[ i]->m_Speed * 1024;
  264. }
  265. }
  266. #endif
  267. return ( _int64)1000000000000; //I hope that when there will be something with 1000GB/s then I'll change it :)
  268. }
  269. _int64 CControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  270. {
  271. if (direction == download)
  272. #ifndef MPEXT_NO_SPEED_LIM_RULES
  273. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE, COptions::m_DownloadSpeedLimits);
  274. #else
  275. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE);
  276. #endif
  277. else
  278. #ifndef MPEXT_NO_SPEED_LIM_RULES
  279. return GetSpeedLimit( time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE, COptions::m_UploadSpeedLimits);
  280. #else
  281. return GetSpeedLimit( time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE);
  282. #endif
  283. return ( _int64)1000000000000;
  284. }
  285. _int64 CControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction, int nBufSize)
  286. {
  287. beenWaiting = false;
  288. CTime nowTime = CTime::GetCurrentTime();
  289. _int64 ableToRead = BUFSIZE;
  290. if ( nowTime == curTime)
  291. {
  292. ableToRead = iter->nBytesAvailable;
  293. if (ableToRead <= 0)
  294. {
  295. // we should wait till next second
  296. nowTime = CTime::GetCurrentTime();
  297. while (nowTime == curTime && !iter->nBytesAvailable)
  298. {
  299. if (beenWaiting)
  300. {
  301. //Check if there are other commands in the command queue.
  302. MSG msg;
  303. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  304. {
  305. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Message waiting in queue, resuming later"));
  306. return 0;
  307. }
  308. }
  309. m_SpeedLimitSync.Unlock();
  310. Sleep(100);
  311. m_SpeedLimitSync.Lock();
  312. nowTime = CTime::GetCurrentTime();
  313. beenWaiting = true;
  314. // Since we didn't hold the critical section for some time, we have to renew the iterator
  315. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  316. if (iter->pOwner == this)
  317. break;
  318. if (iter == m_InstanceList[direction].end())
  319. return 0;
  320. }
  321. }
  322. ableToRead = iter->nBytesAvailable;
  323. }
  324. if (nowTime != curTime)
  325. {
  326. if (ableToRead > 0)
  327. ableToRead = 0;
  328. curLimit = GetSpeedLimit(direction, curTime);
  329. __int64 nMax = curLimit / m_InstanceList[direction].size();
  330. _int64 nLeft = 0;
  331. int nCount = 0;
  332. std::list<t_ActiveList>::iterator iter2;
  333. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  334. {
  335. if (iter2->nBytesAvailable>0)
  336. {
  337. nLeft += iter2->nBytesAvailable;
  338. iter2->nBytesTransferred = 1;
  339. }
  340. else
  341. {
  342. nCount++;
  343. iter2->nBytesTransferred = 0;
  344. }
  345. iter2->nBytesAvailable = nMax;
  346. }
  347. if (nLeft && nCount)
  348. {
  349. nMax = nLeft / nCount;
  350. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  351. {
  352. if (!iter2->nBytesTransferred)
  353. iter2->nBytesAvailable += nMax;
  354. else
  355. iter2->nBytesTransferred = 0;
  356. }
  357. }
  358. ableToRead = iter->nBytesAvailable;
  359. }
  360. curTime = nowTime;
  361. if (!nBufSize)
  362. nBufSize = BUFSIZE;
  363. if (ableToRead > nBufSize)
  364. ableToRead = nBufSize;
  365. return ableToRead;
  366. }
  367. _int64 CControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting, int nBufSize)
  368. {
  369. m_SpeedLimitSync.Lock();
  370. std::list<t_ActiveList>::iterator iter;
  371. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  372. if (iter->pOwner == this)
  373. break;
  374. if (iter == m_InstanceList[direction].end())
  375. {
  376. t_ActiveList item;
  377. #ifdef MPEXT
  378. CTime time = CTime::GetCurrentTime();
  379. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  380. #else
  381. item.nBytesAvailable = GetSpeedLimit(direction, CTime::GetCurrentTime()) / (m_InstanceList[direction].size() + 1);
  382. #endif
  383. item.nBytesTransferred = 0;
  384. item.pOwner = this;
  385. m_InstanceList[direction].push_back(item);
  386. iter = m_InstanceList[direction].end();
  387. iter--;
  388. }
  389. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction, nBufSize);
  390. m_SpeedLimitSync.Unlock();
  391. return limit;
  392. }
  393. BOOL CControlSocket::RemoveActiveTransfer()
  394. {
  395. BOOL bFound = FALSE;
  396. m_SpeedLimitSync.Lock();
  397. std::list<t_ActiveList>::iterator iter;
  398. for (int i = 0; i < 2; i++)
  399. {
  400. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  401. if (iter->pOwner == this)
  402. {
  403. m_InstanceList[i].erase(iter);
  404. bFound = TRUE;
  405. break;
  406. }
  407. }
  408. m_SpeedLimitSync.Unlock();
  409. return bFound;
  410. }
  411. BOOL CControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  412. {
  413. m_SpeedLimitSync.Lock();
  414. std::list<t_ActiveList>::iterator iter;
  415. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  416. if (iter->pOwner == this)
  417. {
  418. if (iter->nBytesAvailable > nBytesTransferred)
  419. iter->nBytesAvailable -= nBytesTransferred;
  420. else
  421. iter->nBytesAvailable = 0;
  422. iter->nBytesTransferred += nBytesTransferred;
  423. m_SpeedLimitSync.Unlock();
  424. return TRUE;
  425. }
  426. m_SpeedLimitSync.Unlock();
  427. return FALSE;
  428. }
  429. CString CControlSocket::ConvertDomainName(CString domain)
  430. {
  431. USES_CONVERSION;
  432. LPCWSTR buffer = T2CW(domain);
  433. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  434. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  435. {
  436. delete [] utf8;
  437. LogMessage(FZ_LOG_WARNING, _T("Could not convert domain name"));
  438. return domain;
  439. }
  440. char *output = 0;
  441. #ifdef MPEXT
  442. output = strdup(utf8);
  443. #else
  444. if (idna_to_ascii_8z(utf8, &output, IDNA_ALLOW_UNASSIGNED))
  445. {
  446. delete [] utf8;
  447. LogMessage(FZ_LOG_WARNING, _T("Could not convert domain name"));
  448. return domain;
  449. }
  450. #endif
  451. delete [] utf8;
  452. CString result = A2T(output);
  453. free(output);
  454. return result;
  455. }
  456. void CControlSocket::LogSocketMessage(int nMessageType, LPCTSTR pMsgFormat)
  457. {
  458. LogMessage(nMessageType, pMsgFormat);
  459. }