]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Main.java
c4a6a4c0eec0b40a120e6cae58e31b1587e720ba
[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
99 TextSecureGroup group = null;
100 List<String> recipients = null;
101 if (ns.getString("group") != null) {
102 try {
103 GroupInfo g = m.getGroupInfo(Base64.decode(ns.getString("group")));
104 if (g == null) {
105 System.err.println("Failed to send to grup \"" + ns.getString("group") + "\": Unknown group");
106 System.err.println("Aborting sending.");
107 System.exit(1);
108 }
109 group = new TextSecureGroup(g.groupId);
110 recipients = g.members;
111 } catch (IOException e) {
112 System.err.println("Failed to send to grup \"" + ns.getString("group") + "\": " + e.getMessage());
113 System.err.println("Aborting sending.");
114 System.exit(1);
115 }
116 } else {
117 recipients = ns.<String>getList("recipient");
118 }
119
120 if (ns.getBoolean("endsession")) {
121 sendEndSessionMessage(m, recipients);
122 } else {
123 final List<String> attachments = ns.getList("attachment");
124 List<TextSecureAttachment> textSecureAttachments = null;
125 if (attachments != null) {
126 textSecureAttachments = new ArrayList<>(attachments.size());
127 for (String attachment : attachments) {
128 try {
129 File attachmentFile = new File(attachment);
130 InputStream attachmentStream = new FileInputStream(attachmentFile);
131 final long attachmentSize = attachmentFile.length();
132 String mime = Files.probeContentType(Paths.get(attachment));
133 textSecureAttachments.add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null));
134 } catch (IOException e) {
135 System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage());
136 System.err.println("Aborting sending.");
137 System.exit(1);
138 }
139 }
140 }
141
142 String messageText = ns.getString("message");
143 if (messageText == null) {
144 try {
145 messageText = IOUtils.toString(System.in);
146 } catch (IOException e) {
147 System.err.println("Failed to read message from stdin: " + e.getMessage());
148 System.err.println("Aborting sending.");
149 System.exit(1);
150 }
151 }
152
153 sendMessage(m, messageText, textSecureAttachments, recipients, group);
154 }
155
156 break;
157 case "receive":
158 if (!m.isRegistered()) {
159 System.err.println("User is not registered.");
160 System.exit(1);
161 }
162 int timeout = 5;
163 if (ns.getInt("timeout") != null) {
164 timeout = ns.getInt("timeout");
165 }
166 boolean returnOnTimeout = true;
167 if (timeout < 0) {
168 returnOnTimeout = false;
169 timeout = 3600;
170 }
171 try {
172 m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
173 } catch (IOException e) {
174 System.err.println("Error while receiving message: " + e.getMessage());
175 System.exit(3);
176 } catch (AssertionError e) {
177 System.err.println("Failed to receive message (Assertion): " + e.getMessage());
178 System.err.println(e.getStackTrace());
179 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
180 System.exit(1);
181 }
182 break;
183 }
184 m.save();
185 System.exit(0);
186 }
187
188 private static Namespace parseArgs(String[] args) {
189 ArgumentParser parser = ArgumentParsers.newArgumentParser("textsecure-cli")
190 .defaultHelp(true)
191 .description("Commandline interface for TextSecure.")
192 .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION);
193
194 parser.addArgument("-u", "--username")
195 .help("Specify your phone number, that will be used for verification.");
196 parser.addArgument("-v", "--version")
197 .help("Show package version.")
198 .action(Arguments.version());
199
200 Subparsers subparsers = parser.addSubparsers()
201 .title("subcommands")
202 .dest("command")
203 .description("valid subcommands")
204 .help("additional help");
205
206 Subparser parserRegister = subparsers.addParser("register");
207 parserRegister.addArgument("-v", "--voice")
208 .help("The verification should be done over voice, not sms.")
209 .action(Arguments.storeTrue());
210
211 Subparser parserVerify = subparsers.addParser("verify");
212 parserVerify.addArgument("verificationCode")
213 .help("The verification code you received via sms or voice call.");
214
215 Subparser parserSend = subparsers.addParser("send");
216 parserSend.addArgument("-g", "--group")
217 .help("Specify the recipient group ID.");
218 parserSend.addArgument("recipient")
219 .help("Specify the recipients' phone number.")
220 .nargs("*");
221 parserSend.addArgument("-m", "--message")
222 .help("Specify the message, if missing standard input is used.");
223 parserSend.addArgument("-a", "--attachment")
224 .nargs("*")
225 .help("Add file as attachment");
226 parserSend.addArgument("-e", "--endsession")
227 .help("Clear session state and send end session message.")
228 .action(Arguments.storeTrue());
229
230 Subparser parserReceive = subparsers.addParser("receive");
231 parserReceive.addArgument("-t", "--timeout")
232 .type(int.class)
233 .help("Number of seconds to wait for new messages (negative values disable timeout)");
234
235 try {
236 Namespace ns = parser.parseArgs(args);
237 if (ns.getString("username") == null) {
238 parser.printUsage();
239 System.err.println("You need to specify a username (phone number)");
240 System.exit(2);
241 }
242 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
243 System.err.println("You cannot specify recipients by phone number and groups a the same time");
244 System.exit(2);
245 }
246 return ns;
247 } catch (ArgumentParserException e) {
248 parser.handleError(e);
249 return null;
250 }
251 }
252
253 private static void sendMessage(Manager m, String messageText, List<TextSecureAttachment> textSecureAttachments,
254 List<String> recipients, TextSecureGroup group) {
255 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
256 if (textSecureAttachments != null) {
257 messageBuilder.withAttachments(textSecureAttachments);
258 }
259 if (group != null) {
260 messageBuilder.asGroupMessage(group);
261 }
262 TextSecureDataMessage message = messageBuilder.build();
263
264 sendMessage(m, message, recipients);
265 }
266
267 private static void sendEndSessionMessage(Manager m, List<String> recipients) {
268 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().asEndSessionMessage();
269
270 TextSecureDataMessage message = messageBuilder.build();
271
272 sendMessage(m, message, recipients);
273 }
274
275 private static void sendMessage(Manager m, TextSecureDataMessage message, List<String> recipients) {
276 try {
277 m.sendMessage(recipients, message);
278 } catch (IOException e) {
279 System.err.println("Failed to send message: " + e.getMessage());
280 } catch (EncapsulatedExceptions e) {
281 System.err.println("Failed to send (some) messages:");
282 for (NetworkFailureException n : e.getNetworkExceptions()) {
283 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
284 }
285 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
286 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
287 }
288 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
289 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
290 }
291 } catch (AssertionError e) {
292 System.err.println("Failed to send message (Assertion): " + e.getMessage());
293 System.err.println(e.getStackTrace());
294 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
295 System.exit(1);
296 }
297 }
298
299 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
300 final Manager m;
301
302 public ReceiveMessageHandler(Manager m) {
303 this.m = m;
304 }
305
306 @Override
307 public void handleMessage(TextSecureEnvelope envelope, TextSecureContent content, GroupInfo group) {
308 System.out.println("Envelope from: " + envelope.getSource());
309 System.out.println("Timestamp: " + envelope.getTimestamp());
310
311 if (envelope.isReceipt()) {
312 System.out.println("Got receipt.");
313 } else if (envelope.isWhisperMessage() | envelope.isPreKeyWhisperMessage()) {
314 if (content == null) {
315 System.out.println("Failed to decrypt message.");
316 } else {
317 if (content.getDataMessage().isPresent()) {
318 TextSecureDataMessage message = content.getDataMessage().get();
319
320 System.out.println("Message timestamp: " + message.getTimestamp());
321
322 if (message.getBody().isPresent()) {
323 System.out.println("Body: " + message.getBody().get());
324 }
325 if (message.getGroupInfo().isPresent()) {
326 TextSecureGroup groupInfo = message.getGroupInfo().get();
327 System.out.println("Group info:");
328 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
329 if (groupInfo.getName().isPresent()) {
330 System.out.println(" Name: " + groupInfo.getName().get());
331 } else if (group != null) {
332 System.out.println(" Name: " + group.name);
333 } else {
334 System.out.println(" Name: <Unknown group>");
335 }
336 System.out.println(" Type: " + groupInfo.getType());
337 if (groupInfo.getMembers().isPresent()) {
338 for (String member : groupInfo.getMembers().get()) {
339 System.out.println(" Member: " + member);
340 }
341 }
342 if (groupInfo.getAvatar().isPresent()) {
343 System.out.println(" Avatar:");
344 printAttachment(groupInfo.getAvatar().get());
345 }
346 }
347 if (message.isEndSession()) {
348 System.out.println("Is end session");
349 }
350
351 if (message.getAttachments().isPresent()) {
352 System.out.println("Attachments: ");
353 for (TextSecureAttachment attachment : message.getAttachments().get()) {
354 printAttachment(attachment);
355 }
356 }
357 }
358 if (content.getSyncMessage().isPresent()) {
359 TextSecureSyncMessage syncMessage = content.getSyncMessage().get();
360 System.out.println("Received sync message");
361 }
362 }
363 } else {
364 System.out.println("Unknown message received.");
365 }
366 System.out.println();
367 }
368
369 private void printAttachment(TextSecureAttachment attachment) {
370 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
371 if (attachment.isPointer()) {
372 final TextSecureAttachmentPointer pointer = attachment.asPointer();
373 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : ""));
374 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
375 File file = m.getAttachmentFile(pointer.getId());
376 if (file.exists()) {
377 System.out.println(" Stored plaintext in: " + file);
378 }
379 }
380 }
381 }
382 }