ControlSocket.cpp 14 KB

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