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
.asamk
.signal
.manager
.util
.Utils
;
7 import org
.slf4j
.Logger
;
8 import org
.slf4j
.LoggerFactory
;
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
.regex
.Matcher
;
25 import java
.util
.regex
.Pattern
;
26 import java
.util
.stream
.Collectors
;
28 public class SessionStore
implements SignalServiceSessionStore
{
30 private final static Logger logger
= LoggerFactory
.getLogger(SessionStore
.class);
32 private final Map
<Key
, SessionRecord
> cachedSessions
= new HashMap
<>();
34 private final File sessionsPath
;
36 private final RecipientResolver resolver
;
39 final File sessionsPath
, final RecipientResolver resolver
41 this.sessionsPath
= sessionsPath
;
42 this.resolver
= resolver
;
46 public SessionRecord
loadSession(SignalProtocolAddress address
) {
47 final var key
= getKey(address
);
49 synchronized (cachedSessions
) {
50 final var session
= loadSessionLocked(key
);
51 if (session
== null) {
52 return new SessionRecord();
59 public List
<Integer
> getSubDeviceSessions(String name
) {
60 final var recipientId
= resolveRecipient(name
);
62 synchronized (cachedSessions
) {
63 return getKeysLocked(recipientId
).stream()
64 // get all sessions for recipient except main device session
65 .filter(key
-> key
.getDeviceId() != 1 && key
.getRecipientId().equals(recipientId
))
66 .map(Key
::getDeviceId
)
67 .collect(Collectors
.toList());
72 public void storeSession(SignalProtocolAddress address
, SessionRecord session
) {
73 final var key
= getKey(address
);
75 synchronized (cachedSessions
) {
76 storeSessionLocked(key
, session
);
81 public boolean containsSession(SignalProtocolAddress address
) {
82 final var key
= getKey(address
);
84 synchronized (cachedSessions
) {
85 final var session
= loadSessionLocked(key
);
86 if (session
== null) {
90 return session
.hasSenderChain() && session
.getSessionVersion() == CiphertextMessage
.CURRENT_VERSION
;
95 public void deleteSession(SignalProtocolAddress address
) {
96 final var key
= getKey(address
);
98 synchronized (cachedSessions
) {
99 deleteSessionLocked(key
);
104 public void deleteAllSessions(String name
) {
105 final var recipientId
= resolveRecipient(name
);
106 deleteAllSessions(recipientId
);
109 public void deleteAllSessions(RecipientId recipientId
) {
110 synchronized (cachedSessions
) {
111 final var keys
= getKeysLocked(recipientId
);
112 for (var key
: keys
) {
113 deleteSessionLocked(key
);
119 public void archiveSession(final SignalProtocolAddress address
) {
120 final var key
= getKey(address
);
122 synchronized (cachedSessions
) {
123 archiveSessionLocked(key
);
127 public void archiveAllSessions() {
128 synchronized (cachedSessions
) {
129 final var keys
= getKeysLocked();
130 for (var key
: keys
) {
131 archiveSessionLocked(key
);
136 public void archiveSessions(final RecipientId recipientId
) {
137 synchronized (cachedSessions
) {
138 getKeysLocked().stream()
139 .filter(key
-> key
.recipientId
.equals(recipientId
))
140 .forEach(this::archiveSessionLocked
);
144 public void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
145 synchronized (cachedSessions
) {
146 final var otherHasSession
= getKeysLocked(toBeMergedRecipientId
).size() > 0;
147 if (!otherHasSession
) {
151 final var hasSession
= getKeysLocked(recipientId
).size() > 0;
153 logger
.debug("To be merged recipient had sessions, deleting.");
154 deleteAllSessions(toBeMergedRecipientId
);
156 logger
.debug("To be merged recipient had sessions, re-assigning to the new recipient.");
157 final var keys
= getKeysLocked(toBeMergedRecipientId
);
158 for (var key
: keys
) {
159 final var session
= loadSessionLocked(key
);
160 deleteSessionLocked(key
);
161 if (session
== null) {
164 final var newKey
= new Key(recipientId
, key
.getDeviceId());
165 storeSessionLocked(newKey
, session
);
172 * @param identifier can be either a serialized uuid or a e164 phone number
174 private RecipientId
resolveRecipient(String identifier
) {
175 return resolver
.resolveRecipient(Utils
.getSignalServiceAddressFromIdentifier(identifier
));
178 private Key
getKey(final SignalProtocolAddress address
) {
179 final var recipientId
= resolveRecipient(address
.getName());
180 return new Key(recipientId
, address
.getDeviceId());
183 private List
<Key
> getKeysLocked(RecipientId recipientId
) {
184 final var files
= sessionsPath
.listFiles((_file
, s
) -> s
.startsWith(recipientId
.getId() + "_"));
188 return parseFileNames(files
);
191 private Collection
<Key
> getKeysLocked() {
192 final var files
= sessionsPath
.listFiles();
196 return parseFileNames(files
);
199 final Pattern sessionFileNamePattern
= Pattern
.compile("([0-9]+)_([0-9]+)");
201 private List
<Key
> parseFileNames(final File
[] files
) {
202 return Arrays
.stream(files
)
203 .map(f
-> sessionFileNamePattern
.matcher(f
.getName()))
204 .filter(Matcher
::matches
)
205 .map(matcher
-> new Key(RecipientId
.of(Long
.parseLong(matcher
.group(1))),
206 Integer
.parseInt(matcher
.group(2))))
207 .collect(Collectors
.toList());
210 private File
getSessionFile(Key key
) {
212 IOUtils
.createPrivateDirectories(sessionsPath
);
213 } catch (IOException e
) {
214 throw new AssertionError("Failed to create sessions path", e
);
216 return new File(sessionsPath
, key
.getRecipientId().getId() + "_" + key
.getDeviceId());
219 private SessionRecord
loadSessionLocked(final Key key
) {
221 final var session
= cachedSessions
.get(key
);
222 if (session
!= null) {
227 final var file
= getSessionFile(key
);
228 if (!file
.exists()) {
231 try (var inputStream
= new FileInputStream(file
)) {
232 final var session
= new SessionRecord(inputStream
.readAllBytes());
233 cachedSessions
.put(key
, session
);
235 } catch (IOException e
) {
236 logger
.warn("Failed to load session, resetting session: {}", e
.getMessage());
241 private void storeSessionLocked(final Key key
, final SessionRecord session
) {
242 cachedSessions
.put(key
, session
);
244 final var file
= getSessionFile(key
);
246 try (var outputStream
= new FileOutputStream(file
)) {
247 outputStream
.write(session
.serialize());
249 } catch (IOException e
) {
250 logger
.warn("Failed to store session, trying to delete file and retry: {}", e
.getMessage());
252 Files
.delete(file
.toPath());
253 try (var outputStream
= new FileOutputStream(file
)) {
254 outputStream
.write(session
.serialize());
256 } catch (IOException e2
) {
257 logger
.error("Failed to store session file {}: {}", file
, e2
.getMessage());
262 private void archiveSessionLocked(final Key key
) {
263 final var session
= loadSessionLocked(key
);
264 if (session
== null) {
267 session
.archiveCurrentState();
268 storeSessionLocked(key
, session
);
271 private void deleteSessionLocked(final Key key
) {
272 cachedSessions
.remove(key
);
274 final var file
= getSessionFile(key
);
275 if (!file
.exists()) {
279 Files
.delete(file
.toPath());
280 } catch (IOException e
) {
281 logger
.error("Failed to delete session file {}: {}", file
, e
.getMessage());
285 private static final class Key
{
287 private final RecipientId recipientId
;
288 private final int deviceId
;
290 public Key(final RecipientId recipientId
, final int deviceId
) {
291 this.recipientId
= recipientId
;
292 this.deviceId
= deviceId
;
295 public RecipientId
getRecipientId() {
299 public int getDeviceId() {
304 public boolean equals(final Object o
) {
305 if (this == o
) return true;
306 if (o
== null || getClass() != o
.getClass()) return false;
308 final var key
= (Key
) o
;
310 if (deviceId
!= key
.deviceId
) return false;
311 return recipientId
.equals(key
.recipientId
);
315 public int hashCode() {
316 int result
= recipientId
.hashCode();
317 result
= 31 * result
+ deviceId
;