AsyncSslSocketLayer.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  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. if (!m_nShutDown)
  562. {
  563. ShutDown();
  564. while (!ShutDownComplete())
  565. {
  566. OnSend(0);
  567. }
  568. }
  569. m_nShutDown = 0;
  570. m_onCloseCalled = false;
  571. ResetSslSession();
  572. CloseNext();
  573. }
  574. BOOL CAsyncSslSocketLayer::Connect(const SOCKADDR *lpSockAddr, int nSockAddrLen)
  575. {
  576. BOOL res = ConnectNext(lpSockAddr, nSockAddrLen);
  577. if (!res)
  578. {
  579. if (GetLastError() != WSAEWOULDBLOCK)
  580. {
  581. ResetSslSession();
  582. }
  583. }
  584. return res;
  585. }
  586. BOOL CAsyncSslSocketLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  587. {
  588. BOOL res = ConnectNext(lpszHostAddress, nHostPort);
  589. if (!res)
  590. {
  591. if (GetLastError()!=WSAEWOULDBLOCK)
  592. {
  593. ResetSslSession();
  594. }
  595. }
  596. return res;
  597. }
  598. bool CAsyncSslSocketLayer::HandleSession(SSL_SESSION * Session)
  599. {
  600. bool Result = false;
  601. if (m_sessionreuse)
  602. {
  603. if (m_sessionid != Session)
  604. {
  605. if (m_sessionid == NULL)
  606. {
  607. if (SSL_session_reused(m_ssl))
  608. {
  609. LogSocketMessageRaw(FZ_LOG_PROGRESS, L"Session ID reused");
  610. }
  611. else
  612. {
  613. if ((m_Main != NULL) && !m_Main->m_sessionreuse_failed)
  614. {
  615. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID not reused, will not try again");
  616. m_Main->m_sessionreuse_failed = true;
  617. }
  618. }
  619. LogSocketMessageRaw(FZ_LOG_DEBUG, L"Saving session ID");
  620. }
  621. else
  622. {
  623. SSL_SESSION_free(m_sessionid);
  624. LogSocketMessageRaw(FZ_LOG_INFO, L"Session ID changed");
  625. }
  626. m_sessionid = Session;
  627. // Some TLS 1.3 servers require reuse of the session of the previous data connection, not of the main session.
  628. // It seems that it's safe to do this even for older TLS versions, but let's not for now.
  629. // Once we do, we can simply always use main session's m_sessionid field in the code above.
  630. if ((SSL_version(m_ssl) >= TLS1_3_VERSION) && (m_Main != NULL))
  631. {
  632. if (m_Main->m_sessionid != NULL)
  633. {
  634. SSL_SESSION_free(m_Main->m_sessionid);
  635. }
  636. m_Main->m_sessionid = Session;
  637. if (Session != NULL)
  638. {
  639. SSL_SESSION_up_ref(Session);
  640. }
  641. }
  642. Result = true;
  643. }
  644. }
  645. return Result;
  646. }
  647. int CAsyncSslSocketLayer::NewSessionCallback(struct ssl_st * Ssl, SSL_SESSION * Session)
  648. {
  649. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  650. int Result = 0;
  651. // This is not called for TLS 1.2 and older when session is reused (so "Session ID reused" won't be logged).
  652. // So for 1.2 and older, we call HandleSession from apps_ssl_info_callback as we always did.
  653. if ((SSL_version(Ssl) >= TLS1_3_VERSION) && Layer->HandleSession(Session))
  654. {
  655. Result = 1;
  656. }
  657. return Result;
  658. }
  659. int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode,
  660. CAsyncSslSocketLayer* main, bool sessionreuse, const CString & host,
  661. CFileZillaTools * tools,
  662. void* pSslContext /*=0*/)
  663. {
  664. if (m_bUseSSL)
  665. return 0;
  666. int res = InitSSL();
  667. if (res)
  668. return res;
  669. m_sCriticalSection.Lock();
  670. if ((SSL_CTX*)pSslContext)
  671. {
  672. if (m_ssl_ctx)
  673. {
  674. m_sCriticalSection.Unlock();
  675. ResetSslSession();
  676. return SSL_FAILURE_INITSSL;
  677. }
  678. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find((SSL_CTX*)pSslContext);
  679. if (iter == m_contextRefCount.end() || iter->second < 1)
  680. {
  681. m_sCriticalSection.Unlock();
  682. ResetSslSession();
  683. return SSL_FAILURE_INITSSL;
  684. }
  685. m_ssl_ctx = (SSL_CTX*)pSslContext;
  686. iter->second++;
  687. }
  688. else if (!m_ssl_ctx)
  689. {
  690. // Create new context if none given
  691. if (!(m_ssl_ctx = SSL_CTX_new( SSLv23_method())))
  692. {
  693. m_sCriticalSection.Unlock();
  694. ResetSslSession();
  695. return SSL_FAILURE_INITSSL;
  696. }
  697. m_contextRefCount[m_ssl_ctx] = 1;
  698. if (clientMode)
  699. {
  700. USES_CONVERSION;
  701. SSL_CTX_set_verify(m_ssl_ctx, SSL_VERIFY_PEER, verify_callback);
  702. SSL_CTX_set_client_cert_cb(m_ssl_ctx, ProvideClientCert);
  703. // https://www.mail-archive.com/[email protected]/msg86186.html
  704. 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);
  705. SSL_CTX_sess_set_new_cb(m_ssl_ctx, NewSessionCallback);
  706. CFileStatus Dummy;
  707. if (CFile::GetStatus((LPCTSTR)m_CertStorage, Dummy))
  708. {
  709. SSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0);
  710. }
  711. }
  712. }
  713. //Create new SSL session
  714. if (!(m_ssl = SSL_new(m_ssl_ctx)))
  715. {
  716. m_sCriticalSection.Unlock();
  717. ResetSslSession();
  718. return SSL_FAILURE_INITSSL;
  719. }
  720. if (clientMode && (host.GetLength() > 0))
  721. {
  722. USES_CONVERSION;
  723. SSL_set_tlsext_host_name(m_ssl, T2CA(host));
  724. }
  725. #ifdef _DEBUG
  726. if ((main == NULL) && LoggingSocketMessage(FZ_LOG_INFO))
  727. {
  728. USES_CONVERSION;
  729. LogSocketMessageRaw(FZ_LOG_INFO, L"Supported ciphersuites:");
  730. STACK_OF(SSL_CIPHER) * ciphers = SSL_get_ciphers(m_ssl);
  731. for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); i++)
  732. {
  733. const SSL_CIPHER * cipher = sk_SSL_CIPHER_value(ciphers, i);
  734. LogSocketMessageRaw(FZ_LOG_INFO, A2CT(SSL_CIPHER_get_name(cipher)));
  735. }
  736. }
  737. #endif
  738. //Add current instance to list of active instances
  739. t_SslLayerList *tmp = m_pSslLayerList;
  740. m_pSslLayerList = new t_SslLayerList;
  741. m_pSslLayerList->pNext = tmp;
  742. m_pSslLayerList->pLayer = this;
  743. m_sCriticalSection.Unlock();
  744. SSL_set_info_callback(m_ssl, apps_ssl_info_callback);
  745. //Create bios
  746. m_sslbio = BIO_new(BIO_f_ssl());
  747. BIO_new_bio_pair(&m_ibio, 32768, &m_nbio, 32768);
  748. if (!m_sslbio || !m_nbio || !m_ibio)
  749. {
  750. ResetSslSession();
  751. return SSL_FAILURE_INITSSL;
  752. }
  753. tools->SetupSsl(m_ssl);
  754. //Init SSL connection
  755. void *ssl_sessionid = NULL;
  756. m_Main = main;
  757. m_sessionreuse = sessionreuse;
  758. if ((m_Main != NULL) && m_sessionreuse)
  759. {
  760. if (m_Main->m_sessionid == NULL)
  761. {
  762. DebugFail();
  763. SSL_set_session(m_ssl, NULL);
  764. }
  765. else if (!m_Main->m_sessionreuse_failed)
  766. {
  767. if (!SSL_set_session(m_ssl, m_Main->m_sessionid))
  768. {
  769. LogSocketMessageRaw(FZ_LOG_INFO, L"SSL_set_session failed");
  770. return SSL_FAILURE_INITSSL;
  771. }
  772. LogSocketMessageRaw(FZ_LOG_INFO, L"Trying reuse main TLS session ID");
  773. }
  774. else
  775. {
  776. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID was not reused previously, not trying again");
  777. SSL_set_session(m_ssl, NULL);
  778. }
  779. }
  780. else
  781. {
  782. SSL_set_session(m_ssl, NULL);
  783. }
  784. if (clientMode)
  785. {
  786. SSL_set_connect_state(m_ssl);
  787. }
  788. else
  789. {
  790. SSL_set_accept_state(m_ssl);
  791. }
  792. SSL_set_bio(m_ssl, m_ibio, m_ibio);
  793. BIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl);
  794. BIO_read(m_sslbio, (void *)1, 0);
  795. // Trigger FD_WRITE so that we can initialize SSL negotiation
  796. if (GetLayerState() == connected || GetLayerState() == attached)
  797. {
  798. TriggerEvent(FD_READ, 0);
  799. TriggerEvent(FD_WRITE, 0);
  800. TriggerEvent(FD_READ, 0, TRUE);
  801. TriggerEvent(FD_WRITE, 0, TRUE);
  802. }
  803. m_bUseSSL = true;
  804. return 0;
  805. }
  806. void CAsyncSslSocketLayer::ResetSslSession()
  807. {
  808. if (m_pRetrySendBuffer)
  809. {
  810. delete [] m_pRetrySendBuffer;
  811. m_pRetrySendBuffer = 0;
  812. }
  813. m_bFailureSent = FALSE;
  814. m_bBlocking = FALSE;
  815. m_nSslAsyncNotifyId++;
  816. m_nNetworkError = 0;
  817. m_bUseSSL = FALSE;
  818. m_nVerificationResult = 0;
  819. m_nVerificationDepth = 0;
  820. m_bSslEstablished = FALSE;
  821. if (m_sslbio)
  822. {
  823. BIO_free(m_sslbio);
  824. }
  825. if (m_ssl)
  826. {
  827. SSL_set_session(m_ssl,NULL);
  828. }
  829. if (m_nbio)
  830. {
  831. BIO_free(m_nbio);
  832. }
  833. if (m_ibio)
  834. {
  835. BIO_free(m_ibio);
  836. }
  837. m_nNetworkSendBufferLen = 0;
  838. m_nbio = 0;
  839. m_ibio = 0;
  840. m_sslbio = 0;
  841. if (m_ssl)
  842. {
  843. SSL_free(m_ssl);
  844. }
  845. m_sCriticalSection.Lock();
  846. if (m_ssl_ctx)
  847. {
  848. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find(m_ssl_ctx);
  849. if (iter != m_contextRefCount.end())
  850. {
  851. if (iter->second <= 1)
  852. {
  853. SSL_CTX_free(m_ssl_ctx);
  854. m_contextRefCount.erase(iter);
  855. }
  856. else
  857. iter->second--;
  858. }
  859. m_ssl_ctx = 0;
  860. }
  861. m_ssl = 0;
  862. t_SslLayerList *cur = m_pSslLayerList;
  863. if (!cur)
  864. {
  865. m_sCriticalSection.Unlock();
  866. return;
  867. }
  868. if (cur->pLayer == this)
  869. {
  870. m_pSslLayerList = cur->pNext;
  871. delete cur;
  872. }
  873. else
  874. while (cur->pNext)
  875. {
  876. if (cur->pNext->pLayer == this)
  877. {
  878. t_SslLayerList *tmp = cur->pNext;
  879. cur->pNext = cur->pNext->pNext;
  880. delete tmp;
  881. m_sCriticalSection.Unlock();
  882. return;
  883. }
  884. cur = cur->pNext;
  885. }
  886. if (m_sessionid != NULL)
  887. {
  888. SSL_SESSION_free(m_sessionid);
  889. m_sessionid = NULL;
  890. }
  891. m_sessionreuse = true;
  892. m_sessionreuse_failed = false;
  893. m_sCriticalSection.Unlock();
  894. }
  895. bool CAsyncSslSocketLayer::IsUsingSSL()
  896. {
  897. return m_bUseSSL;
  898. }
  899. BOOL CAsyncSslSocketLayer::ShutDown(int nHow /*=sends*/)
  900. {
  901. if (m_bUseSSL)
  902. {
  903. if (m_pRetrySendBuffer)
  904. {
  905. if (!m_nShutDown)
  906. m_nShutDown = 1;
  907. WSASetLastError(WSAEWOULDBLOCK);
  908. return false;
  909. }
  910. if (!m_bSslEstablished)
  911. {
  912. m_mayTriggerWriteUp = true;
  913. ::SetLastError(WSAEWOULDBLOCK);
  914. return false;
  915. }
  916. if (!m_nShutDown)
  917. m_nShutDown = 1;
  918. else
  919. {
  920. if (ShutDownComplete())
  921. return ShutDownNext();
  922. else
  923. {
  924. TriggerEvents();
  925. WSASetLastError(WSAEWOULDBLOCK);
  926. return false;
  927. }
  928. }
  929. int res = SSL_shutdown(m_ssl);
  930. if (res == 0)
  931. {
  932. // maybe we do not need to call this at all (as neon does)
  933. SSL_shutdown(m_ssl);
  934. }
  935. if (res >= 0)
  936. {
  937. if (ShutDownComplete())
  938. return ShutDownNext();
  939. else
  940. {
  941. TriggerEvents();
  942. WSASetLastError(WSAEWOULDBLOCK);
  943. return FALSE;
  944. }
  945. }
  946. else
  947. {
  948. int error = SSL_get_error(m_ssl, -1);
  949. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  950. {
  951. // retry shutdown later
  952. m_nShutDown = 0;
  953. TriggerEvents();
  954. WSASetLastError(WSAEWOULDBLOCK);
  955. return FALSE;
  956. }
  957. else if (ShutDownComplete())
  958. return ShutDownNext();
  959. else
  960. {
  961. TriggerEvents();
  962. WSASetLastError(WSAEWOULDBLOCK);
  963. return FALSE;
  964. }
  965. }
  966. }
  967. else
  968. {
  969. if (!m_nShutDown)
  970. m_nShutDown = 1;
  971. return ShutDownNext(nHow);
  972. }
  973. }
  974. BOOL CAsyncSslSocketLayer::ShutDownComplete()
  975. {
  976. //If a ShutDown was issued, has the connection already been shut down?
  977. if (!m_nShutDown)
  978. return FALSE;
  979. else if (!m_bUseSSL)
  980. return FALSE;
  981. else if (m_nNetworkSendBufferLen)
  982. return FALSE;
  983. else if (m_pRetrySendBuffer)
  984. return FALSE;
  985. // Empty read buffer
  986. char buffer[1000];
  987. int numread;
  988. do
  989. {
  990. numread = BIO_read(m_sslbio, buffer, 1000);
  991. } while (numread > 0);
  992. size_t pending = BIO_ctrl_pending(m_nbio);
  993. if (pending)
  994. {
  995. return FALSE;
  996. }
  997. else
  998. {
  999. return TRUE;
  1000. }
  1001. }
  1002. void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int ret)
  1003. {
  1004. USES_CONVERSION;
  1005. CAsyncSslSocketLayer *pLayer = 0;
  1006. m_sCriticalSection.Lock();
  1007. t_SslLayerList *cur = m_pSslLayerList;
  1008. while (cur)
  1009. {
  1010. if (cur->pLayer->m_ssl == s)
  1011. break;
  1012. cur = cur->pNext;
  1013. }
  1014. if (!cur)
  1015. {
  1016. m_sCriticalSection.Unlock();
  1017. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1018. return;
  1019. }
  1020. else
  1021. pLayer = cur->pLayer;
  1022. m_sCriticalSection.Unlock();
  1023. // Called while unloading?
  1024. if (!pLayer->m_bUseSSL && (where != SSL_CB_LOOP))
  1025. return;
  1026. char * str;
  1027. int w;
  1028. w = where& ~SSL_ST_MASK;
  1029. if (w & SSL_ST_CONNECT)
  1030. {
  1031. str = "TLS connect";
  1032. }
  1033. else if (w & SSL_ST_ACCEPT)
  1034. str = "TLS accept";
  1035. else
  1036. str = "Undefined";
  1037. if (where & SSL_CB_LOOP)
  1038. {
  1039. char* debug = NULL;
  1040. // exact SSL_CB_LOOP is abused for debugging
  1041. if (where == SSL_CB_LOOP)
  1042. {
  1043. debug = reinterpret_cast<char*>(ret);
  1044. }
  1045. char *buffer = new char[4096 + ((debug != NULL) ? strlen(debug) : 0)];
  1046. sprintf(buffer, "%s: %s",
  1047. str,
  1048. SSL_state_string_long(s));
  1049. if (debug != NULL)
  1050. {
  1051. sprintf(buffer + strlen(buffer), " [%s]", debug);
  1052. OPENSSL_free(debug);
  1053. }
  1054. USES_CONVERSION;
  1055. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, A2T(buffer));
  1056. delete[] buffer;
  1057. }
  1058. else if (where & SSL_CB_ALERT)
  1059. {
  1060. str=(where & SSL_CB_READ)? "read" : "write";
  1061. const char* desc = SSL_alert_desc_string_long(ret);
  1062. // Don't send close notify warning
  1063. if (desc)
  1064. {
  1065. if (strcmp(desc, "close notify"))
  1066. {
  1067. char *buffer = new char[4096];
  1068. sprintf(buffer, "SSL3 alert %s: %s: %s",
  1069. str,
  1070. SSL_alert_type_string_long(ret),
  1071. desc);
  1072. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1073. pLayer->PrintLastErrorMsg();
  1074. delete [] buffer;
  1075. }
  1076. }
  1077. }
  1078. else if (where & SSL_CB_EXIT)
  1079. {
  1080. if (ret == 0)
  1081. {
  1082. char *buffer = new char[4096];
  1083. sprintf(buffer, "%s: failed in %s",
  1084. str,
  1085. SSL_state_string_long(s));
  1086. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1087. pLayer->PrintLastErrorMsg();
  1088. delete [] buffer;
  1089. if (!pLayer->m_bFailureSent)
  1090. {
  1091. pLayer->m_bFailureSent=TRUE;
  1092. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1093. }
  1094. }
  1095. else if (ret < 0)
  1096. {
  1097. int error = SSL_get_error(s,ret);
  1098. if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
  1099. {
  1100. char *buffer = new char[4096];
  1101. sprintf(buffer, "%s: error in %s",
  1102. str,
  1103. SSL_state_string_long(s));
  1104. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1105. delete [] buffer;
  1106. if (!pLayer->m_bFailureSent)
  1107. {
  1108. pLayer->m_bFailureSent=TRUE;
  1109. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. if (where & SSL_CB_HANDSHAKE_DONE)
  1115. {
  1116. // For 1.2 and older, session is always established at this point.
  1117. // For 1.3, session can be restarted later, so this is handled in NewSessionCallback.
  1118. if (SSL_version(pLayer->m_ssl) < TLS1_3_VERSION)
  1119. {
  1120. SSL_SESSION * sessionid = SSL_get1_session(pLayer->m_ssl);
  1121. if (!pLayer->HandleSession(sessionid))
  1122. {
  1123. SSL_SESSION_free(sessionid);
  1124. }
  1125. }
  1126. int error = SSL_get_verify_result(pLayer->m_ssl);
  1127. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERIFY_CERT, error);
  1128. pLayer->m_bBlocking = TRUE;
  1129. }
  1130. }
  1131. void CAsyncSslSocketLayer::UnloadSSL()
  1132. {
  1133. if (!m_bSslInitialized)
  1134. return;
  1135. ResetSslSession();
  1136. m_bSslInitialized = false;
  1137. m_sCriticalSection.Lock();
  1138. m_nSslRefCount--;
  1139. if (m_nSslRefCount)
  1140. {
  1141. m_sCriticalSection.Unlock();
  1142. return;
  1143. }
  1144. m_sCriticalSection.Unlock();
  1145. }
  1146. bool AsnTimeToValidTime(ASN1_TIME * AsnTime, t_SslCertData::t_validTime & ValidTime)
  1147. {
  1148. int i = AsnTime->length;
  1149. const char * v = (const char *)AsnTime->data;
  1150. if (i < 10)
  1151. {
  1152. return FALSE;
  1153. }
  1154. for (int i2 = 0; i2 < 10; i2++)
  1155. {
  1156. if ((v[i2] > '9') || (v[i2] < '0'))
  1157. {
  1158. return FALSE;
  1159. }
  1160. }
  1161. if (AsnTime->type == V_ASN1_UTCTIME)
  1162. {
  1163. ValidTime.y= (v[0]-'0')*10+(v[1]-'0');
  1164. if (ValidTime.y < 50) ValidTime.y+=100;
  1165. ValidTime.y += 1900;
  1166. v += 2;
  1167. i -= 2;
  1168. }
  1169. else if (AsnTime->type == V_ASN1_GENERALIZEDTIME)
  1170. {
  1171. if (i < 12)
  1172. {
  1173. return FALSE;
  1174. }
  1175. ValidTime.y = (v[0]-'0')*1000+(v[1]-'0')*100 + (v[2]-'0')*10+(v[3]-'0');
  1176. v += 4;
  1177. i -= 4;
  1178. }
  1179. else
  1180. {
  1181. return FALSE;
  1182. }
  1183. ValidTime.M = (v[0]-'0')*10+(v[1]-'0');
  1184. if ((ValidTime.M > 12) || (ValidTime.M < 1))
  1185. {
  1186. return FALSE;
  1187. }
  1188. ValidTime.d = (v[2]-'0')*10+(v[3]-'0');
  1189. ValidTime.h = (v[4]-'0')*10+(v[5]-'0');
  1190. ValidTime.m = (v[6]-'0')*10+(v[7]-'0');
  1191. if ((i >= 10) &&
  1192. (v[8] >= '0') && (v[8] <= '9') &&
  1193. (v[9] >= '0') && (v[9] <= '9'))
  1194. {
  1195. ValidTime.s = (v[8]-'0')*10+(v[9]-'0');
  1196. }
  1197. else
  1198. {
  1199. ValidTime.s = 0;
  1200. }
  1201. return TRUE;
  1202. }
  1203. BOOL CAsyncSslSocketLayer::GetPeerCertificateData(t_SslCertData &SslCertData, LPCTSTR & Error)
  1204. {
  1205. X509 *pX509=SSL_get_peer_certificate(m_ssl);
  1206. if (!pX509)
  1207. {
  1208. Error = L"Cannot get certificate";
  1209. return FALSE;
  1210. }
  1211. //Reset the contents of SslCertData
  1212. memset(&SslCertData, 0, sizeof(t_SslCertData));
  1213. //Set subject data fields
  1214. X509_NAME *pX509Name=X509_get_subject_name(pX509);
  1215. if (pX509Name)
  1216. {
  1217. int count=X509_NAME_entry_count(pX509Name);
  1218. for (int i=0;i<count;i++)
  1219. {
  1220. X509_NAME_ENTRY *pX509NameEntry=X509_NAME_get_entry(pX509Name,i);
  1221. if (!pX509NameEntry)
  1222. continue;
  1223. ASN1_OBJECT *pObject = X509_NAME_ENTRY_get_object(pX509NameEntry);
  1224. ASN1_STRING *pString = X509_NAME_ENTRY_get_data(pX509NameEntry);
  1225. CString str;
  1226. unsigned char *out;
  1227. int len = ASN1_STRING_to_UTF8(&out, pString);
  1228. if (len > 0)
  1229. {
  1230. // Keep it huge
  1231. LPWSTR unicode = new WCHAR[len * 10];
  1232. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1233. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1234. if (unicodeLen > 0)
  1235. {
  1236. #ifdef _UNICODE
  1237. str = unicode;
  1238. #else
  1239. LPSTR ansi = new CHAR[len * 10];
  1240. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1241. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1242. if (ansiLen > 0)
  1243. str = ansi;
  1244. delete [] ansi;
  1245. #endif
  1246. }
  1247. delete [] unicode;
  1248. OPENSSL_free(out);
  1249. }
  1250. switch(OBJ_obj2nid(pObject))
  1251. {
  1252. case NID_organizationName:
  1253. _tcsncpy(SslCertData.subject.Organization, str, 255);
  1254. SslCertData.subject.Organization[255] = 0;
  1255. break;
  1256. case NID_organizationalUnitName:
  1257. _tcsncpy(SslCertData.subject.Unit, str, 255);
  1258. SslCertData.subject.Unit[255] = 0;
  1259. break;
  1260. case NID_commonName:
  1261. _tcsncpy(SslCertData.subject.CommonName, str, 255);
  1262. SslCertData.subject.CommonName[255] = 0;
  1263. break;
  1264. case NID_pkcs9_emailAddress:
  1265. _tcsncpy(SslCertData.subject.Mail, str, 255);
  1266. SslCertData.subject.Mail[255] = 0;
  1267. break;
  1268. case NID_countryName:
  1269. _tcsncpy(SslCertData.subject.Country, str, 255);
  1270. SslCertData.subject.Country[255] = 0;
  1271. break;
  1272. case NID_stateOrProvinceName:
  1273. _tcsncpy(SslCertData.subject.StateProvince, str, 255);
  1274. SslCertData.subject.StateProvince[255] = 0;
  1275. break;
  1276. case NID_localityName:
  1277. _tcsncpy(SslCertData.subject.Town, str, 255);
  1278. SslCertData.subject.Town[255] = 0;
  1279. break;
  1280. default:
  1281. if ( !OBJ_nid2sn(OBJ_obj2nid(pObject)) )
  1282. {
  1283. TCHAR tmp[20];
  1284. _stprintf(tmp, L"%d", OBJ_obj2nid(pObject));
  1285. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1286. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), tmp, maxlen);
  1287. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1288. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L"=", maxlen);
  1289. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1290. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1291. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1292. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L";", maxlen);
  1293. }
  1294. else
  1295. {
  1296. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1297. USES_CONVERSION;
  1298. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), A2CT(OBJ_nid2sn(OBJ_obj2nid(pObject))), maxlen);
  1299. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1300. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L"=", maxlen);
  1301. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1302. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1303. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1304. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L";", maxlen);
  1305. }
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. //Set issuer data fields
  1311. pX509Name=X509_get_issuer_name(pX509);
  1312. if (pX509Name)
  1313. {
  1314. int count=X509_NAME_entry_count(pX509Name);
  1315. for (int i=0;i<count;i++)
  1316. {
  1317. X509_NAME_ENTRY *pX509NameEntry=X509_NAME_get_entry(pX509Name,i);
  1318. if (!pX509NameEntry)
  1319. continue;
  1320. ASN1_STRING *pString=X509_NAME_ENTRY_get_data(pX509NameEntry);
  1321. ASN1_OBJECT *pObject=X509_NAME_ENTRY_get_object(pX509NameEntry);
  1322. CString str;
  1323. unsigned char *out;
  1324. int len = ASN1_STRING_to_UTF8(&out, pString);
  1325. if (len > 0)
  1326. {
  1327. // Keep it huge
  1328. LPWSTR unicode = new WCHAR[len * 10];
  1329. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1330. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1331. if (unicodeLen > 0)
  1332. {
  1333. #ifdef _UNICODE
  1334. str = unicode;
  1335. #else
  1336. LPSTR ansi = new CHAR[len * 10];
  1337. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1338. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1339. if (ansiLen > 0)
  1340. str = ansi;
  1341. delete [] ansi;
  1342. #endif
  1343. }
  1344. delete [] unicode;
  1345. OPENSSL_free(out);
  1346. }
  1347. switch(OBJ_obj2nid(pObject))
  1348. {
  1349. case NID_organizationName:
  1350. _tcsncpy(SslCertData.issuer.Organization, str, 255);
  1351. SslCertData.issuer.Organization[255] = 0;
  1352. break;
  1353. case NID_organizationalUnitName:
  1354. _tcsncpy(SslCertData.issuer.Unit, str, 255);
  1355. SslCertData.issuer.Unit[255] = 0;
  1356. break;
  1357. case NID_commonName:
  1358. _tcsncpy(SslCertData.issuer.CommonName, str, 255);
  1359. SslCertData.issuer.CommonName[255] = 0;
  1360. break;
  1361. case NID_pkcs9_emailAddress:
  1362. _tcsncpy(SslCertData.issuer.Mail, str, 255);
  1363. SslCertData.issuer.Mail[255] = 0;
  1364. break;
  1365. case NID_countryName:
  1366. _tcsncpy(SslCertData.issuer.Country, str, 255);
  1367. SslCertData.issuer.Country[255] = 0;
  1368. break;
  1369. case NID_stateOrProvinceName:
  1370. _tcsncpy(SslCertData.issuer.StateProvince, str, 255);
  1371. SslCertData.issuer.StateProvince[255] = 0;
  1372. break;
  1373. case NID_localityName:
  1374. _tcsncpy(SslCertData.issuer.Town, str, 255);
  1375. SslCertData.issuer.Town[255] = 0;
  1376. break;
  1377. default:
  1378. if ( !OBJ_nid2sn(OBJ_obj2nid(pObject)) )
  1379. {
  1380. TCHAR tmp[20];
  1381. _stprintf(tmp, L"%d", OBJ_obj2nid(pObject));
  1382. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1383. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), tmp, maxlen);
  1384. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1385. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L"=", maxlen);
  1386. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1387. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1388. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1389. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L";", maxlen);
  1390. }
  1391. else
  1392. {
  1393. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1394. USES_CONVERSION;
  1395. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), A2CT(OBJ_nid2sn(OBJ_obj2nid(pObject))), maxlen);
  1396. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1397. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L"=", maxlen);
  1398. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1399. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1400. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1401. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L";", maxlen);
  1402. }
  1403. break;
  1404. }
  1405. }
  1406. }
  1407. //Set date fields
  1408. //Valid from
  1409. ASN1_TIME *pTime=X509_getm_notBefore(pX509);
  1410. if (!pTime)
  1411. {
  1412. X509_free(pX509);
  1413. Error = L"Cannot get start time";
  1414. return FALSE;
  1415. }
  1416. if (!AsnTimeToValidTime(pTime, SslCertData.validFrom))
  1417. {
  1418. X509_free(pX509);
  1419. Error = L"Invalid start time";
  1420. return FALSE;
  1421. }
  1422. //Valid until
  1423. pTime = X509_getm_notAfter(pX509);
  1424. if (!pTime)
  1425. {
  1426. X509_free(pX509);
  1427. Error = L"Cannot get end time";
  1428. return FALSE;
  1429. }
  1430. if (!AsnTimeToValidTime(pTime, SslCertData.validUntil))
  1431. {
  1432. X509_free(pX509);
  1433. Error = L"Invalid end time";
  1434. return FALSE;
  1435. }
  1436. int subjectAltNamePos = X509_get_ext_by_NID(pX509, NID_subject_alt_name, -1);
  1437. if (subjectAltNamePos >= 0)
  1438. {
  1439. X509_EXTENSION * subjectAltNameExtension = X509_get_ext(pX509, subjectAltNamePos);
  1440. BIO * subjectAltNameBio = BIO_new(BIO_s_mem());
  1441. if (X509V3_EXT_print(subjectAltNameBio, subjectAltNameExtension, 0, 0) == 1)
  1442. {
  1443. USES_CONVERSION;
  1444. u_char *data;
  1445. int len = BIO_get_mem_data(subjectAltNameBio, &data);
  1446. char * buf = new char[len + 1];
  1447. memcpy(buf, data, len);
  1448. buf[len] = '\0';
  1449. _tcsncpy(SslCertData.subjectAltName, A2CT(buf), LENOF(SslCertData.subjectAltName));
  1450. SslCertData.subjectAltName[LENOF(SslCertData.subjectAltName) - 1] = '\0';
  1451. delete [] buf;
  1452. }
  1453. BIO_vfree(subjectAltNameBio);
  1454. }
  1455. unsigned int length;
  1456. length = sizeof(SslCertData.hashSha1);
  1457. X509_digest(pX509, EVP_sha1(), SslCertData.hashSha1, &length);
  1458. DebugAssert(length == sizeof(SslCertData.hashSha1));
  1459. length = sizeof(SslCertData.hashSha256);
  1460. X509_digest(pX509, EVP_sha256(), SslCertData.hashSha256, &length);
  1461. DebugAssert(length == sizeof(SslCertData.hashSha256));
  1462. // Inspired by ne_ssl_cert_export()
  1463. // Find the length of the DER encoding.
  1464. SslCertData.certificateLen = i2d_X509(pX509, NULL);
  1465. SslCertData.certificate = new unsigned char[SslCertData.certificateLen];
  1466. unsigned char * p = SslCertData.certificate;
  1467. i2d_X509(pX509, &p);
  1468. SslCertData.priv_data = m_nSslAsyncNotifyId;
  1469. X509_free(pX509);
  1470. SslCertData.verificationResult = m_nVerificationResult;
  1471. SslCertData.verificationDepth = m_nVerificationDepth;
  1472. return TRUE;
  1473. }
  1474. std::string CAsyncSslSocketLayer::GetTlsVersionStr()
  1475. {
  1476. return m_TlsVersionStr;
  1477. }
  1478. std::string CAsyncSslSocketLayer::GetCipherName()
  1479. {
  1480. return m_CipherName;
  1481. }
  1482. void CAsyncSslSocketLayer::SetNotifyReply(int nID, int nCode, int result)
  1483. {
  1484. if (!m_bBlocking)
  1485. return;
  1486. if (nID != m_nSslAsyncNotifyId)
  1487. return;
  1488. if (nCode != SSL_VERIFY_CERT)
  1489. return;
  1490. m_bBlocking = FALSE;
  1491. if (!result)
  1492. {
  1493. m_nNetworkError = WSAECONNABORTED;
  1494. WSASetLastError(WSAECONNABORTED);
  1495. if (!m_bFailureSent)
  1496. {
  1497. m_bFailureSent = TRUE;
  1498. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, SSL_FAILURE_CERTREJECTED);
  1499. }
  1500. TriggerEvent(FD_CLOSE, 0, TRUE);
  1501. return;
  1502. }
  1503. m_bSslEstablished = TRUE;
  1504. PrintSessionInfo();
  1505. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_ESTABLISHED);
  1506. TriggerEvents();
  1507. }
  1508. void CAsyncSslSocketLayer::PrintSessionInfo()
  1509. {
  1510. const SSL_CIPHER *ciph;
  1511. X509 *cert;
  1512. ciph = SSL_get_current_cipher(m_ssl);
  1513. char enc[4096] = {0};
  1514. cert=SSL_get_peer_certificate(m_ssl);
  1515. if (cert != NULL)
  1516. {
  1517. EVP_PKEY *pkey = X509_get_pubkey(cert);
  1518. if (pkey != NULL)
  1519. {
  1520. if (0)
  1521. ;
  1522. #ifndef NO_RSA
  1523. else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
  1524. sprintf(enc, "%d bit RSA", EVP_PKEY_bits(pkey));
  1525. #endif
  1526. #ifndef NO_DSA
  1527. else if (EVP_PKEY_id(pkey) == EVP_PKEY_DSA)
  1528. sprintf(enc, "%d bit DSA", EVP_PKEY_bits(pkey));
  1529. #endif
  1530. EVP_PKEY_free(pkey);
  1531. }
  1532. X509_free(cert);
  1533. /* The SSL API does not allow us to look at temporary RSA/DH keys,
  1534. * otherwise we should print their lengths too */
  1535. }
  1536. const int buffer_size = 4096;
  1537. char *buffer = new char[buffer_size];
  1538. char *buffer2 = new char[buffer_size];
  1539. // see also ne_ssl_get_version and ne_ssl_get_cipher
  1540. m_TlsVersionStr = SSL_get_version(m_ssl);
  1541. sprintf(buffer, "%s: %s, %s, %s",
  1542. SSL_CIPHER_get_version(ciph),
  1543. SSL_CIPHER_get_name(ciph),
  1544. enc,
  1545. SSL_CIPHER_description(ciph, buffer2, buffer_size));
  1546. m_CipherName = buffer;
  1547. // see TWebDAVFileSystem::CollectTLSSessionInfo()
  1548. sprintf(buffer, "Using %s, cipher %s",
  1549. m_TlsVersionStr.c_str(),
  1550. m_CipherName.c_str());
  1551. USES_CONVERSION;
  1552. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1553. delete [] buffer;
  1554. delete [] buffer2;
  1555. }
  1556. void CAsyncSslSocketLayer::OnConnect(int nErrorCode)
  1557. {
  1558. if (m_bUseSSL && nErrorCode)
  1559. TriggerEvent(FD_WRITE, 0);
  1560. TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  1561. }
  1562. CAsyncSslSocketLayer * CAsyncSslSocketLayer::LookupLayer(SSL * Ssl)
  1563. {
  1564. CAsyncSslSocketLayer * Result = NULL;
  1565. m_sCriticalSection.Lock();
  1566. t_SslLayerList * Cur = m_pSslLayerList;
  1567. while (Cur != NULL)
  1568. {
  1569. if (Cur->pLayer->m_ssl == Ssl)
  1570. {
  1571. break;
  1572. }
  1573. Cur = Cur->pNext;
  1574. }
  1575. m_sCriticalSection.Unlock();
  1576. if (Cur == NULL)
  1577. {
  1578. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1579. Result = NULL;
  1580. }
  1581. else
  1582. {
  1583. Result = Cur->pLayer;
  1584. }
  1585. return Result;
  1586. }
  1587. int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1588. {
  1589. X509 *err_cert;
  1590. int err, depth;
  1591. SSL *ssl;
  1592. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  1593. err = X509_STORE_CTX_get_error(ctx);
  1594. depth = X509_STORE_CTX_get_error_depth(ctx);
  1595. /*
  1596. * Retrieve the pointer to the SSL of the connection currently treated
  1597. * and the application specific data stored into the SSL object.
  1598. */
  1599. ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  1600. CAsyncSslSocketLayer * pLayer = LookupLayer(ssl);
  1601. if (pLayer == NULL)
  1602. {
  1603. return 1;
  1604. }
  1605. /*
  1606. * Catch a too long certificate chain. The depth limit set using
  1607. * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
  1608. * that whenever the "depth>verify_depth" condition is met, we
  1609. * have violated the limit and want to log this error condition.
  1610. * We must do it here, because the CHAIN_TOO_LONG error would not
  1611. * be found explicitly; only errors introduced by cutting off the
  1612. * additional certificates would be logged.
  1613. */
  1614. if (depth > 10) {//mydata->verify_depth) {
  1615. preverify_ok = 0;
  1616. err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  1617. X509_STORE_CTX_set_error(ctx, err);
  1618. }
  1619. if (!preverify_ok)
  1620. {
  1621. if (!pLayer->m_nVerificationResult)
  1622. {
  1623. pLayer->m_nVerificationDepth = depth;
  1624. pLayer->m_nVerificationResult = err;
  1625. }
  1626. }
  1627. return 1;
  1628. }
  1629. int CAsyncSslSocketLayer::ProvideClientCert(
  1630. SSL * Ssl, X509 ** Certificate, EVP_PKEY ** PrivateKey)
  1631. {
  1632. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  1633. CString Message;
  1634. Message.LoadString(NEED_CLIENT_CERTIFICATE);
  1635. int Level;
  1636. int Result;
  1637. if ((Layer->FCertificate == NULL) || (Layer->FPrivateKey == NULL))
  1638. {
  1639. Level = FZ_LOG_WARNING;
  1640. Result = 0;
  1641. }
  1642. else
  1643. {
  1644. Level = FZ_LOG_PROGRESS;
  1645. *Certificate = X509_dup(Layer->FCertificate);
  1646. EVP_PKEY_up_ref(Layer->FPrivateKey);
  1647. *PrivateKey = Layer->FPrivateKey;
  1648. Result = 1;
  1649. }
  1650. Layer->LogSocketMessageRaw(Level, static_cast<LPCTSTR>(Message));
  1651. return Result;
  1652. }
  1653. void CAsyncSslSocketLayer::SetClientCertificate(X509 * Certificate, EVP_PKEY * PrivateKey)
  1654. {
  1655. FCertificate = Certificate;
  1656. FPrivateKey = PrivateKey;
  1657. }
  1658. BOOL CAsyncSslSocketLayer::SetCertStorage(CString file)
  1659. {
  1660. m_CertStorage = file;
  1661. return TRUE;
  1662. }
  1663. void CAsyncSslSocketLayer::OnClose(int nErrorCode)
  1664. {
  1665. m_onCloseCalled = true;
  1666. if (m_bUseSSL && BIO_ctrl)
  1667. {
  1668. size_t pending = BIO_ctrl_pending(m_sslbio);
  1669. if (pending > 0)
  1670. {
  1671. TriggerEvents();
  1672. }
  1673. else TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1674. }
  1675. else
  1676. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1677. }
  1678. void CAsyncSslSocketLayer::PrintLastErrorMsg()
  1679. {
  1680. int err = ERR_get_error();
  1681. while (err)
  1682. {
  1683. char *buffer = new char[512];
  1684. const char *reason = ERR_reason_error_string(err);
  1685. ERR_error_string(err, buffer);
  1686. err = ERR_get_error();
  1687. USES_CONVERSION;
  1688. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1689. LogSocketMessageRaw(FZ_LOG_WARNING, A2T(reason));
  1690. delete [] buffer;
  1691. }
  1692. }
  1693. void CAsyncSslSocketLayer::TriggerEvents()
  1694. {
  1695. size_t pending = BIO_ctrl_pending(m_nbio);
  1696. if (pending > 0)
  1697. {
  1698. if (m_mayTriggerWrite)
  1699. {
  1700. m_mayTriggerWrite = false;
  1701. TriggerEvent(FD_WRITE, 0);
  1702. }
  1703. }
  1704. else if (!m_nNetworkSendBufferLen && m_bSslEstablished && !m_pRetrySendBuffer)
  1705. {
  1706. if (BIO_ctrl_get_write_guarantee(m_sslbio) > 0 && m_mayTriggerWriteUp)
  1707. {
  1708. m_mayTriggerWriteUp = false;
  1709. TriggerEvent(FD_WRITE, 0, TRUE);
  1710. }
  1711. }
  1712. if (m_bSslEstablished && BIO_ctrl_pending(m_sslbio) > 0)
  1713. {
  1714. if (m_mayTriggerReadUp && !m_bBlocking)
  1715. {
  1716. m_mayTriggerReadUp = false;
  1717. TriggerEvent(FD_READ, 0, TRUE);
  1718. }
  1719. }
  1720. else
  1721. {
  1722. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  1723. if (len > 0 && m_mayTriggerRead)
  1724. {
  1725. m_mayTriggerRead = false;
  1726. TriggerEvent(FD_READ, 0);
  1727. }
  1728. }
  1729. if (m_onCloseCalled && m_bSslEstablished)
  1730. {
  1731. if (BIO_ctrl_pending(m_sslbio) <= 0)
  1732. {
  1733. TriggerEvent(FD_CLOSE, 0, TRUE);
  1734. }
  1735. }
  1736. }
  1737. //---------------------------------------------------------------------------