org.xmpp.packet.Packet Java Examples

The following examples show how to use org.xmpp.packet.Packet. 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: LocalComponentSession.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void processPacket(Packet packet) {
    if (packet instanceof IQ) {
        IQ iq = (IQ) packet;
        if (iq.getType() == IQ.Type.result || iq.getType() == IQ.Type.error) {
            // Check if this IQ reply belongs to a specific component and route
            // reply to that specific component (if it exists)
            LocalExternalComponent targetComponent;
            synchronized (iqs) {
                targetComponent = iqs.remove(packet.getID());
            }
            if (targetComponent != null) {
                targetComponent.processPacket(packet);
                return;
            }
        }
    }
    // Ask the session to process the outgoing packet. This will
    // give us the chance to apply PacketInterceptors
    session.process(packet);
}
 
Example #2
Source File: RoutingTableImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the specified packet must only be route to available client sessions.
 *
 * @param packet the packet to route.
 * @param fromServer true if the packet was created by the server.
 * @return true if the specified packet must only be route to available client sessions.
 */
private boolean routeOnlyAvailable(Packet packet, boolean fromServer) {
    if (fromServer) {
        // Packets created by the server (no matter their FROM value) must always be delivered no
        // matter the available presence of the user
        return false;
    }
    boolean onlyAvailable = true;
    JID from = packet.getFrom();
    boolean hasSender = from != null;
    if (packet instanceof IQ) {
        onlyAvailable = hasSender && !(serverName.equals(from.getDomain()) && from.getResource() == null) &&
                !componentsCache.containsKey(from.getDomain());
    }
    else if (packet instanceof Message || packet instanceof Presence) {
        onlyAvailable = !hasSender ||
                (!serverName.equals(from.toString()) && !componentsCache.containsKey(from.getDomain()));
    }
    return onlyAvailable;
}
 
Example #3
Source File: PacketCopier.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {
    // Queue intercepted packet only if there are subscribers interested
    if (!subscribers.isEmpty()) {
        boolean queue = false;
        Class packetClass = packet.getClass();
        for (Subscription subscription : subscribers.values()) {
            if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                queue = true;
            }
            else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                queue = true;
            }
            else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                queue = true;
            }
        }
        if (queue) {
            // Queue packet with extra information and let the background thread process it
            packetQueue.add(new InterceptedPacket(packet, incoming, processed));
        }
    }
}
 
Example #4
Source File: PacketRouterImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Routes the given packet based on packet recipient and sender. The
 * router defers actual routing decisions to other classes.
 * <h2>Warning</h2>
 * Be careful to enforce concurrency DbC of concurrent by synchronizing
 * any accesses to class resources.
 *
 * @param packet The packet to route
 */
@Override
public void route(Packet packet) {
    if (packet instanceof Message) {
        route((Message)packet);
    }
    else if (packet instanceof Presence) {
        route((Presence)packet);
    }
    else if (packet instanceof IQ) {
        route((IQ)packet);
    }
    else {
        throw new IllegalArgumentException();
    }
}
 
Example #5
Source File: PubSubModule.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Packet packet) {
    try {
        // Check if the packet is a disco request or a packet with namespace iq:register
        if (packet instanceof IQ) {
            if (engine.process(this, (IQ) packet) == null) {
                process((IQ) packet);
            }
        }
        else if (packet instanceof Presence) {
            engine.process(this, (Presence) packet);
        }
        else {
            engine.process(this, (Message) packet);
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        if (packet instanceof IQ) {
            // Send internal server error
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setError(PacketError.Condition.internal_server_error);
            send(reply);
        }
    }
}
 
Example #6
Source File: WebSocketConnection.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException
{
    final String xml;
    if (Namespace.NO_NAMESPACE.equals(packet.getElement().getNamespace())) {
        // use string-based operation here to avoid cascading xmlns wonkery
        StringBuilder packetXml = new StringBuilder(packet.toXML());
        packetXml.insert(packetXml.indexOf(" "), " xmlns=\"jabber:client\"");
        xml = packetXml.toString();
    } else {
        xml = packet.toXML();
    }
    if (validate()) {
        deliverRawText(xml);
    } else {
        // use fallback delivery mechanism (offline)
        getPacketDeliverer().deliver(packet);
    }
}
 
Example #7
Source File: HttpSession.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private void failDelivery(final Collection<Packet> packets) {
    if (packets == null) {
        // Do nothing if someone asked to deliver nothing :)
        return;
    }
    // use a separate thread to schedule backup delivery
    TaskEngine.getInstance().submit(new Runnable() {
        @Override
        public void run() {
            for (Packet packet : packets) {
                try {
                    backupDeliverer.deliver(packet);
                }
                catch (UnauthorizedException e) {
                    Log.error("On session " + getStreamID() + " unable to deliver message to backup deliverer", e);
                }
            }
        }
    });
}
 
Example #8
Source File: HttpSession.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public Deliverable(Collection<Packet> elements) {
    this.text = null;
    this.packets = new ArrayList<>();
    for (Packet packet : elements) {
        // Append packet namespace according XEP-0206 if needed
        if (Namespace.NO_NAMESPACE.equals(packet.getElement().getNamespace())) {
            // use string-based operation here to avoid cascading xmlns wonkery
            StringBuilder packetXml = new StringBuilder(packet.toXML());
            final int noslash = packetXml.indexOf( ">" );
            final int slash = packetXml.indexOf( "/>" );
            final int insertAt = ( noslash - 1 == slash ? slash : noslash );
            packetXml.insert( insertAt, " xmlns=\"jabber:client\"");
            this.packets.add(packetXml.toString());
        } else {
            this.packets.add(packet.toXML());
        }
    }
}
 
Example #9
Source File: LocalMUCRole.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void send(Packet packet) {
    if (packet == null) {
        return;
    }

    if (this.isRemoteFmuc()) {
        // Sending stanzas to individual occupants that are on remote FMUC nodes defeats the purpose of FMUC, which is to reduce message. This reduction is based on sending data just once, and have it 'fan out' on the remote node (as opposed to sending each occupant on that node a distinct stanza from this node).
        Log.warn( "Sending data directly to an entity ({}) on a remote FMUC node. Instead of individual messages, we expect data to be sent just once (and be fanned out locally by the remote node).", this, new Throwable() );

        // Check if stanza needs to be enriched with FMUC metadata.
        augmentOutboundStanzaWithFMUCData(packet);
    }

    packet.setTo(user.getAddress());


    router.route(packet);
}
 
Example #10
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} does not overwrites
 * a stanza-id element when another is present with a different 'by' value.
 */
@Test
public void testDontOverwriteStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String notExpected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "by", new JID( "someoneelse" ).toString() );
    toOverwrite.addAttribute( "id", notExpected );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final List<Element> elements = result.getElement().elements( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    assertEquals( 2, elements.size() );
}
 
Example #11
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil#findFirstUniqueAndStableStanzaID(Packet, String)} can parse a stanza that contains a
 * stanza ID.
 */
@Test
public void testParseUUIDValue() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String expected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "id", expected );
    toOverwrite.addAttribute( "by", self.toString() );

    // Execute system under test.
    final String result = StanzaIDUtil.findFirstUniqueAndStableStanzaID( input, self.toString() );

    // Verify results.
    assertEquals( expected, result );
}
 
Example #12
Source File: TransportHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Packet packet) throws UnauthorizedException, PacketException {
    boolean handled = false;
    String host = packet.getTo().getDomain();
    for (Channel<Packet> channel : transports.values()) {
        if (channel.getName().equalsIgnoreCase(host)) {
            channel.add(packet);
            handled = true;
        }
    }
    if (!handled) {
        JID recipient = packet.getTo();
        JID sender = packet.getFrom();
        packet.setError(PacketError.Condition.remote_server_timeout);
        packet.setFrom(recipient);
        packet.setTo(sender);
        try {
            deliverer.deliver(packet);
        }
        catch (PacketException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
    }
}
 
Example #13
Source File: PrivacyList.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the specified packet must be blocked based on this privacy list rules.
 * Rules are going to be analyzed based on their order (in ascending order). When a rule
 * is matched then communication will be blocked or allowed based on that rule. No more
 * further analysis is going to be made.
 *
 * @param packet the packet to analyze if it must be blocked.
 * @return true if the specified packet must be blocked based on this privacy list rules.
 */
public boolean shouldBlockPacket(Packet packet) {
    if (packet.getFrom() == null) {
        // Sender is the server so it's not denied
        return false;
    }
    // Iterate over the rules and check each rule condition
    Roster roster = getRoster();
    for (PrivacyItem item : items) {
        if (item.matchesCondition(packet, roster, userJID)) {
            if (item.isAllow()) {
                return false;
            }
            if (Log.isDebugEnabled()) {
                Log.debug("PrivacyList: Packet was blocked: " + packet);
            }
            return true;
        }
    }
    // If no rule blocked the communication then allow the packet to flow
    return false;
}
 
Example #14
Source File: ExternalComponent.java    From Whack with Apache License 2.0 6 votes vote down vote up
public void send(Packet packet) {
    synchronized (writer) {
        try {
            xmlSerializer.write(packet.getElement());
            xmlSerializer.flush();
            // Keep track of the last time a stanza was sent to the server
            lastActive = System.currentTimeMillis();
        }
        catch (IOException e) {
            // Log the exception
            manager.getLog().error(e);
            if (!shutdown) {
                // Connection was lost so try to reconnect
                connectionLost();
            }
        }
    }
}
 
Example #15
Source File: GcmPlugin.java    From Openfire-GCM with Apache License 2.0 6 votes vote down vote up
public void interceptPacket(Packet packet, Session session,
		boolean incoming, boolean processed) throws PacketRejectedException {

	if (processed) {
		return;
	}
	if (!incoming) {
		return;
	}

	if (packet instanceof Message) {
		Message msg = (Message) packet;
		process(msg);
	}

}
 
Example #16
Source File: MultiplexerPacketDeliverer.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    // Check if we can send the packet using another session
    if (connectionManagerDomain == null) {
        // Packet deliverer has not yet been configured so handle unprocessed packet
        handleUnprocessedPacket(packet);
    }
    else {
        // Try getting another session to the same connection manager 
        ConnectionMultiplexerSession session =
                multiplexerManager.getMultiplexerSession(connectionManagerDomain);
        if (session == null || session.isClosed()) {
            // No other session was found so handle unprocessed packet
            handleUnprocessedPacket(packet);
        }
        else {
            // Send the packet using this other session to the same connection manager
            session.process(packet);
        }
    }
}
 
Example #17
Source File: HttpSessionDeliverable.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the default namespace is set on (non-empty) stanzas.
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnStanza() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    message.setTo( "[email protected]/test" );
    message.addChildElement( "unittest", "unit:test:namespace" );
    final List<Packet> packets = new ArrayList<>();
    packets.add( message );

    // Execute system under test
    final HttpSession.Deliverable deliverable = new HttpSession.Deliverable( packets );
    final String result = deliverable.getDeliverable();

    // verify results
    // Note that this assertion depends on the Openfire XML parser-specific ordering of attributes.
    assertEquals( "<message to=\"[email protected]/test\" xmlns=\"jabber:client\"><unittest xmlns=\"unit:test:namespace\"/></message>", result );
}
 
Example #18
Source File: DefaultXmppDevice.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void sendPacket(Packet packet) {
    packet.setTo(this.deviceId.getJid());
    packet.setFrom(new JID(XmppConstants.SERVER_JID));
    Preconditions.checkNotNull(packet);
    if (this.session.isActive()) {
        this.session.sendPacket(packet);
    } else {
        logger.warn("Dropping XMPP packets for switch {} because channel is not connected: {}",
                this.deviceId, packet);
    }
}
 
Example #19
Source File: AuditManagerImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean read, boolean processed) {
    if (!processed) {
        // Ignore packets sent or received by users that are present in the ignore list
        JID from = packet.getFrom();
        JID to = packet.getTo();
        if ((from == null || !ignoreList.contains(from.getNode())) &&
                (to == null || !ignoreList.contains(to.getNode()))) {
            auditor.audit(packet, session);
        }
    }
}
 
Example #20
Source File: AuditorImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public AuditPacket(Packet packet, Session session) {
    element = docFactory.createElement("packet", "http://www.jivesoftware.org");
    creationDate = new Date();
    if (session != null && session.getStreamID() != null) {
        element.addAttribute("streamID", session.getStreamID().toString());
    }
    switch (session == null ? 0 : session.getStatus()) {
        case Session.STATUS_AUTHENTICATED:
            element.addAttribute("status", "auth");
            break;
        case Session.STATUS_CLOSED:
            element.addAttribute("status", "closed");
            break;
        case Session.STATUS_CONNECTED:
            element.addAttribute("status", "connected");
            // This is a workaround. Since we don't want to have an incorrect FROM attribute
            // value we need to clean up the FROM attribute. The FROM attribute will contain
            // an incorrect value since we are setting a fake JID until the user actually
            // authenticates with the server.
            packet.setFrom((String) null);
            break;
        default:
            element.addAttribute("status", "unknown");
            break;
    }
    element.addAttribute("timestamp", auditFormat.format(creationDate));
    element.add(packet.getElement());
}
 
Example #21
Source File: PacketDelivererImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    if (packet == null) {
        throw new PacketException("Packet was null");
    }
    if (deliverHandler == null) {
        throw new PacketException("Could not send packet - no route" + packet.toString());
    }
    // Let the SocketPacketWriteHandler process the packet. SocketPacketWriteHandler may send
    // it over the socket or store it when user is offline or drop it.
    deliverHandler.process(packet);
}
 
Example #22
Source File: LocalComponentSession.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Delivers the packet to the external component.
 *
 * @param packet the packet to deliver.
 */
void deliver(Packet packet) {
    if (connection != null && !connection.isClosed()) {
        try {
            connection.deliver(packet);
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            connection.close();
        }
    }
}
 
Example #23
Source File: InternalComponentManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void sendPacket(Component component, Packet packet) {
    if (packet != null && packet.getFrom() == null) {
        throw new IllegalArgumentException("Packet with no FROM address was received from component.");
    }
    
    PacketRouter router = XMPPServer.getInstance().getPacketRouter();
    if (router != null) {
        router.route(packet);
    }
}
 
Example #24
Source File: HttpSession.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public Collection<Packet> getPackets() {
    List<Packet> packets = new ArrayList<>();
    synchronized (deliverables) {
        for (Deliverable deliverable : deliverables) {
            if (deliverable.packets != null) {
                packets.addAll(deliverable.getPackets());
            }
        }
    }
    return packets;
}
 
Example #25
Source File: OutgoingSessionPromise.java    From Openfire with Apache License 2.0 5 votes vote down vote up
void addPacket( Packet packet )
{
    if ( !packetQueue.offer( packet ) )
    {
        returnErrorToSender(packet);
        Log.debug( "Error sending packet to domain '{}' (outbound queue full): {}", domain, packet );
    }
}
 
Example #26
Source File: S2STestService.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Keeps a log of the XMPP traffic, releasing the wait lock on response received.
 */
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {

    if (ping.getTo() == null || packet.getFrom() == null || packet.getTo() == null) {
        return;
    }

    if (!processed
            && (ping.getTo().getDomain().equals(packet.getFrom().getDomain()) || ping.getTo().getDomain().equals(packet.getTo().getDomain()))) {

        // Log all traffic to and from the domain.
        xml.append(packet.toXML());
        xml.append('\n');

        // If we've received our IQ response, stop the test.
        if ( packet instanceof IQ )
        {
            final IQ iq = (IQ) packet;
            if ( iq.isResponse() && ping.getID().equals( iq.getID() ) && ping.getTo().equals( iq.getFrom() ) ) {
                Log.info("Successful server to server response received.");
                waitUntil.release();
            }
        }
    }
}
 
Example #27
Source File: MultiplexerPacketDeliverer.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void handleUnprocessedPacket(Packet packet) {
    if (packet instanceof Message) {
        messageStrategy.storeOffline((Message) packet);
    }
    else if (packet instanceof Presence) {
        // presence packets are dropped silently
        //dropPacket(packet);
    }
    else if (packet instanceof IQ) {
        IQ iq = (IQ) packet;
        // Check if we need to unwrap the packet
        Element child = iq.getChildElement();
        if (child != null && "session".equals(child.getName()) &&
                "http://jabber.org/protocol/connectionmanager"
                        .equals(child.getNamespacePrefix())) {
            Element send = child.element("send");
            if (send != null) {
                // Unwrap packet
                Element wrappedElement = (Element) send.elements().get(0);
                if ("message".equals(wrappedElement.getName())) {
                    handleUnprocessedPacket(new Message(wrappedElement));
                }
            }
        }
        else {
            // IQ packets are logged but dropped
            Log.warn(LocaleUtils.getLocalizedString("admin.error.routing") + "\n" +
                    packet.toString());
        }
    }
}
 
Example #28
Source File: MultiplexerPacketHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void deliver(Packet reply) {
    // Get any session of the connection manager to deliver the packet
    ConnectionMultiplexerSession session =
            multiplexerManager.getMultiplexerSession(connectionManagerDomain);
    if (session != null) {
        session.process(reply);
    }
    else {
        Log.warn("No multiplexer session found. Packet not delivered: " + reply.toXML());
    }
}
 
Example #29
Source File: FileTransferProxy.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Packet packet) throws UnauthorizedException, PacketException {
    // Check if the packet is a disco request or a packet with namespace iq:register
    if (packet instanceof IQ) {
        if (handleIQ((IQ) packet)) {
            // Do nothing
        }
        else {
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setChildElement(((IQ) packet).getChildElement().createCopy());
            reply.setError(PacketError.Condition.feature_not_implemented);
            router.route(reply);
        }
    }
}
 
Example #30
Source File: MediaProxyService.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Packet packet) throws UnauthorizedException, PacketException {
    // Check if user is allowed to send packet to this service
    if (packet instanceof IQ) {
        // Handle disco packets
        IQ iq = (IQ) packet;
        // Ignore IQs of type ERROR or RESULT
        if (IQ.Type.error == iq.getType() || IQ.Type.result == iq.getType()) {
            return;
        }
        processIQ(iq);
    }
}