1 package org
.asamk
.signal
.manager
.storage
.sessions
;
3 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
4 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
5 import org
.asamk
.signal
.manager
.util
.IOUtils
;
6 import org
.slf4j
.Logger
;
7 import org
.slf4j
.LoggerFactory
;
8 import org
.whispersystems
.libsignal
.NoSessionException
;
9 import org
.whispersystems
.libsignal
.SignalProtocolAddress
;
10 import org
.whispersystems
.libsignal
.protocol
.CiphertextMessage
;
11 import org
.whispersystems
.libsignal
.state
.SessionRecord
;
12 import org
.whispersystems
.signalservice
.api
.SignalServiceSessionStore
;
15 import java
.io
.FileInputStream
;
16 import java
.io
.FileOutputStream
;
17 import java
.io
.IOException
;
18 import java
.nio
.file
.Files
;
19 import java
.util
.Arrays
;
20 import java
.util
.Collection
;
21 import java
.util
.HashMap
;
22 import java
.util
.List
;
24 import java
.util
.Objects
;
26 import java
.util
.regex
.Matcher
;
27 import java
.util
.regex
.Pattern
;
28 import java
.util
.stream
.Collectors
;
30 public class SessionStore
implements SignalServiceSessionStore
{
32 private final static Logger logger
= LoggerFactory
.getLogger(SessionStore
.class);
34 private final Map
<Key
, SessionRecord
> cachedSessions
= new HashMap
<>();
36 private final File sessionsPath
;
38 private final RecipientResolver resolver
;
41 final File sessionsPath
, final RecipientResolver resolver
43 this.sessionsPath
= sessionsPath
;
44 this.resolver
= resolver
;
48 public SessionRecord
loadSession(SignalProtocolAddress address
) {
49 final var key
= getKey(address
);
51 synchronized (cachedSessions
) {
52 final var session
= loadSessionLocked(key
);
53 if (session
== null) {
54 return new SessionRecord();
61 public List
<SessionRecord
> loadExistingSessions(final List
<SignalProtocolAddress
> addresses
) throws NoSessionException
{
62 final var keys
= addresses
.stream().map(this::getKey
).collect(Collectors
.toList());
64 synchronized (cachedSessions
) {
65 final var sessions
= keys
.stream()
66 .map(this::loadSessionLocked
)
67 .filter(Objects
::nonNull
)
68 .collect(Collectors
.toList());
70 if (sessions
.size() != addresses
.size()) {
71 String message
= "Mismatch! Asked for "
73 + " sessions, but only found "
77 throw new NoSessionException(message
);
85 public List
<Integer
> getSubDeviceSessions(String name
) {
86 final var recipientId
= resolveRecipient(name
);
88 synchronized (cachedSessions
) {
89 return getKeysLocked(recipientId
).stream()
90 // get all sessions for recipient except main device session
91 .filter(key
-> key
.getDeviceId() != 1 && key
.getRecipientId().equals(recipientId
))
92 .map(Key
::getDeviceId
)
93 .collect(Collectors
.toList());
98 public void storeSession(SignalProtocolAddress address
, SessionRecord session
) {
99 final var key
= getKey(address
);
101 synchronized (cachedSessions
) {
102 storeSessionLocked(key
, session
);
107 public boolean containsSession(SignalProtocolAddress address
) {
108 final var key
= getKey(address
);
110 synchronized (cachedSessions
) {
111 final var session
= loadSessionLocked(key
);
112 return isActive(session
);
117 public void deleteSession(SignalProtocolAddress address
) {
118 final var key
= getKey(address
);
120 synchronized (cachedSessions
) {
121 deleteSessionLocked(key
);
126 public void deleteAllSessions(String name
) {
127 final var recipientId
= resolveRecipient(name
);
128 deleteAllSessions(recipientId
);
131 public void deleteAllSessions(RecipientId recipientId
) {
132 synchronized (cachedSessions
) {
133 final var keys
= getKeysLocked(recipientId
);
134 for (var key
: keys
) {
135 deleteSessionLocked(key
);
141 public void archiveSession(final SignalProtocolAddress address
) {
142 final var key
= getKey(address
);
144 synchronized (cachedSessions
) {
145 archiveSessionLocked(key
);
150 public Set
<SignalProtocolAddress
> getAllAddressesWithActiveSessions(final List
<String
> addressNames
) {
151 final var recipientIdToNameMap
= addressNames
.stream()
152 .collect(Collectors
.toMap(this::resolveRecipient
, name
-> name
));
153 synchronized (cachedSessions
) {
154 return recipientIdToNameMap
.keySet()
156 .flatMap(recipientId
-> getKeysLocked(recipientId
).stream())
157 .filter(key
-> isActive(this.loadSessionLocked(key
)))
158 .map(key
-> new SignalProtocolAddress(recipientIdToNameMap
.get(key
.recipientId
), key
.getDeviceId()))
159 .collect(Collectors
.toSet());
163 public void archiveAllSessions() {
164 synchronized (cachedSessions
) {
165 final var keys
= getKeysLocked();
166 for (var key
: keys
) {
167 archiveSessionLocked(key
);
172 public void archiveSessions(final RecipientId recipientId
) {
173 synchronized (cachedSessions
) {
174 getKeysLocked().stream()
175 .filter(key
-> key
.recipientId
.equals(recipientId
))
176 .forEach(this::archiveSessionLocked
);
180 public void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
181 synchronized (cachedSessions
) {
182 final var keys
= getKeysLocked(toBeMergedRecipientId
);
183 final var otherHasSession
= keys
.size() > 0;
184 if (!otherHasSession
) {
188 final var hasSession
= getKeysLocked(recipientId
).size() > 0;
190 logger
.debug("To be merged recipient had sessions, deleting.");
191 deleteAllSessions(toBeMergedRecipientId
);
193 logger
.debug("Only to be merged recipient had sessions, re-assigning to the new recipient.");
194 for (var key
: keys
) {
195 final var session
= loadSessionLocked(key
);
196 deleteSessionLocked(key
);
197 if (session
== null) {
200 final var newKey
= new Key(recipientId
, key
.getDeviceId());
201 storeSessionLocked(newKey
, session
);
208 * @param identifier can be either a serialized uuid or a e164 phone number
210 private RecipientId
resolveRecipient(String identifier
) {
211 return resolver
.resolveRecipient(identifier
);
214 private Key
getKey(final SignalProtocolAddress address
) {
215 final var recipientId
= resolveRecipient(address
.getName());
216 return new Key(recipientId
, address
.getDeviceId());
219 private List
<Key
> getKeysLocked(RecipientId recipientId
) {
220 final var files
= sessionsPath
.listFiles((_file
, s
) -> s
.startsWith(recipientId
.getId() + "_"));
224 return parseFileNames(files
);
227 private Collection
<Key
> getKeysLocked() {
228 final var files
= sessionsPath
.listFiles();
232 return parseFileNames(files
);
235 final Pattern sessionFileNamePattern
= Pattern
.compile("([0-9]+)_([0-9]+)");
237 private List
<Key
> parseFileNames(final File
[] files
) {
238 return Arrays
.stream(files
)
239 .map(f
-> sessionFileNamePattern
.matcher(f
.getName()))
240 .filter(Matcher
::matches
)
241 .map(matcher
-> new Key(RecipientId
.of(Long
.parseLong(matcher
.group(1))),
242 Integer
.parseInt(matcher
.group(2))))
243 .collect(Collectors
.toList());
246 private File
getSessionFile(Key key
) {
248 IOUtils
.createPrivateDirectories(sessionsPath
);
249 } catch (IOException e
) {
250 throw new AssertionError("Failed to create sessions path", e
);
252 return new File(sessionsPath
, key
.getRecipientId().getId() + "_" + key
.getDeviceId());
255 private SessionRecord
loadSessionLocked(final Key key
) {
257 final var session
= cachedSessions
.get(key
);
258 if (session
!= null) {
263 final var file
= getSessionFile(key
);
264 if (!file
.exists()) {
267 try (var inputStream
= new FileInputStream(file
)) {
268 final var session
= new SessionRecord(inputStream
.readAllBytes());
269 cachedSessions
.put(key
, session
);
271 } catch (IOException e
) {
272 logger
.warn("Failed to load session, resetting session: {}", e
.getMessage());
277 private void storeSessionLocked(final Key key
, final SessionRecord session
) {
278 cachedSessions
.put(key
, session
);
280 final var file
= getSessionFile(key
);
282 try (var outputStream
= new FileOutputStream(file
)) {
283 outputStream
.write(session
.serialize());
285 } catch (IOException e
) {
286 logger
.warn("Failed to store session, trying to delete file and retry: {}", e
.getMessage());
288 Files
.delete(file
.toPath());
289 try (var outputStream
= new FileOutputStream(file
)) {
290 outputStream
.write(session
.serialize());
292 } catch (IOException e2
) {
293 logger
.error("Failed to store session file {}: {}", file
, e2
.getMessage());
298 private void archiveSessionLocked(final Key key
) {
299 final var session
= loadSessionLocked(key
);
300 if (session
== null) {
303 session
.archiveCurrentState();
304 storeSessionLocked(key
, session
);
307 private void deleteSessionLocked(final Key key
) {
308 cachedSessions
.remove(key
);
310 final var file
= getSessionFile(key
);
311 if (!file
.exists()) {
315 Files
.delete(file
.toPath());
316 } catch (IOException e
) {
317 logger
.error("Failed to delete session file {}: {}", file
, e
.getMessage());
321 private static boolean isActive(SessionRecord
record) {
322 return record != null
323 && record.hasSenderChain()
324 && record.getSessionVersion() == CiphertextMessage
.CURRENT_VERSION
;
327 private static final class Key
{
329 private final RecipientId recipientId
;
330 private final int deviceId
;
332 public Key(final RecipientId recipientId
, final int deviceId
) {
333 this.recipientId
= recipientId
;
334 this.deviceId
= deviceId
;
337 public RecipientId
getRecipientId() {
341 public int getDeviceId() {
346 public boolean equals(final Object o
) {
347 if (this == o
) return true;
348 if (o
== null || getClass() != o
.getClass()) return false;
350 final var key
= (Key
) o
;
352 if (deviceId
!= key
.deviceId
) return false;
353 return recipientId
.equals(key
.recipientId
);
357 public int hashCode() {
358 int result
= recipientId
.hashCode();
359 result
= 31 * result
+ deviceId
;