AsyncSslSocketLayer.cpp 49 KB

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