AsyncSslSocketLayer.cpp 50 KB

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