2 * Copyright (C) 2015 AsamK
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.
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.
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/>.
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
.textsecure
.api
.crypto
.UntrustedIdentityException
;
24 import org
.whispersystems
.textsecure
.api
.messages
.*;
25 import org
.whispersystems
.textsecure
.api
.messages
.multidevice
.TextSecureSyncMessage
;
26 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.EncapsulatedExceptions
;
27 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.NetworkFailureException
;
28 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.UnregisteredUserException
;
29 import org
.whispersystems
.textsecure
.api
.util
.PhoneNumberFormatter
;
32 import java
.io
.IOException
;
33 import java
.security
.Security
;
37 public static void main(String
[] args
) {
38 // Workaround for BKS truststore
39 Security
.insertProviderAt(new org
.spongycastle
.jce
.provider
.BouncyCastleProvider(), 1);
41 Namespace ns
= parseArgs(args
);
46 final String username
= ns
.getString("username");
47 final Manager m
= new Manager(username
);
51 } catch (Exception e
) {
52 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
57 switch (ns
.getString("command")) {
59 if (!m
.userHasKeys()) {
60 m
.createNewIdentity();
63 m
.register(ns
.getBoolean("voice"));
64 } catch (IOException e
) {
65 System
.err
.println("Request verify error: " + e
.getMessage());
70 if (!m
.userHasKeys()) {
71 System
.err
.println("User has no keys, first call register.");
74 if (m
.isRegistered()) {
75 System
.err
.println("User registration is already verified");
79 m
.verifyAccount(ns
.getString("verificationCode"));
80 } catch (IOException e
) {
81 System
.err
.println("Verify error: " + e
.getMessage());
86 if (!m
.isRegistered()) {
87 System
.err
.println("User is not registered.");
91 if (ns
.getBoolean("endsession")) {
92 if (ns
.getList("recipient") == null) {
93 System
.err
.println("No recipients given");
94 System
.err
.println("Aborting sending.");
98 m
.sendEndSessionMessage(ns
.getList("recipient"));
99 } catch (IOException e
) {
100 handleIOException(e
);
101 } catch (EncapsulatedExceptions e
) {
102 handleEncapsulatedExceptions(e
);
103 } catch (AssertionError e
) {
104 handleAssertionError(e
);
107 String messageText
= ns
.getString("message");
108 if (messageText
== null) {
110 messageText
= IOUtils
.toString(System
.in);
111 } catch (IOException e
) {
112 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
113 System
.err
.println("Aborting sending.");
119 if (ns
.getString("group") != null) {
120 byte[] groupId
= decodeGroupId(ns
.getString("group"));
121 m
.sendGroupMessage(messageText
, ns
.<String
>getList("attachment"), groupId
);
123 m
.sendMessage(messageText
, ns
.<String
>getList("attachment"), ns
.getList("recipient"));
125 } catch (IOException e
) {
126 handleIOException(e
);
127 } catch (EncapsulatedExceptions e
) {
128 handleEncapsulatedExceptions(e
);
129 } catch (AssertionError e
) {
130 handleAssertionError(e
);
131 } catch (GroupNotFoundException e
) {
132 handleGroupNotFoundException(e
);
133 } catch (AttachmentInvalidException e
) {
134 System
.err
.println("Failed to add attachment (\"" + e
.getAttachment() + "\"): " + e
.getMessage());
135 System
.err
.println("Aborting sending.");
142 if (!m
.isRegistered()) {
143 System
.err
.println("User is not registered.");
147 if (ns
.getInt("timeout") != null) {
148 timeout
= ns
.getInt("timeout");
150 boolean returnOnTimeout
= true;
152 returnOnTimeout
= false;
156 m
.receiveMessages(timeout
, returnOnTimeout
, new ReceiveMessageHandler(m
));
157 } catch (IOException e
) {
158 System
.err
.println("Error while receiving message: " + e
.getMessage());
160 } catch (AssertionError e
) {
161 System
.err
.println("Failed to receive message (Assertion): " + e
.getMessage());
162 System
.err
.println(e
.getStackTrace());
163 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
168 if (!m
.isRegistered()) {
169 System
.err
.println("User is not registered.");
174 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
175 } catch (IOException e
) {
176 handleIOException(e
);
177 } catch (EncapsulatedExceptions e
) {
178 handleEncapsulatedExceptions(e
);
179 } catch (AssertionError e
) {
180 handleAssertionError(e
);
181 } catch (GroupNotFoundException e
) {
182 handleGroupNotFoundException(e
);
187 if (!m
.isRegistered()) {
188 System
.err
.println("User is not registered.");
193 byte[] groupId
= null;
194 if (ns
.getString("group") != null) {
195 groupId
= decodeGroupId(ns
.getString("group"));
197 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.getList("member"), ns
.getString("avatar"));
198 if (groupId
== null) {
199 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
201 } catch (IOException e
) {
202 handleIOException(e
);
203 } catch (AttachmentInvalidException e
) {
204 System
.err
.println("Failed to add avatar attachment (\"" + e
.getAttachment() + ") for group\": " + e
.getMessage());
205 System
.err
.println("Aborting sending.");
207 } catch (GroupNotFoundException e
) {
208 handleGroupNotFoundException(e
);
209 } catch (EncapsulatedExceptions e
) {
210 handleEncapsulatedExceptions(e
);
219 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
220 System
.err
.println("Failed to send to group \"" + Base64
.encodeBytes(e
.getGroupId()) + "\": Unknown group");
221 System
.err
.println("Aborting sending.");
225 private static byte[] decodeGroupId(String groupId
) {
227 return Base64
.decode(groupId
);
228 } catch (IOException e
) {
229 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
230 System
.err
.println("Aborting sending.");
236 private static Namespace
parseArgs(String
[] args
) {
237 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("textsecure-cli")
239 .description("Commandline interface for TextSecure.")
240 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
242 parser
.addArgument("-u", "--username")
243 .help("Specify your phone number, that will be used for verification.");
244 parser
.addArgument("-v", "--version")
245 .help("Show package version.")
246 .action(Arguments
.version());
248 Subparsers subparsers
= parser
.addSubparsers()
249 .title("subcommands")
251 .description("valid subcommands")
252 .help("additional help");
254 Subparser parserRegister
= subparsers
.addParser("register");
255 parserRegister
.addArgument("-v", "--voice")
256 .help("The verification should be done over voice, not sms.")
257 .action(Arguments
.storeTrue());
259 Subparser parserVerify
= subparsers
.addParser("verify");
260 parserVerify
.addArgument("verificationCode")
261 .help("The verification code you received via sms or voice call.");
263 Subparser parserSend
= subparsers
.addParser("send");
264 parserSend
.addArgument("-g", "--group")
265 .help("Specify the recipient group ID.");
266 parserSend
.addArgument("recipient")
267 .help("Specify the recipients' phone number.")
269 parserSend
.addArgument("-m", "--message")
270 .help("Specify the message, if missing standard input is used.");
271 parserSend
.addArgument("-a", "--attachment")
273 .help("Add file as attachment");
274 parserSend
.addArgument("-e", "--endsession")
275 .help("Clear session state and send end session message.")
276 .action(Arguments
.storeTrue());
278 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
279 parserLeaveGroup
.addArgument("-g", "--group")
281 .help("Specify the recipient group ID.");
283 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
284 parserUpdateGroup
.addArgument("-g", "--group")
285 .help("Specify the recipient group ID.");
286 parserUpdateGroup
.addArgument("-n", "--name")
287 .help("Specify the new group name.");
288 parserUpdateGroup
.addArgument("-a", "--avatar")
289 .help("Specify a new group avatar image file");
290 parserUpdateGroup
.addArgument("-m", "--member")
292 .help("Specify one or more members to add to the group");
294 Subparser parserReceive
= subparsers
.addParser("receive");
295 parserReceive
.addArgument("-t", "--timeout")
297 .help("Number of seconds to wait for new messages (negative values disable timeout)");
300 Namespace ns
= parser
.parseArgs(args
);
301 if (ns
.getString("username") == null) {
303 System
.err
.println("You need to specify a username (phone number)");
306 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
307 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
310 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
311 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
315 } catch (ArgumentParserException e
) {
316 parser
.handleError(e
);
321 private static void handleAssertionError(AssertionError e
) {
322 System
.err
.println("Failed to send message (Assertion): " + e
.getMessage());
323 System
.err
.println(e
.getStackTrace());
324 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
328 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
329 System
.err
.println("Failed to send (some) messages:");
330 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
331 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
333 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
334 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
336 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
337 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
341 private static void handleIOException(IOException e
) {
342 System
.err
.println("Failed to send message: " + e
.getMessage());
345 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
348 public ReceiveMessageHandler(Manager m
) {
353 public void handleMessage(TextSecureEnvelope envelope
, TextSecureContent content
, GroupInfo group
) {
354 System
.out
.println("Envelope from: " + envelope
.getSource());
355 System
.out
.println("Timestamp: " + envelope
.getTimestamp());
357 if (envelope
.isReceipt()) {
358 System
.out
.println("Got receipt.");
359 } else if (envelope
.isWhisperMessage() | envelope
.isPreKeyWhisperMessage()) {
360 if (content
== null) {
361 System
.out
.println("Failed to decrypt message.");
363 if (content
.getDataMessage().isPresent()) {
364 TextSecureDataMessage message
= content
.getDataMessage().get();
366 System
.out
.println("Message timestamp: " + message
.getTimestamp());
368 if (message
.getBody().isPresent()) {
369 System
.out
.println("Body: " + message
.getBody().get());
371 if (message
.getGroupInfo().isPresent()) {
372 TextSecureGroup groupInfo
= message
.getGroupInfo().get();
373 System
.out
.println("Group info:");
374 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
375 if (groupInfo
.getName().isPresent()) {
376 System
.out
.println(" Name: " + groupInfo
.getName().get());
377 } else if (group
!= null) {
378 System
.out
.println(" Name: " + group
.name
);
380 System
.out
.println(" Name: <Unknown group>");
382 System
.out
.println(" Type: " + groupInfo
.getType());
383 if (groupInfo
.getMembers().isPresent()) {
384 for (String member
: groupInfo
.getMembers().get()) {
385 System
.out
.println(" Member: " + member
);
388 if (groupInfo
.getAvatar().isPresent()) {
389 System
.out
.println(" Avatar:");
390 printAttachment(groupInfo
.getAvatar().get());
393 if (message
.isEndSession()) {
394 System
.out
.println("Is end session");
397 if (message
.getAttachments().isPresent()) {
398 System
.out
.println("Attachments: ");
399 for (TextSecureAttachment attachment
: message
.getAttachments().get()) {
400 printAttachment(attachment
);
404 if (content
.getSyncMessage().isPresent()) {
405 TextSecureSyncMessage syncMessage
= content
.getSyncMessage().get();
406 System
.out
.println("Received sync message");
410 System
.out
.println("Unknown message received.");
412 System
.out
.println();
415 private void printAttachment(TextSecureAttachment attachment
) {
416 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
417 if (attachment
.isPointer()) {
418 final TextSecureAttachmentPointer pointer
= attachment
.asPointer();
419 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
420 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
421 File file
= m
.getAttachmentFile(pointer
.getId());
423 System
.out
.println(" Stored plaintext in: " + file
);