DnsTlsSessionCache.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (C) 2018 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "DnsTlsSessionCache.h"
  17. #define LOG_TAG "DnsTlsSessionCache"
  18. //#define LOG_NDEBUG 0
  19. #include "log/log.h"
  20. namespace android {
  21. namespace net {
  22. bool DnsTlsSessionCache::prepareSsl(SSL* ssl) {
  23. // Add this cache as the 0-index extra data for the socket.
  24. // This is used by newSessionCallback.
  25. int ret = SSL_set_ex_data(ssl, 0, this);
  26. return ret == 1;
  27. }
  28. void DnsTlsSessionCache::prepareSslContext(SSL_CTX* ssl_ctx) {
  29. SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT);
  30. SSL_CTX_sess_set_new_cb(ssl_ctx, &DnsTlsSessionCache::newSessionCallback);
  31. }
  32. // static
  33. int DnsTlsSessionCache::newSessionCallback(SSL* ssl, SSL_SESSION* session) {
  34. if (!ssl || !session) {
  35. ALOGE("Null SSL object in new session callback");
  36. return 0;
  37. }
  38. DnsTlsSessionCache* cache = reinterpret_cast<DnsTlsSessionCache*>(
  39. SSL_get_ex_data(ssl, 0));
  40. if (!cache) {
  41. ALOGE("null transport in new session callback");
  42. return 0;
  43. }
  44. ALOGV("Recording session");
  45. cache->recordSession(session);
  46. return 1; // Increment the refcount of session.
  47. }
  48. void DnsTlsSessionCache::recordSession(SSL_SESSION* session) {
  49. std::lock_guard guard(mLock);
  50. mSessions.emplace_front(session);
  51. if (mSessions.size() > kMaxSize) {
  52. ALOGV("Too many sessions; trimming");
  53. mSessions.pop_back();
  54. }
  55. }
  56. bssl::UniquePtr<SSL_SESSION> DnsTlsSessionCache::getSession() {
  57. std::lock_guard guard(mLock);
  58. if (mSessions.size() == 0) {
  59. ALOGV("No known sessions");
  60. return nullptr;
  61. }
  62. bssl::UniquePtr<SSL_SESSION> ret = std::move(mSessions.front());
  63. mSessions.pop_front();
  64. return ret;
  65. }
  66. } // end of namespace net
  67. } // end of namespace android