AsyncSslSocketLayer.cpp 47 KB

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