AsyncSslSocketLayer.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. // CAsyncSslSocketLayer by Tim Kosse ([email protected])
  2. // Version 2.0 (2005-02-27)
  3. //---------------------------------------------------------------------------
  4. // Feel free to use this class, as long as you don't claim that you wrote it
  5. // and this copyright notice stays intact in the source files.
  6. // If you use this class in commercial applications, please send a short message
  7. // to [email protected]
  8. //---------------------------------------------------------------------------
  9. #include "stdafx.h"
  10. #include "AsyncSslSocketLayer.h"
  11. #include "FilezillaTools.h"
  12. #include <openssl/x509v3.h>
  13. #include <openssl/err.h>
  14. #include <openssl/tls1.h>
  15. #pragma hdrstop
  16. #include "Common.h"
  17. /////////////////////////////////////////////////////////////////////////////
  18. // CAsyncSslSocketLayer
  19. std::unique_ptr<TCriticalSection> CAsyncSslSocketLayer::m_sCriticalSection(TraceInitPtr(new TCriticalSection()));
  20. CAsyncSslSocketLayer::t_SslLayerList* CAsyncSslSocketLayer::m_pSslLayerList = 0;
  21. bool CAsyncSslSocketLayer::m_bSslInitialized = false;
  22. CAsyncSslSocketLayer::CAsyncSslSocketLayer()
  23. {
  24. m_ssl = 0;
  25. m_sslbio = 0;
  26. m_ibio = 0;
  27. m_nbio = 0;
  28. m_ssl_ctx = 0;
  29. m_bUseSSL = false;
  30. m_bSslInitialized = FALSE;
  31. m_bSslEstablished = FALSE;
  32. m_nNetworkSendBufferLen = 0;
  33. m_nNetworkSendBufferMaxLen = 0;
  34. m_pNetworkSendBuffer = NULL;
  35. m_pRetrySendBuffer = 0;
  36. m_nRetrySendBufferLen = 0;
  37. m_nNetworkError = 0;
  38. m_nShutDown = 0;
  39. m_bBlocking = FALSE;
  40. m_nSslAsyncNotifyId = 0;
  41. m_bFailureSent = FALSE;
  42. m_nVerificationResult = 0;
  43. m_nVerificationDepth = 0;
  44. m_mayTriggerRead = true;
  45. m_mayTriggerWrite = true;
  46. m_mayTriggerReadUp = true;
  47. m_mayTriggerWriteUp = true;
  48. m_onCloseCalled = false;
  49. m_Main = NULL;
  50. m_sessionid = NULL;
  51. m_sessionidSerialized = NULL;
  52. m_sessionreuse = true;
  53. m_sessionreuse_failed = false;
  54. FCertificate = NULL;
  55. FPrivateKey = NULL;
  56. m_CriticalSection.reset(new TCriticalSection());
  57. }
  58. CAsyncSslSocketLayer::~CAsyncSslSocketLayer()
  59. {
  60. ResetSslSession();
  61. delete [] m_pNetworkSendBuffer;
  62. delete [] m_pRetrySendBuffer;
  63. }
  64. int CAsyncSslSocketLayer::InitSSL()
  65. {
  66. TGuard Guard(m_sCriticalSection.get());
  67. if (!m_bSslInitialized)
  68. {
  69. if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL))
  70. {
  71. return SSL_FAILURE_INITSSL;
  72. }
  73. m_bSslInitialized = true;
  74. }
  75. return 0;
  76. }
  77. void CAsyncSslSocketLayer::OnReceive(int nErrorCode)
  78. {
  79. if (m_bUseSSL)
  80. {
  81. if (m_bBlocking)
  82. {
  83. m_mayTriggerRead = true;
  84. return;
  85. }
  86. if (m_nNetworkError)
  87. {
  88. return;
  89. }
  90. char buffer[16384];
  91. m_mayTriggerRead = false;
  92. //Get number of bytes we can receive and store in the network input bio
  93. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  94. if (len > 16384)
  95. len = 16384;
  96. else if (!len)
  97. {
  98. m_mayTriggerRead = true;
  99. TriggerEvents();
  100. return;
  101. }
  102. int numread = 0;
  103. // Receive data
  104. numread = ReceiveNext(buffer, len);
  105. if (numread > 0)
  106. {
  107. //Store it in the network input bio and process data
  108. int numwritten = BIO_write(m_nbio, buffer, numread);
  109. BIO_ctrl(m_nbio, BIO_CTRL_FLUSH, 0, NULL);
  110. // I have no idea why this call is needed, but without it, connections
  111. // will stall. Perhaps it triggers some internal processing.
  112. // Also, ignore return value, don't do any error checking. This function
  113. // can report errors, even though a later call can succeed.
  114. char buffer;
  115. BIO_read(m_sslbio, &buffer, 0);
  116. }
  117. if (!numread)
  118. {
  119. if (GetLayerState() == connected)
  120. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  121. }
  122. else if (numread == SOCKET_ERROR)
  123. {
  124. int nError = GetLastError();
  125. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  126. {
  127. m_nNetworkError = GetLastError();
  128. TriggerEvent(FD_CLOSE, 0, TRUE);
  129. return;
  130. }
  131. }
  132. if (m_pRetrySendBuffer != NULL)
  133. {
  134. if (ProcessSendBuffer() == -2)
  135. {
  136. TriggerEvent(FD_CLOSE, 0, TRUE);
  137. return;
  138. }
  139. }
  140. if (!m_nShutDown && SSL_get_shutdown(m_ssl))
  141. {
  142. size_t pending = BIO_ctrl_pending(m_sslbio);
  143. if (pending <= 0)
  144. {
  145. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  146. {
  147. if (ShutDownComplete())
  148. TriggerEvent(FD_CLOSE, 0, TRUE);
  149. }
  150. else
  151. {
  152. m_nNetworkError = WSAECONNABORTED;
  153. WSASetLastError(WSAECONNABORTED);
  154. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  155. }
  156. return;
  157. }
  158. }
  159. if (ShutDownComplete() && m_nShutDown == 1)
  160. {
  161. //Send shutdown notification if all pending data has been sent
  162. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  163. m_nShutDown++;
  164. }
  165. TriggerEvents();
  166. }
  167. else
  168. {
  169. TriggerEvent(FD_READ, nErrorCode, TRUE);
  170. }
  171. }
  172. int CAsyncSslSocketLayer::ProcessSendBuffer()
  173. {
  174. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  175. if (numwrite >= 0)
  176. {
  177. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  178. delete [] m_pRetrySendBuffer;
  179. m_pRetrySendBuffer = 0;
  180. return numwrite;
  181. }
  182. else
  183. {
  184. DebugAssert(numwrite == -1);
  185. if (!BIO_should_retry(m_sslbio))
  186. {
  187. delete [] m_pRetrySendBuffer;
  188. m_pRetrySendBuffer = 0;
  189. ::SetLastError(WSAECONNABORTED);
  190. return -2;
  191. }
  192. else
  193. {
  194. return -1;
  195. }
  196. }
  197. }
  198. void CAsyncSslSocketLayer::OnSend(int nErrorCode)
  199. {
  200. if (m_bUseSSL)
  201. {
  202. if (m_nNetworkError)
  203. {
  204. return;
  205. }
  206. m_mayTriggerWrite = false;
  207. //Send data in the send buffer
  208. while (m_nNetworkSendBufferLen)
  209. {
  210. int numsent = SendNext(m_pNetworkSendBuffer, m_nNetworkSendBufferLen);
  211. if (numsent == SOCKET_ERROR)
  212. {
  213. int nError = GetLastError();
  214. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  215. {
  216. m_nNetworkError = nError;
  217. TriggerEvent(FD_CLOSE, 0, TRUE);
  218. }
  219. return;
  220. }
  221. else if (!numsent)
  222. {
  223. if (GetLayerState() == connected)
  224. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  225. }
  226. if (numsent == m_nNetworkSendBufferLen)
  227. {
  228. m_nNetworkSendBufferLen = 0;
  229. }
  230. else
  231. {
  232. memmove(m_pNetworkSendBuffer, m_pNetworkSendBuffer + numsent, m_nNetworkSendBufferLen - numsent);
  233. m_nNetworkSendBufferLen -= numsent;
  234. }
  235. }
  236. //Send the data waiting in the network bio
  237. char buffer[32 * 1024];
  238. size_t len = BIO_ctrl_pending(m_nbio);
  239. int numread = BIO_read(m_nbio, buffer, std::min(len, sizeof(buffer)));
  240. if (numread <= 0)
  241. m_mayTriggerWrite = true;
  242. while (numread > 0)
  243. {
  244. int numsent = SendNext(buffer, numread);
  245. if (!numsent)
  246. {
  247. if (GetLayerState() == connected)
  248. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  249. }
  250. if (numsent == SOCKET_ERROR || numsent < numread)
  251. {
  252. if (numsent == SOCKET_ERROR)
  253. if (GetLastError() != WSAEWOULDBLOCK && GetLastError() != WSAENOTCONN)
  254. {
  255. m_nNetworkError = GetLastError();
  256. TriggerEvent(FD_CLOSE, 0, TRUE);
  257. return;
  258. }
  259. else
  260. numsent = 0;
  261. // Add all data that was retrieved from the network bio but could not be sent to the send buffer.
  262. if (m_nNetworkSendBufferMaxLen < (m_nNetworkSendBufferLen + numread - numsent))
  263. {
  264. char * tmp = m_pNetworkSendBuffer;
  265. m_nNetworkSendBufferMaxLen = static_cast<int>((m_nNetworkSendBufferLen + numread - numsent) * 1.5);
  266. m_pNetworkSendBuffer = new char[m_nNetworkSendBufferMaxLen];
  267. if (tmp)
  268. {
  269. memcpy(m_pNetworkSendBuffer, tmp, m_nNetworkSendBufferLen);
  270. delete [] tmp;
  271. }
  272. }
  273. DebugAssert(m_pNetworkSendBuffer);
  274. memcpy(m_pNetworkSendBuffer + m_nNetworkSendBufferLen, buffer, numread-numsent);
  275. m_nNetworkSendBufferLen += numread - numsent;
  276. }
  277. if (!numsent)
  278. {
  279. break;
  280. }
  281. len = BIO_ctrl_pending(m_nbio);
  282. if (!len)
  283. {
  284. m_mayTriggerWrite = true;
  285. break;
  286. }
  287. numread = BIO_read(m_nbio, buffer, len);
  288. if (numread <= 0)
  289. {
  290. m_mayTriggerWrite = true;
  291. }
  292. }
  293. if (m_pRetrySendBuffer != NULL)
  294. {
  295. if (ProcessSendBuffer() == -2)
  296. {
  297. TriggerEvent(FD_CLOSE, 0, TRUE);
  298. return;
  299. }
  300. }
  301. // No more data available, ask for more.
  302. TriggerEvents();
  303. if (m_nShutDown == 1 && ShutDownComplete())
  304. {
  305. //Send shutdown notification if all pending data has been sent
  306. // FileZilla3 calls ShutDownNext() here
  307. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  308. m_nShutDown++;
  309. }
  310. }
  311. else
  312. {
  313. TriggerEvent(FD_WRITE, nErrorCode, TRUE);
  314. }
  315. }
  316. int CAsyncSslSocketLayer::Send(const void* lpBuf, int nBufLen, int nFlags)
  317. {
  318. if (m_bUseSSL)
  319. {
  320. if (!lpBuf)
  321. {
  322. return 0;
  323. }
  324. if (m_bBlocking || m_pRetrySendBuffer)
  325. {
  326. m_mayTriggerWriteUp = true;
  327. ::SetLastError(WSAEWOULDBLOCK);
  328. return SOCKET_ERROR;
  329. }
  330. if (m_nNetworkError)
  331. {
  332. SetLastError(m_nNetworkError);
  333. return SOCKET_ERROR;
  334. }
  335. if (m_nShutDown)
  336. {
  337. ::SetLastError(WSAESHUTDOWN);
  338. return SOCKET_ERROR;
  339. }
  340. if (!m_bSslEstablished)
  341. {
  342. m_mayTriggerWriteUp = true;
  343. ::SetLastError(WSAEWOULDBLOCK);
  344. return SOCKET_ERROR;
  345. }
  346. if (!nBufLen)
  347. {
  348. return 0;
  349. }
  350. if (m_onCloseCalled)
  351. {
  352. TriggerEvent(FD_CLOSE, 0, TRUE);
  353. return 0;
  354. }
  355. int len = BIO_ctrl_get_write_guarantee(m_sslbio);
  356. if (nBufLen > len)
  357. nBufLen = len;
  358. if (!len)
  359. {
  360. m_mayTriggerWriteUp = true;
  361. TriggerEvents();
  362. ::SetLastError(WSAEWOULDBLOCK);
  363. }
  364. m_pRetrySendBuffer = new char[nBufLen];
  365. m_nRetrySendBufferLen = nBufLen;
  366. memcpy(m_pRetrySendBuffer, lpBuf, nBufLen);
  367. int ProcessResult = ProcessSendBuffer();
  368. if (ProcessResult == -2)
  369. {
  370. return SOCKET_ERROR;
  371. }
  372. else if (ProcessResult == -1)
  373. {
  374. if (GetLayerState() == closed)
  375. {
  376. return 0;
  377. }
  378. else if (GetLayerState() != connected)
  379. {
  380. SetLastError(m_nNetworkError);
  381. return SOCKET_ERROR;
  382. }
  383. TriggerEvents();
  384. return nBufLen;
  385. }
  386. m_mayTriggerWriteUp = true;
  387. TriggerEvents();
  388. return ProcessResult;
  389. }
  390. else
  391. {
  392. return SendNext(lpBuf, nBufLen, nFlags);
  393. }
  394. }
  395. int CAsyncSslSocketLayer::Receive(void* lpBuf, int nBufLen, int nFlags)
  396. {
  397. if (m_bUseSSL)
  398. {
  399. if (m_bBlocking)
  400. {
  401. m_mayTriggerReadUp = true;
  402. ::SetLastError(WSAEWOULDBLOCK);
  403. return SOCKET_ERROR;
  404. }
  405. if (m_nNetworkError)
  406. {
  407. size_t pending = BIO_ctrl_pending(m_sslbio);
  408. if (pending && !m_nShutDown)
  409. {
  410. m_mayTriggerReadUp = true;
  411. TriggerEvents();
  412. return BIO_read(m_sslbio, lpBuf,nBufLen);
  413. }
  414. WSASetLastError(m_nNetworkError);
  415. return SOCKET_ERROR;
  416. }
  417. if (m_nShutDown)
  418. {
  419. ::SetLastError(WSAESHUTDOWN);
  420. return SOCKET_ERROR;
  421. }
  422. if (!nBufLen)
  423. {
  424. return 0;
  425. }
  426. size_t pending = BIO_ctrl_pending(m_sslbio);
  427. if (!pending)
  428. {
  429. if (GetLayerState() == closed)
  430. {
  431. return 0;
  432. }
  433. if (m_onCloseCalled)
  434. {
  435. TriggerEvent(FD_CLOSE, 0, TRUE);
  436. return 0;
  437. }
  438. else if (GetLayerState() != connected)
  439. {
  440. SetLastError(m_nNetworkError);
  441. return SOCKET_ERROR;
  442. }
  443. else
  444. {
  445. if (SSL_get_shutdown(m_ssl))
  446. {
  447. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  448. {
  449. if (ShutDownComplete())
  450. {
  451. TriggerEvent(FD_CLOSE, 0, TRUE);
  452. return 0;
  453. }
  454. else
  455. WSASetLastError(WSAEWOULDBLOCK);
  456. }
  457. else
  458. {
  459. m_nNetworkError = WSAECONNABORTED;
  460. WSASetLastError(WSAECONNABORTED);
  461. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  462. }
  463. return SOCKET_ERROR;
  464. }
  465. }
  466. m_mayTriggerReadUp = true;
  467. TriggerEvents();
  468. ::SetLastError(WSAEWOULDBLOCK);
  469. return SOCKET_ERROR;
  470. }
  471. int numread = BIO_read(m_sslbio, lpBuf, nBufLen);
  472. if (!numread)
  473. {
  474. if (SSL_get_shutdown(m_ssl))
  475. {
  476. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  477. {
  478. if (ShutDownComplete())
  479. {
  480. TriggerEvent(FD_CLOSE, 0, TRUE);
  481. return 0;
  482. }
  483. else
  484. WSASetLastError(WSAEWOULDBLOCK);
  485. }
  486. else
  487. {
  488. m_nNetworkError = WSAECONNABORTED;
  489. WSASetLastError(WSAECONNABORTED);
  490. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  491. }
  492. return SOCKET_ERROR;
  493. }
  494. m_mayTriggerReadUp = true;
  495. TriggerEvents();
  496. ::SetLastError(WSAEWOULDBLOCK);
  497. return SOCKET_ERROR;
  498. }
  499. if (numread < 0)
  500. {
  501. if (!BIO_should_retry(m_sslbio))
  502. {
  503. PrintLastErrorMsg();
  504. m_nNetworkError = WSAECONNABORTED;
  505. WSASetLastError(WSAECONNABORTED);
  506. TriggerEvent(FD_CLOSE, 0, TRUE);
  507. return SOCKET_ERROR;
  508. }
  509. else
  510. {
  511. if (SSL_get_shutdown(m_ssl))
  512. {
  513. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  514. {
  515. if (ShutDownComplete())
  516. {
  517. TriggerEvent(FD_CLOSE, 0, TRUE);
  518. return 0;
  519. }
  520. else
  521. WSASetLastError(WSAEWOULDBLOCK);
  522. }
  523. else
  524. {
  525. m_nNetworkError = WSAECONNABORTED;
  526. WSASetLastError(WSAECONNABORTED);
  527. TriggerEvent(FD_CLOSE, 0, TRUE);
  528. }
  529. return SOCKET_ERROR;
  530. }
  531. m_mayTriggerReadUp = true;
  532. TriggerEvents();
  533. ::SetLastError(WSAEWOULDBLOCK);
  534. return SOCKET_ERROR;
  535. }
  536. }
  537. m_mayTriggerReadUp = true;
  538. TriggerEvents();
  539. return numread;
  540. }
  541. else
  542. {
  543. return ReceiveNext(lpBuf, nBufLen, nFlags);
  544. }
  545. }
  546. void CAsyncSslSocketLayer::Close()
  547. {
  548. if (!m_nShutDown && m_bSslEstablished && !m_nNetworkError && !m_nCriticalError)
  549. {
  550. ShutDown();
  551. while (!ShutDownComplete() && !m_nNetworkError && !m_nCriticalError &&
  552. ((m_nNetworkSendBufferLen > 0) || (BIO_ctrl_pending(m_nbio) > 0) || m_pRetrySendBuffer))
  553. {
  554. OnSend(0);
  555. }
  556. }
  557. m_nShutDown = 0;
  558. m_onCloseCalled = false;
  559. ResetSslSession();
  560. CloseNext();
  561. }
  562. BOOL CAsyncSslSocketLayer::Connect(const SOCKADDR *lpSockAddr, int nSockAddrLen)
  563. {
  564. BOOL res = ConnectNext(lpSockAddr, nSockAddrLen);
  565. if (!res)
  566. {
  567. if (GetLastError() != WSAEWOULDBLOCK)
  568. {
  569. ResetSslSession();
  570. }
  571. }
  572. return res;
  573. }
  574. BOOL CAsyncSslSocketLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  575. {
  576. BOOL res = ConnectNext(lpszHostAddress, nHostPort);
  577. if (!res)
  578. {
  579. if (GetLastError()!=WSAEWOULDBLOCK)
  580. {
  581. ResetSslSession();
  582. }
  583. }
  584. return res;
  585. }
  586. void CAsyncSslSocketLayer::SetSession(SSL_SESSION * Session)
  587. {
  588. TGuard Guard(m_CriticalSection.get());
  589. if (m_sessionid != NULL)
  590. {
  591. SSL_SESSION_free(m_sessionid);
  592. }
  593. bool Serialize = (m_Main == NULL);
  594. if ((m_sessionidSerialized != NULL) && DebugAlwaysTrue(Serialize))
  595. {
  596. delete[] m_sessionidSerialized;
  597. m_sessionidSerialized = NULL;
  598. }
  599. m_sessionid = Session;
  600. if ((m_sessionid != NULL) && Serialize)
  601. {
  602. LogSocketMessageRaw(FZ_LOG_INFO, L"Saving session ID");
  603. m_sessionidSerializedLen = i2d_SSL_SESSION(m_sessionid, NULL);
  604. m_sessionidSerialized = new unsigned char[m_sessionidSerializedLen];
  605. unsigned char * P = m_sessionidSerialized;
  606. i2d_SSL_SESSION(m_sessionid, &P);
  607. }
  608. }
  609. bool CAsyncSslSocketLayer::HandleSession(SSL_SESSION * Session)
  610. {
  611. bool Result = false;
  612. if (m_sessionreuse)
  613. {
  614. if (m_sessionid != Session)
  615. {
  616. if (m_sessionid == NULL)
  617. {
  618. if (SSL_session_reused(m_ssl))
  619. {
  620. LogSocketMessageRaw(FZ_LOG_PROGRESS, L"Session ID reused");
  621. }
  622. else
  623. {
  624. if ((m_Main != NULL) && !m_Main->m_sessionreuse_failed)
  625. {
  626. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID not reused, will not try again");
  627. m_Main->m_sessionreuse_failed = true;
  628. }
  629. }
  630. }
  631. else
  632. {
  633. LogSocketMessageRaw(FZ_LOG_INFO, L"Session ID changed");
  634. }
  635. SetSession(Session);
  636. Result = true;
  637. }
  638. }
  639. return Result;
  640. }
  641. int CAsyncSslSocketLayer::NewSessionCallback(struct ssl_st * Ssl, SSL_SESSION * Session)
  642. {
  643. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  644. int Result = 0;
  645. // This is not called for TLS 1.2 and older when session is reused (so "Session ID reused" won't be logged).
  646. // So for 1.2 and older, we call HandleSession from apps_ssl_info_callback as we always did.
  647. if ((SSL_version(Ssl) >= TLS1_3_VERSION) && Layer->HandleSession(Session))
  648. {
  649. Result = 1;
  650. }
  651. return Result;
  652. }
  653. int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode,
  654. CAsyncSslSocketLayer* main, bool sessionreuse, const CString & host,
  655. CFileZillaTools * tools)
  656. {
  657. if (m_bUseSSL)
  658. return 0;
  659. int res = InitSSL();
  660. if (res)
  661. return res;
  662. {
  663. // What is the point of this guard?
  664. // Maybe the m_ssl_ctx was intended to be global. But as it is not, the guard is probably pointless.
  665. TGuard Guard(m_sCriticalSection.get());
  666. if (!m_ssl_ctx)
  667. {
  668. // Create new context if none given
  669. if (!(m_ssl_ctx = SSL_CTX_new( TLS_method())))
  670. {
  671. ResetSslSession();
  672. return SSL_FAILURE_INITSSL;
  673. }
  674. if (clientMode)
  675. {
  676. USES_CONVERSION;
  677. SSL_CTX_set_verify(m_ssl_ctx, SSL_VERIFY_PEER, verify_callback);
  678. SSL_CTX_set_client_cert_cb(m_ssl_ctx, ProvideClientCert);
  679. // https://www.mail-archive.com/[email protected]/msg86186.html
  680. SSL_CTX_set_session_cache_mode(m_ssl_ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE | SSL_SESS_CACHE_NO_AUTO_CLEAR);
  681. SSL_CTX_sess_set_new_cb(m_ssl_ctx, NewSessionCallback);
  682. CFileStatus Dummy;
  683. if (!m_CertStorage.IsEmpty() &&
  684. CFile::GetStatus((LPCTSTR)m_CertStorage, Dummy))
  685. {
  686. SSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0);
  687. }
  688. }
  689. }
  690. //Create new SSL session
  691. if (!(m_ssl = SSL_new(m_ssl_ctx)))
  692. {
  693. ResetSslSession();
  694. return SSL_FAILURE_INITSSL;
  695. }
  696. if (clientMode && (host.GetLength() > 0))
  697. {
  698. USES_CONVERSION;
  699. SSL_set_tlsext_host_name(m_ssl, T2CA(host));
  700. }
  701. #ifdef _DEBUG
  702. if ((main == NULL) && LoggingSocketMessage(FZ_LOG_INFO))
  703. {
  704. USES_CONVERSION;
  705. LogSocketMessageRaw(FZ_LOG_INFO, L"Supported ciphersuites:");
  706. STACK_OF(SSL_CIPHER) * ciphers = SSL_get_ciphers(m_ssl);
  707. for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); i++)
  708. {
  709. const SSL_CIPHER * cipher = sk_SSL_CIPHER_value(ciphers, i);
  710. LogSocketMessageRaw(FZ_LOG_INFO, A2CT(SSL_CIPHER_get_name(cipher)));
  711. }
  712. }
  713. #endif
  714. //Add current instance to list of active instances
  715. t_SslLayerList *tmp = m_pSslLayerList;
  716. m_pSslLayerList = new t_SslLayerList;
  717. m_pSslLayerList->pNext = tmp;
  718. m_pSslLayerList->pLayer = this;
  719. }
  720. SSL_set_info_callback(m_ssl, apps_ssl_info_callback);
  721. //Create bios
  722. m_sslbio = BIO_new(BIO_f_ssl());
  723. // WORKAROUND: Upload over TLS 1.3 fails for specific sizes in relation to OpenSSL buffer size.
  724. // For 32768 buffer, the sizes are 32725-32746, 65471-65492, 98217-98238 (tested up to 1048576)
  725. // Do not know how to fix that, so as a workaround, using buffer size that does not result in the problem.
  726. unsigned long TransferSize = 0;
  727. if (main != NULL)
  728. {
  729. TransferSize = static_cast<unsigned long>(GetSocketOptionVal(OPTION_MPEXT_TRANSFER_SIZE));
  730. }
  731. unsigned BufferKBs = 32;
  732. unsigned long BufferSize;
  733. do
  734. {
  735. BufferSize = BufferKBs * 1024;
  736. int Remainder = TransferSize % BufferSize;
  737. int BufferCount = (TransferSize / BufferSize) + (Remainder > 0 ? 1 : 0);
  738. int ProblemHigh = BufferSize - (BufferCount * 22);
  739. int ProblemLow = ProblemHigh - 21;
  740. if ((ProblemLow <= Remainder) && (Remainder <= ProblemHigh))
  741. {
  742. BufferKBs++;
  743. }
  744. else
  745. {
  746. break;
  747. }
  748. }
  749. while (true);
  750. BIO_new_bio_pair(&m_ibio, BufferSize, &m_nbio, BufferSize);
  751. if (!m_sslbio || !m_nbio || !m_ibio)
  752. {
  753. ResetSslSession();
  754. return SSL_FAILURE_INITSSL;
  755. }
  756. m_Tools = tools;
  757. m_Tools->SetupSsl(m_ssl);
  758. //Init SSL connection
  759. void *ssl_sessionid = NULL;
  760. m_Main = main;
  761. m_sessionreuse = sessionreuse;
  762. if ((m_Main != NULL) && m_sessionreuse)
  763. {
  764. TGuard Guard(m_Main->m_CriticalSection.get());
  765. if (m_Main->m_sessionidSerialized == NULL)
  766. {
  767. DebugFail();
  768. SSL_set_session(m_ssl, NULL);
  769. }
  770. else if (!m_Main->m_sessionreuse_failed)
  771. {
  772. // This is what Python SSL module does, instead of directly using SSL_SESSION of the other session,
  773. // claiming a bug in OpenSSL 1.1.1 and newer. See PySSL_get_session/PySSL_set_session.
  774. // OpenSSL refutes this as a bug in Python session handling.
  775. // https://github.com/openssl/openssl/issues/1550
  776. // But it works for us too.
  777. // For alternative (better) API, see
  778. // https://github.com/notroj/neon/pull/203/commits/36c918a66691ed1a40ab512821aa8c278081818f
  779. const unsigned char * P = m_Main->m_sessionidSerialized;
  780. SSL_SESSION * Session = DebugNotNull(d2i_SSL_SESSION(NULL, &P, m_Main->m_sessionidSerializedLen));
  781. if (!SSL_set_session(m_ssl, Session))
  782. {
  783. LogSocketMessageRaw(FZ_LOG_INFO, L"SSL_set_session failed");
  784. return SSL_FAILURE_INITSSL;
  785. }
  786. LogSocketMessageRaw(FZ_LOG_INFO, L"Trying reuse main TLS session ID");
  787. }
  788. else
  789. {
  790. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID was not reused previously, not trying again");
  791. SSL_set_session(m_ssl, NULL);
  792. }
  793. }
  794. else
  795. {
  796. SSL_set_session(m_ssl, NULL);
  797. }
  798. if (clientMode)
  799. {
  800. SSL_set_connect_state(m_ssl);
  801. }
  802. else
  803. {
  804. SSL_set_accept_state(m_ssl);
  805. }
  806. SSL_set_bio(m_ssl, m_ibio, m_ibio);
  807. BIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl);
  808. BIO_read(m_sslbio, (void *)1, 0);
  809. // Trigger FD_WRITE so that we can initialize SSL negotiation
  810. if (GetLayerState() == connected || GetLayerState() == attached)
  811. {
  812. TriggerEvent(FD_READ, 0);
  813. TriggerEvent(FD_WRITE, 0);
  814. TriggerEvent(FD_READ, 0, TRUE);
  815. TriggerEvent(FD_WRITE, 0, TRUE);
  816. }
  817. m_bUseSSL = true;
  818. return 0;
  819. }
  820. void CAsyncSslSocketLayer::ResetSslSession()
  821. {
  822. if (m_pRetrySendBuffer)
  823. {
  824. delete [] m_pRetrySendBuffer;
  825. m_pRetrySendBuffer = 0;
  826. }
  827. m_bFailureSent = FALSE;
  828. m_bBlocking = FALSE;
  829. m_nSslAsyncNotifyId++;
  830. m_nNetworkError = 0;
  831. m_bUseSSL = FALSE;
  832. m_nVerificationResult = 0;
  833. m_nVerificationDepth = 0;
  834. m_bSslEstablished = FALSE;
  835. if (m_sslbio)
  836. {
  837. BIO_free(m_sslbio);
  838. }
  839. if (m_ssl)
  840. {
  841. SSL_set_session(m_ssl,NULL);
  842. }
  843. if (m_nbio)
  844. {
  845. BIO_free(m_nbio);
  846. }
  847. if (m_ibio)
  848. {
  849. BIO_free(m_ibio);
  850. }
  851. m_nNetworkSendBufferLen = 0;
  852. m_nbio = 0;
  853. m_ibio = 0;
  854. m_sslbio = 0;
  855. if (m_ssl)
  856. {
  857. SSL_free(m_ssl);
  858. }
  859. TGuard Guard(m_sCriticalSection.get());
  860. if (m_ssl_ctx)
  861. {
  862. SSL_CTX_free(m_ssl_ctx);
  863. m_ssl_ctx = 0;
  864. }
  865. m_ssl = 0;
  866. t_SslLayerList *cur = m_pSslLayerList;
  867. if (!cur)
  868. {
  869. return;
  870. }
  871. if (cur->pLayer == this)
  872. {
  873. m_pSslLayerList = cur->pNext;
  874. delete cur;
  875. }
  876. else
  877. while (cur->pNext)
  878. {
  879. if (cur->pNext->pLayer == this)
  880. {
  881. t_SslLayerList *tmp = cur->pNext;
  882. cur->pNext = cur->pNext->pNext;
  883. delete tmp;
  884. return;
  885. }
  886. cur = cur->pNext;
  887. }
  888. SetSession(NULL);
  889. m_sessionreuse = true;
  890. m_sessionreuse_failed = false;
  891. }
  892. bool CAsyncSslSocketLayer::IsUsingSSL()
  893. {
  894. return m_bUseSSL;
  895. }
  896. BOOL CAsyncSslSocketLayer::ShutDown(int nHow /*=sends*/)
  897. {
  898. if (m_bUseSSL)
  899. {
  900. if (m_pRetrySendBuffer)
  901. {
  902. if (!m_nShutDown)
  903. m_nShutDown = 1;
  904. WSASetLastError(WSAEWOULDBLOCK);
  905. return false;
  906. }
  907. if (!m_bSslEstablished)
  908. {
  909. m_mayTriggerWriteUp = true;
  910. ::SetLastError(WSAEWOULDBLOCK);
  911. return false;
  912. }
  913. if (!m_nShutDown)
  914. m_nShutDown = 1;
  915. else
  916. {
  917. if (ShutDownComplete())
  918. return ShutDownNext();
  919. else
  920. {
  921. TriggerEvents();
  922. WSASetLastError(WSAEWOULDBLOCK);
  923. return false;
  924. }
  925. }
  926. int res = SSL_shutdown(m_ssl);
  927. if (res == 0)
  928. {
  929. // Without bi-directional shutdown, file uploads are incomplete on some servers
  930. res = SSL_shutdown(m_ssl);
  931. int completeShutdown = GetSocketOptionVal(OPTION_MPEXT_COMPLETE_TLS_SHUTDOWN);
  932. if ((completeShutdown < 0) ||
  933. ((completeShutdown == 0) && (SSL_version(m_ssl) <= TLS1_2_VERSION)))
  934. {
  935. LogSocketMessageRaw(FZ_LOG_INFO, L"Not waiting for complete TLS shutdown");
  936. res = 0;
  937. }
  938. }
  939. if (res >= 0)
  940. {
  941. if (ShutDownComplete())
  942. return ShutDownNext();
  943. else
  944. {
  945. TriggerEvents();
  946. WSASetLastError(WSAEWOULDBLOCK);
  947. return FALSE;
  948. }
  949. }
  950. else
  951. {
  952. int error = SSL_get_error(m_ssl, -1);
  953. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  954. {
  955. // retry shutdown later
  956. m_nShutDown = 0;
  957. TriggerEvents();
  958. WSASetLastError(WSAEWOULDBLOCK);
  959. return FALSE;
  960. }
  961. else if (ShutDownComplete())
  962. return ShutDownNext();
  963. else
  964. {
  965. TriggerEvents();
  966. WSASetLastError(WSAEWOULDBLOCK);
  967. return FALSE;
  968. }
  969. }
  970. }
  971. else
  972. {
  973. if (!m_nShutDown)
  974. m_nShutDown = 1;
  975. return ShutDownNext(nHow);
  976. }
  977. }
  978. BOOL CAsyncSslSocketLayer::ShutDownComplete()
  979. {
  980. //If a ShutDown was issued, has the connection already been shut down?
  981. if (!m_nShutDown)
  982. return FALSE;
  983. else if (!m_bUseSSL)
  984. return FALSE;
  985. else if (m_nNetworkSendBufferLen)
  986. return FALSE;
  987. else if (m_pRetrySendBuffer)
  988. return FALSE;
  989. // Empty read buffer
  990. char buffer[1000];
  991. int numread;
  992. do
  993. {
  994. numread = BIO_read(m_sslbio, buffer, 1000);
  995. } while (numread > 0);
  996. size_t pending = BIO_ctrl_pending(m_nbio);
  997. if (pending)
  998. {
  999. return FALSE;
  1000. }
  1001. else
  1002. {
  1003. return TRUE;
  1004. }
  1005. }
  1006. void CAsyncSslSocketLayer::LogSslError(const SSL *s, const char * str, const char * fmt, int nMessageType, char * debug)
  1007. {
  1008. USES_CONVERSION;
  1009. const char * StateString = SSL_state_string_long(s);
  1010. if ((strcmp(StateString, "error") != 0) || (debug != NULL))
  1011. {
  1012. char * buffer = new char[4096 + ((debug != NULL) ? strlen(debug) : 0)];
  1013. sprintf(buffer, fmt, str, StateString);
  1014. if (debug != NULL)
  1015. {
  1016. sprintf(buffer + strlen(buffer), " [%s]", debug);
  1017. OPENSSL_free(debug);
  1018. }
  1019. LogSocketMessageRaw(nMessageType, A2T(buffer));
  1020. delete[] buffer;
  1021. }
  1022. }
  1023. void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int ret)
  1024. {
  1025. USES_CONVERSION;
  1026. CAsyncSslSocketLayer *pLayer = 0;
  1027. {
  1028. TGuard Guard(m_sCriticalSection.get());
  1029. t_SslLayerList *cur = m_pSslLayerList;
  1030. while (cur)
  1031. {
  1032. if (cur->pLayer->m_ssl == s)
  1033. break;
  1034. cur = cur->pNext;
  1035. }
  1036. if (!cur)
  1037. {
  1038. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1039. return;
  1040. }
  1041. else
  1042. pLayer = cur->pLayer;
  1043. }
  1044. // Called while unloading?
  1045. if (!pLayer->m_bUseSSL && (where != SSL_CB_LOOP))
  1046. return;
  1047. const char * str;
  1048. int w;
  1049. w = where& ~SSL_ST_MASK;
  1050. if (w & SSL_ST_CONNECT)
  1051. {
  1052. str = "TLS connect";
  1053. }
  1054. else if (w & SSL_ST_ACCEPT)
  1055. str = "TLS accept";
  1056. else
  1057. str = "Undefined";
  1058. if (where & SSL_CB_LOOP)
  1059. {
  1060. char* debug = NULL;
  1061. // exact SSL_CB_LOOP is abused for debugging
  1062. if (where == SSL_CB_LOOP)
  1063. {
  1064. debug = reinterpret_cast<char*>(ret);
  1065. }
  1066. pLayer->LogSslError(s, str, "%s: %s", FZ_LOG_INFO, debug);
  1067. }
  1068. else if (where & SSL_CB_ALERT)
  1069. {
  1070. str=(where & SSL_CB_READ)? "read" : "write";
  1071. const char* desc = SSL_alert_desc_string_long(ret);
  1072. // Don't send close notify warning
  1073. if (desc)
  1074. {
  1075. if (strcmp(desc, "close notify"))
  1076. {
  1077. char *buffer = new char[4096];
  1078. sprintf(buffer, "SSL3 alert %s: %s: %s",
  1079. str,
  1080. SSL_alert_type_string_long(ret),
  1081. desc);
  1082. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1083. pLayer->PrintLastErrorMsg();
  1084. delete [] buffer;
  1085. }
  1086. }
  1087. }
  1088. else if (where & SSL_CB_EXIT)
  1089. {
  1090. bool SendFailure = false;
  1091. if (ret == 0)
  1092. {
  1093. pLayer->LogSslError(s, str, "%s: failed in %s", FZ_LOG_WARNING);
  1094. pLayer->PrintLastErrorMsg();
  1095. SendFailure = true;
  1096. }
  1097. else if (ret < 0)
  1098. {
  1099. int error = SSL_get_error(s,ret);
  1100. if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
  1101. {
  1102. pLayer->LogSslError(s, str, "%s: error in %s", FZ_LOG_WARNING);
  1103. pLayer->PrintLastErrorMsg();
  1104. SendFailure = true;
  1105. }
  1106. }
  1107. if (SendFailure && !pLayer->m_bFailureSent)
  1108. {
  1109. pLayer->m_bFailureSent = TRUE;
  1110. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1111. }
  1112. }
  1113. if (where & SSL_CB_HANDSHAKE_DONE)
  1114. {
  1115. // For 1.2 and older, session is always established at this point.
  1116. // For 1.3, session can be restarted later, so this is handled in NewSessionCallback.
  1117. // But at least with Cerberus server, it is not, so if we want to have "reuse" logged, we need to do it here.
  1118. SSL_SESSION * sessionid = SSL_get1_session(pLayer->m_ssl);
  1119. if (!pLayer->HandleSession(sessionid))
  1120. {
  1121. SSL_SESSION_free(sessionid);
  1122. }
  1123. int error = SSL_get_verify_result(pLayer->m_ssl);
  1124. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERIFY_CERT, error);
  1125. pLayer->m_bBlocking = TRUE;
  1126. }
  1127. }
  1128. bool AsnTimeToValidTime(ASN1_TIME * AsnTime, t_SslCertData::t_validTime & ValidTime)
  1129. {
  1130. int i = AsnTime->length;
  1131. const char * v = (const char *)AsnTime->data;
  1132. if (i < 10)
  1133. {
  1134. return FALSE;
  1135. }
  1136. for (int i2 = 0; i2 < 10; i2++)
  1137. {
  1138. if ((v[i2] > '9') || (v[i2] < '0'))
  1139. {
  1140. return FALSE;
  1141. }
  1142. }
  1143. if (AsnTime->type == V_ASN1_UTCTIME)
  1144. {
  1145. ValidTime.y= (v[0]-'0')*10+(v[1]-'0');
  1146. if (ValidTime.y < 50) ValidTime.y+=100;
  1147. ValidTime.y += 1900;
  1148. v += 2;
  1149. i -= 2;
  1150. }
  1151. else if (AsnTime->type == V_ASN1_GENERALIZEDTIME)
  1152. {
  1153. if (i < 12)
  1154. {
  1155. return FALSE;
  1156. }
  1157. ValidTime.y = (v[0]-'0')*1000+(v[1]-'0')*100 + (v[2]-'0')*10+(v[3]-'0');
  1158. v += 4;
  1159. i -= 4;
  1160. }
  1161. else
  1162. {
  1163. return FALSE;
  1164. }
  1165. ValidTime.M = (v[0]-'0')*10+(v[1]-'0');
  1166. if ((ValidTime.M > 12) || (ValidTime.M < 1))
  1167. {
  1168. return FALSE;
  1169. }
  1170. ValidTime.d = (v[2]-'0')*10+(v[3]-'0');
  1171. ValidTime.h = (v[4]-'0')*10+(v[5]-'0');
  1172. ValidTime.m = (v[6]-'0')*10+(v[7]-'0');
  1173. if ((i >= 10) &&
  1174. (v[8] >= '0') && (v[8] <= '9') &&
  1175. (v[9] >= '0') && (v[9] <= '9'))
  1176. {
  1177. ValidTime.s = (v[8]-'0')*10+(v[9]-'0');
  1178. }
  1179. else
  1180. {
  1181. ValidTime.s = 0;
  1182. }
  1183. return TRUE;
  1184. }
  1185. BOOL CAsyncSslSocketLayer::GetPeerCertificateData(t_SslCertData &SslCertData, LPCTSTR & Error)
  1186. {
  1187. X509 *pX509=SSL_get_peer_certificate(m_ssl);
  1188. if (!pX509)
  1189. {
  1190. Error = L"Cannot get certificate";
  1191. return FALSE;
  1192. }
  1193. //Reset the contents of SslCertData
  1194. memset(&SslCertData, 0, sizeof(t_SslCertData));
  1195. //Set subject data fields
  1196. X509_NAME *pX509Name=X509_get_subject_name(pX509);
  1197. if (pX509Name)
  1198. {
  1199. int count=X509_NAME_entry_count(pX509Name);
  1200. for (int i=0;i<count;i++)
  1201. {
  1202. X509_NAME_ENTRY *pX509NameEntry=X509_NAME_get_entry(pX509Name,i);
  1203. if (!pX509NameEntry)
  1204. continue;
  1205. ASN1_OBJECT *pObject = X509_NAME_ENTRY_get_object(pX509NameEntry);
  1206. ASN1_STRING *pString = X509_NAME_ENTRY_get_data(pX509NameEntry);
  1207. CString str;
  1208. unsigned char *out;
  1209. int len = ASN1_STRING_to_UTF8(&out, pString);
  1210. if (len > 0)
  1211. {
  1212. // Keep it huge
  1213. LPWSTR unicode = new WCHAR[len * 10];
  1214. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1215. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1216. if (unicodeLen > 0)
  1217. {
  1218. #ifdef _UNICODE
  1219. str = unicode;
  1220. #else
  1221. LPSTR ansi = new CHAR[len * 10];
  1222. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1223. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1224. if (ansiLen > 0)
  1225. str = ansi;
  1226. delete [] ansi;
  1227. #endif
  1228. }
  1229. delete [] unicode;
  1230. OPENSSL_free(out);
  1231. }
  1232. switch(OBJ_obj2nid(pObject))
  1233. {
  1234. case NID_organizationName:
  1235. _tcsncpy(SslCertData.subject.Organization, str, 255);
  1236. SslCertData.subject.Organization[255] = 0;
  1237. break;
  1238. case NID_organizationalUnitName:
  1239. _tcsncpy(SslCertData.subject.Unit, str, 255);
  1240. SslCertData.subject.Unit[255] = 0;
  1241. break;
  1242. case NID_commonName:
  1243. _tcsncpy(SslCertData.subject.CommonName, str, 255);
  1244. SslCertData.subject.CommonName[255] = 0;
  1245. break;
  1246. case NID_pkcs9_emailAddress:
  1247. _tcsncpy(SslCertData.subject.Mail, str, 255);
  1248. SslCertData.subject.Mail[255] = 0;
  1249. break;
  1250. case NID_countryName:
  1251. _tcsncpy(SslCertData.subject.Country, str, 255);
  1252. SslCertData.subject.Country[255] = 0;
  1253. break;
  1254. case NID_stateOrProvinceName:
  1255. _tcsncpy(SslCertData.subject.StateProvince, str, 255);
  1256. SslCertData.subject.StateProvince[255] = 0;
  1257. break;
  1258. case NID_localityName:
  1259. _tcsncpy(SslCertData.subject.Town, str, 255);
  1260. SslCertData.subject.Town[255] = 0;
  1261. break;
  1262. default:
  1263. if ( !OBJ_nid2sn(OBJ_obj2nid(pObject)) )
  1264. {
  1265. TCHAR tmp[20];
  1266. _stprintf(tmp, L"%d", OBJ_obj2nid(pObject));
  1267. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1268. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), tmp, maxlen);
  1269. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1270. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L"=", maxlen);
  1271. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1272. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1273. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1274. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L";", maxlen);
  1275. }
  1276. else
  1277. {
  1278. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1279. USES_CONVERSION;
  1280. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), A2CT(OBJ_nid2sn(OBJ_obj2nid(pObject))), maxlen);
  1281. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1282. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L"=", maxlen);
  1283. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1284. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1285. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1286. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L";", maxlen);
  1287. }
  1288. break;
  1289. }
  1290. }
  1291. }
  1292. //Set issuer data fields
  1293. pX509Name=X509_get_issuer_name(pX509);
  1294. if (pX509Name)
  1295. {
  1296. int count=X509_NAME_entry_count(pX509Name);
  1297. for (int i=0;i<count;i++)
  1298. {
  1299. X509_NAME_ENTRY *pX509NameEntry=X509_NAME_get_entry(pX509Name,i);
  1300. if (!pX509NameEntry)
  1301. continue;
  1302. ASN1_STRING *pString=X509_NAME_ENTRY_get_data(pX509NameEntry);
  1303. ASN1_OBJECT *pObject=X509_NAME_ENTRY_get_object(pX509NameEntry);
  1304. CString str;
  1305. unsigned char *out;
  1306. int len = ASN1_STRING_to_UTF8(&out, pString);
  1307. if (len > 0)
  1308. {
  1309. // Keep it huge
  1310. LPWSTR unicode = new WCHAR[len * 10];
  1311. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1312. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1313. if (unicodeLen > 0)
  1314. {
  1315. #ifdef _UNICODE
  1316. str = unicode;
  1317. #else
  1318. LPSTR ansi = new CHAR[len * 10];
  1319. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1320. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1321. if (ansiLen > 0)
  1322. str = ansi;
  1323. delete [] ansi;
  1324. #endif
  1325. }
  1326. delete [] unicode;
  1327. OPENSSL_free(out);
  1328. }
  1329. switch(OBJ_obj2nid(pObject))
  1330. {
  1331. case NID_organizationName:
  1332. _tcsncpy(SslCertData.issuer.Organization, str, 255);
  1333. SslCertData.issuer.Organization[255] = 0;
  1334. break;
  1335. case NID_organizationalUnitName:
  1336. _tcsncpy(SslCertData.issuer.Unit, str, 255);
  1337. SslCertData.issuer.Unit[255] = 0;
  1338. break;
  1339. case NID_commonName:
  1340. _tcsncpy(SslCertData.issuer.CommonName, str, 255);
  1341. SslCertData.issuer.CommonName[255] = 0;
  1342. break;
  1343. case NID_pkcs9_emailAddress:
  1344. _tcsncpy(SslCertData.issuer.Mail, str, 255);
  1345. SslCertData.issuer.Mail[255] = 0;
  1346. break;
  1347. case NID_countryName:
  1348. _tcsncpy(SslCertData.issuer.Country, str, 255);
  1349. SslCertData.issuer.Country[255] = 0;
  1350. break;
  1351. case NID_stateOrProvinceName:
  1352. _tcsncpy(SslCertData.issuer.StateProvince, str, 255);
  1353. SslCertData.issuer.StateProvince[255] = 0;
  1354. break;
  1355. case NID_localityName:
  1356. _tcsncpy(SslCertData.issuer.Town, str, 255);
  1357. SslCertData.issuer.Town[255] = 0;
  1358. break;
  1359. default:
  1360. if ( !OBJ_nid2sn(OBJ_obj2nid(pObject)) )
  1361. {
  1362. TCHAR tmp[20];
  1363. _stprintf(tmp, L"%d", OBJ_obj2nid(pObject));
  1364. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1365. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), tmp, maxlen);
  1366. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1367. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L"=", maxlen);
  1368. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1369. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1370. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1371. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L";", maxlen);
  1372. }
  1373. else
  1374. {
  1375. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1376. USES_CONVERSION;
  1377. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), A2CT(OBJ_nid2sn(OBJ_obj2nid(pObject))), maxlen);
  1378. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1379. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L"=", maxlen);
  1380. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1381. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1382. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1383. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L";", maxlen);
  1384. }
  1385. break;
  1386. }
  1387. }
  1388. }
  1389. //Set date fields
  1390. //Valid from
  1391. ASN1_TIME *pTime=X509_getm_notBefore(pX509);
  1392. if (!pTime)
  1393. {
  1394. X509_free(pX509);
  1395. Error = L"Cannot get start time";
  1396. return FALSE;
  1397. }
  1398. if (!AsnTimeToValidTime(pTime, SslCertData.validFrom))
  1399. {
  1400. X509_free(pX509);
  1401. Error = L"Invalid start time";
  1402. return FALSE;
  1403. }
  1404. //Valid until
  1405. pTime = X509_getm_notAfter(pX509);
  1406. if (!pTime)
  1407. {
  1408. X509_free(pX509);
  1409. Error = L"Cannot get end time";
  1410. return FALSE;
  1411. }
  1412. if (!AsnTimeToValidTime(pTime, SslCertData.validUntil))
  1413. {
  1414. X509_free(pX509);
  1415. Error = L"Invalid end time";
  1416. return FALSE;
  1417. }
  1418. int subjectAltNamePos = X509_get_ext_by_NID(pX509, NID_subject_alt_name, -1);
  1419. if (subjectAltNamePos >= 0)
  1420. {
  1421. X509_EXTENSION * subjectAltNameExtension = X509_get_ext(pX509, subjectAltNamePos);
  1422. BIO * subjectAltNameBio = BIO_new(BIO_s_mem());
  1423. if (X509V3_EXT_print(subjectAltNameBio, subjectAltNameExtension, 0, 0) == 1)
  1424. {
  1425. USES_CONVERSION;
  1426. u_char *data;
  1427. int len = BIO_get_mem_data(subjectAltNameBio, &data);
  1428. char * buf = new char[len + 1];
  1429. memcpy(buf, data, len);
  1430. buf[len] = '\0';
  1431. _tcsncpy(SslCertData.subjectAltName, A2CT(buf), LENOF(SslCertData.subjectAltName));
  1432. SslCertData.subjectAltName[LENOF(SslCertData.subjectAltName) - 1] = '\0';
  1433. delete [] buf;
  1434. }
  1435. BIO_vfree(subjectAltNameBio);
  1436. }
  1437. unsigned int length;
  1438. length = sizeof(SslCertData.hashSha1);
  1439. X509_digest(pX509, EVP_sha1(), SslCertData.hashSha1, &length);
  1440. DebugAssert(length == sizeof(SslCertData.hashSha1));
  1441. length = sizeof(SslCertData.hashSha256);
  1442. X509_digest(pX509, EVP_sha256(), SslCertData.hashSha256, &length);
  1443. DebugAssert(length == sizeof(SslCertData.hashSha256));
  1444. // Inspired by ne_ssl_cert_export()
  1445. // Find the length of the DER encoding.
  1446. SslCertData.certificateLen = i2d_X509(pX509, NULL);
  1447. SslCertData.certificate = new unsigned char[SslCertData.certificateLen];
  1448. unsigned char * p = SslCertData.certificate;
  1449. i2d_X509(pX509, &p);
  1450. SslCertData.priv_data = m_nSslAsyncNotifyId;
  1451. X509_free(pX509);
  1452. SslCertData.verificationResult = m_nVerificationResult;
  1453. SslCertData.verificationDepth = m_nVerificationDepth;
  1454. return TRUE;
  1455. }
  1456. std::string CAsyncSslSocketLayer::GetTlsVersionStr()
  1457. {
  1458. return m_TlsVersionStr;
  1459. }
  1460. std::string CAsyncSslSocketLayer::GetCipherName()
  1461. {
  1462. return m_CipherName;
  1463. }
  1464. void CAsyncSslSocketLayer::SetNotifyReply(int nID, int nCode, int result)
  1465. {
  1466. if (!m_bBlocking)
  1467. return;
  1468. if (nID != m_nSslAsyncNotifyId)
  1469. return;
  1470. if (nCode != SSL_VERIFY_CERT)
  1471. return;
  1472. m_bBlocking = FALSE;
  1473. if (!result)
  1474. {
  1475. m_nNetworkError = WSAECONNABORTED;
  1476. WSASetLastError(WSAECONNABORTED);
  1477. if (!m_bFailureSent)
  1478. {
  1479. m_bFailureSent = TRUE;
  1480. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, SSL_FAILURE_CERTREJECTED);
  1481. }
  1482. TriggerEvent(FD_CLOSE, 0, TRUE);
  1483. return;
  1484. }
  1485. m_bSslEstablished = TRUE;
  1486. PrintSessionInfo();
  1487. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_ESTABLISHED);
  1488. TriggerEvents();
  1489. }
  1490. void CAsyncSslSocketLayer::PrintSessionInfo()
  1491. {
  1492. const SSL_CIPHER *ciph;
  1493. X509 *cert;
  1494. ciph = SSL_get_current_cipher(m_ssl);
  1495. char enc[4096] = {0};
  1496. cert=SSL_get_peer_certificate(m_ssl);
  1497. if (cert != NULL)
  1498. {
  1499. EVP_PKEY *pkey = X509_get_pubkey(cert);
  1500. if (pkey != NULL)
  1501. {
  1502. if (0)
  1503. ;
  1504. #ifndef NO_RSA
  1505. else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
  1506. sprintf(enc, "%d bit RSA", EVP_PKEY_bits(pkey));
  1507. #endif
  1508. #ifndef NO_DSA
  1509. else if (EVP_PKEY_id(pkey) == EVP_PKEY_DSA)
  1510. sprintf(enc, "%d bit DSA", EVP_PKEY_bits(pkey));
  1511. #endif
  1512. EVP_PKEY_free(pkey);
  1513. }
  1514. X509_free(cert);
  1515. /* The SSL API does not allow us to look at temporary RSA/DH keys,
  1516. * otherwise we should print their lengths too */
  1517. }
  1518. const int buffer_size = 4096;
  1519. char *buffer = new char[buffer_size];
  1520. char *buffer2 = new char[buffer_size];
  1521. // see also ne_ssl_get_version and ne_ssl_get_cipher
  1522. m_TlsVersionStr = SSL_get_version(m_ssl);
  1523. sprintf(buffer, "%s: %s, %s, %s",
  1524. SSL_CIPHER_get_version(ciph),
  1525. SSL_CIPHER_get_name(ciph),
  1526. enc,
  1527. SSL_CIPHER_description(ciph, buffer2, buffer_size));
  1528. m_CipherName = buffer;
  1529. // see TWebDAVFileSystem::CollectTLSSessionInfo()
  1530. sprintf(buffer, "Using %s, cipher %s",
  1531. m_TlsVersionStr.c_str(),
  1532. m_CipherName.c_str());
  1533. USES_CONVERSION;
  1534. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1535. delete [] buffer;
  1536. delete [] buffer2;
  1537. }
  1538. void CAsyncSslSocketLayer::OnConnect(int nErrorCode)
  1539. {
  1540. if (m_bUseSSL && nErrorCode)
  1541. TriggerEvent(FD_WRITE, 0);
  1542. TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  1543. }
  1544. CAsyncSslSocketLayer * CAsyncSslSocketLayer::LookupLayer(SSL * Ssl)
  1545. {
  1546. CAsyncSslSocketLayer * Result = NULL;
  1547. t_SslLayerList * Cur = NULL;
  1548. {
  1549. TGuard Guard(m_sCriticalSection.get());
  1550. Cur = m_pSslLayerList;
  1551. while (Cur != NULL)
  1552. {
  1553. if (Cur->pLayer->m_ssl == Ssl)
  1554. {
  1555. break;
  1556. }
  1557. Cur = Cur->pNext;
  1558. }
  1559. }
  1560. if (Cur == NULL)
  1561. {
  1562. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1563. Result = NULL;
  1564. }
  1565. else
  1566. {
  1567. Result = Cur->pLayer;
  1568. }
  1569. return Result;
  1570. }
  1571. int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1572. {
  1573. X509 *err_cert;
  1574. int err, depth;
  1575. SSL *ssl;
  1576. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  1577. err = X509_STORE_CTX_get_error(ctx);
  1578. depth = X509_STORE_CTX_get_error_depth(ctx);
  1579. /*
  1580. * Retrieve the pointer to the SSL of the connection currently treated
  1581. * and the application specific data stored into the SSL object.
  1582. */
  1583. ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  1584. CAsyncSslSocketLayer * pLayer = LookupLayer(ssl);
  1585. if (pLayer == NULL)
  1586. {
  1587. return 1;
  1588. }
  1589. /*
  1590. * Catch a too long certificate chain. The depth limit set using
  1591. * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
  1592. * that whenever the "depth>verify_depth" condition is met, we
  1593. * have violated the limit and want to log this error condition.
  1594. * We must do it here, because the CHAIN_TOO_LONG error would not
  1595. * be found explicitly; only errors introduced by cutting off the
  1596. * additional certificates would be logged.
  1597. */
  1598. if (depth > 10) {//mydata->verify_depth) {
  1599. preverify_ok = 0;
  1600. err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  1601. X509_STORE_CTX_set_error(ctx, err);
  1602. }
  1603. if (!preverify_ok)
  1604. {
  1605. if (!pLayer->m_nVerificationResult)
  1606. {
  1607. pLayer->m_nVerificationDepth = depth;
  1608. pLayer->m_nVerificationResult = err;
  1609. }
  1610. }
  1611. return 1;
  1612. }
  1613. int CAsyncSslSocketLayer::ProvideClientCert(
  1614. SSL * Ssl, X509 ** Certificate, EVP_PKEY ** PrivateKey)
  1615. {
  1616. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  1617. CString Message;
  1618. Message.LoadString(NEED_CLIENT_CERTIFICATE);
  1619. int Level;
  1620. int Result;
  1621. if ((Layer->FCertificate == NULL) || (Layer->FPrivateKey == NULL))
  1622. {
  1623. Level = FZ_LOG_WARNING;
  1624. Result = 0;
  1625. }
  1626. else
  1627. {
  1628. Level = FZ_LOG_PROGRESS;
  1629. *Certificate = X509_dup(Layer->FCertificate);
  1630. EVP_PKEY_up_ref(Layer->FPrivateKey);
  1631. *PrivateKey = Layer->FPrivateKey;
  1632. Result = 1;
  1633. }
  1634. Layer->LogSocketMessageRaw(Level, static_cast<LPCTSTR>(Message));
  1635. return Result;
  1636. }
  1637. void CAsyncSslSocketLayer::SetClientCertificate(X509 * Certificate, EVP_PKEY * PrivateKey)
  1638. {
  1639. FCertificate = Certificate;
  1640. FPrivateKey = PrivateKey;
  1641. }
  1642. BOOL CAsyncSslSocketLayer::SetCertStorage(CString file)
  1643. {
  1644. m_CertStorage = file;
  1645. return TRUE;
  1646. }
  1647. void CAsyncSslSocketLayer::OnClose(int nErrorCode)
  1648. {
  1649. m_onCloseCalled = true;
  1650. if (m_bUseSSL)
  1651. {
  1652. size_t pending = BIO_ctrl_pending(m_sslbio);
  1653. if (pending > 0)
  1654. {
  1655. TriggerEvents();
  1656. }
  1657. else TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1658. }
  1659. else
  1660. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1661. }
  1662. void CAsyncSslSocketLayer::PrintLastErrorMsg()
  1663. {
  1664. unsigned long err = ERR_get_error();
  1665. while (err)
  1666. {
  1667. USES_CONVERSION;
  1668. unsigned long aerr = err;
  1669. err = ERR_get_error();
  1670. char *buffer = new char[512];
  1671. ERR_error_string(aerr, buffer);
  1672. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1673. delete [] buffer;
  1674. std::wstring CustomReason = m_Tools->CustomReason(aerr);
  1675. if (!CustomReason.empty())
  1676. {
  1677. LogSocketMessageRaw(FZ_LOG_WARNING, CustomReason.c_str());
  1678. }
  1679. else
  1680. {
  1681. UnicodeString S = GetTlsErrorStr(aerr);
  1682. LogSocketMessageRaw(FZ_LOG_WARNING, S.c_str());
  1683. }
  1684. }
  1685. }
  1686. void CAsyncSslSocketLayer::TriggerEvents()
  1687. {
  1688. size_t pending = BIO_ctrl_pending(m_nbio);
  1689. if (pending > 0)
  1690. {
  1691. if (m_mayTriggerWrite)
  1692. {
  1693. m_mayTriggerWrite = false;
  1694. TriggerEvent(FD_WRITE, 0);
  1695. }
  1696. }
  1697. else if (!m_nNetworkSendBufferLen && m_bSslEstablished && !m_pRetrySendBuffer)
  1698. {
  1699. if (BIO_ctrl_get_write_guarantee(m_sslbio) > 0 && m_mayTriggerWriteUp)
  1700. {
  1701. m_mayTriggerWriteUp = false;
  1702. TriggerEvent(FD_WRITE, 0, TRUE);
  1703. }
  1704. }
  1705. if (m_bSslEstablished && BIO_ctrl_pending(m_sslbio) > 0)
  1706. {
  1707. if (m_mayTriggerReadUp && !m_bBlocking)
  1708. {
  1709. m_mayTriggerReadUp = false;
  1710. TriggerEvent(FD_READ, 0, TRUE);
  1711. }
  1712. }
  1713. else
  1714. {
  1715. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  1716. if (len > 0 && m_mayTriggerRead)
  1717. {
  1718. m_mayTriggerRead = false;
  1719. TriggerEvent(FD_READ, 0);
  1720. }
  1721. }
  1722. if (m_onCloseCalled && m_bSslEstablished)
  1723. {
  1724. if (BIO_ctrl_pending(m_sslbio) <= 0)
  1725. {
  1726. TriggerEvent(FD_CLOSE, 0, TRUE);
  1727. }
  1728. }
  1729. }
  1730. //---------------------------------------------------------------------------