AsyncSslSocketLayer.cpp 49 KB

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