]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Main.java
85ca227d987744cdb07a71fe5a20731dd050c920
[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 int timeout = 5;
145 if (ns.getInt("timeout") != null) {
146 timeout = ns.getInt("timeout");
147 }
148 boolean returnOnTimeout = true;
149 if (timeout < 0) {
150 returnOnTimeout = false;
151 timeout = 3600;
152 }
153 try {
154 m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
155 } catch (IOException e) {
156 System.err.println("Error while receiving message: " + e.getMessage());
157 System.exit(3);
158 } catch (AssertionError e) {
159 System.err.println("Failed to receive message (Assertion): " + e.getMessage());
160 System.err.println(e.getStackTrace());
161 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
162 System.exit(1);
163 }
164 break;
165 }
166 m.save();
167 System.exit(0);
168 }
169
170 private static Namespace parseArgs(String[] args) {
171 ArgumentParser parser = ArgumentParsers.newArgumentParser("textsecure-cli")
172 .defaultHelp(true)
173 .description("Commandline interface for TextSecure.")
174 .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION);
175
176 parser.addArgument("-u", "--username")
177 .help("Specify your phone number, that will be used for verification.");
178 parser.addArgument("-v", "--version")
179 .help("Show package version.")
180 .action(Arguments.version());
181
182 Subparsers subparsers = parser.addSubparsers()
183 .title("subcommands")
184 .dest("command")
185 .description("valid subcommands")
186 .help("additional help");
187
188 Subparser parserRegister = subparsers.addParser("register");
189 parserRegister.addArgument("-v", "--voice")
190 .help("The verification should be done over voice, not sms.")
191 .action(Arguments.storeTrue());
192
193 Subparser parserVerify = subparsers.addParser("verify");
194 parserVerify.addArgument("verificationCode")
195 .help("The verification code you received via sms or voice call.");
196
197 Subparser parserSend = subparsers.addParser("send");
198 parserSend.addArgument("recipient")
199 .help("Specify the recipients' phone number.")
200 .nargs("*");
201 parserSend.addArgument("-m", "--message")
202 .help("Specify the message, if missing standard input is used.");
203 parserSend.addArgument("-a", "--attachment")
204 .nargs("*")
205 .help("Add file as attachment");
206
207 Subparser parserReceive = subparsers.addParser("receive");
208 parserReceive.addArgument("-t", "--timeout")
209 .type(int.class)
210 .help("Number of seconds to wait for new messages (negative values disable timeout)");
211
212 try {
213 Namespace ns = parser.parseArgs(args);
214 if (ns.getString("username") == null) {
215 parser.printUsage();
216 System.err.println("You need to specify a username (phone number)");
217 System.exit(2);
218 }
219 return ns;
220 } catch (ArgumentParserException e) {
221 parser.handleError(e);
222 return null;
223 }
224 }
225
226 private static void sendMessage(Manager m, String messageText, List<TextSecureAttachment> textSecureAttachments,
227 List<TextSecureAddress> recipients) {
228 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
229 if (textSecureAttachments != null) {
230 messageBuilder.withAttachments(textSecureAttachments);
231 }
232 TextSecureDataMessage message = messageBuilder.build();
233
234 try {
235 m.sendMessage(recipients, message);
236 } catch (IOException e) {
237 System.err.println("Failed to send message: " + e.getMessage());
238 } catch (EncapsulatedExceptions e) {
239 System.err.println("Failed to send (some) messages:");
240 for (NetworkFailureException n : e.getNetworkExceptions()) {
241 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
242 }
243 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
244 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
245 }
246 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
247 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
248 }
249 } catch (AssertionError e) {
250 System.err.println("Failed to send message (Assertion): " + e.getMessage());
251 System.err.println(e.getStackTrace());
252 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
253 System.exit(1);
254 }
255 }
256
257 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
258 final Manager m;
259
260 public ReceiveMessageHandler(Manager m) {
261 this.m = m;
262 }
263
264 @Override
265 public void handleMessage(TextSecureEnvelope envelope, TextSecureContent content, GroupInfo group) {
266 System.out.println("Envelope from: " + envelope.getSource());
267 System.out.println("Timestamp: " + envelope.getTimestamp());
268
269 if (envelope.isReceipt()) {
270 System.out.println("Got receipt.");
271 } else if (envelope.isWhisperMessage() | envelope.isPreKeyWhisperMessage()) {
272 if (content == null) {
273 System.out.println("Failed to decrypt message.");
274 } else {
275 if (content.getDataMessage().isPresent()) {
276 TextSecureDataMessage message = content.getDataMessage().get();
277
278 System.out.println("Message timestamp: " + message.getTimestamp());
279
280 if (message.getBody().isPresent()) {
281 System.out.println("Body: " + message.getBody().get());
282 }
283 if (message.getGroupInfo().isPresent()) {
284 TextSecureGroup groupInfo = message.getGroupInfo().get();
285 System.out.println("Group info:");
286 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
287 if (groupInfo.getName().isPresent()) {
288 System.out.println(" Name: " + groupInfo.getName().get());
289 } else if (group != null) {
290 System.out.println(" Name: " + group.name);
291 } else {
292 System.out.println(" Name: <Unknown group>");
293 }
294 System.out.println(" Type: " + groupInfo.getType());
295 if (groupInfo.getMembers().isPresent()) {
296 for (String member : groupInfo.getMembers().get()) {
297 System.out.println(" Member: " + member);
298 }
299 }
300 if (groupInfo.getAvatar().isPresent()) {
301 System.out.println(" Avatar:");
302 printAttachment(groupInfo.getAvatar().get());
303 }
304 }
305 if (message.isEndSession()) {
306 System.out.println("Is end session");
307 m.handleEndSession(envelope.getSource());
308 }
309
310 if (message.getAttachments().isPresent()) {
311 System.out.println("Attachments: ");
312 for (TextSecureAttachment attachment : message.getAttachments().get()) {
313 printAttachment(attachment);
314 }
315 }
316 }
317 if (content.getSyncMessage().isPresent()) {
318 TextSecureSyncMessage syncMessage = content.getSyncMessage().get();
319 System.out.println("Received sync message");
320 }
321 }
322 } else {
323 System.out.println("Unknown message received.");
324 }
325 System.out.println();
326 }
327
328 private void printAttachment(TextSecureAttachment attachment) {
329 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
330 if (attachment.isPointer()) {
331 final TextSecureAttachmentPointer pointer = attachment.asPointer();
332 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : ""));
333 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
334 try {
335 File file = m.retrieveAttachment(pointer);
336 System.out.println(" Stored plaintext in: " + file);
337 } catch (IOException | InvalidMessageException e) {
338 System.out.println("Failed to retrieve attachment: " + e.getMessage());
339 }
340 }
341 }
342 }
343 }