AsyncSslSocketLayer.cpp 50 KB

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