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
.signal
;
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
.apache
.http
.util
.TextUtils
;
24 import org
.asamk
.Signal
;
25 import org
.freedesktop
.dbus
.DBusConnection
;
26 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
27 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
28 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
29 import org
.whispersystems
.signalservice
.api
.messages
.*;
30 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
31 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
32 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
33 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
34 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
35 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
38 import java
.io
.IOException
;
39 import java
.security
.Security
;
40 import java
.util
.ArrayList
;
41 import java
.util
.List
;
45 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
46 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
48 public static void main(String
[] args
) {
49 // Workaround for BKS truststore
50 Security
.insertProviderAt(new org
.spongycastle
.jce
.provider
.BouncyCastleProvider(), 1);
52 Namespace ns
= parseArgs(args
);
57 final String username
= ns
.getString("username");
60 DBusConnection dBusConn
= null;
62 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
66 if (ns
.getBoolean("dbus_system")) {
67 busType
= DBusConnection
.SYSTEM
;
69 busType
= DBusConnection
.SESSION
;
71 dBusConn
= DBusConnection
.getConnection(busType
);
72 ts
= (Signal
) dBusConn
.getRemoteObject(
73 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
75 } catch (DBusException e
) {
77 if (dBusConn
!= null) {
78 dBusConn
.disconnect();
84 String settingsPath
= ns
.getString("config");
85 if (TextUtils
.isEmpty(settingsPath
)) {
86 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
87 if (!new File(settingsPath
).exists()) {
88 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
89 if (new File(legacySettingsPath
).exists()) {
90 settingsPath
= legacySettingsPath
;
95 m
= new Manager(username
, settingsPath
);
100 } catch (Exception e
) {
101 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
108 switch (ns
.getString("command")) {
110 if (dBusConn
!= null) {
111 System
.err
.println("register is not yet implementd via dbus");
114 if (!m
.userHasKeys()) {
115 m
.createNewIdentity();
118 m
.register(ns
.getBoolean("voice"));
119 } catch (IOException e
) {
120 System
.err
.println("Request verify error: " + e
.getMessage());
125 if (dBusConn
!= null) {
126 System
.err
.println("verify is not yet implementd via dbus");
129 if (!m
.userHasKeys()) {
130 System
.err
.println("User has no keys, first call register.");
133 if (m
.isRegistered()) {
134 System
.err
.println("User registration is already verified");
138 m
.verifyAccount(ns
.getString("verificationCode"));
139 } catch (IOException e
) {
140 System
.err
.println("Verify error: " + e
.getMessage());
145 if (dBusConn
== null && !m
.isRegistered()) {
146 System
.err
.println("User is not registered.");
150 if (ns
.getBoolean("endsession")) {
151 if (ns
.getList("recipient") == null) {
152 System
.err
.println("No recipients given");
153 System
.err
.println("Aborting sending.");
157 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
158 } catch (IOException e
) {
159 handleIOException(e
);
160 } catch (EncapsulatedExceptions e
) {
161 handleEncapsulatedExceptions(e
);
162 } catch (AssertionError e
) {
163 handleAssertionError(e
);
164 } catch (DBusExecutionException e
) {
165 handleDBusExecutionException(e
);
168 String messageText
= ns
.getString("message");
169 if (messageText
== null) {
171 messageText
= IOUtils
.toString(System
.in);
172 } catch (IOException e
) {
173 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
174 System
.err
.println("Aborting sending.");
180 List
<String
> attachments
= ns
.getList("attachment");
181 if (attachments
== null) {
182 attachments
= new ArrayList
<>();
184 if (ns
.getString("group") != null) {
185 byte[] groupId
= decodeGroupId(ns
.getString("group"));
186 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
188 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
190 } catch (IOException e
) {
191 handleIOException(e
);
192 } catch (EncapsulatedExceptions e
) {
193 handleEncapsulatedExceptions(e
);
194 } catch (AssertionError e
) {
195 handleAssertionError(e
);
196 } catch (GroupNotFoundException e
) {
197 handleGroupNotFoundException(e
);
198 } catch (AttachmentInvalidException e
) {
199 System
.err
.println("Failed to add attachment: " + e
.getMessage());
200 System
.err
.println("Aborting sending.");
202 } catch (DBusExecutionException e
) {
203 handleDBusExecutionException(e
);
209 if (dBusConn
!= null) {
210 System
.err
.println("receive is not yet implementd via dbus");
213 if (!m
.isRegistered()) {
214 System
.err
.println("User is not registered.");
218 if (ns
.getInt("timeout") != null) {
219 timeout
= ns
.getInt("timeout");
221 boolean returnOnTimeout
= true;
223 returnOnTimeout
= false;
227 m
.receiveMessages(timeout
, returnOnTimeout
, new ReceiveMessageHandler(m
));
228 } catch (IOException e
) {
229 System
.err
.println("Error while receiving messages: " + e
.getMessage());
231 } catch (AssertionError e
) {
232 handleAssertionError(e
);
236 if (dBusConn
!= null) {
237 System
.err
.println("quitGroup is not yet implementd via dbus");
240 if (!m
.isRegistered()) {
241 System
.err
.println("User is not registered.");
246 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
247 } catch (IOException e
) {
248 handleIOException(e
);
249 } catch (EncapsulatedExceptions e
) {
250 handleEncapsulatedExceptions(e
);
251 } catch (AssertionError e
) {
252 handleAssertionError(e
);
253 } catch (GroupNotFoundException e
) {
254 handleGroupNotFoundException(e
);
259 if (dBusConn
!= null) {
260 System
.err
.println("updateGroup is not yet implementd via dbus");
263 if (!m
.isRegistered()) {
264 System
.err
.println("User is not registered.");
269 byte[] groupId
= null;
270 if (ns
.getString("group") != null) {
271 groupId
= decodeGroupId(ns
.getString("group"));
273 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
274 if (groupId
== null) {
275 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
277 } catch (IOException e
) {
278 handleIOException(e
);
279 } catch (AttachmentInvalidException e
) {
280 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
281 System
.err
.println("Aborting sending.");
283 } catch (GroupNotFoundException e
) {
284 handleGroupNotFoundException(e
);
285 } catch (EncapsulatedExceptions e
) {
286 handleEncapsulatedExceptions(e
);
291 if (dBusConn
!= null) {
292 System
.err
.println("Stop it.");
295 if (!m
.isRegistered()) {
296 System
.err
.println("User is not registered.");
299 DBusConnection conn
= null;
303 if (ns
.getBoolean("system")) {
304 busType
= DBusConnection
.SYSTEM
;
306 busType
= DBusConnection
.SESSION
;
308 conn
= DBusConnection
.getConnection(busType
);
309 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
310 conn
.requestBusName(SIGNAL_BUSNAME
);
311 } catch (DBusException e
) {
316 m
.receiveMessages(3600, false, new DbusReceiveMessageHandler(m
, conn
));
317 } catch (IOException e
) {
318 System
.err
.println("Error while receiving messages: " + e
.getMessage());
320 } catch (AssertionError e
) {
321 handleAssertionError(e
);
333 if (dBusConn
!= null) {
334 dBusConn
.disconnect();
339 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
340 System
.err
.println("Failed to send to group: " + e
.getMessage());
341 System
.err
.println("Aborting sending.");
345 private static void handleDBusExecutionException(DBusExecutionException e
) {
346 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
347 System
.err
.println("Aborting.");
351 private static byte[] decodeGroupId(String groupId
) {
353 return Base64
.decode(groupId
);
354 } catch (IOException e
) {
355 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
356 System
.err
.println("Aborting sending.");
362 private static Namespace
parseArgs(String
[] args
) {
363 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
365 .description("Commandline interface for Signal.")
366 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
368 parser
.addArgument("-v", "--version")
369 .help("Show package version.")
370 .action(Arguments
.version());
371 parser
.addArgument("--config")
372 .help("Set the path, where to store the config (Default: $HOME/.config/signal-cli).");
374 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
375 mut
.addArgument("-u", "--username")
376 .help("Specify your phone number, that will be used for verification.");
377 mut
.addArgument("--dbus")
378 .help("Make request via user dbus.")
379 .action(Arguments
.storeTrue());
380 mut
.addArgument("--dbus-system")
381 .help("Make request via system dbus.")
382 .action(Arguments
.storeTrue());
384 Subparsers subparsers
= parser
.addSubparsers()
385 .title("subcommands")
387 .description("valid subcommands")
388 .help("additional help");
390 Subparser parserRegister
= subparsers
.addParser("register");
391 parserRegister
.addArgument("-v", "--voice")
392 .help("The verification should be done over voice, not sms.")
393 .action(Arguments
.storeTrue());
395 Subparser parserVerify
= subparsers
.addParser("verify");
396 parserVerify
.addArgument("verificationCode")
397 .help("The verification code you received via sms or voice call.");
399 Subparser parserSend
= subparsers
.addParser("send");
400 parserSend
.addArgument("-g", "--group")
401 .help("Specify the recipient group ID.");
402 parserSend
.addArgument("recipient")
403 .help("Specify the recipients' phone number.")
405 parserSend
.addArgument("-m", "--message")
406 .help("Specify the message, if missing standard input is used.");
407 parserSend
.addArgument("-a", "--attachment")
409 .help("Add file as attachment");
410 parserSend
.addArgument("-e", "--endsession")
411 .help("Clear session state and send end session message.")
412 .action(Arguments
.storeTrue());
414 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
415 parserLeaveGroup
.addArgument("-g", "--group")
417 .help("Specify the recipient group ID.");
419 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
420 parserUpdateGroup
.addArgument("-g", "--group")
421 .help("Specify the recipient group ID.");
422 parserUpdateGroup
.addArgument("-n", "--name")
423 .help("Specify the new group name.");
424 parserUpdateGroup
.addArgument("-a", "--avatar")
425 .help("Specify a new group avatar image file");
426 parserUpdateGroup
.addArgument("-m", "--member")
428 .help("Specify one or more members to add to the group");
430 Subparser parserReceive
= subparsers
.addParser("receive");
431 parserReceive
.addArgument("-t", "--timeout")
433 .help("Number of seconds to wait for new messages (negative values disable timeout)");
435 Subparser parserDaemon
= subparsers
.addParser("daemon");
436 parserDaemon
.addArgument("--system")
437 .action(Arguments
.storeTrue())
438 .help("Use DBus system bus instead of user bus.");
441 Namespace ns
= parser
.parseArgs(args
);
442 if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
443 if (ns
.getString("username") == null) {
445 System
.err
.println("You need to specify a username (phone number)");
448 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
449 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
453 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
454 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
458 } catch (ArgumentParserException e
) {
459 parser
.handleError(e
);
464 private static void handleAssertionError(AssertionError e
) {
465 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
467 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
471 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
472 System
.err
.println("Failed to send (some) messages:");
473 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
474 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
476 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
477 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
479 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
480 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
484 private static void handleIOException(IOException e
) {
485 System
.err
.println("Failed to send message: " + e
.getMessage());
488 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
491 public ReceiveMessageHandler(Manager m
) {
496 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, GroupInfo group
) {
497 SignalServiceAddress source
= envelope
.getSourceAddress();
498 System
.out
.println(String
.format("Envelope from: %s (device: %d)", source
.getNumber(), envelope
.getSourceDevice()));
499 if (source
.getRelay().isPresent()) {
500 System
.out
.println("Relayed by: " + source
.getRelay().get());
502 System
.out
.println("Timestamp: " + envelope
.getTimestamp());
504 if (envelope
.isReceipt()) {
505 System
.out
.println("Got receipt.");
506 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
507 if (content
== null) {
508 System
.out
.println("Failed to decrypt message.");
510 if (content
.getDataMessage().isPresent()) {
511 SignalServiceDataMessage message
= content
.getDataMessage().get();
513 System
.out
.println("Message timestamp: " + message
.getTimestamp());
515 if (message
.getBody().isPresent()) {
516 System
.out
.println("Body: " + message
.getBody().get());
518 if (message
.getGroupInfo().isPresent()) {
519 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
520 System
.out
.println("Group info:");
521 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
522 if (groupInfo
.getName().isPresent()) {
523 System
.out
.println(" Name: " + groupInfo
.getName().get());
524 } else if (group
!= null) {
525 System
.out
.println(" Name: " + group
.name
);
527 System
.out
.println(" Name: <Unknown group>");
529 System
.out
.println(" Type: " + groupInfo
.getType());
530 if (groupInfo
.getMembers().isPresent()) {
531 for (String member
: groupInfo
.getMembers().get()) {
532 System
.out
.println(" Member: " + member
);
535 if (groupInfo
.getAvatar().isPresent()) {
536 System
.out
.println(" Avatar:");
537 printAttachment(groupInfo
.getAvatar().get());
540 if (message
.isEndSession()) {
541 System
.out
.println("Is end session");
544 if (message
.getAttachments().isPresent()) {
545 System
.out
.println("Attachments: ");
546 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
547 printAttachment(attachment
);
551 if (content
.getSyncMessage().isPresent()) {
552 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
553 System
.out
.println("Received sync message");
557 System
.out
.println("Unknown message received.");
559 System
.out
.println();
562 private void printAttachment(SignalServiceAttachment attachment
) {
563 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
564 if (attachment
.isPointer()) {
565 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
566 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
567 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
568 File file
= m
.getAttachmentFile(pointer
.getId());
570 System
.out
.println(" Stored plaintext in: " + file
);
576 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
577 final DBusConnection conn
;
579 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
585 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, GroupInfo group
) {
586 super.handleMessage(envelope
, content
, group
);
588 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
589 SignalServiceDataMessage message
= content
.getDataMessage().get();
591 if (!message
.isEndSession() &&
592 !(message
.getGroupInfo().isPresent() &&
593 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
594 List
<String
> attachments
= new ArrayList
<>();
595 if (message
.getAttachments().isPresent()) {
596 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
597 if (attachment
.isPointer()) {
598 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
604 conn
.sendSignal(new Signal
.MessageReceived(
606 message
.getTimestamp(),
607 envelope
.getSource(),
608 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
609 message
.getBody().isPresent() ? message
.getBody().get() : "",
611 } catch (DBusException e
) {
618 private void printAttachment(SignalServiceAttachment attachment
) {
619 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
620 if (attachment
.isPointer()) {
621 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
622 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
623 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
624 File file
= m
.getAttachmentFile(pointer
.getId());
626 System
.out
.println(" Stored plaintext in: " + file
);