AsyncSslSocketLayer.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  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. CCriticalSectionWrapper CAsyncSslSocketLayer::m_sCriticalSection;
  18. CAsyncSslSocketLayer::t_SslLayerList* CAsyncSslSocketLayer::m_pSslLayerList = 0;
  19. int CAsyncSslSocketLayer::m_nSslRefCount = 0;
  20. std::map<SSL_CTX *, int> CAsyncSslSocketLayer::m_contextRefCount;
  21. CAsyncSslSocketLayer::CAsyncSslSocketLayer()
  22. {
  23. m_ssl = 0;
  24. m_sslbio = 0;
  25. m_ibio = 0;
  26. m_nbio = 0;
  27. m_ssl_ctx = 0;
  28. m_bUseSSL = false;
  29. m_bSslInitialized = FALSE;
  30. m_bSslEstablished = FALSE;
  31. m_nNetworkSendBufferLen = 0;
  32. m_nNetworkSendBufferMaxLen = 0;
  33. m_pNetworkSendBuffer = NULL;
  34. m_pRetrySendBuffer = 0;
  35. m_nRetrySendBufferLen = 0;
  36. m_nNetworkError = 0;
  37. m_nShutDown = 0;
  38. m_bBlocking = FALSE;
  39. m_nSslAsyncNotifyId = 0;
  40. m_bFailureSent = FALSE;
  41. m_nVerificationResult = 0;
  42. m_nVerificationDepth = 0;
  43. m_mayTriggerRead = true;
  44. m_mayTriggerWrite = true;
  45. m_mayTriggerReadUp = true;
  46. m_mayTriggerWriteUp = true;
  47. m_onCloseCalled = false;
  48. m_Main = NULL;
  49. m_sessionid = NULL;
  50. m_sessionreuse = true;
  51. m_sessionreuse_failed = false;
  52. FCertificate = NULL;
  53. FPrivateKey = NULL;
  54. }
  55. CAsyncSslSocketLayer::~CAsyncSslSocketLayer()
  56. {
  57. UnloadSSL();
  58. delete [] m_pNetworkSendBuffer;
  59. delete [] m_pRetrySendBuffer;
  60. }
  61. int CAsyncSslSocketLayer::InitSSL()
  62. {
  63. if (m_bSslInitialized)
  64. return 0;
  65. m_sCriticalSection.Lock();
  66. if (!m_nSslRefCount)
  67. {
  68. if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL))
  69. {
  70. return SSL_FAILURE_INITSSL;
  71. }
  72. }
  73. m_nSslRefCount++;
  74. m_sCriticalSection.Unlock();
  75. m_bSslInitialized = true;
  76. return 0;
  77. }
  78. void CAsyncSslSocketLayer::OnReceive(int nErrorCode)
  79. {
  80. if (m_bUseSSL)
  81. {
  82. if (m_bBlocking)
  83. {
  84. m_mayTriggerRead = true;
  85. return;
  86. }
  87. if (m_nNetworkError)
  88. {
  89. return;
  90. }
  91. char buffer[16384];
  92. m_mayTriggerRead = false;
  93. //Get number of bytes we can receive and store in the network input bio
  94. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  95. if (len > 16384)
  96. len = 16384;
  97. else if (!len)
  98. {
  99. m_mayTriggerRead = true;
  100. TriggerEvents();
  101. return;
  102. }
  103. int numread = 0;
  104. // Receive data
  105. numread = ReceiveNext(buffer, len);
  106. if (numread > 0)
  107. {
  108. //Store it in the network input bio and process data
  109. int numwritten = BIO_write(m_nbio, buffer, numread);
  110. BIO_ctrl(m_nbio, BIO_CTRL_FLUSH, 0, NULL);
  111. // I have no idea why this call is needed, but without it, connections
  112. // will stall. Perhaps it triggers some internal processing.
  113. // Also, ignore return value, don't do any error checking. This function
  114. // can report errors, even though a later call can succeed.
  115. char buffer;
  116. BIO_read(m_sslbio, &buffer, 0);
  117. }
  118. if (!numread)
  119. {
  120. if (GetLayerState() == connected)
  121. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  122. }
  123. else if (numread == SOCKET_ERROR)
  124. {
  125. int nError = GetLastError();
  126. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  127. {
  128. m_nNetworkError = GetLastError();
  129. TriggerEvent(FD_CLOSE, 0, TRUE);
  130. return;
  131. }
  132. }
  133. if (m_pRetrySendBuffer)
  134. {
  135. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  136. if (numwrite >= 0)
  137. {
  138. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  139. delete [] m_pRetrySendBuffer;
  140. m_pRetrySendBuffer = 0;
  141. }
  142. else if (numwrite == -1)
  143. {
  144. if (!BIO_should_retry(m_sslbio))
  145. {
  146. delete [] m_pRetrySendBuffer;
  147. m_pRetrySendBuffer = 0;
  148. ::SetLastError(WSAECONNABORTED);
  149. TriggerEvent(FD_CLOSE, 0, TRUE);
  150. return;
  151. }
  152. }
  153. }
  154. if (!m_nShutDown && SSL_get_shutdown(m_ssl))
  155. {
  156. size_t pending = BIO_ctrl_pending(m_sslbio);
  157. if (pending <= 0)
  158. {
  159. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  160. {
  161. if (ShutDownComplete())
  162. TriggerEvent(FD_CLOSE, 0, TRUE);
  163. }
  164. else
  165. {
  166. m_nNetworkError = WSAECONNABORTED;
  167. WSASetLastError(WSAECONNABORTED);
  168. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  169. }
  170. return;
  171. }
  172. }
  173. if (ShutDownComplete() && m_nShutDown == 1)
  174. {
  175. //Send shutdown notification if all pending data has been sent
  176. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  177. m_nShutDown++;
  178. }
  179. TriggerEvents();
  180. }
  181. else
  182. {
  183. TriggerEvent(FD_READ, nErrorCode, TRUE);
  184. }
  185. }
  186. void CAsyncSslSocketLayer::OnSend(int nErrorCode)
  187. {
  188. if (m_bUseSSL)
  189. {
  190. if (m_nNetworkError)
  191. {
  192. return;
  193. }
  194. m_mayTriggerWrite = false;
  195. //Send data in the send buffer
  196. while (m_nNetworkSendBufferLen)
  197. {
  198. int numsent = SendNext(m_pNetworkSendBuffer, m_nNetworkSendBufferLen);
  199. if (numsent == SOCKET_ERROR)
  200. {
  201. int nError = GetLastError();
  202. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  203. {
  204. m_nNetworkError = nError;
  205. TriggerEvent(FD_CLOSE, 0, TRUE);
  206. }
  207. return;
  208. }
  209. else if (!numsent)
  210. {
  211. if (GetLayerState() == connected)
  212. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  213. }
  214. if (numsent == m_nNetworkSendBufferLen)
  215. {
  216. m_nNetworkSendBufferLen = 0;
  217. }
  218. else
  219. {
  220. memmove(m_pNetworkSendBuffer, m_pNetworkSendBuffer + numsent, m_nNetworkSendBufferLen - numsent);
  221. m_nNetworkSendBufferLen -= numsent;
  222. }
  223. }
  224. //Send the data waiting in the network bio
  225. char buffer[32 * 1024];
  226. size_t len = BIO_ctrl_pending(m_nbio);
  227. int numread = BIO_read(m_nbio, buffer, std::min(len, sizeof(buffer)));
  228. if (numread <= 0)
  229. m_mayTriggerWrite = true;
  230. while (numread > 0)
  231. {
  232. int numsent = SendNext(buffer, numread);
  233. if (!numsent)
  234. {
  235. if (GetLayerState() == connected)
  236. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  237. }
  238. if (numsent == SOCKET_ERROR || numsent < numread)
  239. {
  240. if (numsent == SOCKET_ERROR)
  241. if (GetLastError() != WSAEWOULDBLOCK && GetLastError() != WSAENOTCONN)
  242. {
  243. m_nNetworkError = GetLastError();
  244. TriggerEvent(FD_CLOSE, 0, TRUE);
  245. return;
  246. }
  247. else
  248. numsent = 0;
  249. // Add all data that was retrieved from the network bio but could not be sent to the send buffer.
  250. if (m_nNetworkSendBufferMaxLen < (m_nNetworkSendBufferLen + numread - numsent))
  251. {
  252. char * tmp = m_pNetworkSendBuffer;
  253. m_nNetworkSendBufferMaxLen = static_cast<int>((m_nNetworkSendBufferLen + numread - numsent) * 1.5);
  254. m_pNetworkSendBuffer = new char[m_nNetworkSendBufferMaxLen];
  255. if (tmp)
  256. {
  257. memcpy(m_pNetworkSendBuffer, tmp, m_nNetworkSendBufferLen);
  258. delete [] tmp;
  259. }
  260. }
  261. DebugAssert(m_pNetworkSendBuffer);
  262. memcpy(m_pNetworkSendBuffer + m_nNetworkSendBufferLen, buffer, numread-numsent);
  263. m_nNetworkSendBufferLen += numread - numsent;
  264. }
  265. if (!numsent)
  266. {
  267. break;
  268. }
  269. len = BIO_ctrl_pending(m_nbio);
  270. if (!len)
  271. {
  272. m_mayTriggerWrite = true;
  273. break;
  274. }
  275. numread = BIO_read(m_nbio, buffer, len);
  276. if (numread <= 0)
  277. {
  278. m_mayTriggerWrite = true;
  279. }
  280. }
  281. if (m_pRetrySendBuffer)
  282. {
  283. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  284. if (numwrite >= 0)
  285. {
  286. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  287. delete [] m_pRetrySendBuffer;
  288. m_pRetrySendBuffer = 0;
  289. }
  290. else if (numwrite == -1)
  291. {
  292. if (!BIO_should_retry(m_sslbio))
  293. {
  294. delete [] m_pRetrySendBuffer;
  295. m_pRetrySendBuffer = 0;
  296. ::SetLastError(WSAECONNABORTED);
  297. TriggerEvent(FD_CLOSE, 0, TRUE);
  298. return;
  299. }
  300. }
  301. }
  302. // No more data available, ask for more.
  303. TriggerEvents();
  304. if (m_nShutDown == 1 && ShutDownComplete())
  305. {
  306. //Send shutdown notification if all pending data has been sent
  307. // FileZilla3 calls ShutDownNext() here
  308. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  309. m_nShutDown++;
  310. }
  311. }
  312. else
  313. {
  314. TriggerEvent(FD_WRITE, nErrorCode, TRUE);
  315. }
  316. }
  317. int CAsyncSslSocketLayer::Send(const void* lpBuf, int nBufLen, int nFlags)
  318. {
  319. if (m_bUseSSL)
  320. {
  321. if (!lpBuf)
  322. {
  323. return 0;
  324. }
  325. if (m_bBlocking || m_pRetrySendBuffer)
  326. {
  327. m_mayTriggerWriteUp = true;
  328. ::SetLastError(WSAEWOULDBLOCK);
  329. return SOCKET_ERROR;
  330. }
  331. if (m_nNetworkError)
  332. {
  333. SetLastError(m_nNetworkError);
  334. return SOCKET_ERROR;
  335. }
  336. if (m_nShutDown)
  337. {
  338. ::SetLastError(WSAESHUTDOWN);
  339. return SOCKET_ERROR;
  340. }
  341. if (!m_bSslEstablished)
  342. {
  343. m_mayTriggerWriteUp = true;
  344. ::SetLastError(WSAEWOULDBLOCK);
  345. return SOCKET_ERROR;
  346. }
  347. if (!nBufLen)
  348. {
  349. return 0;
  350. }
  351. if (m_onCloseCalled)
  352. {
  353. TriggerEvent(FD_CLOSE, 0, TRUE);
  354. return 0;
  355. }
  356. int len = BIO_ctrl_get_write_guarantee(m_sslbio);
  357. if (nBufLen > len)
  358. nBufLen = len;
  359. if (!len)
  360. {
  361. m_mayTriggerWriteUp = true;
  362. TriggerEvents();
  363. ::SetLastError(WSAEWOULDBLOCK);
  364. }
  365. m_pRetrySendBuffer = new char[nBufLen];
  366. m_nRetrySendBufferLen = nBufLen;
  367. memcpy(m_pRetrySendBuffer, lpBuf, nBufLen);
  368. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  369. if (numwrite >= 0)
  370. {
  371. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  372. delete [] m_pRetrySendBuffer;
  373. m_pRetrySendBuffer = 0;
  374. }
  375. else if (numwrite == -1)
  376. {
  377. if (BIO_should_retry(m_sslbio))
  378. {
  379. if (GetLayerState() == closed)
  380. {
  381. return 0;
  382. }
  383. else if (GetLayerState() != connected)
  384. {
  385. SetLastError(m_nNetworkError);
  386. return SOCKET_ERROR;
  387. }
  388. TriggerEvents();
  389. return nBufLen;
  390. }
  391. else
  392. {
  393. delete [] m_pRetrySendBuffer;
  394. m_pRetrySendBuffer = 0;
  395. ::SetLastError(WSAECONNABORTED);
  396. }
  397. return SOCKET_ERROR;
  398. }
  399. m_mayTriggerWriteUp = true;
  400. TriggerEvents();
  401. return numwrite;
  402. }
  403. else
  404. {
  405. return SendNext(lpBuf, nBufLen, nFlags);
  406. }
  407. }
  408. int CAsyncSslSocketLayer::Receive(void* lpBuf, int nBufLen, int nFlags)
  409. {
  410. if (m_bUseSSL)
  411. {
  412. if (m_bBlocking)
  413. {
  414. m_mayTriggerReadUp = true;
  415. ::SetLastError(WSAEWOULDBLOCK);
  416. return SOCKET_ERROR;
  417. }
  418. if (m_nNetworkError)
  419. {
  420. size_t pending = BIO_ctrl_pending(m_sslbio);
  421. if (pending && !m_nShutDown)
  422. {
  423. m_mayTriggerReadUp = true;
  424. TriggerEvents();
  425. return BIO_read(m_sslbio, lpBuf,nBufLen);
  426. }
  427. WSASetLastError(m_nNetworkError);
  428. return SOCKET_ERROR;
  429. }
  430. if (m_nShutDown)
  431. {
  432. ::SetLastError(WSAESHUTDOWN);
  433. return SOCKET_ERROR;
  434. }
  435. if (!nBufLen)
  436. {
  437. return 0;
  438. }
  439. size_t pending = BIO_ctrl_pending(m_sslbio);
  440. if (!pending)
  441. {
  442. if (GetLayerState() == closed)
  443. {
  444. return 0;
  445. }
  446. if (m_onCloseCalled)
  447. {
  448. TriggerEvent(FD_CLOSE, 0, TRUE);
  449. return 0;
  450. }
  451. else if (GetLayerState() != connected)
  452. {
  453. SetLastError(m_nNetworkError);
  454. return SOCKET_ERROR;
  455. }
  456. else
  457. {
  458. if (SSL_get_shutdown(m_ssl))
  459. {
  460. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  461. {
  462. if (ShutDownComplete())
  463. {
  464. TriggerEvent(FD_CLOSE, 0, TRUE);
  465. return 0;
  466. }
  467. else
  468. WSASetLastError(WSAEWOULDBLOCK);
  469. }
  470. else
  471. {
  472. m_nNetworkError = WSAECONNABORTED;
  473. WSASetLastError(WSAECONNABORTED);
  474. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  475. }
  476. return SOCKET_ERROR;
  477. }
  478. }
  479. m_mayTriggerReadUp = true;
  480. TriggerEvents();
  481. ::SetLastError(WSAEWOULDBLOCK);
  482. return SOCKET_ERROR;
  483. }
  484. int numread = BIO_read(m_sslbio, lpBuf, nBufLen);
  485. if (!numread)
  486. {
  487. if (SSL_get_shutdown(m_ssl))
  488. {
  489. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  490. {
  491. if (ShutDownComplete())
  492. {
  493. TriggerEvent(FD_CLOSE, 0, TRUE);
  494. return 0;
  495. }
  496. else
  497. WSASetLastError(WSAEWOULDBLOCK);
  498. }
  499. else
  500. {
  501. m_nNetworkError = WSAECONNABORTED;
  502. WSASetLastError(WSAECONNABORTED);
  503. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  504. }
  505. return SOCKET_ERROR;
  506. }
  507. m_mayTriggerReadUp = true;
  508. TriggerEvents();
  509. ::SetLastError(WSAEWOULDBLOCK);
  510. return SOCKET_ERROR;
  511. }
  512. if (numread < 0)
  513. {
  514. if (!BIO_should_retry(m_sslbio))
  515. {
  516. PrintLastErrorMsg();
  517. m_nNetworkError = WSAECONNABORTED;
  518. WSASetLastError(WSAECONNABORTED);
  519. TriggerEvent(FD_CLOSE, 0, TRUE);
  520. return SOCKET_ERROR;
  521. }
  522. else
  523. {
  524. if (SSL_get_shutdown(m_ssl))
  525. {
  526. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  527. {
  528. if (ShutDownComplete())
  529. {
  530. TriggerEvent(FD_CLOSE, 0, TRUE);
  531. return 0;
  532. }
  533. else
  534. WSASetLastError(WSAEWOULDBLOCK);
  535. }
  536. else
  537. {
  538. m_nNetworkError = WSAECONNABORTED;
  539. WSASetLastError(WSAECONNABORTED);
  540. TriggerEvent(FD_CLOSE, 0, TRUE);
  541. }
  542. return SOCKET_ERROR;
  543. }
  544. m_mayTriggerReadUp = true;
  545. TriggerEvents();
  546. ::SetLastError(WSAEWOULDBLOCK);
  547. return SOCKET_ERROR;
  548. }
  549. }
  550. m_mayTriggerReadUp = true;
  551. TriggerEvents();
  552. return numread;
  553. }
  554. else
  555. {
  556. return ReceiveNext(lpBuf, nBufLen, nFlags);
  557. }
  558. }
  559. void CAsyncSslSocketLayer::Close()
  560. {
  561. m_nShutDown = 0;
  562. m_onCloseCalled = false;
  563. ResetSslSession();
  564. CloseNext();
  565. }
  566. BOOL CAsyncSslSocketLayer::Connect(const SOCKADDR *lpSockAddr, int nSockAddrLen)
  567. {
  568. BOOL res = ConnectNext(lpSockAddr, nSockAddrLen);
  569. if (!res)
  570. {
  571. if (GetLastError() != WSAEWOULDBLOCK)
  572. {
  573. ResetSslSession();
  574. }
  575. }
  576. return res;
  577. }
  578. BOOL CAsyncSslSocketLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  579. {
  580. BOOL res = ConnectNext(lpszHostAddress, nHostPort);
  581. if (!res)
  582. {
  583. if (GetLastError()!=WSAEWOULDBLOCK)
  584. {
  585. ResetSslSession();
  586. }
  587. }
  588. return res;
  589. }
  590. bool CAsyncSslSocketLayer::HandleSession(SSL_SESSION * Session)
  591. {
  592. bool Result = false;
  593. if (m_sessionreuse)
  594. {
  595. if (m_sessionid != Session)
  596. {
  597. if (m_sessionid == NULL)
  598. {
  599. if (SSL_session_reused(m_ssl))
  600. {
  601. LogSocketMessageRaw(FZ_LOG_PROGRESS, L"Session ID reused");
  602. }
  603. else
  604. {
  605. if ((m_Main != NULL) && !m_Main->m_sessionreuse_failed)
  606. {
  607. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID not reused, will not try again");
  608. m_Main->m_sessionreuse_failed = true;
  609. }
  610. }
  611. LogSocketMessageRaw(FZ_LOG_DEBUG, L"Saving session ID");
  612. }
  613. else
  614. {
  615. SSL_SESSION_free(m_sessionid);
  616. LogSocketMessageRaw(FZ_LOG_INFO, L"Session ID changed");
  617. }
  618. m_sessionid = Session;
  619. Result = true;
  620. }
  621. }
  622. return Result;
  623. }
  624. int CAsyncSslSocketLayer::NewSessionCallback(struct ssl_st * Ssl, SSL_SESSION * Session)
  625. {
  626. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  627. int Result = 0;
  628. // This is not called for TLS 1.2 and older when session is reused (so "Session ID reused" won't be logged).
  629. // So for 1.2 and older, we call HandleSession from apps_ssl_info_callback as we always did.
  630. if ((SSL_version(Ssl) >= TLS1_3_VERSION) && Layer->HandleSession(Session))
  631. {
  632. Result = 1;
  633. }
  634. return Result;
  635. }
  636. int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode,
  637. CAsyncSslSocketLayer* main, bool sessionreuse, const CString & host,
  638. CFileZillaTools * tools,
  639. void* pSslContext /*=0*/)
  640. {
  641. if (m_bUseSSL)
  642. return 0;
  643. int res = InitSSL();
  644. if (res)
  645. return res;
  646. m_sCriticalSection.Lock();
  647. if ((SSL_CTX*)pSslContext)
  648. {
  649. if (m_ssl_ctx)
  650. {
  651. m_sCriticalSection.Unlock();
  652. ResetSslSession();
  653. return SSL_FAILURE_INITSSL;
  654. }
  655. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find((SSL_CTX*)pSslContext);
  656. if (iter == m_contextRefCount.end() || iter->second < 1)
  657. {
  658. m_sCriticalSection.Unlock();
  659. ResetSslSession();
  660. return SSL_FAILURE_INITSSL;
  661. }
  662. m_ssl_ctx = (SSL_CTX*)pSslContext;
  663. iter->second++;
  664. }
  665. else if (!m_ssl_ctx)
  666. {
  667. // Create new context if none given
  668. if (!(m_ssl_ctx = SSL_CTX_new( SSLv23_method())))
  669. {
  670. m_sCriticalSection.Unlock();
  671. ResetSslSession();
  672. return SSL_FAILURE_INITSSL;
  673. }
  674. m_contextRefCount[m_ssl_ctx] = 1;
  675. if (clientMode)
  676. {
  677. USES_CONVERSION;
  678. SSL_CTX_set_verify(m_ssl_ctx, SSL_VERIFY_PEER, verify_callback);
  679. SSL_CTX_set_client_cert_cb(m_ssl_ctx, ProvideClientCert);
  680. // https://www.mail-archive.com/[email protected]/msg86186.html
  681. 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);
  682. SSL_CTX_sess_set_new_cb(m_ssl_ctx, NewSessionCallback);
  683. CFileStatus Dummy;
  684. if (CFile::GetStatus((LPCTSTR)m_CertStorage, Dummy))
  685. {
  686. SSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0);
  687. }
  688. }
  689. }
  690. //Create new SSL session
  691. if (!(m_ssl = SSL_new(m_ssl_ctx)))
  692. {
  693. m_sCriticalSection.Unlock();
  694. ResetSslSession();
  695. return SSL_FAILURE_INITSSL;
  696. }
  697. if (clientMode && (host.GetLength() > 0))
  698. {
  699. USES_CONVERSION;
  700. SSL_set_tlsext_host_name(m_ssl, T2CA(host));
  701. }
  702. #ifdef _DEBUG
  703. if ((main == NULL) && LoggingSocketMessage(FZ_LOG_INFO))
  704. {
  705. USES_CONVERSION;
  706. LogSocketMessageRaw(FZ_LOG_INFO, L"Supported ciphersuites:");
  707. STACK_OF(SSL_CIPHER) * ciphers = SSL_get_ciphers(m_ssl);
  708. for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); i++)
  709. {
  710. const SSL_CIPHER * cipher = sk_SSL_CIPHER_value(ciphers, i);
  711. LogSocketMessageRaw(FZ_LOG_INFO, A2CT(SSL_CIPHER_get_name(cipher)));
  712. }
  713. }
  714. #endif
  715. //Add current instance to list of active instances
  716. t_SslLayerList *tmp = m_pSslLayerList;
  717. m_pSslLayerList = new t_SslLayerList;
  718. m_pSslLayerList->pNext = tmp;
  719. m_pSslLayerList->pLayer = this;
  720. m_sCriticalSection.Unlock();
  721. SSL_set_info_callback(m_ssl, apps_ssl_info_callback);
  722. //Create bios
  723. m_sslbio = BIO_new(BIO_f_ssl());
  724. BIO_new_bio_pair(&m_ibio, 32768, &m_nbio, 32768);
  725. if (!m_sslbio || !m_nbio || !m_ibio)
  726. {
  727. ResetSslSession();
  728. return SSL_FAILURE_INITSSL;
  729. }
  730. tools->SetupSsl(m_ssl);
  731. //Init SSL connection
  732. void *ssl_sessionid = NULL;
  733. m_Main = main;
  734. m_sessionreuse = sessionreuse;
  735. if ((m_Main != NULL) && m_sessionreuse)
  736. {
  737. if (m_Main->m_sessionid == NULL)
  738. {
  739. DebugFail();
  740. SSL_set_session(m_ssl, NULL);
  741. }
  742. else if (!m_Main->m_sessionreuse_failed)
  743. {
  744. if (!SSL_set_session(m_ssl, m_Main->m_sessionid))
  745. {
  746. LogSocketMessageRaw(FZ_LOG_INFO, L"SSL_set_session failed");
  747. return SSL_FAILURE_INITSSL;
  748. }
  749. LogSocketMessageRaw(FZ_LOG_INFO, L"Trying reuse main TLS session ID");
  750. }
  751. else
  752. {
  753. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID was not reused previously, not trying again");
  754. SSL_set_session(m_ssl, NULL);
  755. }
  756. }
  757. else
  758. {
  759. SSL_set_session(m_ssl, NULL);
  760. }
  761. if (clientMode)
  762. {
  763. SSL_set_connect_state(m_ssl);
  764. }
  765. else
  766. {
  767. SSL_set_accept_state(m_ssl);
  768. }
  769. SSL_set_bio(m_ssl, m_ibio, m_ibio);
  770. BIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl);
  771. BIO_read(m_sslbio, (void *)1, 0);
  772. // Trigger FD_WRITE so that we can initialize SSL negotiation
  773. if (GetLayerState() == connected || GetLayerState() == attached)
  774. {
  775. TriggerEvent(FD_READ, 0);
  776. TriggerEvent(FD_WRITE, 0);
  777. TriggerEvent(FD_READ, 0, TRUE);
  778. TriggerEvent(FD_WRITE, 0, TRUE);
  779. }
  780. m_bUseSSL = true;
  781. return 0;
  782. }
  783. void CAsyncSslSocketLayer::ResetSslSession()
  784. {
  785. if (m_pRetrySendBuffer)
  786. {
  787. delete [] m_pRetrySendBuffer;
  788. m_pRetrySendBuffer = 0;
  789. }
  790. m_bFailureSent = FALSE;
  791. m_bBlocking = FALSE;
  792. m_nSslAsyncNotifyId++;
  793. m_nNetworkError = 0;
  794. m_bUseSSL = FALSE;
  795. m_nVerificationResult = 0;
  796. m_nVerificationDepth = 0;
  797. m_bSslEstablished = FALSE;
  798. if (m_sslbio)
  799. {
  800. BIO_free(m_sslbio);
  801. }
  802. if (m_ssl)
  803. {
  804. SSL_set_session(m_ssl,NULL);
  805. }
  806. if (m_nbio)
  807. {
  808. BIO_free(m_nbio);
  809. }
  810. if (m_ibio)
  811. {
  812. BIO_free(m_ibio);
  813. }
  814. m_nNetworkSendBufferLen = 0;
  815. m_nbio = 0;
  816. m_ibio = 0;
  817. m_sslbio = 0;
  818. if (m_ssl)
  819. {
  820. SSL_free(m_ssl);
  821. }
  822. m_sCriticalSection.Lock();
  823. if (m_ssl_ctx)
  824. {
  825. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find(m_ssl_ctx);
  826. if (iter != m_contextRefCount.end())
  827. {
  828. if (iter->second <= 1)
  829. {
  830. SSL_CTX_free(m_ssl_ctx);
  831. m_contextRefCount.erase(iter);
  832. }
  833. else
  834. iter->second--;
  835. }
  836. m_ssl_ctx = 0;
  837. }
  838. m_ssl = 0;
  839. t_SslLayerList *cur = m_pSslLayerList;
  840. if (!cur)
  841. {
  842. m_sCriticalSection.Unlock();
  843. return;
  844. }
  845. if (cur->pLayer == this)
  846. {
  847. m_pSslLayerList = cur->pNext;
  848. delete cur;
  849. }
  850. else
  851. while (cur->pNext)
  852. {
  853. if (cur->pNext->pLayer == this)
  854. {
  855. t_SslLayerList *tmp = cur->pNext;
  856. cur->pNext = cur->pNext->pNext;
  857. delete tmp;
  858. m_sCriticalSection.Unlock();
  859. return;
  860. }
  861. cur = cur->pNext;
  862. }
  863. if (m_sessionid != NULL)
  864. {
  865. SSL_SESSION_free(m_sessionid);
  866. m_sessionid = NULL;
  867. }
  868. m_sessionreuse = true;
  869. m_sessionreuse_failed = false;
  870. m_sCriticalSection.Unlock();
  871. }
  872. bool CAsyncSslSocketLayer::IsUsingSSL()
  873. {
  874. return m_bUseSSL;
  875. }
  876. BOOL CAsyncSslSocketLayer::ShutDown(int nHow /*=sends*/)
  877. {
  878. if (m_bUseSSL)
  879. {
  880. if (m_pRetrySendBuffer)
  881. {
  882. if (!m_nShutDown)
  883. m_nShutDown = 1;
  884. WSASetLastError(WSAEWOULDBLOCK);
  885. return false;
  886. }
  887. if (!m_bSslEstablished)
  888. {
  889. m_mayTriggerWriteUp = true;
  890. ::SetLastError(WSAEWOULDBLOCK);
  891. return false;
  892. }
  893. if (!m_nShutDown)
  894. m_nShutDown = 1;
  895. else
  896. {
  897. if (ShutDownComplete())
  898. return ShutDownNext();
  899. else
  900. {
  901. TriggerEvents();
  902. WSASetLastError(WSAEWOULDBLOCK);
  903. return false;
  904. }
  905. }
  906. int res = SSL_shutdown(m_ssl);
  907. if (res == 0)
  908. {
  909. res = SSL_shutdown(m_ssl);
  910. // While this should not be necessary, with IIS we get timeout otherwise
  911. if (SSL_version(m_ssl) <= TLS1_2_VERSION)
  912. {
  913. res = 0;
  914. }
  915. }
  916. if (res >= 0)
  917. {
  918. if (ShutDownComplete())
  919. return ShutDownNext();
  920. else
  921. {
  922. TriggerEvents();
  923. WSASetLastError(WSAEWOULDBLOCK);
  924. return FALSE;
  925. }
  926. }
  927. else
  928. {
  929. int error = SSL_get_error(m_ssl, -1);
  930. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  931. {
  932. // retry shutdown later
  933. m_nShutDown = 0;
  934. TriggerEvents();
  935. WSASetLastError(WSAEWOULDBLOCK);
  936. return FALSE;
  937. }
  938. else if (ShutDownComplete())
  939. return ShutDownNext();
  940. else
  941. {
  942. TriggerEvents();
  943. WSASetLastError(WSAEWOULDBLOCK);
  944. return FALSE;
  945. }
  946. }
  947. }
  948. else
  949. {
  950. if (!m_nShutDown)
  951. m_nShutDown = 1;
  952. return ShutDownNext(nHow);
  953. }
  954. }
  955. BOOL CAsyncSslSocketLayer::ShutDownComplete()
  956. {
  957. //If a ShutDown was issued, has the connection already been shut down?
  958. if (!m_nShutDown)
  959. return FALSE;
  960. else if (!m_bUseSSL)
  961. return FALSE;
  962. else if (m_nNetworkSendBufferLen)
  963. return FALSE;
  964. else if (m_pRetrySendBuffer)
  965. return FALSE;
  966. // Empty read buffer
  967. char buffer[1000];
  968. int numread;
  969. do
  970. {
  971. numread = BIO_read(m_sslbio, buffer, 1000);
  972. } while (numread > 0);
  973. size_t pending = BIO_ctrl_pending(m_nbio);
  974. if (pending)
  975. {
  976. return FALSE;
  977. }
  978. else
  979. {
  980. return TRUE;
  981. }
  982. }
  983. void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int ret)
  984. {
  985. USES_CONVERSION;
  986. CAsyncSslSocketLayer *pLayer = 0;
  987. m_sCriticalSection.Lock();
  988. t_SslLayerList *cur = m_pSslLayerList;
  989. while (cur)
  990. {
  991. if (cur->pLayer->m_ssl == s)
  992. break;
  993. cur = cur->pNext;
  994. }
  995. if (!cur)
  996. {
  997. m_sCriticalSection.Unlock();
  998. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  999. return;
  1000. }
  1001. else
  1002. pLayer = cur->pLayer;
  1003. m_sCriticalSection.Unlock();
  1004. // Called while unloading?
  1005. if (!pLayer->m_bUseSSL && (where != SSL_CB_LOOP))
  1006. return;
  1007. char * str;
  1008. int w;
  1009. w = where& ~SSL_ST_MASK;
  1010. if (w & SSL_ST_CONNECT)
  1011. {
  1012. str = "TLS connect";
  1013. }
  1014. else if (w & SSL_ST_ACCEPT)
  1015. str = "TLS accept";
  1016. else
  1017. str = "Undefined";
  1018. if (where & SSL_CB_LOOP)
  1019. {
  1020. char* debug = NULL;
  1021. // exact SSL_CB_LOOP is abused for debugging
  1022. if (where == SSL_CB_LOOP)
  1023. {
  1024. debug = reinterpret_cast<char*>(ret);
  1025. }
  1026. char *buffer = new char[4096 + ((debug != NULL) ? strlen(debug) : 0)];
  1027. sprintf(buffer, "%s: %s",
  1028. str,
  1029. SSL_state_string_long(s));
  1030. if (debug != NULL)
  1031. {
  1032. sprintf(buffer + strlen(buffer), " [%s]", debug);
  1033. OPENSSL_free(debug);
  1034. }
  1035. USES_CONVERSION;
  1036. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, A2T(buffer));
  1037. delete[] buffer;
  1038. }
  1039. else if (where & SSL_CB_ALERT)
  1040. {
  1041. str=(where & SSL_CB_READ)? "read" : "write";
  1042. const char* desc = SSL_alert_desc_string_long(ret);
  1043. // Don't send close notify warning
  1044. if (desc)
  1045. {
  1046. if (strcmp(desc, "close notify"))
  1047. {
  1048. char *buffer = new char[4096];
  1049. sprintf(buffer, "SSL3 alert %s: %s: %s",
  1050. str,
  1051. SSL_alert_type_string_long(ret),
  1052. desc);
  1053. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1054. pLayer->PrintLastErrorMsg();
  1055. delete [] buffer;
  1056. }
  1057. }
  1058. }
  1059. else if (where & SSL_CB_EXIT)
  1060. {
  1061. if (ret == 0)
  1062. {
  1063. char *buffer = new char[4096];
  1064. sprintf(buffer, "%s: failed in %s",
  1065. str,
  1066. SSL_state_string_long(s));
  1067. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1068. pLayer->PrintLastErrorMsg();
  1069. delete [] buffer;
  1070. if (!pLayer->m_bFailureSent)
  1071. {
  1072. pLayer->m_bFailureSent=TRUE;
  1073. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1074. }
  1075. }
  1076. else if (ret < 0)
  1077. {
  1078. int error = SSL_get_error(s,ret);
  1079. if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
  1080. {
  1081. char *buffer = new char[4096];
  1082. sprintf(buffer, "%s: error in %s",
  1083. str,
  1084. SSL_state_string_long(s));
  1085. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  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. }
  1094. }
  1095. if (where & SSL_CB_HANDSHAKE_DONE)
  1096. {
  1097. // For 1.2 and older, session is always established at this point.
  1098. // For 1.3, session can be restarted later, so this is handled in NewSessionCallback.
  1099. if (SSL_version(pLayer->m_ssl) < TLS1_3_VERSION)
  1100. {
  1101. SSL_SESSION * sessionid = SSL_get1_session(pLayer->m_ssl);
  1102. if (!pLayer->HandleSession(sessionid))
  1103. {
  1104. SSL_SESSION_free(sessionid);
  1105. }
  1106. }
  1107. int error = SSL_get_verify_result(pLayer->m_ssl);
  1108. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERIFY_CERT, error);
  1109. pLayer->m_bBlocking = TRUE;
  1110. }
  1111. }
  1112. void CAsyncSslSocketLayer::UnloadSSL()
  1113. {
  1114. if (!m_bSslInitialized)
  1115. return;
  1116. ResetSslSession();
  1117. m_bSslInitialized = false;
  1118. m_sCriticalSection.Lock();
  1119. m_nSslRefCount--;
  1120. if (m_nSslRefCount)
  1121. {
  1122. m_sCriticalSection.Unlock();
  1123. return;
  1124. }
  1125. m_sCriticalSection.Unlock();
  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. m_sCriticalSection.Lock();
  1547. t_SslLayerList * Cur = m_pSslLayerList;
  1548. while (Cur != NULL)
  1549. {
  1550. if (Cur->pLayer->m_ssl == Ssl)
  1551. {
  1552. break;
  1553. }
  1554. Cur = Cur->pNext;
  1555. }
  1556. m_sCriticalSection.Unlock();
  1557. if (Cur == NULL)
  1558. {
  1559. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1560. Result = NULL;
  1561. }
  1562. else
  1563. {
  1564. Result = Cur->pLayer;
  1565. }
  1566. return Result;
  1567. }
  1568. int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1569. {
  1570. X509 *err_cert;
  1571. int err, depth;
  1572. SSL *ssl;
  1573. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  1574. err = X509_STORE_CTX_get_error(ctx);
  1575. depth = X509_STORE_CTX_get_error_depth(ctx);
  1576. /*
  1577. * Retrieve the pointer to the SSL of the connection currently treated
  1578. * and the application specific data stored into the SSL object.
  1579. */
  1580. ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  1581. CAsyncSslSocketLayer * pLayer = LookupLayer(ssl);
  1582. if (pLayer == NULL)
  1583. {
  1584. return 1;
  1585. }
  1586. /*
  1587. * Catch a too long certificate chain. The depth limit set using
  1588. * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
  1589. * that whenever the "depth>verify_depth" condition is met, we
  1590. * have violated the limit and want to log this error condition.
  1591. * We must do it here, because the CHAIN_TOO_LONG error would not
  1592. * be found explicitly; only errors introduced by cutting off the
  1593. * additional certificates would be logged.
  1594. */
  1595. if (depth > 10) {//mydata->verify_depth) {
  1596. preverify_ok = 0;
  1597. err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  1598. X509_STORE_CTX_set_error(ctx, err);
  1599. }
  1600. if (!preverify_ok)
  1601. {
  1602. if (!pLayer->m_nVerificationResult)
  1603. {
  1604. pLayer->m_nVerificationDepth = depth;
  1605. pLayer->m_nVerificationResult = err;
  1606. }
  1607. }
  1608. return 1;
  1609. }
  1610. int CAsyncSslSocketLayer::ProvideClientCert(
  1611. SSL * Ssl, X509 ** Certificate, EVP_PKEY ** PrivateKey)
  1612. {
  1613. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  1614. USES_CONVERSION;
  1615. CString Message;
  1616. Message.LoadString(NEED_CLIENT_CERTIFICATE);
  1617. char * Buffer = new char[Message.GetLength() + 1];
  1618. strcpy(Buffer, T2A(Message));
  1619. int Level;
  1620. int Result;
  1621. if ((Layer->FCertificate == NULL) || (Layer->FPrivateKey == NULL))
  1622. {
  1623. Level = FZ_LOG_WARNING;
  1624. Result = 0;
  1625. }
  1626. else
  1627. {
  1628. Level = FZ_LOG_PROGRESS;
  1629. *Certificate = X509_dup(Layer->FCertificate);
  1630. EVP_PKEY_up_ref(Layer->FPrivateKey);
  1631. *PrivateKey = Layer->FPrivateKey;
  1632. Result = 1;
  1633. }
  1634. Layer->LogSocketMessageRaw(Level, A2T(Buffer));
  1635. delete [] Buffer;
  1636. return Result;
  1637. }
  1638. void CAsyncSslSocketLayer::SetClientCertificate(X509 * Certificate, EVP_PKEY * PrivateKey)
  1639. {
  1640. FCertificate = Certificate;
  1641. FPrivateKey = PrivateKey;
  1642. }
  1643. BOOL CAsyncSslSocketLayer::SetCertStorage(CString file)
  1644. {
  1645. m_CertStorage = file;
  1646. return TRUE;
  1647. }
  1648. void CAsyncSslSocketLayer::OnClose(int nErrorCode)
  1649. {
  1650. m_onCloseCalled = true;
  1651. if (m_bUseSSL && BIO_ctrl)
  1652. {
  1653. size_t pending = BIO_ctrl_pending(m_sslbio);
  1654. if (pending > 0)
  1655. {
  1656. TriggerEvents();
  1657. }
  1658. else TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1659. }
  1660. else
  1661. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1662. }
  1663. void CAsyncSslSocketLayer::PrintLastErrorMsg()
  1664. {
  1665. int err = ERR_get_error();
  1666. while (err)
  1667. {
  1668. char *buffer = new char[512];
  1669. const char *reason = ERR_reason_error_string(err);
  1670. ERR_error_string(err, buffer);
  1671. err = ERR_get_error();
  1672. USES_CONVERSION;
  1673. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1674. LogSocketMessageRaw(FZ_LOG_WARNING, A2T(reason));
  1675. delete [] buffer;
  1676. }
  1677. }
  1678. void CAsyncSslSocketLayer::TriggerEvents()
  1679. {
  1680. size_t pending = BIO_ctrl_pending(m_nbio);
  1681. if (pending > 0)
  1682. {
  1683. if (m_mayTriggerWrite)
  1684. {
  1685. m_mayTriggerWrite = false;
  1686. TriggerEvent(FD_WRITE, 0);
  1687. }
  1688. }
  1689. else if (!m_nNetworkSendBufferLen && m_bSslEstablished && !m_pRetrySendBuffer)
  1690. {
  1691. if (BIO_ctrl_get_write_guarantee(m_sslbio) > 0 && m_mayTriggerWriteUp)
  1692. {
  1693. m_mayTriggerWriteUp = false;
  1694. TriggerEvent(FD_WRITE, 0, TRUE);
  1695. }
  1696. }
  1697. if (m_bSslEstablished && BIO_ctrl_pending(m_sslbio) > 0)
  1698. {
  1699. if (m_mayTriggerReadUp && !m_bBlocking)
  1700. {
  1701. m_mayTriggerReadUp = false;
  1702. TriggerEvent(FD_READ, 0, TRUE);
  1703. }
  1704. }
  1705. else
  1706. {
  1707. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  1708. if (len > 0 && m_mayTriggerRead)
  1709. {
  1710. m_mayTriggerRead = false;
  1711. TriggerEvent(FD_READ, 0);
  1712. }
  1713. }
  1714. if (m_onCloseCalled && m_bSslEstablished)
  1715. {
  1716. if (BIO_ctrl_pending(m_sslbio) <= 0)
  1717. {
  1718. TriggerEvent(FD_CLOSE, 0, TRUE);
  1719. }
  1720. }
  1721. }
  1722. //---------------------------------------------------------------------------