1 /* 2 * Copyright (C) 2009 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 17 package org.conscrypt; 18 19 import javax.net.ssl.SSLContext; 20 21 /** 22 * Caches server sessions. Indexes by session ID. Users typically look up 23 * sessions using the ID provided by an SSL client. 24 * 25 * @hide 26 */ 27 @Internal 28 public final class ServerSessionContext extends AbstractSessionContext { 29 private SSLServerSessionCache persistentCache; 30 31 ServerSessionContext() { 32 super(100); 33 34 // TODO make sure SSL_CTX does not automaticaly clear sessions we want it to cache 35 // SSL_CTX_set_session_cache_mode(sslCtxNativePointer, SSL_SESS_CACHE_NO_AUTO_CLEAR); 36 37 // TODO remove SSL_CTX session cache limit so we can manage it 38 // SSL_CTX_sess_set_cache_size(sslCtxNativePointer, 0); 39 40 // TODO override trimToSize and removeEldestEntry to use 41 // SSL_CTX_sessions to remove from native cache 42 43 // Set a trivial session id context. OpenSSL uses this to make 44 // sure you don't reuse sessions externalized with i2d_SSL_SESSION 45 // between apps. However our sessions are either in memory or 46 // exported to a app's SSLServerSessionCache. 47 NativeCrypto.SSL_CTX_set_session_id_context(sslCtxNativePointer, this, new byte[] { ' ' }); 48 } 49 50 /** 51 * Applications should not use this method. Instead use {@link 52 * Conscrypt#setServerSessionCache(SSLContext, SSLServerSessionCache)}. 53 */ 54 public void setPersistentCache(SSLServerSessionCache persistentCache) { 55 this.persistentCache = persistentCache; 56 } 57 58 @Override 59 NativeSslSession getSessionFromPersistentCache(byte[] sessionId) { 60 if (persistentCache != null) { 61 byte[] data = persistentCache.getSessionData(sessionId); 62 if (data != null) { 63 NativeSslSession session = NativeSslSession.newInstance(this, data, null, -1); 64 if (session != null && session.isValid()) { 65 cacheSession(session); 66 return session; 67 } 68 } 69 } 70 71 return null; 72 } 73 74 @Override 75 void onBeforeAddSession(NativeSslSession session) { 76 // TODO: Do this in background thread. 77 if (persistentCache != null) { 78 byte[] data = session.toBytes(); 79 if (data != null) { 80 persistentCache.putSessionData(session.toSSLSession(), data); 81 } 82 } 83 } 84 85 @Override 86 void onBeforeRemoveSession(NativeSslSession session) { 87 // Do nothing. 88 } 89 } 90