]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
Fix minor inspection issues
[signal-cli] / src / main / java / org / asamk / signal / Main.java
1 /*
2 Copyright (C) 2015-2018 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 org.asamk.signal;
18
19 import net.sourceforge.argparse4j.ArgumentParsers;
20 import net.sourceforge.argparse4j.impl.Arguments;
21 import net.sourceforge.argparse4j.inf.*;
22 import org.apache.http.util.TextUtils;
23 import org.asamk.Signal;
24 import org.asamk.signal.manager.BaseConfig;
25 import org.asamk.signal.manager.Manager;
26 import org.asamk.signal.storage.groups.GroupInfo;
27 import org.asamk.signal.storage.protocol.JsonIdentityKeyStore;
28 import org.asamk.signal.util.DateUtils;
29 import org.asamk.signal.util.Hex;
30 import org.asamk.signal.util.IOUtils;
31 import org.asamk.signal.util.Util;
32 import org.freedesktop.dbus.DBusConnection;
33 import org.freedesktop.dbus.DBusSigHandler;
34 import org.freedesktop.dbus.exceptions.DBusException;
35 import org.freedesktop.dbus.exceptions.DBusExecutionException;
36 import org.whispersystems.libsignal.InvalidKeyException;
37 import org.whispersystems.libsignal.util.guava.Optional;
38 import org.whispersystems.signalservice.api.messages.multidevice.DeviceInfo;
39 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
40 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
41 import org.whispersystems.signalservice.internal.push.LockedException;
42 import org.whispersystems.signalservice.internal.util.Base64;
43
44 import java.io.File;
45 import java.io.IOException;
46 import java.net.URI;
47 import java.net.URISyntaxException;
48 import java.nio.charset.Charset;
49 import java.security.Security;
50 import java.util.ArrayList;
51 import java.util.List;
52 import java.util.Locale;
53 import java.util.Map;
54 import java.util.concurrent.TimeUnit;
55 import java.util.concurrent.TimeoutException;
56
57 import static org.asamk.signal.util.ErrorUtils.*;
58
59 public class Main {
60
61 private static final String SIGNAL_BUSNAME = "org.asamk.Signal";
62 private static final String SIGNAL_OBJECTPATH = "/org/asamk/Signal";
63
64 public static void main(String[] args) {
65 // Workaround for BKS truststore
66 Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);
67
68 Namespace ns = parseArgs(args);
69 if (ns == null) {
70 System.exit(1);
71 }
72
73 int res = handleCommands(ns);
74 System.exit(res);
75 }
76
77 private static int handleCommands(Namespace ns) {
78 final String username = ns.getString("username");
79 Manager m;
80 Signal ts;
81 DBusConnection dBusConn = null;
82 try {
83 if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
84 try {
85 m = null;
86 int busType;
87 if (ns.getBoolean("dbus_system")) {
88 busType = DBusConnection.SYSTEM;
89 } else {
90 busType = DBusConnection.SESSION;
91 }
92 dBusConn = DBusConnection.getConnection(busType);
93 ts = dBusConn.getRemoteObject(
94 SIGNAL_BUSNAME, SIGNAL_OBJECTPATH,
95 Signal.class);
96 } catch (UnsatisfiedLinkError e) {
97 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
98 return 1;
99 } catch (DBusException e) {
100 e.printStackTrace();
101 if (dBusConn != null) {
102 dBusConn.disconnect();
103 }
104 return 3;
105 }
106 } else {
107 String settingsPath = ns.getString("config");
108 if (TextUtils.isEmpty(settingsPath)) {
109 settingsPath = System.getProperty("user.home") + "/.config/signal";
110 if (!new File(settingsPath).exists()) {
111 String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
112 if (new File(legacySettingsPath).exists()) {
113 settingsPath = legacySettingsPath;
114 }
115 }
116 }
117
118 m = new Manager(username, settingsPath);
119 ts = m;
120 try {
121 m.init();
122 } catch (Exception e) {
123 System.err.println("Error loading state file: " + e.getMessage());
124 return 2;
125 }
126 }
127
128 switch (ns.getString("command")) {
129 case "register":
130 if (dBusConn != null) {
131 System.err.println("register is not yet implemented via dbus");
132 return 1;
133 }
134 try {
135 m.register(ns.getBoolean("voice"));
136 } catch (IOException e) {
137 System.err.println("Request verify error: " + e.getMessage());
138 return 3;
139 }
140 break;
141 case "unregister":
142 if (dBusConn != null) {
143 System.err.println("unregister is not yet implemented via dbus");
144 return 1;
145 }
146 if (!m.isRegistered()) {
147 System.err.println("User is not registered.");
148 return 1;
149 }
150 try {
151 m.unregister();
152 } catch (IOException e) {
153 System.err.println("Unregister error: " + e.getMessage());
154 return 3;
155 }
156 break;
157 case "updateAccount":
158 if (dBusConn != null) {
159 System.err.println("updateAccount is not yet implemented via dbus");
160 return 1;
161 }
162 if (!m.isRegistered()) {
163 System.err.println("User is not registered.");
164 return 1;
165 }
166 try {
167 m.updateAccountAttributes();
168 } catch (IOException e) {
169 System.err.println("UpdateAccount error: " + e.getMessage());
170 return 3;
171 }
172 break;
173 case "setPin":
174 if (dBusConn != null) {
175 System.err.println("setPin is not yet implemented via dbus");
176 return 1;
177 }
178 if (!m.isRegistered()) {
179 System.err.println("User is not registered.");
180 return 1;
181 }
182 try {
183 String registrationLockPin = ns.getString("registrationLockPin");
184 m.setRegistrationLockPin(Optional.of(registrationLockPin));
185 } catch (IOException e) {
186 System.err.println("Set pin error: " + e.getMessage());
187 return 3;
188 }
189 break;
190 case "removePin":
191 if (dBusConn != null) {
192 System.err.println("removePin is not yet implemented via dbus");
193 return 1;
194 }
195 if (!m.isRegistered()) {
196 System.err.println("User is not registered.");
197 return 1;
198 }
199 try {
200 m.setRegistrationLockPin(Optional.<String>absent());
201 } catch (IOException e) {
202 System.err.println("Remove pin error: " + e.getMessage());
203 return 3;
204 }
205 break;
206 case "verify":
207 if (dBusConn != null) {
208 System.err.println("verify is not yet implemented via dbus");
209 return 1;
210 }
211 if (!m.userHasKeys()) {
212 System.err.println("User has no keys, first call register.");
213 return 1;
214 }
215 if (m.isRegistered()) {
216 System.err.println("User registration is already verified");
217 return 1;
218 }
219 try {
220 String verificationCode = ns.getString("verificationCode");
221 String pin = ns.getString("pin");
222 m.verifyAccount(verificationCode, pin);
223 } catch (LockedException e) {
224 System.err.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e.getTimeRemaining() / 1000 / 60 / 60));
225 System.err.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
226 return 3;
227 } catch (IOException e) {
228 System.err.println("Verify error: " + e.getMessage());
229 return 3;
230 }
231 break;
232 case "link":
233 if (dBusConn != null) {
234 System.err.println("link is not yet implemented via dbus");
235 return 1;
236 }
237
238 String deviceName = ns.getString("name");
239 if (deviceName == null) {
240 deviceName = "cli";
241 }
242 try {
243 System.out.println(m.getDeviceLinkUri());
244 m.finishDeviceLink(deviceName);
245 System.out.println("Associated with: " + m.getUsername());
246 } catch (TimeoutException e) {
247 System.err.println("Link request timed out, please try again.");
248 return 3;
249 } catch (IOException e) {
250 System.err.println("Link request error: " + e.getMessage());
251 return 3;
252 } catch (AssertionError e) {
253 handleAssertionError(e);
254 return 1;
255 } catch (InvalidKeyException e) {
256 e.printStackTrace();
257 return 2;
258 } catch (UserAlreadyExists e) {
259 System.err.println("The user " + e.getUsername() + " already exists\nDelete \"" + e.getFileName() + "\" before trying again.");
260 return 1;
261 }
262 break;
263 case "addDevice":
264 if (dBusConn != null) {
265 System.err.println("link is not yet implemented via dbus");
266 return 1;
267 }
268 if (!m.isRegistered()) {
269 System.err.println("User is not registered.");
270 return 1;
271 }
272 try {
273 m.addDeviceLink(new URI(ns.getString("uri")));
274 } catch (IOException e) {
275 e.printStackTrace();
276 return 3;
277 } catch (InvalidKeyException | URISyntaxException e) {
278 e.printStackTrace();
279 return 2;
280 } catch (AssertionError e) {
281 handleAssertionError(e);
282 return 1;
283 }
284 break;
285 case "listDevices":
286 if (dBusConn != null) {
287 System.err.println("listDevices is not yet implemented via dbus");
288 return 1;
289 }
290 if (!m.isRegistered()) {
291 System.err.println("User is not registered.");
292 return 1;
293 }
294 try {
295 List<DeviceInfo> devices = m.getLinkedDevices();
296 for (DeviceInfo d : devices) {
297 System.out.println("Device " + d.getId() + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
298 System.out.println(" Name: " + d.getName());
299 System.out.println(" Created: " + DateUtils.formatTimestamp(d.getCreated()));
300 System.out.println(" Last seen: " + DateUtils.formatTimestamp(d.getLastSeen()));
301 }
302 } catch (IOException e) {
303 e.printStackTrace();
304 return 3;
305 }
306 break;
307 case "removeDevice":
308 if (dBusConn != null) {
309 System.err.println("removeDevice is not yet implemented via dbus");
310 return 1;
311 }
312 if (!m.isRegistered()) {
313 System.err.println("User is not registered.");
314 return 1;
315 }
316 try {
317 int deviceId = ns.getInt("deviceId");
318 m.removeLinkedDevices(deviceId);
319 } catch (IOException e) {
320 e.printStackTrace();
321 return 3;
322 }
323 break;
324 case "send":
325 if (dBusConn == null && !m.isRegistered()) {
326 System.err.println("User is not registered.");
327 return 1;
328 }
329
330 if (ns.getBoolean("endsession")) {
331 if (ns.getList("recipient") == null) {
332 System.err.println("No recipients given");
333 System.err.println("Aborting sending.");
334 return 1;
335 }
336 try {
337 ts.sendEndSessionMessage(ns.<String>getList("recipient"));
338 } catch (IOException e) {
339 handleIOException(e);
340 return 3;
341 } catch (EncapsulatedExceptions e) {
342 handleEncapsulatedExceptions(e);
343 return 3;
344 } catch (AssertionError e) {
345 handleAssertionError(e);
346 return 1;
347 } catch (DBusExecutionException e) {
348 handleDBusExecutionException(e);
349 return 1;
350 }
351 } else {
352 String messageText = ns.getString("message");
353 if (messageText == null) {
354 try {
355 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
356 } catch (IOException e) {
357 System.err.println("Failed to read message from stdin: " + e.getMessage());
358 System.err.println("Aborting sending.");
359 return 1;
360 }
361 }
362
363 try {
364 List<String> attachments = ns.getList("attachment");
365 if (attachments == null) {
366 attachments = new ArrayList<>();
367 }
368 if (ns.getString("group") != null) {
369 byte[] groupId = Util.decodeGroupId(ns.getString("group"));
370 ts.sendGroupMessage(messageText, attachments, groupId);
371 } else {
372 ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
373 }
374 } catch (IOException e) {
375 handleIOException(e);
376 return 3;
377 } catch (EncapsulatedExceptions e) {
378 handleEncapsulatedExceptions(e);
379 return 3;
380 } catch (AssertionError e) {
381 handleAssertionError(e);
382 return 1;
383 } catch (GroupNotFoundException e) {
384 handleGroupNotFoundException(e);
385 return 1;
386 } catch (NotAGroupMemberException e) {
387 handleNotAGroupMemberException(e);
388 return 1;
389 } catch (AttachmentInvalidException e) {
390 System.err.println("Failed to add attachment: " + e.getMessage());
391 System.err.println("Aborting sending.");
392 return 1;
393 } catch (DBusExecutionException e) {
394 handleDBusExecutionException(e);
395 return 1;
396 } catch (GroupIdFormatException e) {
397 handleGroupIdFormatException(e);
398 return 1;
399 }
400 }
401
402 break;
403 case "receive":
404 if (dBusConn != null) {
405 try {
406 dBusConn.addSigHandler(Signal.MessageReceived.class, new DBusSigHandler<Signal.MessageReceived>() {
407 @Override
408 public void handle(Signal.MessageReceived s) {
409 System.out.print(String.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
410 s.getSender(), DateUtils.formatTimestamp(s.getTimestamp()), s.getMessage()));
411 if (s.getGroupId().length > 0) {
412 System.out.println("Group info:");
413 System.out.println(" Id: " + Base64.encodeBytes(s.getGroupId()));
414 }
415 if (s.getAttachments().size() > 0) {
416 System.out.println("Attachments: ");
417 for (String attachment : s.getAttachments()) {
418 System.out.println("- Stored plaintext in: " + attachment);
419 }
420 }
421 System.out.println();
422 }
423 });
424 dBusConn.addSigHandler(Signal.ReceiptReceived.class, new DBusSigHandler<Signal.ReceiptReceived>() {
425 @Override
426 public void handle(Signal.ReceiptReceived s) {
427 System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
428 s.getSender(), DateUtils.formatTimestamp(s.getTimestamp())));
429 }
430 });
431 } catch (UnsatisfiedLinkError e) {
432 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
433 return 1;
434 } catch (DBusException e) {
435 e.printStackTrace();
436 return 1;
437 }
438 while (true) {
439 try {
440 Thread.sleep(10000);
441 } catch (InterruptedException e) {
442 return 0;
443 }
444 }
445 }
446 if (!m.isRegistered()) {
447 System.err.println("User is not registered.");
448 return 1;
449 }
450 double timeout = 5;
451 if (ns.getDouble("timeout") != null) {
452 timeout = ns.getDouble("timeout");
453 }
454 boolean returnOnTimeout = true;
455 if (timeout < 0) {
456 returnOnTimeout = false;
457 timeout = 3600;
458 }
459 boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
460 try {
461 final Manager.ReceiveMessageHandler handler = ns.getBoolean("json") ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m);
462 m.receiveMessages((long) (timeout * 1000), TimeUnit.MILLISECONDS, returnOnTimeout, ignoreAttachments, handler);
463 } catch (IOException e) {
464 System.err.println("Error while receiving messages: " + e.getMessage());
465 return 3;
466 } catch (AssertionError e) {
467 handleAssertionError(e);
468 return 1;
469 }
470 break;
471 case "quitGroup":
472 if (dBusConn != null) {
473 System.err.println("quitGroup is not yet implemented via dbus");
474 return 1;
475 }
476 if (!m.isRegistered()) {
477 System.err.println("User is not registered.");
478 return 1;
479 }
480
481 try {
482 m.sendQuitGroupMessage(Util.decodeGroupId(ns.getString("group")));
483 } catch (IOException e) {
484 handleIOException(e);
485 return 3;
486 } catch (EncapsulatedExceptions e) {
487 handleEncapsulatedExceptions(e);
488 return 3;
489 } catch (AssertionError e) {
490 handleAssertionError(e);
491 return 1;
492 } catch (GroupNotFoundException e) {
493 handleGroupNotFoundException(e);
494 return 1;
495 } catch (NotAGroupMemberException e) {
496 handleNotAGroupMemberException(e);
497 return 1;
498 } catch (GroupIdFormatException e) {
499 handleGroupIdFormatException(e);
500 return 1;
501 }
502
503 break;
504 case "updateGroup":
505 if (dBusConn == null && !m.isRegistered()) {
506 System.err.println("User is not registered.");
507 return 1;
508 }
509
510 try {
511 byte[] groupId = null;
512 if (ns.getString("group") != null) {
513 groupId = Util.decodeGroupId(ns.getString("group"));
514 }
515 if (groupId == null) {
516 groupId = new byte[0];
517 }
518 String groupName = ns.getString("name");
519 if (groupName == null) {
520 groupName = "";
521 }
522 List<String> groupMembers = ns.getList("member");
523 if (groupMembers == null) {
524 groupMembers = new ArrayList<>();
525 }
526 String groupAvatar = ns.getString("avatar");
527 if (groupAvatar == null) {
528 groupAvatar = "";
529 }
530 byte[] newGroupId = ts.updateGroup(groupId, groupName, groupMembers, groupAvatar);
531 if (groupId.length != newGroupId.length) {
532 System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" …");
533 }
534 } catch (IOException e) {
535 handleIOException(e);
536 return 3;
537 } catch (AttachmentInvalidException e) {
538 System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
539 System.err.println("Aborting sending.");
540 return 1;
541 } catch (GroupNotFoundException e) {
542 handleGroupNotFoundException(e);
543 return 1;
544 } catch (NotAGroupMemberException e) {
545 handleNotAGroupMemberException(e);
546 return 1;
547 } catch (EncapsulatedExceptions e) {
548 handleEncapsulatedExceptions(e);
549 return 3;
550 } catch (GroupIdFormatException e) {
551 handleGroupIdFormatException(e);
552 return 1;
553 }
554
555 break;
556 case "listGroups":
557 if (dBusConn != null) {
558 System.err.println("listGroups is not yet implemented via dbus");
559 return 1;
560 }
561 if (!m.isRegistered()) {
562 System.err.println("User is not registered.");
563 return 1;
564 }
565
566 List<GroupInfo> groups = m.getGroups();
567 boolean detailed = ns.getBoolean("detailed");
568
569 for (GroupInfo group : groups) {
570 printGroup(group, detailed);
571 }
572 break;
573 case "listIdentities":
574 if (dBusConn != null) {
575 System.err.println("listIdentities is not yet implemented via dbus");
576 return 1;
577 }
578 if (!m.isRegistered()) {
579 System.err.println("User is not registered.");
580 return 1;
581 }
582 if (ns.get("number") == null) {
583 for (Map.Entry<String, List<JsonIdentityKeyStore.Identity>> keys : m.getIdentities().entrySet()) {
584 for (JsonIdentityKeyStore.Identity id : keys.getValue()) {
585 printIdentityFingerprint(m, keys.getKey(), id);
586 }
587 }
588 } else {
589 String number = ns.getString("number");
590 for (JsonIdentityKeyStore.Identity id : m.getIdentities(number)) {
591 printIdentityFingerprint(m, number, id);
592 }
593 }
594 break;
595 case "trust":
596 if (dBusConn != null) {
597 System.err.println("trust is not yet implemented via dbus");
598 return 1;
599 }
600 if (!m.isRegistered()) {
601 System.err.println("User is not registered.");
602 return 1;
603 }
604 String number = ns.getString("number");
605 if (ns.getBoolean("trust_all_known_keys")) {
606 boolean res = m.trustIdentityAllKeys(number);
607 if (!res) {
608 System.err.println("Failed to set the trust for this number, make sure the number is correct.");
609 return 1;
610 }
611 } else {
612 String fingerprint = ns.getString("verified_fingerprint");
613 if (fingerprint != null) {
614 fingerprint = fingerprint.replaceAll(" ", "");
615 if (fingerprint.length() == 66) {
616 byte[] fingerprintBytes;
617 try {
618 fingerprintBytes = Hex.toByteArray(fingerprint.toLowerCase(Locale.ROOT));
619 } catch (Exception e) {
620 System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
621 return 1;
622 }
623 boolean res = m.trustIdentityVerified(number, fingerprintBytes);
624 if (!res) {
625 System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
626 return 1;
627 }
628 } else if (fingerprint.length() == 60) {
629 boolean res = m.trustIdentityVerifiedSafetyNumber(number, fingerprint);
630 if (!res) {
631 System.err.println("Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");
632 return 1;
633 }
634 } else {
635 System.err.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
636 return 1;
637 }
638 } else {
639 System.err.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
640 return 1;
641 }
642 }
643 break;
644 case "daemon":
645 if (dBusConn != null) {
646 System.err.println("Stop it.");
647 return 1;
648 }
649 if (!m.isRegistered()) {
650 System.err.println("User is not registered.");
651 return 1;
652 }
653 DBusConnection conn = null;
654 try {
655 try {
656 int busType;
657 if (ns.getBoolean("system")) {
658 busType = DBusConnection.SYSTEM;
659 } else {
660 busType = DBusConnection.SESSION;
661 }
662 conn = DBusConnection.getConnection(busType);
663 conn.exportObject(SIGNAL_OBJECTPATH, m);
664 conn.requestBusName(SIGNAL_BUSNAME);
665 } catch (UnsatisfiedLinkError e) {
666 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
667 return 1;
668 } catch (DBusException e) {
669 e.printStackTrace();
670 return 2;
671 }
672 ignoreAttachments = ns.getBoolean("ignore_attachments");
673 try {
674 m.receiveMessages(1, TimeUnit.HOURS, false, ignoreAttachments, ns.getBoolean("json") ? new JsonDbusReceiveMessageHandler(m, conn, Main.SIGNAL_OBJECTPATH) : new DbusReceiveMessageHandler(m, conn, Main.SIGNAL_OBJECTPATH));
675 } catch (IOException e) {
676 System.err.println("Error while receiving messages: " + e.getMessage());
677 return 3;
678 } catch (AssertionError e) {
679 handleAssertionError(e);
680 return 1;
681 }
682 } finally {
683 if (conn != null) {
684 conn.disconnect();
685 }
686 }
687
688 break;
689 }
690 return 0;
691 } finally {
692 if (dBusConn != null) {
693 dBusConn.disconnect();
694 }
695 }
696 }
697
698 private static void printIdentityFingerprint(Manager m, String theirUsername, JsonIdentityKeyStore.Identity theirId) {
699 String digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirUsername, theirId.getIdentityKey()));
700 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername,
701 theirId.getTrustLevel(), theirId.getDateAdded(), Hex.toStringCondensed(theirId.getFingerprint()), digits));
702 }
703
704 private static void printGroup(GroupInfo group, boolean detailed) {
705 if (detailed) {
706 System.out.println(String.format("Id: %s Name: %s Active: %s Members: %s",
707 Base64.encodeBytes(group.groupId), group.name, group.active, group.members));
708 } else {
709 System.out.println(String.format("Id: %s Name: %s Active: %s", Base64.encodeBytes(group.groupId),
710 group.name, group.active));
711 }
712 }
713
714 private static Namespace parseArgs(String[] args) {
715 ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
716 .build()
717 .defaultHelp(true)
718 .description("Commandline interface for Signal.")
719 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
720
721 parser.addArgument("-v", "--version")
722 .help("Show package version.")
723 .action(Arguments.version());
724 parser.addArgument("--config")
725 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
726
727 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
728 mut.addArgument("-u", "--username")
729 .help("Specify your phone number, that will be used for verification.");
730 mut.addArgument("--dbus")
731 .help("Make request via user dbus.")
732 .action(Arguments.storeTrue());
733 mut.addArgument("--dbus-system")
734 .help("Make request via system dbus.")
735 .action(Arguments.storeTrue());
736
737 Subparsers subparsers = parser.addSubparsers()
738 .title("subcommands")
739 .dest("command")
740 .description("valid subcommands")
741 .help("additional help");
742
743 Subparser parserLink = subparsers.addParser("link");
744 parserLink.addArgument("-n", "--name")
745 .help("Specify a name to describe this new device.");
746
747 Subparser parserAddDevice = subparsers.addParser("addDevice");
748 parserAddDevice.addArgument("--uri")
749 .required(true)
750 .help("Specify the uri contained in the QR code shown by the new device.");
751
752 Subparser parserDevices = subparsers.addParser("listDevices");
753
754 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
755 parserRemoveDevice.addArgument("-d", "--deviceId")
756 .type(int.class)
757 .required(true)
758 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
759
760 Subparser parserRegister = subparsers.addParser("register");
761 parserRegister.addArgument("-v", "--voice")
762 .help("The verification should be done over voice, not sms.")
763 .action(Arguments.storeTrue());
764
765 Subparser parserUnregister = subparsers.addParser("unregister");
766 parserUnregister.help("Unregister the current device from the signal server.");
767
768 Subparser parserUpdateAccount = subparsers.addParser("updateAccount");
769 parserUpdateAccount.help("Update the account attributes on the signal server.");
770
771 Subparser parserSetPin = subparsers.addParser("setPin");
772 parserSetPin.addArgument("registrationLockPin")
773 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
774
775 Subparser parserRemovePin = subparsers.addParser("removePin");
776
777 Subparser parserVerify = subparsers.addParser("verify");
778 parserVerify.addArgument("verificationCode")
779 .help("The verification code you received via sms or voice call.");
780 parserVerify.addArgument("-p", "--pin")
781 .help("The registration lock PIN, that was set by the user (Optional)");
782
783 Subparser parserSend = subparsers.addParser("send");
784 parserSend.addArgument("-g", "--group")
785 .help("Specify the recipient group ID.");
786 parserSend.addArgument("recipient")
787 .help("Specify the recipients' phone number.")
788 .nargs("*");
789 parserSend.addArgument("-m", "--message")
790 .help("Specify the message, if missing standard input is used.");
791 parserSend.addArgument("-a", "--attachment")
792 .nargs("*")
793 .help("Add file as attachment");
794 parserSend.addArgument("-e", "--endsession")
795 .help("Clear session state and send end session message.")
796 .action(Arguments.storeTrue());
797
798 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
799 parserLeaveGroup.addArgument("-g", "--group")
800 .required(true)
801 .help("Specify the recipient group ID.");
802
803 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
804 parserUpdateGroup.addArgument("-g", "--group")
805 .help("Specify the recipient group ID.");
806 parserUpdateGroup.addArgument("-n", "--name")
807 .help("Specify the new group name.");
808 parserUpdateGroup.addArgument("-a", "--avatar")
809 .help("Specify a new group avatar image file");
810 parserUpdateGroup.addArgument("-m", "--member")
811 .nargs("*")
812 .help("Specify one or more members to add to the group");
813
814 Subparser parserListGroups = subparsers.addParser("listGroups");
815 parserListGroups.addArgument("-d", "--detailed").action(Arguments.storeTrue())
816 .help("List members of each group");
817 parserListGroups.help("List group name and ids");
818
819 Subparser parserListIdentities = subparsers.addParser("listIdentities");
820 parserListIdentities.addArgument("-n", "--number")
821 .help("Only show identity keys for the given phone number.");
822
823 Subparser parserTrust = subparsers.addParser("trust");
824 parserTrust.addArgument("number")
825 .help("Specify the phone number, for which to set the trust.")
826 .required(true);
827 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
828 mutTrust.addArgument("-a", "--trust-all-known-keys")
829 .help("Trust all known keys of this user, only use this for testing.")
830 .action(Arguments.storeTrue());
831 mutTrust.addArgument("-v", "--verified-fingerprint")
832 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
833
834 Subparser parserReceive = subparsers.addParser("receive");
835 parserReceive.addArgument("-t", "--timeout")
836 .type(double.class)
837 .help("Number of seconds to wait for new messages (negative values disable timeout)");
838 parserReceive.addArgument("--ignore-attachments")
839 .help("Don’t download attachments of received messages.")
840 .action(Arguments.storeTrue());
841 parserReceive.addArgument("--json")
842 .help("Output received messages in json format, one json object per line.")
843 .action(Arguments.storeTrue());
844
845 Subparser parserDaemon = subparsers.addParser("daemon");
846 parserDaemon.addArgument("--system")
847 .action(Arguments.storeTrue())
848 .help("Use DBus system bus instead of user bus.");
849 parserDaemon.addArgument("--ignore-attachments")
850 .help("Don’t download attachments of received messages.")
851 .action(Arguments.storeTrue());
852 parserDaemon.addArgument("--json")
853 .help("Output received messages in json format, one json object per line.")
854 .action(Arguments.storeTrue());
855
856 try {
857 Namespace ns = parser.parseArgs(args);
858 if ("link".equals(ns.getString("command"))) {
859 if (ns.getString("username") != null) {
860 parser.printUsage();
861 System.err.println("You cannot specify a username (phone number) when linking");
862 System.exit(2);
863 }
864 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
865 if (ns.getString("username") == null) {
866 parser.printUsage();
867 System.err.println("You need to specify a username (phone number)");
868 System.exit(2);
869 }
870 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
871 System.err.println("Invalid username (phone number), make sure you include the country code.");
872 System.exit(2);
873 }
874 }
875 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
876 System.err.println("You cannot specify recipients by phone number and groups a the same time");
877 System.exit(2);
878 }
879 return ns;
880 } catch (ArgumentParserException e) {
881 parser.handleError(e);
882 return null;
883 }
884 }
885 }