ControlSocket.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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
  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
  242. _int64 CControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue, SPEEDLIMITSLIST &list)
  243. {
  244. int type = COptions::GetOptionVal(valType);
  245. if ( type == 1)
  246. return ( _int64)COptions::GetOptionVal(valValue) * 1024;
  247. if ( type == 2)
  248. {
  249. CSingleLock lock(&COptions::m_Sync, TRUE);
  250. for ( unsigned int i = 0; i < list.size(); i++)
  251. {
  252. if ( list[ i]->IsItActive(time) && list[i]->m_Speed)
  253. return list[ i]->m_Speed * 1024;
  254. }
  255. }
  256. return ( _int64)1000000000000; //I hope that when there will be something with 1000GB/s then I'll change it :)
  257. }
  258. #endif
  259. _int64 CControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  260. {
  261. #ifndef MPEXT_NO_SPEED_LIM
  262. if (direction == download)
  263. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE, COptions::m_DownloadSpeedLimits);
  264. else
  265. return GetSpeedLimit( time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE, COptions::m_UploadSpeedLimits);
  266. #else
  267. return ( _int64)1000000000000;
  268. #endif
  269. }
  270. _int64 CControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction, int nBufSize)
  271. {
  272. beenWaiting = false;
  273. CTime nowTime = CTime::GetCurrentTime();
  274. _int64 ableToRead = BUFSIZE;
  275. if ( nowTime == curTime)
  276. {
  277. ableToRead = iter->nBytesAvailable;
  278. if (ableToRead <= 0)
  279. {
  280. // we should wait till next second
  281. nowTime = CTime::GetCurrentTime();
  282. while (nowTime == curTime && !iter->nBytesAvailable)
  283. {
  284. if (beenWaiting)
  285. {
  286. //Check if there are other commands in the command queue.
  287. MSG msg;
  288. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  289. {
  290. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Message waiting in queue, resuming later"));
  291. return 0;
  292. }
  293. }
  294. m_SpeedLimitSync.Unlock();
  295. Sleep(100);
  296. m_SpeedLimitSync.Lock();
  297. nowTime = CTime::GetCurrentTime();
  298. beenWaiting = true;
  299. // Since we didn't hold the critical section for some time, we have to renew the iterator
  300. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  301. if (iter->pOwner == this)
  302. break;
  303. if (iter == m_InstanceList[direction].end())
  304. return 0;
  305. }
  306. }
  307. ableToRead = iter->nBytesAvailable;
  308. }
  309. if (nowTime != curTime)
  310. {
  311. if (ableToRead > 0)
  312. ableToRead = 0;
  313. curLimit = GetSpeedLimit(direction, curTime);
  314. __int64 nMax = curLimit / m_InstanceList[direction].size();
  315. _int64 nLeft = 0;
  316. int nCount = 0;
  317. std::list<t_ActiveList>::iterator iter2;
  318. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  319. {
  320. if (iter2->nBytesAvailable>0)
  321. {
  322. nLeft += iter2->nBytesAvailable;
  323. iter2->nBytesTransferred = 1;
  324. }
  325. else
  326. {
  327. nCount++;
  328. iter2->nBytesTransferred = 0;
  329. }
  330. iter2->nBytesAvailable = nMax;
  331. }
  332. if (nLeft && nCount)
  333. {
  334. nMax = nLeft / nCount;
  335. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  336. {
  337. if (!iter2->nBytesTransferred)
  338. iter2->nBytesAvailable += nMax;
  339. else
  340. iter2->nBytesTransferred = 0;
  341. }
  342. }
  343. ableToRead = iter->nBytesAvailable;
  344. }
  345. curTime = nowTime;
  346. if (!nBufSize)
  347. nBufSize = BUFSIZE;
  348. if (ableToRead > nBufSize)
  349. ableToRead = nBufSize;
  350. return ableToRead;
  351. }
  352. _int64 CControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting, int nBufSize)
  353. {
  354. m_SpeedLimitSync.Lock();
  355. std::list<t_ActiveList>::iterator iter;
  356. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  357. if (iter->pOwner == this)
  358. break;
  359. if (iter == m_InstanceList[direction].end())
  360. {
  361. t_ActiveList item;
  362. #ifdef MPEXT
  363. CTime time = CTime::GetCurrentTime();
  364. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  365. #else
  366. item.nBytesAvailable = GetSpeedLimit(direction, CTime::GetCurrentTime()) / (m_InstanceList[direction].size() + 1);
  367. #endif
  368. item.nBytesTransferred = 0;
  369. item.pOwner = this;
  370. m_InstanceList[direction].push_back(item);
  371. iter = m_InstanceList[direction].end();
  372. iter--;
  373. }
  374. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction, nBufSize);
  375. m_SpeedLimitSync.Unlock();
  376. return limit;
  377. }
  378. BOOL CControlSocket::RemoveActiveTransfer()
  379. {
  380. BOOL bFound = FALSE;
  381. m_SpeedLimitSync.Lock();
  382. std::list<t_ActiveList>::iterator iter;
  383. for (int i = 0; i < 2; i++)
  384. {
  385. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  386. if (iter->pOwner == this)
  387. {
  388. m_InstanceList[i].erase(iter);
  389. bFound = TRUE;
  390. break;
  391. }
  392. }
  393. m_SpeedLimitSync.Unlock();
  394. return bFound;
  395. }
  396. BOOL CControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  397. {
  398. m_SpeedLimitSync.Lock();
  399. std::list<t_ActiveList>::iterator iter;
  400. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  401. if (iter->pOwner == this)
  402. {
  403. if (iter->nBytesAvailable > nBytesTransferred)
  404. iter->nBytesAvailable -= nBytesTransferred;
  405. else
  406. iter->nBytesAvailable = 0;
  407. iter->nBytesTransferred += nBytesTransferred;
  408. m_SpeedLimitSync.Unlock();
  409. return TRUE;
  410. }
  411. m_SpeedLimitSync.Unlock();
  412. return FALSE;
  413. }
  414. CString CControlSocket::ConvertDomainName(CString domain)
  415. {
  416. USES_CONVERSION;
  417. LPCWSTR buffer = T2CW(domain);
  418. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  419. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  420. {
  421. delete [] utf8;
  422. LogMessage(FZ_LOG_WARNING, _T("Could not convert domain name"));
  423. return domain;
  424. }
  425. char *output = 0;
  426. #ifdef MPEXT
  427. output = strdup(utf8);
  428. #else
  429. if (idna_to_ascii_8z(utf8, &output, IDNA_ALLOW_UNASSIGNED))
  430. {
  431. delete [] utf8;
  432. LogMessage(FZ_LOG_WARNING, _T("Could not convert domain name"));
  433. return domain;
  434. }
  435. #endif
  436. delete [] utf8;
  437. CString result = A2T(output);
  438. free(output);
  439. return result;
  440. }