AsyncSslSocketLayer.cpp 48 KB

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