Add --verbose flag to show extended logging

Fixes #379
This commit is contained in:
AsamK 2021-01-15 11:43:53 +01:00
parent 20681b8d89
commit 5938d54784
6 changed files with 315 additions and 207 deletions

View file

@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
### Added
- `--verbose` flag to increase log level
### Fixed
- Disable registration lock before removing the PIN

View file

@ -32,6 +32,9 @@ Show help message and quit.
*-v*, *--version*::
Print the version and quit.
*--verbose*::
Raise log level and include lib signal logs.
*--config* CONFIG::
Set the path, where to store the config.
Make sure you have full read/write access to the given directory.

View file

@ -0,0 +1,206 @@
package org.asamk.signal;
import net.sourceforge.argparse4j.inf.Namespace;
import org.asamk.Signal;
import org.asamk.signal.commands.Command;
import org.asamk.signal.commands.Commands;
import org.asamk.signal.commands.DbusCommand;
import org.asamk.signal.commands.ExtendedDbusCommand;
import org.asamk.signal.commands.LocalCommand;
import org.asamk.signal.commands.ProvisioningCommand;
import org.asamk.signal.commands.RegistrationCommand;
import org.asamk.signal.dbus.DbusSignalImpl;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.NotRegisteredException;
import org.asamk.signal.manager.ProvisioningManager;
import org.asamk.signal.manager.RegistrationManager;
import org.asamk.signal.manager.ServiceConfig;
import org.asamk.signal.util.IOUtils;
import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration;
import java.io.File;
import java.io.IOException;
public class Cli {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
private final Namespace ns;
public Cli(final Namespace ns) {
this.ns = ns;
}
public int init() {
Command command = getCommand();
if (command == null) {
logger.error("Command not implemented!");
return 2;
}
if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
return initDbusClient(command, ns.getBoolean("dbus_system"));
}
final String username = ns.getString("username");
final File dataPath;
String config = ns.getString("config");
if (config != null) {
dataPath = new File(config);
} else {
dataPath = getDefaultDataPath();
}
final SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(
BaseConfig.USER_AGENT);
if (!ServiceConfig.getCapabilities().isGv2()) {
logger.warn("WARNING: Support for new group V2 is disabled,"
+ " because the required native library dependency is missing: libzkgroup");
}
if (username == null) {
ProvisioningManager pm = new ProvisioningManager(dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
return handleCommand(command, pm);
}
if (command instanceof RegistrationCommand) {
final RegistrationManager manager;
try {
manager = RegistrationManager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
} catch (Throwable e) {
logger.error("Error loading or creating state file: {}", e.getMessage());
return 1;
}
try (RegistrationManager m = manager) {
return handleCommand(command, m);
} catch (Exception e) {
logger.error("Cleanup failed", e);
return 2;
}
}
Manager manager;
try {
manager = Manager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
} catch (NotRegisteredException e) {
System.err.println("User is not registered.");
return 0;
} catch (Throwable e) {
logger.error("Error loading state file: {}", e.getMessage());
return 1;
}
try (Manager m = manager) {
try {
m.checkAccountState();
} catch (IOException e) {
logger.error("Error while checking account: {}", e.getMessage());
return 1;
}
return handleCommand(command, m);
} catch (IOException e) {
logger.error("Cleanup failed", e);
return 2;
}
}
private Command getCommand() {
String commandKey = ns.getString("command");
return Commands.getCommand(commandKey);
}
private int initDbusClient(final Command command, final boolean systemBus) {
try {
DBusConnection.DBusBusType busType;
if (systemBus) {
busType = DBusConnection.DBusBusType.SYSTEM;
} else {
busType = DBusConnection.DBusBusType.SESSION;
}
try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
Signal ts = dBusConn.getRemoteObject(DbusConfig.SIGNAL_BUSNAME,
DbusConfig.SIGNAL_OBJECTPATH,
Signal.class);
return handleCommand(command, ts, dBusConn);
}
} catch (DBusException | IOException e) {
logger.error("Dbus client failed", e);
return 2;
}
}
private int handleCommand(Command command, Signal ts, DBusConnection dBusConn) {
if (command instanceof ExtendedDbusCommand) {
return ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
} else if (command instanceof DbusCommand) {
return ((DbusCommand) command).handleCommand(ns, ts);
} else {
System.err.println("Command is not yet implemented via dbus");
return 1;
}
}
private int handleCommand(Command command, ProvisioningManager pm) {
if (command instanceof ProvisioningCommand) {
return ((ProvisioningCommand) command).handleCommand(ns, pm);
} else {
System.err.println("Command only works with a username");
return 1;
}
}
private int handleCommand(Command command, RegistrationManager m) {
if (command instanceof RegistrationCommand) {
return ((RegistrationCommand) command).handleCommand(ns, m);
}
return 1;
}
private int handleCommand(Command command, Manager m) {
if (command instanceof LocalCommand) {
return ((LocalCommand) command).handleCommand(ns, m);
} else if (command instanceof DbusCommand) {
return ((DbusCommand) command).handleCommand(ns, new DbusSignalImpl(m));
} else {
System.err.println("Command only works via dbus");
return 1;
}
}
/**
* Uses $XDG_DATA_HOME/signal-cli if it exists, or if none of the legacy directories exist:
* - $HOME/.config/signal
* - $HOME/.config/textsecure
*
* @return the data directory to be used by signal-cli.
*/
private static File getDefaultDataPath() {
File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
if (dataPath.exists()) {
return dataPath;
}
File configPath = new File(System.getProperty("user.home"), ".config");
File legacySettingsPath = new File(configPath, "signal");
if (legacySettingsPath.exists()) {
return legacySettingsPath;
}
legacySettingsPath = new File(configPath, "textsecure");
if (legacySettingsPath.exists()) {
return legacySettingsPath;
}
return dataPath;
}
}

View file

@ -25,227 +25,62 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import org.asamk.Signal;
import org.asamk.signal.commands.Command;
import org.asamk.signal.commands.Commands;
import org.asamk.signal.commands.DbusCommand;
import org.asamk.signal.commands.ExtendedDbusCommand;
import org.asamk.signal.commands.LocalCommand;
import org.asamk.signal.commands.ProvisioningCommand;
import org.asamk.signal.commands.RegistrationCommand;
import org.asamk.signal.dbus.DbusSignalImpl;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.NotRegisteredException;
import org.asamk.signal.manager.ProvisioningManager;
import org.asamk.signal.manager.RegistrationManager;
import org.asamk.signal.manager.ServiceConfig;
import org.asamk.signal.util.IOUtils;
import org.asamk.signal.manager.LibSignalLogger;
import org.asamk.signal.util.SecurityProvider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration;
import java.io.File;
import java.io.IOException;
import java.security.Security;
import java.util.Map;
public class Main {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
installSecurityProviderWorkaround();
// Configuring the logger needs to happen before any logger is initialized
if (isVerbose(args)) {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
System.setProperty("org.slf4j.simpleLogger.showThreadName", "true");
System.setProperty("org.slf4j.simpleLogger.showShortLogName", "false");
System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd'T'HH:mm:ss.SSSXX");
LibSignalLogger.initLogger();
} else {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
System.setProperty("org.slf4j.simpleLogger.showShortLogName", "true");
System.setProperty("org.slf4j.simpleLogger.showDateTime", "false");
}
Namespace ns = parseArgs(args);
if (ns == null) {
System.exit(1);
}
int res = init(ns);
int res = new Cli(ns).init();
System.exit(res);
}
public static void installSecurityProviderWorkaround() {
private static void installSecurityProviderWorkaround() {
// Register our own security provider
Security.insertProviderAt(new SecurityProvider(), 1);
Security.addProvider(new BouncyCastleProvider());
}
public static int init(Namespace ns) {
Command command = getCommand(ns);
if (command == null) {
logger.error("Command not implemented!");
return 3;
}
private static boolean isVerbose(String[] args) {
ArgumentParser parser = buildBaseArgumentParser();
if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
return initDbusClient(command, ns, ns.getBoolean("dbus_system"));
}
final String username = ns.getString("username");
final File dataPath;
String config = ns.getString("config");
if (config != null) {
dataPath = new File(config);
} else {
dataPath = getDefaultDataPath();
}
final SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(
BaseConfig.USER_AGENT);
if (!ServiceConfig.getCapabilities().isGv2()) {
logger.warn("WARNING: Support for new group V2 is disabled,"
+ " because the required native library dependency is missing: libzkgroup");
}
if (username == null) {
ProvisioningManager pm = new ProvisioningManager(dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
return handleCommand(command, ns, pm);
}
if (command instanceof RegistrationCommand) {
final RegistrationManager manager;
Namespace ns;
try {
manager = RegistrationManager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
} catch (Throwable e) {
logger.error("Error loading or creating state file: {}", e.getMessage());
return 2;
}
try (RegistrationManager m = manager) {
return handleCommand(command, ns, m);
} catch (Exception e) {
logger.error("Cleanup failed", e);
return 3;
}
ns = parser.parseKnownArgs(args, null);
} catch (ArgumentParserException e) {
return false;
}
Manager manager;
try {
manager = Manager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
} catch (NotRegisteredException e) {
System.err.println("User is not registered.");
return 1;
} catch (Throwable e) {
logger.error("Error loading state file: {}", e.getMessage());
return 2;
}
try (Manager m = manager) {
try {
m.checkAccountState();
} catch (IOException e) {
logger.error("Error while checking account: {}", e.getMessage());
return 2;
}
return handleCommand(command, ns, m);
} catch (IOException e) {
logger.error("Cleanup failed", e);
return 3;
}
}
private static int initDbusClient(final Command command, final Namespace ns, final boolean systemBus) {
try {
DBusConnection.DBusBusType busType;
if (systemBus) {
busType = DBusConnection.DBusBusType.SYSTEM;
} else {
busType = DBusConnection.DBusBusType.SESSION;
}
try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
Signal ts = dBusConn.getRemoteObject(DbusConfig.SIGNAL_BUSNAME,
DbusConfig.SIGNAL_OBJECTPATH,
Signal.class);
return handleCommand(command, ns, ts, dBusConn);
}
} catch (DBusException | IOException e) {
logger.error("Dbus client failed", e);
return 3;
}
}
private static Command getCommand(Namespace ns) {
String commandKey = ns.getString("command");
final Map<String, Command> commands = Commands.getCommands();
if (!commands.containsKey(commandKey)) {
return null;
}
return commands.get(commandKey);
}
private static int handleCommand(Command command, Namespace ns, Signal ts, DBusConnection dBusConn) {
if (command instanceof ExtendedDbusCommand) {
return ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
} else if (command instanceof DbusCommand) {
return ((DbusCommand) command).handleCommand(ns, ts);
} else {
System.err.println("Command is not yet implemented via dbus");
return 1;
}
}
private static int handleCommand(Command command, Namespace ns, ProvisioningManager pm) {
if (command instanceof ProvisioningCommand) {
return ((ProvisioningCommand) command).handleCommand(ns, pm);
} else {
System.err.println("Command only works with a username");
return 1;
}
}
private static int handleCommand(Command command, Namespace ns, RegistrationManager m) {
if (command instanceof RegistrationCommand) {
return ((RegistrationCommand) command).handleCommand(ns, m);
}
return 1;
}
private static int handleCommand(Command command, Namespace ns, Manager m) {
if (command instanceof LocalCommand) {
return ((LocalCommand) command).handleCommand(ns, m);
} else if (command instanceof DbusCommand) {
return ((DbusCommand) command).handleCommand(ns, new DbusSignalImpl(m));
} else {
System.err.println("Command only works via dbus");
return 1;
}
}
/**
* Uses $XDG_DATA_HOME/signal-cli if it exists, or if none of the legacy directories exist:
* - $HOME/.config/signal
* - $HOME/.config/textsecure
*
* @return the data directory to be used by signal-cli.
*/
private static File getDefaultDataPath() {
File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
if (dataPath.exists()) {
return dataPath;
}
File configPath = new File(System.getProperty("user.home"), ".config");
File legacySettingsPath = new File(configPath, "signal");
if (legacySettingsPath.exists()) {
return legacySettingsPath;
}
legacySettingsPath = new File(configPath, "textsecure");
if (legacySettingsPath.exists()) {
return legacySettingsPath;
}
return dataPath;
return ns.getBoolean("verbose");
}
private static Namespace parseArgs(String[] args) {
@ -276,31 +111,17 @@ public class Main {
System.exit(2);
}
}
if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
System.err.println("You cannot specify recipients by phone number and groups at the same time");
System.exit(2);
}
return ns;
}
private static ArgumentParser buildArgumentParser() {
ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
.build()
.defaultHelp(true)
.description("Commandline interface for Signal.")
.version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
parser.addArgument("--config")
.help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
mut.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
mut.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments.storeTrue());
parser.addArgument("-o", "--output").help("Choose to output in plain text or JSON")
.choices("plain-text", "json").setDefault("plain-text");
ArgumentParser parser = buildBaseArgumentParser();
Subparsers subparsers = parser.addSubparsers()
.title("subcommands")
@ -313,6 +134,34 @@ public class Main {
Subparser subparser = subparsers.addParser(entry.getKey());
entry.getValue().attachToSubparser(subparser);
}
return parser;
}
private static ArgumentParser buildBaseArgumentParser() {
ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
.build()
.defaultHelp(true)
.description("Commandline interface for Signal.")
.version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
parser.addArgument("--verbose")
.help("Raise log level and include lib signal logs.")
.action(Arguments.storeTrue());
parser.addArgument("--config")
.help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
mut.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
mut.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments.storeTrue());
parser.addArgument("-o", "--output")
.help("Choose to output in plain text or JSON")
.choices("plain-text", "json")
.setDefault("plain-text");
return parser;
}
}

View file

@ -42,6 +42,13 @@ public class Commands {
return commands;
}
public static Command getCommand(String commandKey) {
if (!commands.containsKey(commandKey)) {
return null;
}
return commands.get(commandKey);
}
private static void addCommand(String name, Command command) {
commands.put(name, command);
}

View file

@ -0,0 +1,41 @@
package org.asamk.signal.manager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.libsignal.logging.SignalProtocolLogger;
import org.whispersystems.libsignal.logging.SignalProtocolLoggerProvider;
public class LibSignalLogger implements SignalProtocolLogger {
private final static Logger logger = LoggerFactory.getLogger("LibSignal");
public static void initLogger() {
SignalProtocolLoggerProvider.setProvider(new LibSignalLogger());
}
private LibSignalLogger() {
}
@Override
public void log(final int priority, final String tag, final String message) {
final String logMessage = String.format("[%s]: %s", tag, message);
switch (priority) {
case SignalProtocolLogger.VERBOSE:
logger.trace(logMessage);
break;
case SignalProtocolLogger.DEBUG:
logger.debug(logMessage);
break;
case SignalProtocolLogger.INFO:
logger.info(logMessage);
break;
case SignalProtocolLogger.WARN:
logger.warn(logMessage);
break;
case SignalProtocolLogger.ERROR:
case SignalProtocolLogger.ASSERT:
logger.error(logMessage);
break;
}
}
}