AsyncSslSocketLayer.cpp 49 KB

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