AsyncSslSocketLayer.cpp 50 KB

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