AsyncSslSocketLayer.cpp 50 KB

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