AsyncSslSocketLayer.cpp 48 KB

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