1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2025-09-09 17:19:39 +02:00

Add smack-examples

This commit is contained in:
Florian Schmaus 2023-11-28 10:46:16 +01:00
parent 5a78534443
commit 04dc212db8
17 changed files with 245 additions and 146 deletions

View file

@ -1,83 +0,0 @@
/**
*
* Copyright 2019 Florian Schmaus
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.io.IOException;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.debugger.ConsoleDebugger;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.dox.DnsOverXmppManager;
import org.jivesoftware.smackx.dox.resolver.minidns.DnsOverXmppMiniDnsResolver;
import org.jxmpp.jid.Jid;
import org.jxmpp.jid.impl.JidCreate;
import org.minidns.dnsmessage.DnsMessage;
import org.minidns.dnsmessage.Question;
import org.minidns.record.Record;
public class DoX {
public static void main(String[] args) throws XMPPException, SmackException, IOException, InterruptedException {
SmackConfiguration.DEBUG = true;
XMPPTCPConnection connection = new XMPPTCPConnection(args[0], args[1]);
connection.setReplyTimeout(60000);
connection.connect().login();
DnsOverXmppManager dox = DnsOverXmppManager.getInstanceFor(connection);
Jid target = JidCreate.from("dns@moparisthebest.com/listener");
Question question = new Question("geekplace.eu", Record.TYPE.A);
DnsMessage response = dox.query(target, question);
// CHECKSTYLE:OFF
System.out.println(response);
// CHECKSTYLE:ON
connection.disconnect();
}
public static XMPPTCPConnection runDoxResolver(String jid, String password)
throws XMPPException, SmackException, IOException, InterruptedException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setXmppAddressAndPassword(jid, password)
.setResource("dns")
.setDebuggerFactory(ConsoleDebugger.Factory.INSTANCE)
.build();
XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect().login();
DnsOverXmppManager dox = DnsOverXmppManager.getInstanceFor(connection);
dox.setDnsOverXmppResolver(DnsOverXmppMiniDnsResolver.INSTANCE);
dox.enable();
return connection;
}
}

View file

@ -1,231 +0,0 @@
/**
*
* Copyright 2016 Florian Schmaus
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterUtil;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.iot.IoTDiscoveryIntegrationTest;
import org.jivesoftware.smackx.iot.Thing;
import org.jivesoftware.smackx.iot.data.IoTDataManager;
import org.jivesoftware.smackx.iot.data.ThingMomentaryReadOutRequest;
import org.jivesoftware.smackx.iot.data.ThingMomentaryReadOutResult;
import org.jivesoftware.smackx.iot.data.element.IoTDataField;
import org.jivesoftware.smackx.iot.data.element.IoTDataField.IntField;
import org.jivesoftware.smackx.iot.data.element.IoTFieldsExtension;
import org.jivesoftware.smackx.iot.discovery.AbstractThingStateChangeListener;
import org.jivesoftware.smackx.iot.discovery.IoTDiscoveryManager;
import org.jivesoftware.smackx.iot.discovery.ThingState;
import org.jivesoftware.smackx.iot.provisioning.BecameFriendListener;
import org.jivesoftware.smackx.iot.provisioning.IoTProvisioningManager;
import org.igniterealtime.smack.inttest.util.SimpleResultSyncPoint;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
public class IoT {
// A 10 minute timeout.
private static final long TIMEOUT = 10 * 60 * 1000;
private interface IotScenario {
void iotScenario(XMPPTCPConnection dataThingConnection, XMPPTCPConnection readingThingConnection) throws Exception;
}
public static void iotScenario(String dataThingJidString, String dataThingPassword, String readingThingJidString,
String readingThingPassword, IotScenario scenario) throws Exception {
final EntityBareJid dataThingJid = JidCreate.entityBareFrom(dataThingJidString);
final EntityBareJid readingThingJid = JidCreate.entityBareFrom(readingThingJidString);
final XMPPTCPConnectionConfiguration dataThingConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(dataThingJid.getLocalpart(), dataThingPassword)
.setXmppDomain(dataThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
.enableDefaultDebugger().build();
final XMPPTCPConnectionConfiguration readingThingConnectionConfiguration = XMPPTCPConnectionConfiguration
.builder().setUsernameAndPassword(readingThingJid.getLocalpart(), readingThingPassword)
.setXmppDomain(readingThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
.enableDefaultDebugger().build();
final XMPPTCPConnection dataThingConnection = new XMPPTCPConnection(dataThingConnectionConfiguration);
final XMPPTCPConnection readingThingConnection = new XMPPTCPConnection(readingThingConnectionConfiguration);
dataThingConnection.setReplyTimeout(TIMEOUT);
readingThingConnection.setReplyTimeout(TIMEOUT);
dataThingConnection.setUseStreamManagement(false);
readingThingConnection.setUseStreamManagement(false);
try {
dataThingConnection.connect().login();
readingThingConnection.connect().login();
scenario.iotScenario(dataThingConnection, readingThingConnection);
} finally {
dataThingConnection.disconnect();
readingThingConnection.disconnect();
}
}
public static void iotReadOutScenario(String dataThingJidString, String dataThingPassword, String readingThingJidString,
String readingThingPassword)
throws Exception {
iotScenario(dataThingJidString, dataThingPassword, readingThingJidString, readingThingPassword, READ_OUT_SCENARIO);
}
public static final IotScenario READ_OUT_SCENARIO = new IotScenario() {
@Override
public void iotScenario(XMPPTCPConnection dataThingConnection, XMPPTCPConnection readingThingConnection) throws TimeoutException, Exception {
ThingState dataThingState = actAsDataThing(dataThingConnection);
final SimpleResultSyncPoint syncPoint = new SimpleResultSyncPoint();
dataThingState.setThingStateChangeListener(new AbstractThingStateChangeListener() {
@Override
public void owned(BareJid jid) {
syncPoint.signal();
}
});
// Wait until the thing is owned.
syncPoint.waitForResult(TIMEOUT);
printStatus("OWNED - Thing now owned by " + dataThingState.getOwner());
// Make sure things are befriended.
IoTProvisioningManager readingThingProvisioningManager = IoTProvisioningManager.getInstanceFor(readingThingConnection);
readingThingProvisioningManager.sendFriendshipRequestIfRequired(dataThingConnection.getUser().asBareJid());
Roster dataThingRoster = Roster.getInstanceFor(dataThingConnection);
RosterUtil.waitUntilOtherEntityIsSubscribed(dataThingRoster, readingThingConnection.getUser().asBareJid(), TIMEOUT);
printStatus("FRIENDSHIP ACCEPTED - Trying to read out data");
IoTDataManager readingThingDataManager = IoTDataManager.getInstanceFor(readingThingConnection);
List<IoTFieldsExtension> values = readingThingDataManager.requestMomentaryValuesReadOut(dataThingConnection.getUser());
if (values.size() != 1) {
throw new IllegalStateException("Unexpected number of values returned: " + values.size());
}
IoTFieldsExtension field = values.get(0);
printStatus("DATA READ-OUT SUCCESS: " + field.toXML());
printStatus("IoT SCENARIO FINISHED SUCCESSFULLY");
}
};
public static void iotOwnerApprovesFriendScenario(String dataThingJidString, String dataThingPassword,
String readingThingJidString, String readingThingPassword) throws Exception {
iotScenario(dataThingJidString, dataThingPassword, readingThingJidString, readingThingPassword,
OWNER_APPROVES_FRIEND_SCENARIO);
}
public static final IotScenario OWNER_APPROVES_FRIEND_SCENARIO = new IotScenario() {
@Override
public void iotScenario(XMPPTCPConnection dataThingConnection, XMPPTCPConnection readingThingConnection) throws TimeoutException, Exception {
// First ensure that the two XMPP entities are not already subscribed to each other presences.
RosterUtil.ensureNotSubscribedToEachOther(dataThingConnection, readingThingConnection);
final BareJid dataThingBareJid = dataThingConnection.getUser().asBareJid();
final BareJid readingThingBareJid = readingThingConnection.getUser().asBareJid();
final ThingState dataThingState = actAsDataThing(dataThingConnection);
printStatus("WAITING for 'claimed' notification. Please claim thing now");
final SimpleResultSyncPoint syncPoint = new SimpleResultSyncPoint();
dataThingState.setThingStateChangeListener(new AbstractThingStateChangeListener() {
@Override
public void owned(BareJid jid) {
syncPoint.signal();
}
});
// Wait until the thing is owned.
syncPoint.waitForResult(TIMEOUT);
printStatus("OWNED - Thing now owned by " + dataThingState.getOwner());
// Now, ReadingThing sends a friendship request to data thing, which
// will proxy the request to its provisioning service, which will
// likely return that both a not friends since the owner did not
// authorize the friendship yet.
final SimpleResultSyncPoint friendshipApprovedSyncPoint = new SimpleResultSyncPoint();
final IoTProvisioningManager readingThingProvisioningManager = IoTProvisioningManager.getInstanceFor(readingThingConnection);
final BecameFriendListener becameFriendListener = new BecameFriendListener() {
@Override
public void becameFriend(BareJid jid, Presence presence) {
if (jid.equals(dataThingBareJid)) {
friendshipApprovedSyncPoint.signal();
}
}
};
readingThingProvisioningManager.addBecameFriendListener(becameFriendListener);
try {
readingThingProvisioningManager
.sendFriendshipRequestIfRequired(dataThingConnection.getUser().asBareJid());
friendshipApprovedSyncPoint.waitForResult(TIMEOUT);
} finally {
readingThingProvisioningManager.removeBecameFriendListener(becameFriendListener);
}
printStatus("FRIENDSHIP APPROVED - ReadingThing " + readingThingBareJid + " is now a friend of DataThing " + dataThingBareJid);
}
};
private static ThingState actAsDataThing(XMPPTCPConnection connection) throws XMPPException, SmackException, InterruptedException {
final String key = StringUtils.randomString(12);
final String sn = StringUtils.randomString(12);
Thing dataThing = Thing.builder()
.setKey(key)
.setSerialNumber(sn)
.setManufacturer("IgniteRealtime")
.setModel("Smack")
.setVersion("0.1")
.setMomentaryReadOutRequestHandler(new ThingMomentaryReadOutRequest() {
@Override
public void momentaryReadOutRequest(ThingMomentaryReadOutResult callback) {
IoTDataField.IntField field = new IntField("timestamp", (int) (System.currentTimeMillis() / 1000));
callback.momentaryReadOut(Collections.singletonList(field));
}
})
.build();
IoTDiscoveryManager iotDiscoveryManager = IoTDiscoveryManager.getInstanceFor(connection);
ThingState state = IoTDiscoveryIntegrationTest.registerThing(iotDiscoveryManager, dataThing);
printStatus("SUCCESS: Thing registered:" + dataThing);
return state;
}
private static void printStatus(CharSequence status) {
// CHECKSTYLE:OFF
System.out.println(status);
// CHECKSTYLE:ON
}
public static void main(String[] args) throws Exception {
if (args.length != 4) {
throw new IllegalArgumentException();
}
iotOwnerApprovesFriendScenario(args[0], args[1], args[2], args[3]);
}
}

View file

@ -1,108 +0,0 @@
/**
*
* Copyright 2018-2021 Florian Schmaus
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection;
import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnectionConfiguration;
import org.jivesoftware.smack.compression.CompressionModuleDescriptor;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.compression.XMPPInputOutputStream.FlushMethod;
import org.jivesoftware.smack.debugger.ConsoleDebugger;
import org.jivesoftware.smack.debugger.SmackDebuggerFactory;
import org.jivesoftware.smack.sm.StreamManagementModuleDescriptor;
import org.jivesoftware.smack.tcp.XmppTcpTransportModuleDescriptor;
public class Nio {
public static void main(String[] args) throws SmackException, IOException, XMPPException, InterruptedException {
doNio(args[0], args[1], args[2]);
}
public static void doNio(String username, String password, String service)
throws SmackException, IOException, XMPPException, InterruptedException {
boolean useTls = true;
boolean useStreamMangement = false;
boolean useCompression = true;
boolean useFullFlush = true;
boolean javaNetDebug = false;
boolean smackDebug = true;
if (useFullFlush) {
XMPPInputOutputStream.setFlushMethod(FlushMethod.FULL_FLUSH);
}
if (javaNetDebug) {
System.setProperty("javax.net.debug", "all");
}
final SecurityMode securityMode;
if (useTls) {
securityMode = SecurityMode.required;
} else {
securityMode = SecurityMode.disabled;
}
final SmackDebuggerFactory smackDebuggerFactory;
if (smackDebug) {
smackDebuggerFactory = ConsoleDebugger.Factory.INSTANCE;
} else {
smackDebuggerFactory = null;
}
ModularXmppClientToServerConnectionConfiguration.Builder configurationBuilder = ModularXmppClientToServerConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setXmppDomain(service)
.setDebuggerFactory(smackDebuggerFactory)
.setSecurityMode(securityMode)
.removeAllModules()
.addModule(XmppTcpTransportModuleDescriptor.class);
if (useCompression) {
configurationBuilder.addModule(CompressionModuleDescriptor.class);
configurationBuilder.setCompressionEnabled(true);
}
if (useStreamMangement) {
configurationBuilder.addModule(StreamManagementModuleDescriptor.class);
}
ModularXmppClientToServerConnectionConfiguration configuration = configurationBuilder.build();
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8)));
configuration.printStateGraphInDotFormat(printWriter, false);
printWriter.flush();
ModularXmppClientToServerConnection connection = new ModularXmppClientToServerConnection(configuration);
connection.setReplyTimeout(5 * 60 * 1000);
XmppTools.modularConnectionTest(connection, "flo@geekplace.eu");
}
}

View file

@ -1,220 +0,0 @@
/**
*
* Copyright 2019 Paul Schaub
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.NotLoggedInException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.MessageBuilder;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.carbons.packet.CarbonExtension;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.omemo.OmemoManager;
import org.jivesoftware.smackx.omemo.OmemoMessage;
import org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException;
import org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException;
import org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException;
import org.jivesoftware.smackx.omemo.exceptions.UndecidedOmemoIdentityException;
import org.jivesoftware.smackx.omemo.internal.OmemoDevice;
import org.jivesoftware.smackx.omemo.listener.OmemoMessageListener;
import org.jivesoftware.smackx.omemo.listener.OmemoMucMessageListener;
import org.jivesoftware.smackx.omemo.signal.SignalCachingOmemoStore;
import org.jivesoftware.smackx.omemo.signal.SignalFileBasedOmemoStore;
import org.jivesoftware.smackx.omemo.signal.SignalOmemoService;
import org.jivesoftware.smackx.omemo.trust.OmemoFingerprint;
import org.jivesoftware.smackx.omemo.trust.OmemoTrustCallback;
import org.jivesoftware.smackx.omemo.trust.TrustState;
import org.jivesoftware.smackx.pubsub.PubSubException;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
public class OmemoClient {
public static final Logger LOGGER = Logger.getLogger(OmemoClient.class.getName());
private static final Scanner scanner = new Scanner(System.in, "UTF-8");
private final XMPPTCPConnection connection;
private final OmemoManager omemoManager;
public static void main(String[] args)
throws XMPPException, SmackException, IOException, InterruptedException, CorruptedOmemoKeyException {
SmackConfiguration.DEBUG = true;
if (args.length != 2) {
print("Missing arguments: <jid> <password>");
return;
}
SignalOmemoService.acknowledgeLicense();
SignalOmemoService.setup();
SignalOmemoService omemoService = (SignalOmemoService) SignalOmemoService.getInstance();
Path omemoStoreDirectory = Files.createTempDirectory("omemo-store");
omemoService.setOmemoStoreBackend(new SignalCachingOmemoStore(new SignalFileBasedOmemoStore(omemoStoreDirectory.toFile())));
EntityBareJid jid = JidCreate.entityBareFromOrThrowUnchecked(args[0]);
String password = args[1];
OmemoClient client = new OmemoClient(jid, password);
try {
client.start();
while (true) {
String input = scanner.nextLine();
if (input.startsWith("/quit")) {
break;
}
if (input.isEmpty()) {
continue;
}
client.handleInput(input);
}
} finally {
client.stop();
}
}
public OmemoClient(EntityBareJid jid, String password) {
connection = new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
.setXmppAddressAndPassword(jid, password).build());
connection.setReplyTimeout(10 * 1000);
omemoManager = OmemoManager.getInstanceFor(connection);
omemoManager.setTrustCallback(new OmemoTrustCallback() {
// In a real app you'd want to persist these decisions
private final Map<OmemoFingerprint, TrustState> trustStateMap = new HashMap<>();
@Override
public TrustState getTrust(OmemoDevice device, OmemoFingerprint fingerprint) {
return trustStateMap.get(fingerprint) != null ? trustStateMap.get(fingerprint) : TrustState.undecided;
}
@Override
public void setTrust(OmemoDevice device, OmemoFingerprint fingerprint, TrustState state) {
trustStateMap.put(fingerprint, state);
}
});
omemoManager.addOmemoMessageListener(new OmemoMessageListener() {
@Override
public void onOmemoMessageReceived(Stanza s, OmemoMessage.Received m) {
print(m.getSenderDevice() + ": " + (m.getBody() != null ? m.getBody() : "<keyTransportMessage>"));
}
@Override
public void onOmemoCarbonCopyReceived(CarbonExtension.Direction d, Message cc, Message wm, OmemoMessage.Received m) {
onOmemoMessageReceived(cc, m);
}
});
omemoManager.addOmemoMucMessageListener(new OmemoMucMessageListener() {
@Override
public void onOmemoMucMessageReceived(MultiUserChat muc, Stanza s, OmemoMessage.Received m) {
print(s.getFrom() + ":" + m.getSenderDevice().getDeviceId() + ": " + (m.getBody() != null ? m.getBody() : "<keyTransportMessage>"));
}
});
}
public void start()
throws XMPPException, SmackException, IOException, InterruptedException, CorruptedOmemoKeyException {
connection.connect().login();
omemoManager.initialize();
print("Logged in!");
}
public void stop() {
connection.disconnect();
}
public void handleInput(String input)
throws NotConnectedException, NotLoggedInException, InterruptedException, IOException {
String[] com = input.split(" ", 3);
switch (com[0]) {
case "/omemo":
if (com.length < 3) {
print("Usage: /omemo <contact-jid> <message>");
return;
}
BareJid recipient = JidCreate.bareFrom(com[1]);
String body = com[2];
MessageBuilder messageBuilder = connection.getStanzaFactory().buildMessageStanza();
try {
Message omemoMessage = omemoManager.encrypt(recipient, body).buildMessage(messageBuilder, recipient);
connection.sendStanza(omemoMessage);
} catch (UndecidedOmemoIdentityException e) {
print("Undecided Identities!\n" + Arrays.toString(e.getUndecidedDevices().toArray()));
} catch (CryptoFailedException | SmackException.NoResponseException e) {
LOGGER.log(Level.SEVERE, "Unexpected Exception", e);
}
break;
case "/trust":
print("Trust");
if (com.length != 2) {
print("Usage: /trust <contact-jid>");
}
BareJid contact = JidCreate.bareFrom(com[1]);
HashMap<OmemoDevice, OmemoFingerprint> devices;
try {
devices = omemoManager.getActiveFingerprints(contact);
} catch (CorruptedOmemoKeyException | CannotEstablishOmemoSessionException | SmackException.NoResponseException e) {
LOGGER.log(Level.SEVERE, "Unexpected Exception", e);
return;
}
for (OmemoDevice d : devices.keySet()) {
print("Trust (1) or distrust (2)?\n" + devices.get(d).blocksOf8Chars());
if (Integer.parseInt(scanner.nextLine()) == 1) {
omemoManager.trustOmemoIdentity(d, devices.get(d));
} else {
omemoManager.distrustOmemoIdentity(d, devices.get(d));
}
}
print("Done.");
break;
case "/purge":
try {
omemoManager.purgeDeviceList();
print("Purged.");
} catch (XMPPException.XMPPErrorException | SmackException.NoResponseException | PubSubException.NotALeafNodeException e) {
LOGGER.log(Level.SEVERE, "Unexpected Exception", e);
}
}
}
private static void print(String msg) {
// CHECKSTYLE:OFF
System.out.println(msg);
// CHECKSTYLE:ON
}
}

View file

@ -1,121 +0,0 @@
/**
*
* Copyright 2016 Florian Schmaus
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.util.StringUtils;
import eu.geekplace.javapinning.java7.Java7Pinning;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
public class TlsTest {
// private static final Logger LOGGER = Logger.getLogger(TlsTest.class.getName());
public static boolean DEBUG = false;
public static void main(String[] args) throws XmppStringprepException, KeyManagementException, NoSuchAlgorithmException {
DEBUG = true;
tlsTest(args[0], args[1], args[2], args[3], args[4], args[5], true);
}
public static void tlsTest(String runsString, CharSequence jidCs, String password, String host, String portString,
String tlsPin, boolean shouldThrow) throws XmppStringprepException, KeyManagementException, NoSuchAlgorithmException {
int runs = Integer.parseInt(runsString);
int port = Integer.parseInt(portString);
tlsTest(runs, jidCs, password, host, port, tlsPin, shouldThrow);
}
public static void tlsTest(int runs, CharSequence jidCs, String password, String host, int port,
String tlsPin, boolean shouldThrow) throws XmppStringprepException, KeyManagementException, NoSuchAlgorithmException {
EntityBareJid jid = JidCreate.entityBareFrom(jidCs);
for (int i = 0; i < runs; i++) {
boolean res = tlsTest(jid, password, host, port, tlsPin, shouldThrow);
if (!res) {
throw new IllegalStateException();
}
}
}
public static boolean tlsTest(CharSequence jidCs, String password, String host, int port,
String tlsPin, boolean shouldThrow) throws XmppStringprepException, KeyManagementException, NoSuchAlgorithmException {
EntityBareJid jid = JidCreate.entityBareFrom(jidCs);
return tlsTest(jid, password, host, port, tlsPin, shouldThrow);
}
public static boolean tlsTest(EntityBareJid jid, String password, String host, int port,
String tlsPin, boolean shouldThrow) throws KeyManagementException, NoSuchAlgorithmException {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
// @formatter:off
builder.setUsernameAndPassword(jid.getLocalpart(), password)
.setXmppDomain(JidCreate.domainBareFrom(jid.getDomain()))
.setHost(host)
.setPort(port)
.setSecurityMode(SecurityMode.required);
// @formatter:on
if (DEBUG) {
builder.enableDefaultDebugger();
}
if (StringUtils.isNotEmpty(tlsPin)) {
SSLContext sslContext = Java7Pinning.forPin(tlsPin);
builder.setSslContextFactory(() -> sslContext);
}
XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());
connection.setReplyTimeout(20000);
try {
connection.connect().login();
if (shouldThrow) {
// Test not success, should have thrown on login().
return false;
}
}
catch (SecurityRequiredByClientException e) {
if (!shouldThrow) {
return false;
}
}
catch (XMPPException | SmackException | IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
finally {
connection.disconnect();
}
return true;
}
}

View file

@ -1,78 +0,0 @@
/**
*
* Copyright 2021 Florian Schmaus
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.io.IOException;
import java.net.URISyntaxException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection;
import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnectionConfiguration;
import org.jivesoftware.smack.util.TLSUtils;
import org.jivesoftware.smack.websocket.XmppWebSocketTransportModuleDescriptor;
public class WebSocketConnection {
public static void main(String[] args)
throws URISyntaxException, SmackException, IOException, XMPPException, InterruptedException {
String jid, password, websocketEndpoint, messageTo = null;
if (args.length < 3 || args.length > 4) {
throw new IllegalArgumentException();
}
jid = args[0];
password = args[1];
websocketEndpoint = args[2];
if (args.length >= 4) {
messageTo = args[3];
}
TLSUtils.setDefaultTrustStoreTypeToJksIfRequired();
testWebSocketConnection(jid, password, websocketEndpoint, messageTo);
}
public static void testWebSocketConnection(String jid, String password, String websocketEndpoint)
throws URISyntaxException, SmackException, IOException, XMPPException, InterruptedException {
testWebSocketConnection(jid, password, websocketEndpoint, null);
}
public static void testWebSocketConnection(String jid, String password, String websocketEndpoint, String messageTo)
throws URISyntaxException, SmackException, IOException, XMPPException, InterruptedException {
ModularXmppClientToServerConnectionConfiguration.Builder builder = ModularXmppClientToServerConnectionConfiguration.builder();
builder.removeAllModules()
.setXmppAddressAndPassword(jid, password)
;
XmppWebSocketTransportModuleDescriptor.Builder websocketBuilder = XmppWebSocketTransportModuleDescriptor.getBuilder(builder);
websocketBuilder.explicitlySetWebSocketEndpointAndDiscovery(websocketEndpoint, false);
builder.addModule(websocketBuilder.build());
ModularXmppClientToServerConnectionConfiguration config = builder.build();
ModularXmppClientToServerConnection connection = new ModularXmppClientToServerConnection(config);
connection.setReplyTimeout(5 * 60 * 1000);
XmppTools.modularConnectionTest(connection, messageTo);
}
}

View file

@ -1,151 +0,0 @@
/**
*
* Copyright 2016-2021 Florian Schmaus
*
* This file is part of smack-repl.
*
* smack-repl is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.igniterealtime.smack.smackrepl;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.logging.Logger;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.util.TLSUtils;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.iqregister.AccountManager;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.jid.parts.Localpart;
import org.jxmpp.stringprep.XmppStringprepException;
import org.jxmpp.util.XmppDateTime;
public class XmppTools {
public static void main(String[] args) throws SmackException, IOException, XMPPException, InterruptedException,
KeyManagementException, NoSuchAlgorithmException {
boolean one = createAccount("xmpp.foobar.io", "smack1", "smack1");
boolean two = createAccount("xmpp.foobar.io", "smack2", "smack2");
// CHECKSTYLE:OFF
System.out.println("Account created: " + one + ' ' + two);
// CHECKSTYLE:ON
}
public static boolean supportsIbr(String xmppDomain) throws SmackException, IOException, XMPPException,
InterruptedException, KeyManagementException, NoSuchAlgorithmException {
DomainBareJid xmppDomainJid = JidCreate.domainBareFrom(xmppDomain);
return supportsIbr(xmppDomainJid);
}
public static boolean supportsIbr(DomainBareJid xmppDomain) throws SmackException, IOException, XMPPException,
InterruptedException, KeyManagementException, NoSuchAlgorithmException {
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain(xmppDomain);
TLSUtils.acceptAllCertificates(configBuilder);
XMPPTCPConnectionConfiguration config = configBuilder.build();
XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
try {
return supportsIbr(connection);
} finally {
connection.disconnect();
}
}
public static boolean supportsIbr(XMPPConnection connection)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
AccountManager accountManager = AccountManager.getInstance(connection);
return accountManager.supportsAccountCreation();
}
public static boolean createAccount(String xmppDomain, String username, String password)
throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
InterruptedException {
DomainBareJid xmppDomainJid = JidCreate.domainBareFrom(xmppDomain);
Localpart localpart = Localpart.from(username);
return createAccount(xmppDomainJid, localpart, password);
}
public static boolean createAccount(DomainBareJid xmppDomain, Localpart username, String password)
throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
InterruptedException {
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain(xmppDomain);
TLSUtils.acceptAllCertificates(configBuilder);
XMPPTCPConnectionConfiguration config = configBuilder.build();
XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
try {
if (!supportsIbr(connection))
return false;
AccountManager accountManager = AccountManager.getInstance(connection);
accountManager.createAccount(username, password);
return true;
} finally {
connection.disconnect();
}
}
public static void modularConnectionTest(ModularXmppClientToServerConnection connection, String messageTo) throws XMPPException, SmackException, IOException, InterruptedException {
connection.addConnectionStateMachineListener((event, c) -> {
Logger.getAnonymousLogger().info("Connection event: " + event);
});
connection.connect();
connection.login();
XmppTools.sendItsAlive(messageTo, connection);
Thread.sleep(1000);
connection.disconnect();
ModularXmppClientToServerConnection.Stats connectionStats = connection.getStats();
ServiceDiscoveryManager.Stats serviceDiscoveryManagerStats = ServiceDiscoveryManager.getInstanceFor(connection).getStats();
// CHECKSTYLE:OFF
System.out.println("NIO successfully finished, yeah!\n" + connectionStats + '\n' + serviceDiscoveryManagerStats);
// CHECKSTYLE:ON
}
public static void sendItsAlive(String to, XMPPConnection connection)
throws XmppStringprepException, NotConnectedException, InterruptedException {
if (to == null) {
return;
}
Message message = connection.getStanzaFactory().buildMessageStanza()
.to(to)
.setBody("It is alive! " + XmppDateTime.formatXEP0082Date(new Date()))
.build();
connection.sendStanza(message);
}
}