AsyncSslSocketLayer.cpp 49 KB

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