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