2 * Copyright (c) 2017 Thomas Pornin <pornin@bolet.org>
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 using System.Collections.Generic;
32 * A basic implementation of an SSL session cache. It stores up to a
33 * predetermined number of sessions, and uses a least-recently-used
34 * eviction policy. Sessions are kept in RAM.
36 * Instances use locking to be thread-safe, so that multiple SSL server
37 * engines managed in different threads may share the same cache (though
38 * each engine, individually, is not thread-safe).
41 public class SSLSessionCacheLRU : ISessionCache {
44 * TODO: use a doubly-linked list for LRU policy. Right now,
45 * values are indexed in an array, and eviction/moving implies
46 * shifting many pointers in that array. This is fine for small
47 * caches, up to a few thousands of entries.
51 IDictionary<string, int> spx;
52 SSLSessionParameters[] data;
55 public SSLSessionCacheLRU(int maxCount)
57 spx = new Dictionary<string, int>();
58 data = new SSLSessionParameters[maxCount];
60 this.maxCount = maxCount;
64 /* see ISessionCache */
65 public SSLSessionParameters Retrieve(byte[] id, string serverName)
69 if (!spx.TryGetValue(IDToString(id), out x)) {
72 SSLSessionParameters sp = data[x];
73 if ((x + 1) < count) {
74 Array.Copy(data, x + 1,
75 data, x, count - x - 1);
82 /* see ISessionCache */
83 public void Store(SSLSessionParameters sp)
86 string ids = IDToString(sp.SessionID);
88 if (spx.TryGetValue(ids, out x)) {
89 if ((x + 1) < count) {
90 Array.Copy(data, x + 1,
91 data, x, count - x - 1);
97 if (count == maxCount) {
98 SSLSessionParameters esp = data[0];
99 Array.Copy(data, 1, data, 0, count - 1);
101 spx.Remove(IDToString(esp.SessionID));
109 static string IDToString(byte[] id)
111 StringBuilder sb = new StringBuilder();
112 foreach (byte b in id) {
113 sb.AppendFormat("{0:x2}", b);
115 return sb.ToString();