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/>.
17 package org
.asamk
.textsecure
;
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
.asamk
.TextSecure
;
24 import org
.freedesktop
.dbus
.DBusConnection
;
25 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
26 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
27 import org
.whispersystems
.textsecure
.api
.crypto
.UntrustedIdentityException
;
28 import org
.whispersystems
.textsecure
.api
.messages
.*;
29 import org
.whispersystems
.textsecure
.api
.messages
.multidevice
.TextSecureSyncMessage
;
30 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.EncapsulatedExceptions
;
31 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.NetworkFailureException
;
32 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.UnregisteredUserException
;
33 import org
.whispersystems
.textsecure
.api
.util
.PhoneNumberFormatter
;
36 import java
.io
.IOException
;
37 import java
.security
.Security
;
38 import java
.util
.ArrayList
;
39 import java
.util
.List
;
43 public static final String TEXTSECURE_BUSNAME
= "org.asamk.TextSecure";
44 public static final String TEXTSECURE_OBJECTPATH
= "/org/asamk/TextSecure";
46 public static void main(String
[] args
) {
47 // Workaround for BKS truststore
48 Security
.insertProviderAt(new org
.spongycastle
.jce
.provider
.BouncyCastleProvider(), 1);
50 Namespace ns
= parseArgs(args
);
55 final String username
= ns
.getString("username");
58 DBusConnection dBusConn
= null;
60 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
64 if (ns
.getBoolean("dbus_system")) {
65 busType
= DBusConnection
.SYSTEM
;
67 busType
= DBusConnection
.SESSION
;
69 dBusConn
= DBusConnection
.getConnection(busType
);
70 ts
= (TextSecure
) dBusConn
.getRemoteObject(
71 TEXTSECURE_BUSNAME
, TEXTSECURE_OBJECTPATH
,
73 } catch (DBusException e
) {
75 if (dBusConn
!= null) {
76 dBusConn
.disconnect();
82 m
= new Manager(username
);
87 } catch (Exception e
) {
88 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
95 switch (ns
.getString("command")) {
97 if (dBusConn
!= null) {
98 System
.err
.println("register is not yet implementd via dbus");
101 if (!m
.userHasKeys()) {
102 m
.createNewIdentity();
105 m
.register(ns
.getBoolean("voice"));
106 } catch (IOException e
) {
107 System
.err
.println("Request verify error: " + e
.getMessage());
112 if (dBusConn
!= null) {
113 System
.err
.println("verify is not yet implementd via dbus");
116 if (!m
.userHasKeys()) {
117 System
.err
.println("User has no keys, first call register.");
120 if (m
.isRegistered()) {
121 System
.err
.println("User registration is already verified");
125 m
.verifyAccount(ns
.getString("verificationCode"));
126 } catch (IOException e
) {
127 System
.err
.println("Verify error: " + e
.getMessage());
132 if (dBusConn
== null && !m
.isRegistered()) {
133 System
.err
.println("User is not registered.");
137 if (ns
.getBoolean("endsession")) {
138 if (ns
.getList("recipient") == null) {
139 System
.err
.println("No recipients given");
140 System
.err
.println("Aborting sending.");
144 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
145 } catch (IOException e
) {
146 handleIOException(e
);
147 } catch (EncapsulatedExceptions e
) {
148 handleEncapsulatedExceptions(e
);
149 } catch (AssertionError e
) {
150 handleAssertionError(e
);
151 } catch (DBusExecutionException e
) {
152 handleDBusExecutionException(e
);
155 String messageText
= ns
.getString("message");
156 if (messageText
== null) {
158 messageText
= IOUtils
.toString(System
.in);
159 } catch (IOException e
) {
160 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
161 System
.err
.println("Aborting sending.");
167 List
<String
> attachments
= ns
.getList("attachment");
168 if (attachments
== null) {
169 attachments
= new ArrayList
<>();
171 if (ns
.getString("group") != null) {
172 byte[] groupId
= decodeGroupId(ns
.getString("group"));
173 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
175 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
177 } catch (IOException e
) {
178 handleIOException(e
);
179 } catch (EncapsulatedExceptions e
) {
180 handleEncapsulatedExceptions(e
);
181 } catch (AssertionError e
) {
182 handleAssertionError(e
);
183 } catch (GroupNotFoundException e
) {
184 handleGroupNotFoundException(e
);
185 } catch (AttachmentInvalidException e
) {
186 System
.err
.println("Failed to add attachment: " + e
.getMessage());
187 System
.err
.println("Aborting sending.");
189 } catch (DBusExecutionException e
) {
190 handleDBusExecutionException(e
);
196 if (dBusConn
!= null) {
197 System
.err
.println("receive is not yet implementd via dbus");
200 if (!m
.isRegistered()) {
201 System
.err
.println("User is not registered.");
205 if (ns
.getInt("timeout") != null) {
206 timeout
= ns
.getInt("timeout");
208 boolean returnOnTimeout
= true;
210 returnOnTimeout
= false;
214 m
.receiveMessages(timeout
, returnOnTimeout
, new ReceiveMessageHandler(m
));
215 } catch (IOException e
) {
216 System
.err
.println("Error while receiving messages: " + e
.getMessage());
218 } catch (AssertionError e
) {
219 handleAssertionError(e
);
223 if (dBusConn
!= null) {
224 System
.err
.println("quitGroup is not yet implementd via dbus");
227 if (!m
.isRegistered()) {
228 System
.err
.println("User is not registered.");
233 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
234 } catch (IOException e
) {
235 handleIOException(e
);
236 } catch (EncapsulatedExceptions e
) {
237 handleEncapsulatedExceptions(e
);
238 } catch (AssertionError e
) {
239 handleAssertionError(e
);
240 } catch (GroupNotFoundException e
) {
241 handleGroupNotFoundException(e
);
246 if (dBusConn
!= null) {
247 System
.err
.println("updateGroup is not yet implementd via dbus");
250 if (!m
.isRegistered()) {
251 System
.err
.println("User is not registered.");
256 byte[] groupId
= null;
257 if (ns
.getString("group") != null) {
258 groupId
= decodeGroupId(ns
.getString("group"));
260 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
261 if (groupId
== null) {
262 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
264 } catch (IOException e
) {
265 handleIOException(e
);
266 } catch (AttachmentInvalidException e
) {
267 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
268 System
.err
.println("Aborting sending.");
270 } catch (GroupNotFoundException e
) {
271 handleGroupNotFoundException(e
);
272 } catch (EncapsulatedExceptions e
) {
273 handleEncapsulatedExceptions(e
);
278 if (dBusConn
!= null) {
279 System
.err
.println("Stop it.");
282 if (!m
.isRegistered()) {
283 System
.err
.println("User is not registered.");
286 DBusConnection conn
= null;
290 if (ns
.getBoolean("system")) {
291 busType
= DBusConnection
.SYSTEM
;
293 busType
= DBusConnection
.SESSION
;
295 conn
= DBusConnection
.getConnection(busType
);
296 conn
.exportObject(TEXTSECURE_OBJECTPATH
, m
);
297 conn
.requestBusName(TEXTSECURE_BUSNAME
);
298 } catch (DBusException e
) {
303 m
.receiveMessages(3600, false, new DbusReceiveMessageHandler(m
, conn
));
304 } catch (IOException e
) {
305 System
.err
.println("Error while receiving messages: " + e
.getMessage());
307 } catch (AssertionError e
) {
308 handleAssertionError(e
);
320 if (dBusConn
!= null) {
321 dBusConn
.disconnect();
326 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
327 System
.err
.println("Failed to send to group: " + e
.getMessage());
328 System
.err
.println("Aborting sending.");
332 private static void handleDBusExecutionException(DBusExecutionException e
) {
333 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
334 System
.err
.println("Aborting.");
338 private static byte[] decodeGroupId(String groupId
) {
340 return Base64
.decode(groupId
);
341 } catch (IOException e
) {
342 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
343 System
.err
.println("Aborting sending.");
349 private static Namespace
parseArgs(String
[] args
) {
350 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("textsecure-cli")
352 .description("Commandline interface for TextSecure.")
353 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
355 parser
.addArgument("-v", "--version")
356 .help("Show package version.")
357 .action(Arguments
.version());
359 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
360 mut
.addArgument("-u", "--username")
361 .help("Specify your phone number, that will be used for verification.");
362 mut
.addArgument("--dbus")
363 .help("Make request via user dbus.")
364 .action(Arguments
.storeTrue());
365 mut
.addArgument("--dbus-system")
366 .help("Make request via system dbus.")
367 .action(Arguments
.storeTrue());
369 Subparsers subparsers
= parser
.addSubparsers()
370 .title("subcommands")
372 .description("valid subcommands")
373 .help("additional help");
375 Subparser parserRegister
= subparsers
.addParser("register");
376 parserRegister
.addArgument("-v", "--voice")
377 .help("The verification should be done over voice, not sms.")
378 .action(Arguments
.storeTrue());
380 Subparser parserVerify
= subparsers
.addParser("verify");
381 parserVerify
.addArgument("verificationCode")
382 .help("The verification code you received via sms or voice call.");
384 Subparser parserSend
= subparsers
.addParser("send");
385 parserSend
.addArgument("-g", "--group")
386 .help("Specify the recipient group ID.");
387 parserSend
.addArgument("recipient")
388 .help("Specify the recipients' phone number.")
390 parserSend
.addArgument("-m", "--message")
391 .help("Specify the message, if missing standard input is used.");
392 parserSend
.addArgument("-a", "--attachment")
394 .help("Add file as attachment");
395 parserSend
.addArgument("-e", "--endsession")
396 .help("Clear session state and send end session message.")
397 .action(Arguments
.storeTrue());
399 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
400 parserLeaveGroup
.addArgument("-g", "--group")
402 .help("Specify the recipient group ID.");
404 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
405 parserUpdateGroup
.addArgument("-g", "--group")
406 .help("Specify the recipient group ID.");
407 parserUpdateGroup
.addArgument("-n", "--name")
408 .help("Specify the new group name.");
409 parserUpdateGroup
.addArgument("-a", "--avatar")
410 .help("Specify a new group avatar image file");
411 parserUpdateGroup
.addArgument("-m", "--member")
413 .help("Specify one or more members to add to the group");
415 Subparser parserReceive
= subparsers
.addParser("receive");
416 parserReceive
.addArgument("-t", "--timeout")
418 .help("Number of seconds to wait for new messages (negative values disable timeout)");
420 Subparser parserDaemon
= subparsers
.addParser("daemon");
421 parserDaemon
.addArgument("--system")
422 .action(Arguments
.storeTrue())
423 .help("Use DBus system bus instead of user bus.");
426 Namespace ns
= parser
.parseArgs(args
);
427 if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
428 if (ns
.getString("username") == null) {
430 System
.err
.println("You need to specify a username (phone number)");
433 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
434 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
438 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
439 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
443 } catch (ArgumentParserException e
) {
444 parser
.handleError(e
);
449 private static void handleAssertionError(AssertionError e
) {
450 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
451 System
.err
.println(e
.getStackTrace());
452 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
456 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
457 System
.err
.println("Failed to send (some) messages:");
458 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
459 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
461 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
462 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
464 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
465 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
469 private static void handleIOException(IOException e
) {
470 System
.err
.println("Failed to send message: " + e
.getMessage());
473 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
476 public ReceiveMessageHandler(Manager m
) {
481 public void handleMessage(TextSecureEnvelope envelope
, TextSecureContent content
, GroupInfo group
) {
482 System
.out
.println("Envelope from: " + envelope
.getSource());
483 System
.out
.println("Timestamp: " + envelope
.getTimestamp());
485 if (envelope
.isReceipt()) {
486 System
.out
.println("Got receipt.");
487 } else if (envelope
.isWhisperMessage() | envelope
.isPreKeyWhisperMessage()) {
488 if (content
== null) {
489 System
.out
.println("Failed to decrypt message.");
491 if (content
.getDataMessage().isPresent()) {
492 TextSecureDataMessage message
= content
.getDataMessage().get();
494 System
.out
.println("Message timestamp: " + message
.getTimestamp());
496 if (message
.getBody().isPresent()) {
497 System
.out
.println("Body: " + message
.getBody().get());
499 if (message
.getGroupInfo().isPresent()) {
500 TextSecureGroup groupInfo
= message
.getGroupInfo().get();
501 System
.out
.println("Group info:");
502 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
503 if (groupInfo
.getName().isPresent()) {
504 System
.out
.println(" Name: " + groupInfo
.getName().get());
505 } else if (group
!= null) {
506 System
.out
.println(" Name: " + group
.name
);
508 System
.out
.println(" Name: <Unknown group>");
510 System
.out
.println(" Type: " + groupInfo
.getType());
511 if (groupInfo
.getMembers().isPresent()) {
512 for (String member
: groupInfo
.getMembers().get()) {
513 System
.out
.println(" Member: " + member
);
516 if (groupInfo
.getAvatar().isPresent()) {
517 System
.out
.println(" Avatar:");
518 printAttachment(groupInfo
.getAvatar().get());
521 if (message
.isEndSession()) {
522 System
.out
.println("Is end session");
525 if (message
.getAttachments().isPresent()) {
526 System
.out
.println("Attachments: ");
527 for (TextSecureAttachment attachment
: message
.getAttachments().get()) {
528 printAttachment(attachment
);
532 if (content
.getSyncMessage().isPresent()) {
533 TextSecureSyncMessage syncMessage
= content
.getSyncMessage().get();
534 System
.out
.println("Received sync message");
538 System
.out
.println("Unknown message received.");
540 System
.out
.println();
543 private void printAttachment(TextSecureAttachment attachment
) {
544 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
545 if (attachment
.isPointer()) {
546 final TextSecureAttachmentPointer pointer
= attachment
.asPointer();
547 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
548 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
549 File file
= m
.getAttachmentFile(pointer
.getId());
551 System
.out
.println(" Stored plaintext in: " + file
);
557 private static class DbusReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
559 final DBusConnection conn
;
561 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
567 public void handleMessage(TextSecureEnvelope envelope
, TextSecureContent content
, GroupInfo group
) {
568 System
.out
.println("Envelope from: " + envelope
.getSource());
569 System
.out
.println("Timestamp: " + envelope
.getTimestamp());
571 if (envelope
.isReceipt()) {
572 System
.out
.println("Got receipt.");
573 } else if (envelope
.isWhisperMessage() | envelope
.isPreKeyWhisperMessage()) {
574 if (content
== null) {
575 System
.out
.println("Failed to decrypt message.");
577 if (content
.getDataMessage().isPresent()) {
578 TextSecureDataMessage message
= content
.getDataMessage().get();
580 System
.out
.println("Message timestamp: " + message
.getTimestamp());
582 if (message
.getBody().isPresent()) {
583 System
.out
.println("Body: " + message
.getBody().get());
586 if (message
.getGroupInfo().isPresent()) {
587 TextSecureGroup groupInfo
= message
.getGroupInfo().get();
588 System
.out
.println("Group info:");
589 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
590 if (groupInfo
.getName().isPresent()) {
591 System
.out
.println(" Name: " + groupInfo
.getName().get());
592 } else if (group
!= null) {
593 System
.out
.println(" Name: " + group
.name
);
595 System
.out
.println(" Name: <Unknown group>");
597 System
.out
.println(" Type: " + groupInfo
.getType());
598 if (groupInfo
.getMembers().isPresent()) {
599 for (String member
: groupInfo
.getMembers().get()) {
600 System
.out
.println(" Member: " + member
);
603 if (groupInfo
.getAvatar().isPresent()) {
604 System
.out
.println(" Avatar:");
605 printAttachment(groupInfo
.getAvatar().get());
608 if (message
.isEndSession()) {
609 System
.out
.println("Is end session");
612 List
<String
> attachments
= new ArrayList
<>();
613 if (message
.getAttachments().isPresent()) {
614 System
.out
.println("Attachments: ");
615 for (TextSecureAttachment attachment
: message
.getAttachments().get()) {
616 if (attachment
.isPointer()) {
617 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
619 printAttachment(attachment
);
622 if (!message
.isEndSession() &&
623 !(message
.getGroupInfo().isPresent() && message
.getGroupInfo().get().getType() != TextSecureGroup
.Type
.DELIVER
)) {
625 conn
.sendSignal(new TextSecure
.MessageReceived(
626 TEXTSECURE_OBJECTPATH
,
627 envelope
.getSource(),
628 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
629 message
.getBody().isPresent() ? message
.getBody().get() : "",
631 } catch (DBusException e
) {
636 if (content
.getSyncMessage().isPresent()) {
637 TextSecureSyncMessage syncMessage
= content
.getSyncMessage().get();
638 System
.out
.println("Received sync message");
642 System
.out
.println("Unknown message received.");
644 System
.out
.println();
647 private void printAttachment(TextSecureAttachment attachment
) {
648 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
649 if (attachment
.isPointer()) {
650 final TextSecureAttachmentPointer pointer
= attachment
.asPointer();
651 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
652 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
653 File file
= m
.getAttachmentFile(pointer
.getId());
655 System
.out
.println(" Stored plaintext in: " + file
);