AsyncSslSocketLayer.cpp 50 KB

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