Java Code Examples for org.jivesoftware.smack.XMPPConnection#getUser()

The following examples show how to use org.jivesoftware.smack.XMPPConnection#getUser() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Socks5BytestreamManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the stream host information of the local SOCKS5 proxy containing the IP address and
 * the port or null if local SOCKS5 proxy is not running.
 *
 * @return the stream host information of the local SOCKS5 proxy or null if local SOCKS5 proxy
 *         is not running
 */
public List<StreamHost> getLocalStreamHost() {
    List<StreamHost> streamHosts = new ArrayList<>();

    XMPPConnection connection = connection();
    EntityFullJid myJid = connection.getUser();

    for (Socks5Proxy socks5Server : Socks5Proxy.getRunningProxies()) {
        List<InetAddress> addresses = socks5Server.getLocalAddresses();
        if (addresses.isEmpty()) {
            continue;
        }

        final int port = socks5Server.getPort();
        for (InetAddress address : addresses) {
            // Prevent loopback addresses from appearing as streamhost
            if (address.isLoopbackAddress()) {
                continue;
            }
            streamHosts.add(new StreamHost(myJid, address, port));
        }
    }

    return streamHosts;
}
 
Example 2
Source File: CarbonManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void addCarbonsListener(XMPPConnection connection) {
    EntityFullJid localAddress = connection.getUser();
    if (localAddress == null) {
        // We where not connected yet and thus we don't know our XMPP address at the moment, which we need to match incoming
        // carbons securely. Abort here. The ConnectionListener above will eventually setup the carbons listener.
        return;
    }

    // XEP-0280 § 11. Security Considerations "Any forwarded copies received by a Carbons-enabled client MUST be
    // from that user's bare JID; any copies that do not meet this requirement MUST be ignored." Otherwise, if
    // those copies do not get ignored, malicious users may be able to impersonate other users. That is why the
    // 'from' matcher is important here.
    connection.addSyncStanzaListener(carbonsListener, new AndFilter(CARBON_EXTENSION_FILTER,
                    FromMatchesFilter.createBare(localAddress)));
}
 
Example 3
Source File: IQReplyFilter.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Filters for packets which are a valid reply to an IQ request.
 * <p>
 * Such a stanza must have the same stanza id and must be an IQ stanza of type
 * <code>RESULT</code> or <code>ERROR</code>. Moreover, it is necessary to check
 * the <code>from</code> address to ignore forged replies.
 * <p>
 * We accept a <code>from</code> address if one of the following is true:
 * <ul>
 * <li>It matches the <code>to</code> address of the request.
 * <li>The <code>to</code> address of the request was empty and the
 * <code>from</code> address matches either the bare jid of the server or the
 * (bare or full jid) of the client.
 * <li>To <code>to</code> was our bare address and the <code>from</code> is empty.
 * </ul>
 * <p>
 * For a discussion of the issues, see the thread "Spoofing of iq ids and
 * misbehaving servers" from 2014-01 on the [email protected] mailing list
 * and following discussion in February and March.
 *
 * @param iqPacket An IQ request. Filter for replies to this packet.
 * @param conn connection.
 */
public IQReplyFilter(IQ iqPacket, XMPPConnection conn) {
    if (!iqPacket.isRequestIQ()) {
        throw new IllegalArgumentException("IQ must be a request IQ, i.e. of type 'get' or 'set'.");
    }
    to = iqPacket.getTo();
    local = conn.getUser();
    if (local == null) {
        throw new IllegalArgumentException("Must have a local (user) JID set. Either you didn't configure one or you where not connected at least once");
    }

    server = conn.getXMPPServiceDomain();
    packetId = iqPacket.getStanzaId();

    StanzaFilter iqFilter = new OrFilter(IQTypeFilter.ERROR, IQTypeFilter.RESULT);
    StanzaFilter idFilter = new StanzaIdFilter(iqPacket);
    iqAndIdFilter = new AndFilter(iqFilter, idFilter);
    fromFilter = new OrFilter();
    fromFilter.addFilter(FromMatchesFilter.createFull(to));
    if (to == null) {
        fromFilter.addFilter(FromMatchesFilter.createBare(local));
        fromFilter.addFilter(FromMatchesFilter.createFull(server));
    }
    else if (to.equals(local.asBareJid())) {
        fromFilter.addFilter(FromMatchesFilter.createFull(null));
    }
}
 
Example 4
Source File: Socks5ClientForInitiatorTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If the target is not connected to the local SOCKS5 proxy an exception should be thrown.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldFailIfTargetIsNotConnectedToLocalSocks5Proxy() throws Exception {
    Protocol protocol = new Protocol();
    XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);

    // start a local SOCKS5 proxy
    Socks5Proxy socks5Proxy = new Socks5Proxy();
    socks5Proxy.start();
    try {
        // build stream host information for local SOCKS5 proxy
        StreamHost streamHost = new StreamHost(connection.getUser(),
                        loopbackAddress,
                        socks5Proxy.getPort());

        // create digest to get the socket opened by target
        String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

        Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest,
                        connection, sessionID, targetJID);

        try {
            socks5Client.getSocket(GET_SOCKET_TIMEOUT);

            fail("exception should be thrown");
        }
        catch (SmackException e) {
            assertTrue(e.getMessage().contains("target is not connected to SOCKS5 proxy"));
            protocol.verifyAll(); // assert no XMPP messages were sent
        }
    } finally {
        socks5Proxy.stop();
    }
}
 
Example 5
Source File: JMeterXMPPSampler.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
@Override
public SampleResult sample(Entry entry) {
    SampleResult res = new SampleResult();
    res.setSampleLabel(getName());
    res.setDataType(SampleResult.TEXT);
    res.setSuccessful(true);
    res.setResponseCode("200");
    res.setResponseMessage("OK");

    res.sampleStart();
    try {
        if (connConfig == null) {
            throw new RuntimeException("Cannot sample XMPP without XMPP Connection component");
        }

        XMPPConnection conn = getXMPPConnection();

        if (conn == null) {
            throw new RuntimeException("No XMPP Connection available");
        }

        String headers = "Connection ID: " + conn.getConnectionID() + "\r\n";

        String action = getAction();
        if (!conn.isConnected() && !action.equals(Connect.class.getCanonicalName())) {
            log.error("Please call Connect before calling other actions");
            throw new SmackException.NotConnectedException();
        }

        headers += "User: " + conn.getUser() + "\r\n";

        res.setRequestHeaders(headers);

        AbstractXMPPAction actObject = connConfig.getActions().get(action);
        if (actObject.perform(this, res) == null) {
            return null;
        }
    } catch (Exception e) {
        log.error("Error in XMPP Sampler: ", e);
        res.setSuccessful(false);
        res.setResponseCode("500");
        res.setResponseMessage((e.getMessage() == null || e.getMessage().isEmpty()) ? e.toString() : e.getMessage());
        res.setResponseData(ExceptionUtils.getStackTrace(e).getBytes());
    }

    res.sampleEnd();
    return res;
}
 
Example 6
Source File: Roster.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public IQ handleIQRequest(IQ iqRequest) {
    final XMPPConnection connection = connection();
    RosterPacket rosterPacket = (RosterPacket) iqRequest;

    EntityFullJid ourFullJid = connection.getUser();
    if (ourFullJid == null) {
        LOGGER.warning("Ignoring roster push " + iqRequest + " while " + connection
                        + " has no bound resource. This may be a server bug.");
        return null;
    }

    // Roster push (RFC 6121, 2.1.6)
    // A roster push with a non-empty from not matching our address MUST be ignored
    EntityBareJid ourBareJid = ourFullJid.asEntityBareJid();
    Jid from = rosterPacket.getFrom();
    if (from != null) {
        if (from.equals(ourFullJid)) {
            // Since RFC 6121 roster pushes are no longer allowed to
            // origin from the full JID as it was the case with RFC
            // 3921. Log a warning an continue processing the push.
            // See also SMACK-773.
            LOGGER.warning(
                    "Received roster push from full JID. This behavior is since RFC 6121 not longer standard compliant. "
                            + "Please ask your server vendor to fix this and comply to RFC 6121 § 2.1.6. IQ roster push stanza: "
                            + iqRequest);
        } else if (!from.equals(ourBareJid)) {
            LOGGER.warning("Ignoring roster push with a non matching 'from' ourJid='" + ourBareJid + "' from='"
                    + from + "'");
            return IQ.createErrorResponse(iqRequest, Condition.service_unavailable);
        }
    }

    // A roster push must contain exactly one entry
    Collection<Item> items = rosterPacket.getRosterItems();
    if (items.size() != 1) {
        LOGGER.warning("Ignoring roster push with not exactly one entry. size=" + items.size());
        return IQ.createErrorResponse(iqRequest, Condition.bad_request);
    }

    Collection<Jid> addedEntries = new ArrayList<>();
    Collection<Jid> updatedEntries = new ArrayList<>();
    Collection<Jid> deletedEntries = new ArrayList<>();
    Collection<Jid> unchangedEntries = new ArrayList<>();

    // We assured above that the size of items is exactly 1, therefore we are able to
    // safely retrieve this single item here.
    Item item = items.iterator().next();
    RosterEntry entry = new RosterEntry(item, Roster.this, connection);
    String version = rosterPacket.getVersion();

    if (item.getItemType().equals(RosterPacket.ItemType.remove)) {
        deleteEntry(deletedEntries, entry);
        if (rosterStore != null) {
            rosterStore.removeEntry(entry.getJid(), version);
        }
    }
    else if (hasValidSubscriptionType(item)) {
        addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
        if (rosterStore != null) {
            rosterStore.addEntry(item, version);
        }
    }

    removeEmptyGroups();

    // Fire event for roster listeners.
    fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries);

    return IQ.createResultIQ(rosterPacket);
}
 
Example 7
Source File: IntegrationTestRosterUtil.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void ensureSubscribedTo(final XMPPConnection presenceRequestReceiverConnection, final XMPPConnection presenceRequestingConnection, long timeout) throws TimeoutException, Exception {
    final Roster presenceRequestReceiverRoster = Roster.getInstanceFor(presenceRequestReceiverConnection);
    final Roster presenceRequestingRoster = Roster.getInstanceFor(presenceRequestingConnection);

    final EntityFullJid presenceRequestReceiverAddress = presenceRequestReceiverConnection.getUser();
    final EntityFullJid presenceRequestingAddress = presenceRequestingConnection.getUser();

    if (presenceRequestReceiverRoster.isSubscribedToMyPresence(presenceRequestingAddress)) {
        return;
    }

    final SubscribeListener subscribeListener = new SubscribeListener() {
        @Override
        public SubscribeAnswer processSubscribe(Jid from, Presence subscribeRequest) {
            if (from.equals(presenceRequestingConnection.getUser().asBareJid())) {
                return SubscribeAnswer.Approve;
            }
            return SubscribeAnswer.Deny;
        }
    };
    presenceRequestReceiverRoster.addSubscribeListener(subscribeListener);

    final SimpleResultSyncPoint syncPoint = new SimpleResultSyncPoint();
    final PresenceEventListener presenceEventListener = new AbstractPresenceEventListener() {
        @Override
        public void presenceSubscribed(BareJid address, Presence subscribedPresence) {
            if (!address.equals(presenceRequestReceiverAddress.asBareJid())) {
                return;
            }
            syncPoint.signal();
        }
    };
    presenceRequestingRoster.addPresenceEventListener(presenceEventListener);

    try {
        presenceRequestingRoster.sendSubscriptionRequest(presenceRequestReceiverAddress.asBareJid());

        syncPoint.waitForResult(timeout);
    } finally {
        presenceRequestReceiverRoster.removeSubscribeListener(subscribeListener);
        presenceRequestingRoster.removePresenceEventListener(presenceEventListener);
    }
}