AsyncSslSocketLayer.cpp 50 KB

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