1 package org
.asamk
.signal
.manager
;
3 import org
.asamk
.signal
.AttachmentInvalidException
;
4 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
5 import org
.whispersystems
.libsignal
.IdentityKey
;
6 import org
.whispersystems
.libsignal
.InvalidKeyException
;
7 import org
.whispersystems
.libsignal
.ecc
.Curve
;
8 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
9 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
10 import org
.whispersystems
.libsignal
.fingerprint
.NumericFingerprintGenerator
;
11 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
12 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
13 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
14 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
15 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
16 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
17 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
18 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
19 import org
.whispersystems
.util
.Base64
;
21 import java
.io
.BufferedInputStream
;
22 import java
.io
.DataInputStream
;
23 import java
.io
.DataOutputStream
;
25 import java
.io
.FileInputStream
;
26 import java
.io
.FileNotFoundException
;
27 import java
.io
.FileOutputStream
;
28 import java
.io
.IOException
;
29 import java
.io
.InputStream
;
30 import java
.io
.OutputStream
;
31 import java
.io
.UnsupportedEncodingException
;
33 import java
.net
.URLConnection
;
34 import java
.net
.URLDecoder
;
35 import java
.net
.URLEncoder
;
36 import java
.nio
.file
.Files
;
37 import java
.util
.ArrayList
;
38 import java
.util
.Collection
;
39 import java
.util
.HashMap
;
40 import java
.util
.HashSet
;
41 import java
.util
.List
;
45 import static org
.whispersystems
.signalservice
.internal
.util
.Util
.isEmpty
;
49 static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
50 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
51 if (attachments
!= null) {
52 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
53 for (String attachment
: attachments
) {
55 SignalServiceAttachments
.add(createAttachment(new File(attachment
)));
56 } catch (IOException e
) {
57 throw new AttachmentInvalidException(attachment
, e
);
61 return SignalServiceAttachments
;
64 private static String
getFileMimeType(File file
) throws IOException
{
65 String mime
= Files
.probeContentType(file
.toPath());
67 try (InputStream bufferedStream
= new BufferedInputStream(new FileInputStream(file
))) {
68 mime
= URLConnection
.guessContentTypeFromStream(bufferedStream
);
72 mime
= "application/octet-stream";
77 static SignalServiceAttachmentStream
createAttachment(File attachmentFile
) throws IOException
{
78 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
79 final long attachmentSize
= attachmentFile
.length();
80 final String mime
= getFileMimeType(attachmentFile
);
81 // TODO mabybe add a parameter to set the voiceNote, preview, width, height and caption option
82 Optional
<byte[]> preview
= Optional
.absent();
83 Optional
<String
> caption
= Optional
.absent();
84 Optional
<String
> blurHash
= Optional
.absent();
85 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, Optional
.of(attachmentFile
.getName()), false, preview
, 0, 0, caption
, blurHash
, null);
88 static StreamDetails
createStreamDetailsFromFile(File file
) throws IOException
{
89 InputStream stream
= new FileInputStream(file
);
90 final long size
= file
.length();
91 String mime
= Files
.probeContentType(file
.toPath());
93 mime
= "application/octet-stream";
95 return new StreamDetails(stream
, mime
, size
);
98 static CertificateValidator
getCertificateValidator() {
100 ECPublicKey unidentifiedSenderTrustRoot
= Curve
.decodePoint(Base64
.decode(BaseConfig
.UNIDENTIFIED_SENDER_TRUST_ROOT
), 0);
101 return new CertificateValidator(unidentifiedSenderTrustRoot
);
102 } catch (InvalidKeyException
| IOException e
) {
103 throw new AssertionError(e
);
107 private static Map
<String
, String
> getQueryMap(String query
) {
108 String
[] params
= query
.split("&");
109 Map
<String
, String
> map
= new HashMap
<>();
110 for (String param
: params
) {
112 final String
[] paramParts
= param
.split("=");
114 name
= URLDecoder
.decode(paramParts
[0], "utf-8");
115 } catch (UnsupportedEncodingException e
) {
120 value
= URLDecoder
.decode(paramParts
[1], "utf-8");
121 } catch (UnsupportedEncodingException e
) {
124 map
.put(name
, value
);
129 static String
createDeviceLinkUri(DeviceLinkInfo info
) {
131 return "tsdevice:/?uuid=" + URLEncoder
.encode(info
.deviceIdentifier
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(info
.deviceKey
.serialize()), "utf-8");
132 } catch (UnsupportedEncodingException e
) {
138 static DeviceLinkInfo
parseDeviceLinkUri(URI linkUri
) throws IOException
, InvalidKeyException
{
139 Map
<String
, String
> query
= getQueryMap(linkUri
.getRawQuery());
140 String deviceIdentifier
= query
.get("uuid");
141 String publicKeyEncoded
= query
.get("pub_key");
143 if (isEmpty(deviceIdentifier
) || isEmpty(publicKeyEncoded
)) {
144 throw new RuntimeException("Invalid device link uri");
147 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
149 return new DeviceLinkInfo(deviceIdentifier
, deviceKey
);
152 static Set
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> recipients
, String localNumber
) {
153 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
154 for (String recipient
: recipients
) {
156 recipientsTS
.add(getPushAddress(recipient
, localNumber
));
157 } catch (InvalidNumberException e
) {
158 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
159 System
.err
.println("Aborting sending.");
166 static String
canonicalizeNumber(String number
, String localNumber
) throws InvalidNumberException
{
167 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
170 private static SignalServiceAddress
getPushAddress(String number
, String localNumber
) throws InvalidNumberException
{
171 String e164number
= canonicalizeNumber(number
, localNumber
);
172 return new SignalServiceAddress(null, e164number
);
175 static SignalServiceEnvelope
loadEnvelope(File file
) throws IOException
{
176 try (FileInputStream f
= new FileInputStream(file
)) {
177 DataInputStream
in = new DataInputStream(f
);
178 int version
= in.readInt();
182 int type
= in.readInt();
183 String source
= in.readUTF();
184 int sourceDevice
= in.readInt();
186 // read legacy relay field
189 long timestamp
= in.readLong();
190 byte[] content
= null;
191 int contentLen
= in.readInt();
192 if (contentLen
> 0) {
193 content
= new byte[contentLen
];
194 in.readFully(content
);
196 byte[] legacyMessage
= null;
197 int legacyMessageLen
= in.readInt();
198 if (legacyMessageLen
> 0) {
199 legacyMessage
= new byte[legacyMessageLen
];
200 in.readFully(legacyMessage
);
202 long serverTimestamp
= 0;
205 serverTimestamp
= in.readLong();
207 if ("".equals(uuid
)) {
211 return new SignalServiceEnvelope(type
, Optional
.of(new SignalServiceAddress(null, source
)), sourceDevice
, timestamp
, legacyMessage
, content
, serverTimestamp
, uuid
);
215 static void storeEnvelope(SignalServiceEnvelope envelope
, File file
) throws IOException
{
216 try (FileOutputStream f
= new FileOutputStream(file
)) {
217 try (DataOutputStream out
= new DataOutputStream(f
)) {
218 out
.writeInt(2); // version
219 out
.writeInt(envelope
.getType());
220 out
.writeUTF(envelope
.getSourceE164().get());
221 out
.writeInt(envelope
.getSourceDevice());
222 out
.writeLong(envelope
.getTimestamp());
223 if (envelope
.hasContent()) {
224 out
.writeInt(envelope
.getContent().length
);
225 out
.write(envelope
.getContent());
229 if (envelope
.hasLegacyMessage()) {
230 out
.writeInt(envelope
.getLegacyMessage().length
);
231 out
.write(envelope
.getLegacyMessage());
235 out
.writeLong(envelope
.getServerTimestamp());
236 String uuid
= envelope
.getUuid();
237 out
.writeUTF(uuid
== null ?
"" : uuid
);
242 static File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
{
243 InputStream input
= stream
.getInputStream();
245 try (OutputStream output
= new FileOutputStream(outputFile
)) {
246 byte[] buffer
= new byte[4096];
249 while ((read
= input
.read(buffer
)) != -1) {
250 output
.write(buffer
, 0, read
);
252 } catch (FileNotFoundException e
) {
259 static String
computeSafetyNumber(String ownUsername
, IdentityKey ownIdentityKey
, String theirUsername
, IdentityKey theirIdentityKey
) {
260 Fingerprint fingerprint
= new NumericFingerprintGenerator(5200).createFor(1, ownUsername
.getBytes(), ownIdentityKey
, theirUsername
.getBytes(), theirIdentityKey
);
261 return fingerprint
.getDisplayableFingerprint().getDisplayText();
264 static class DeviceLinkInfo
{
266 final String deviceIdentifier
;
267 final ECPublicKey deviceKey
;
269 DeviceLinkInfo(final String deviceIdentifier
, final ECPublicKey deviceKey
) {
270 this.deviceIdentifier
= deviceIdentifier
;
271 this.deviceKey
= deviceKey
;