]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Main.java
b1822aafb02ad413e8f3f1bb1ac36c40f9b71768
[signal-cli] / src / main / java / cli / Main.java
1 /**
2 * Copyright (C) 2015 AsamK
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package cli;
18
19 import net.sourceforge.argparse4j.ArgumentParsers;
20 import net.sourceforge.argparse4j.impl.Arguments;
21 import net.sourceforge.argparse4j.inf.*;
22 import org.apache.commons.io.IOUtils;
23 import org.whispersystems.libaxolotl.InvalidMessageException;
24 import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
25 import org.whispersystems.textsecure.api.messages.*;
26 import org.whispersystems.textsecure.api.messages.multidevice.TextSecureSyncMessage;
27 import org.whispersystems.textsecure.api.push.TextSecureAddress;
28 import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
29 import org.whispersystems.textsecure.api.push.exceptions.NetworkFailureException;
30 import org.whispersystems.textsecure.api.push.exceptions.UnregisteredUserException;
31 import org.whispersystems.textsecure.api.util.InvalidNumberException;
32
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.nio.file.Files;
38 import java.nio.file.Paths;
39 import java.security.Security;
40 import java.util.ArrayList;
41 import java.util.List;
42
43 public class Main {
44
45 public static void main(String[] args) {
46 // Workaround for BKS truststore
47 Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
48
49 Namespace ns = parseArgs(args);
50 if (ns == null) {
51 System.exit(1);
52 }
53
54 final String username = ns.getString("username");
55 final Manager m = new Manager(username);
56 if (m.userExists()) {
57 try {
58 m.load();
59 } catch (Exception e) {
60 System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
61 System.exit(2);
62 }
63 }
64
65 switch (ns.getString("command")) {
66 case "register":
67 if (!m.userHasKeys()) {
68 m.createNewIdentity();
69 }
70 try {
71 m.register(ns.getBoolean("voice"));
72 } catch (IOException e) {
73 System.err.println("Request verify error: " + e.getMessage());
74 System.exit(3);
75 }
76 break;
77 case "verify":
78 if (!m.userHasKeys()) {
79 System.err.println("User has no keys, first call register.");
80 System.exit(1);
81 }
82 if (m.isRegistered()) {
83 System.err.println("User registration is already verified");
84 System.exit(1);
85 }
86 try {
87 m.verifyAccount(ns.getString("verificationCode"));
88 } catch (IOException e) {
89 System.err.println("Verify error: " + e.getMessage());
90 System.exit(3);
91 }
92 break;
93 case "send":
94 if (!m.isRegistered()) {
95 System.err.println("User is not registered.");
96 System.exit(1);
97 }
98 String messageText = ns.getString("message");
99 if (messageText == null) {
100 try {
101 messageText = IOUtils.toString(System.in);
102 } catch (IOException e) {
103 System.err.println("Failed to read message from stdin: " + e.getMessage());
104 System.exit(1);
105 }
106 }
107
108 final List<String> attachments = ns.getList("attachment");
109 List<TextSecureAttachment> textSecureAttachments = null;
110 if (attachments != null) {
111 textSecureAttachments = new ArrayList<>(attachments.size());
112 for (String attachment : attachments) {
113 try {
114 File attachmentFile = new File(attachment);
115 InputStream attachmentStream = new FileInputStream(attachmentFile);
116 final long attachmentSize = attachmentFile.length();
117 String mime = Files.probeContentType(Paths.get(attachment));
118 textSecureAttachments.add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null));
119 } catch (IOException e) {
120 System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage());
121 System.err.println("Aborting sending.");
122 System.exit(1);
123 }
124 }
125 }
126
127 List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size());
128 for (String recipient : ns.<String>getList("recipient")) {
129 try {
130 recipients.add(m.getPushAddress(recipient));
131 } catch (InvalidNumberException e) {
132 System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
133 System.err.println("Aborting sending.");
134 System.exit(1);
135 }
136 }
137 sendMessage(m, messageText, textSecureAttachments, recipients);
138 break;
139 case "receive":
140 if (!m.isRegistered()) {
141 System.err.println("User is not registered.");
142 System.exit(1);
143 }
144 try {
145 m.receiveMessages(5, true, new ReceiveMessageHandler(m));
146 } catch (IOException e) {
147 System.err.println("Error while receiving message: " + e.getMessage());
148 System.exit(3);
149 } catch (AssertionError e) {
150 System.err.println("Failed to receive message (Assertion): " + e.getMessage());
151 System.err.println(e.getStackTrace());
152 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
153 System.exit(1);
154 }
155 break;
156 }
157 m.save();
158 System.exit(0);
159 }
160
161 private static Namespace parseArgs(String[] args) {
162 ArgumentParser parser = ArgumentParsers.newArgumentParser("textsecure-cli")
163 .defaultHelp(true)
164 .description("Commandline interface for TextSecure.");
165 Subparsers subparsers = parser.addSubparsers()
166 .title("subcommands")
167 .dest("command")
168 .description("valid subcommands")
169 .help("additional help");
170
171 Subparser parserRegister = subparsers.addParser("register");
172 parserRegister.addArgument("-v", "--voice")
173 .help("The verification should be done over voice, not sms.")
174 .action(Arguments.storeTrue());
175
176 Subparser parserVerify = subparsers.addParser("verify");
177 parserVerify.addArgument("verificationCode")
178 .help("The verification code you received via sms or voice call.");
179
180 Subparser parserSend = subparsers.addParser("send");
181 parserSend.addArgument("recipient")
182 .help("Specify the recipients' phone number.")
183 .nargs("*");
184 parserSend.addArgument("-m", "--message")
185 .help("Specify the message, if missing standard input is used.");
186 parserSend.addArgument("-a", "--attachment")
187 .nargs("*")
188 .help("Add file as attachment");
189
190 Subparser parserReceive = subparsers.addParser("receive");
191 parser.addArgument("-u", "--username")
192 .required(true)
193 .help("Specify your phone number, that will be used for verification.");
194
195 try {
196 return parser.parseArgs(args);
197 } catch (ArgumentParserException e) {
198 parser.handleError(e);
199 return null;
200 }
201 }
202
203 private static void sendMessage(Manager m, String messageText, List<TextSecureAttachment> textSecureAttachments,
204 List<TextSecureAddress> recipients) {
205 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
206 if (textSecureAttachments != null) {
207 messageBuilder.withAttachments(textSecureAttachments);
208 }
209 TextSecureDataMessage message = messageBuilder.build();
210
211 try {
212 m.sendMessage(recipients, message);
213 } catch (IOException e) {
214 System.err.println("Failed to send message: " + e.getMessage());
215 } catch (EncapsulatedExceptions e) {
216 System.err.println("Failed to send (some) messages:");
217 for (NetworkFailureException n : e.getNetworkExceptions()) {
218 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
219 }
220 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
221 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
222 }
223 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
224 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
225 }
226 } catch (AssertionError e) {
227 System.err.println("Failed to send message (Assertion): " + e.getMessage());
228 System.err.println(e.getStackTrace());
229 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
230 System.exit(1);
231 }
232 }
233
234 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
235 final Manager m;
236
237 public ReceiveMessageHandler(Manager m) {
238 this.m = m;
239 }
240
241 @Override
242 public void handleMessage(TextSecureEnvelope envelope) {
243 System.out.println("Envelope from: " + envelope.getSource());
244 System.out.println("Timestamp: " + envelope.getTimestamp());
245
246 if (envelope.isReceipt()) {
247 System.out.println("Got receipt.");
248 } else if (envelope.isWhisperMessage() | envelope.isPreKeyWhisperMessage()) {
249 TextSecureContent content = m.decryptMessage(envelope);
250
251 if (content == null) {
252 System.out.println("Failed to decrypt message.");
253 } else {
254 if (content.getDataMessage().isPresent()) {
255 TextSecureDataMessage message = content.getDataMessage().get();
256 System.out.println("Body: " + message.getBody().get());
257
258 if (message.isEndSession()) {
259 m.handleEndSession(envelope.getSource());
260 } else if (message.getAttachments().isPresent()) {
261 System.out.println("Attachments: ");
262 for (TextSecureAttachment attachment : message.getAttachments().get()) {
263 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
264 if (attachment.isPointer()) {
265 final TextSecureAttachmentPointer pointer = attachment.asPointer();
266 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : ""));
267 System.out.println((pointer.getSize().isPresent() ? " Size: " + pointer.getSize().get() : " bytes") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
268 try {
269 File file = m.retrieveAttachment(pointer);
270 System.out.println(" Stored plaintext in: " + file);
271 } catch (IOException | InvalidMessageException e) {
272 System.out.println("Failed to retrieve attachment: " + e.getMessage());
273 }
274 }
275 }
276 }
277 }
278 if (content.getSyncMessage().isPresent()) {
279 TextSecureSyncMessage syncMessage = content.getSyncMessage().get();
280 System.out.println("Received sync message");
281 }
282 }
283 } else {
284 System.out.println("Unknown message received.");
285 }
286 System.out.println();
287 }
288 }
289 }