1
2
3
4
5
6
7
8 """Class for caching TLS sessions."""
9
10 import threading
11 import time
12
14 """This class is used by the server to cache TLS sessions.
15
16 Caching sessions allows the client to use TLS session resumption
17 and avoid the expense of a full handshake. To use this class,
18 simply pass a SessionCache instance into the server handshake
19 function.
20
21 This class is thread-safe.
22 """
23
24
25
26
27
28
29 - def __init__(self, maxEntries=10000, maxAge=14400):
30 """Create a new SessionCache.
31
32 @type maxEntries: int
33 @param maxEntries: The maximum size of the cache. When this
34 limit is reached, the oldest sessions will be deleted as
35 necessary to make room for new ones. The default is 10000.
36
37 @type maxAge: int
38 @param maxAge: The number of seconds before a session expires
39 from the cache. The default is 14400 (i.e. 4 hours)."""
40
41 self.lock = threading.Lock()
42
43
44 self.entriesDict = {}
45
46
47 self.entriesList = [(None,None)] * maxEntries
48
49 self.firstIndex = 0
50 self.lastIndex = 0
51 self.maxAge = maxAge
52
54 self.lock.acquire()
55 try:
56 self._purge()
57 session = self.entriesDict[bytes(sessionID)]
58
59
60
61
62
63
64 if session.valid():
65 return session
66 else:
67 raise KeyError()
68 finally:
69 self.lock.release()
70
71
73 self.lock.acquire()
74 try:
75
76 self.entriesDict[bytes(sessionID)] = session
77 self.entriesList[self.lastIndex] = (bytes(sessionID), time.time())
78 self.lastIndex = (self.lastIndex+1) % len(self.entriesList)
79
80
81
82 if self.lastIndex == self.firstIndex:
83 del(self.entriesDict[self.entriesList[self.firstIndex][0]])
84 self.firstIndex = (self.firstIndex+1) % len(self.entriesList)
85 finally:
86 self.lock.release()
87
88
90 currentTime = time.time()
91
92
93
94
95
96 index = self.firstIndex
97 while index != self.lastIndex:
98 if currentTime - self.entriesList[index][1] > self.maxAge:
99 del(self.entriesDict[self.entriesList[index][0]])
100 index = (index+1) % len(self.entriesList)
101 else:
102 break
103 self.firstIndex = index
104