Java Code Examples for org.jivesoftware.openfire.auth.UnauthorizedException

The following examples show how to use org.jivesoftware.openfire.auth.UnauthorizedException. These examples are extracted from open source projects. 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 Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the user provided the correct password, if applicable.
 *
 * @param user The user that attempts to join.
 * @throws UnauthorizedException when joining is prevented by virtue of password protection.
 */
private void checkJoinRoomPreconditionPasswordProtection( @Nonnull final LocalMUCUser user, @Nullable String providedPassword ) throws UnauthorizedException
{
    boolean canJoin = true;
    final JID bareJID = user.getAddress().asBareJID();
    if (isPasswordProtected()) {
        final boolean isCorrectPassword = (providedPassword != null && providedPassword.equals(getPassword()));
        final boolean isSysadmin = mucService.isSysadmin(bareJID);
        final boolean requirePassword = !isSysadmin || mucService.isPasswordRequiredForSysadminsToJoinRoom();
        if (!isCorrectPassword && requirePassword ) {
            canJoin = false;
        }
    }
    Log.trace( "{} Room join precondition 'password protection': User '{}' {} join room '{}'.", canJoin ? "PASS" : "FAIL", user.getAddress(), canJoin ? "can" : "cannot", this.getJID() );
    if (!canJoin) {
        throw new UnauthorizedException( "You did not supply the correct password needed to join this room." );
    }
}
 
Example 2
Source Project: Openfire   Source File: WebSocketConnection.java    License: 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 3
Source Project: Openfire   Source File: SessionManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@code ClientSession} with the specified streamID.
 *
 * @param connection the connection to create the session from.
 * @param id the streamID to use for the new session.
 * @param language The language to use for the session
 * @return a newly created session.
 * @throws UnauthorizedException if the server has not been initialised
 * @throws UnknownHostException if no IP address for the peer could be found,
 */
public HttpSession createClientHttpSession(StreamID id, HttpConnection connection, Locale language)
    throws UnauthorizedException, UnknownHostException
{
    if (serverName == null) {
        throw new UnauthorizedException("Server not initialized");
    }
    PacketDeliverer backupDeliverer = server.getPacketDeliverer();
    HttpSession session = new HttpSession(backupDeliverer, serverName, id, connection, language);
    Connection conn = session.getConnection();
    conn.init(session);
    conn.registerCloseListener(clientSessionListener, session);
    localSessionManager.getPreAuthenticatedSessions().put(session.getAddress().getResource(), session);
    connectionsCounter.incrementAndGet();
    return session;
}
 
Example 4
Source Project: Openfire   Source File: PacketTransporterImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delivers the given packet based on packet recipient and sender. The
 * deliverer 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
 * @throws NullPointerException If the packet is null or the
 *                              packet could not be routed
 * @throws UnauthorizedException if the user is not authorised
 */
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    if (packet == null) {
        throw new NullPointerException();
    }

    if (xmppServer != null && xmppServer.isLocal(packet.getTo())) {
        deliverer.deliver(packet);
    }
    else if (transportHandler != null) {
        transportHandler.process(packet);
    }
    else {
        Log.warn("Could not deliver message: no deliverer available "
                + packet.toString());
    }
}
 
Example 5
Source Project: Openfire   Source File: PresenceUpdateHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Handle presence updates that affect roster subscriptions.
 *
 * @param presence The presence presence to handle
 * @throws PacketException if the packet is null or the packet could not be routed.
 */
public void process(Presence presence) throws PacketException {
    try {
        process((Packet)presence);
    }
    catch (UnauthorizedException e) {
        try {
            LocalSession session = (LocalSession) sessionManager.getSession(presence.getFrom());
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.not_authorized);
            deliverer.deliver(presence);
        }
        catch (Exception err) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), err);
        }
    }
}
 
Example 6
Source Project: Openfire   Source File: IQSharedGroupHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ result = IQ.createResultIQ(packet);
    String username = packet.getFrom().getNode();
    if (!serverName.equals(packet.getFrom().getDomain()) || username == null) {
        // Users of remote servers are not allowed to get their "shared groups". Users of
        // remote servers cannot have shared groups in this server.
        // Besides, anonymous users do not belong to shared groups so answer an error
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.not_allowed);
        return result;
    }

    Collection<Group> groups = rosterManager.getSharedGroups(username);
    Element sharedGroups = result.setChildElement("sharedgroup",
            "http://www.jivesoftware.org/protocol/sharedgroup");
    for (Group sharedGroup : groups) {
        String displayName = sharedGroup.getProperties().get("sharedRoster.displayName");
        if (displayName != null) {
            sharedGroups.addElement("group").setText(displayName);
        }
    }
    return result;
}
 
Example 7
Source Project: Openfire   Source File: HttpBindServlet.java    License: Apache License 2.0 6 votes vote down vote up
protected void createNewSession(AsyncContext context, HttpBindBody body)
        throws IOException
{
    final long rid = body.getRid();

    try {
        final HttpConnection connection = new HttpConnection(rid, context);

        SessionEventDispatcher.dispatchEvent( null, SessionEventDispatcher.EventType.pre_session_created, connection, context );

        connection.setSession(sessionManager.createSession(body, connection));
        if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
            Log.info("HTTP RECV(" + connection.getSession().getStreamID().getID() + "): " + body.asXML());
        }

        SessionEventDispatcher.dispatchEvent( connection.getSession(), SessionEventDispatcher.EventType.post_session_created, connection, context );
    }
    catch (UnauthorizedException | HttpBindException e) {
        // Server wasn't initialized yet.
        sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization." );
    }
}
 
Example 8
Source Project: Openfire   Source File: HttpSession.java    License: 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 9
Source Project: Openfire   Source File: MultiplexerPacketDeliverer.java    License: 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 10
Source Project: Openfire   Source File: TransportHandler.java    License: 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 11
Source Project: Openfire   Source File: ServerStanzaHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
boolean processUnknowPacket(Element doc) throws UnauthorizedException {
    // Handle subsequent db:result packets
    if ("db".equals(doc.getNamespacePrefix()) && "result".equals(doc.getName())) {
        if (!((LocalIncomingServerSession) session).validateSubsequentDomain(doc)) {
            throw new UnauthorizedException("Failed to validate domain when using piggyback.");
        }
        return true;
    }
    else if ("db".equals(doc.getNamespacePrefix()) && "verify".equals(doc.getName())) {
        // The Receiving Server is reusing an existing connection for sending the
        // Authoritative Server a request for verification of a key
        ((LocalIncomingServerSession) session).verifyReceivedKey(doc);
        return true;
    }
    return false;
}
 
Example 12
Source Project: Openfire   Source File: ComponentStanzaHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void processIQ(IQ packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        IQ reply = new IQ();
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    // Keep track of the component that sent an IQ get/set
    if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
        // Handle subsequent bind packets
        LocalComponentSession componentSession = (LocalComponentSession) session;
        // Get the external component of this session
        LocalComponentSession.LocalExternalComponent component =
                (LocalComponentSession.LocalExternalComponent) componentSession.getExternalComponent();
        component.track(packet);
    }
    super.processIQ(packet);
}
 
Example 13
Source Project: Openfire   Source File: RemoteMUCUser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(Packet packet) throws UnauthorizedException, PacketException {
    if (packet instanceof IQ) {
        throw new UnsupportedOperationException("Cannot process IQ packets of remote users: " + packet);
    }
    else if (packet instanceof Message) {
        throw new UnsupportedOperationException("Cannot process Message packets of remote users: " + packet);
    }
    else if (packet instanceof Presence) {
        process((Presence)packet);
    }
}
 
Example 14
Source Project: Openfire   Source File: LocalMUCUser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method does all packet routing in the chat server. Packet routing is actually very simple:
 *
 * <ul>
 *   <li>Discover the room the user is talking to</li>
 *   <li>If the room is not registered and this is a presence "available" packet, try to join the room</li>
 *   <li>If the room is registered, and presence "unavailable" leave the room</li>
 *   <li>Otherwise, rewrite the sender address and send to the room.</li>
 * </ul>
 *
 * @param packet          The stanza to route
 * @param roomName        The name of the room that the stanza was addressed to.
 * @param preExistingRole The role of this user in the addressed room prior to processing of this stanza, if any.
 */
@Override
public void process( Packet packet ) throws UnauthorizedException, PacketException
{
    // Name of the room that the stanza is addressed to. Can't be null, given the check above.
    final String roomName = packet.getTo().getNode();

    if ( roomName == null )
    {
        // Packets to the groupchat service (as opposed to a specific room on the service). This should not occur
        // (should be handled by MultiUserChatServiceImpl instead).
        Log.warn(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString());
        if ( packet instanceof IQ && ((IQ) packet).isRequest() )
        {
            sendErrorPacket(packet, PacketError.Condition.feature_not_implemented, "Unable to process stanza.");
        }
        return;
    }

    lastPacketTime = System.currentTimeMillis();

    StanzaIDUtil.ensureUniqueAndStableStanzaID(packet, packet.getTo());

    // Determine if this user has a pre-existing role in the addressed room.
    final MUCRole preExistingRole = roles.get(roomName);

    if ( packet instanceof IQ )
    {
        process((IQ) packet, roomName, preExistingRole);
    }
    else if ( packet instanceof Message )
    {
        process((Message) packet, roomName, preExistingRole);
    }
    else if ( packet instanceof Presence )
    {
        process((Presence) packet, roomName, preExistingRole);
    }
}
 
Example 15
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks all preconditions for joining a room. If one of them fails, an Exception is thrown.
 */
private void checkJoinRoomPreconditions(
        @Nonnull final LocalMUCUser user,
        @Nonnull final String nickname,
        @Nonnull final MUCRole.Affiliation affiliation,
        @Nullable final String password,
        @Nonnull final Presence presence)
    throws ServiceUnavailableException, RoomLockedException, UserAlreadyExistsException, UnauthorizedException, ConflictException, NotAcceptableException, ForbiddenException, RegistrationRequiredException
{
    Log.debug( "Checking all preconditions for user '{}' to join room '{}'.", user.getAddress(), this.getJID() );

    checkJoinRoomPreconditionDelegate( user );

    // If the room has a limit of max user then check if the limit has been reached
    checkJoinRoomPreconditionMaxOccupants( user );

    // If the room is locked and this user is not an owner raise a RoomLocked exception
    checkJoinRoomPreconditionLocked( user );

    // Check if the nickname is already used in the room
    checkJoinRoomPreconditionNicknameInUse( user, nickname );

    // If the room is password protected and the provided password is incorrect raise a
    // Unauthorized exception - unless the JID that is joining is a system admin.
    checkJoinRoomPreconditionPasswordProtection( user, password );

    // If another user attempts to join the room with a nickname reserved by the first user
    // raise a ConflictException
    checkJoinRoomPreconditionNicknameReserved( user, nickname );

    checkJoinRoomPreconditionRestrictedToNickname( user, nickname );

    // Check if the user can join the room.
    checkJoinRoomPreconditionIsOutcast( user, affiliation );

    // If the room is members-only and the user is not a member. Raise a "Registration Required" exception.
    checkJoinRoomPreconditionMemberOnly( user, affiliation );

    Log.debug( "All preconditions for user '{}' to join room '{}' have been met. User can join the room.", user.getAddress(), this.getJID() );
}
 
Example 16
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
private void checkJoinRoomPreconditionDelegate( @Nonnull final LocalMUCUser user ) throws UnauthorizedException
{
    boolean canJoin = true;
    if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
        if (!((MultiUserChatServiceImpl)mucService).getMUCDelegate().joiningRoom(this, user.getAddress())) {
            // Delegate said no, reject join.
            canJoin = false;
        }
    }
    Log.trace( "{} Room join precondition 'delegate': User '{}' {} join room '{}'.", canJoin ? "PASS" : "FAIL", user.getAddress(), canJoin ? "can" : "cannot", this.getJID() );
    if (!canJoin) {
        throw new UnauthorizedException();
    }
}
 
Example 17
Source Project: Openfire   Source File: SessionManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a session for a remote server. The session should be created only after the
 * remote server has been authenticated either using "server dialback" or SASL.
 *
 * @param conn the connection to the remote server.
 * @param id the stream ID used in the stream element when authenticating the server.
 * @param fromDomain The originating domain
 * @return the newly created {@link IncomingServerSession}.
 * @throws UnauthorizedException if the local server has not been initialized yet.
 */
public LocalIncomingServerSession createIncomingServerSession(Connection conn, StreamID id, String fromDomain)
        throws UnauthorizedException {
    if (serverName == null) {
        throw new UnauthorizedException("Server not initialized");
    }
    LocalIncomingServerSession session = new LocalIncomingServerSession(serverName, conn, id, fromDomain);
    conn.init(session);
    // Register to receive close notification on this session so we can
    // remove its route from the sessions set
    conn.registerCloseListener(incomingServerListener, session);

    return session;
}
 
Example 18
Source Project: Openfire   Source File: LocalClientSession.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException {
    if (conn != null) {
        conn.deliver(packet);
    }
    streamManager.sentStanza(packet);
}
 
Example 19
Source Project: Openfire   Source File: CrowdAuthProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns if the username and password are valid; otherwise this
 * method throws an UnauthorizedException.<p>
 *
 * @param username the username or full JID.
 * @param password the password
 * @throws UnauthorizedException if the username and password do
 *      not match any existing user.
 * @throws ConnectionException it there is a problem connecting to user and group sytem
 * @throws InternalUnauthenticatedException if there is a problem authentication Openfire itself into the user and group system
 */
@Override
public void authenticate(String username, String password) throws UnauthorizedException, ConnectionException, InternalUnauthenticatedException {
    if (manager == null) {
        throw new ConnectionException("Unable to connect to Crowd");
    }

    if (username == null || password == null || "".equals(password.trim())) {
        throw new UnauthorizedException();
    }

    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain. Return authentication failed.
            throw new UnauthorizedException();
        }
    }

    try {
        manager.authenticate(username, password);
    } catch (RemoteException re) {
        throw new UnauthorizedException();
    }
}
 
Example 20
Source Project: Openfire   Source File: PacketDelivererImpl.java    License: 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 21
Source Project: Openfire   Source File: IQPrivateHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ replyPacket = IQ.createResultIQ(packet);

    Element child = packet.getChildElement();
    Element dataElement = child.elementIterator().next();

    if ( !XMPPServer.getInstance().isLocal( packet.getFrom()) || !UserManager.getInstance().isRegisteredUser( packet.getFrom()) ) {
        replyPacket.setChildElement(packet.getChildElement().createCopy());
        replyPacket.setError(PacketError.Condition.service_unavailable);
        replyPacket.getError().setText( "Service available only to locally registered users." );
        return replyPacket;
    }

    if (dataElement != null) {
        if (IQ.Type.get.equals(packet.getType())) {
            Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement);
            dataStored.setParent(null);

            child.remove(dataElement);
            child.setParent(null);
            replyPacket.setChildElement(child);
            child.add(dataStored);
        }
        else {
            if (privateStorage.isEnabled()) {
                privateStorage.add(packet.getFrom().getNode(), dataElement);
            } else {
                replyPacket.setChildElement(packet.getChildElement().createCopy());
                replyPacket.setError(PacketError.Condition.service_unavailable);
            }
        }
    }
    else {
        replyPacket.setChildElement("query", "jabber:iq:private");
    }
    return replyPacket;
}
 
Example 22
Source Project: Openfire   Source File: HttpSessionManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP binding session which will allow a user to exchange packets with Openfire.
 *
 * @param body the body element that was sent containing the request for a new session.
 * @param connection the HTTP connection object which abstracts the individual connections to
 * Openfire over the HTTP binding protocol. The initial session creation response is returned to
 * this connection.
 * @return the created HTTP session.
 *
 * @throws UnauthorizedException if the Openfire server is currently in an uninitialized state.
 * Either shutting down or starting up.
 * @throws HttpBindException when there is an internal server error related to the creation of
 * the initial session creation response.
 * @throws UnknownHostException if no IP address for the peer could be found
 */
public HttpSession createSession(HttpBindBody body, HttpConnection connection)
    throws UnauthorizedException, HttpBindException, UnknownHostException
{
    // TODO Check if IP address is allowed to connect to the server
    HttpSession session = createSession(connection, Locale.forLanguageTag(body.getLanguage()));
    session.setWait(Math.min(body.getWait(), getMaxWait()));
    session.setHold(body.getHold());
    session.setSecure(connection.isSecure());
    session.setMaxPollingInterval(getPollingInterval());
    session.setMaxRequests(getMaxRequests());
    session.setMaxPause(getMaxPause());
    
    if(session.isPollingSession()) {
        session.setDefaultInactivityTimeout(getPollingInactivityTimeout());
    }
    else {
        session.setDefaultInactivityTimeout(getInactivityTimeout());
    }
    session.resetInactivityTimeout();
    
    session.setMajorVersion(body.getMajorVersion());
    session.setMinorVersion(body.getMinorVersion());

    connection.setSession(session);
    try {
        connection.deliverBody(createSessionCreationResponse(session), true);
    }
    catch (HttpConnectionClosedException | DocumentException | IOException e) {
        Log.error("Error creating session.", e);
        throw new HttpBindException("Internal server error", BoshBindingError.internalServerError);
    }
    return session;
}
 
Example 23
Source Project: Openfire   Source File: HttpSessionManager.java    License: Apache License 2.0 5 votes vote down vote up
private HttpSession createSession(HttpConnection connection, Locale language) throws UnauthorizedException, UnknownHostException
{
    // Create a ClientSession for this user.
    StreamID streamID = SessionManager.getInstance().nextStreamID();
    // Send to the server that a new client session has been created
    HttpSession session = sessionManager.createClientHttpSession(streamID, connection, language);
    // Register that the new session is associated with the specified stream ID
    sessionMap.put(streamID.getID(), session);
    SessionEventDispatcher.addListener( sessionListener );
    return session;
}
 
Example 24
Source Project: Openfire   Source File: FileTransferProxy.java    License: 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 25
Source Project: Openfire   Source File: DefaultFileTransferManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void registerProxyTransfer(String transferDigest, ProxyTransfer proxyTransfer)
        throws UnauthorizedException
{
    FileTransfer transfer = retrieveFileTransfer(transferDigest);
    if (isMatchProxyTransfer() && transfer == null) {
        throw new UnauthorizedException("Unable to match proxy transfer with a file transfer");
    }
    else if (transfer == null) {
        return;
    }

    transfer.setProgress(proxyTransfer);
    cacheFileTransfer(transferDigest, transfer);
}
 
Example 26
Source Project: Openfire   Source File: ServerSocketReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
boolean createSession(String namespace) throws UnauthorizedException, XmlPullParserException,
        IOException {
    if ("jabber:server".equals(namespace)) {
        // The connected client is a server so create an IncomingServerSession
        session = LocalIncomingServerSession.createSession(serverName, reader, connection, directTLS);
        // After the session has been created, inform all listeners as well.
        ServerSessionEventDispatcher.dispatchEvent(session, ServerSessionEventDispatcher.EventType.session_created);
        return true;
    }
    return false;
}
 
Example 27
Source Project: Openfire   Source File: SocketPacketWriteHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
 public void process(Packet packet) throws UnauthorizedException, PacketException {
    try {
        JID recipient = packet.getTo();
        // Check if the target domain belongs to a remote server or a component
        if (server.matchesComponent(recipient) || server.isRemote(recipient)) {
            routingTable.routePacket(recipient, packet, false);
        }
        // The target domain belongs to the local server
        else if (recipient == null || (recipient.getNode() == null && recipient.getResource() == null)) {
            // no TO was found so send back the packet to the sender
            routingTable.routePacket(packet.getFrom(), packet, false);
        }
        else if (recipient.getResource() != null || !(packet instanceof Presence)) {
            // JID is of the form <[email protected]/resource>
            routingTable.routePacket(recipient, packet, false);
        }
        else {
            // JID is of the form <[email protected]>
            for (JID route : routingTable.getRoutes(recipient, null)) {
                routingTable.routePacket(route, packet, false);
            }
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error.deliver") + "\n" + packet.toString(), e);
    }
}
 
Example 28
Source Project: Openfire   Source File: SocketConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    if (isClosed()) {
        backupDeliverer.deliver(packet);
    }
    else {
        boolean errorDelivering = false;
        boolean allowedToWrite = false;
        try {
            requestWriting();
            allowedToWrite = true;
            xmlSerializer.write(packet.getElement());
            if (flashClient) {
                writer.write('\0');
            }
            xmlSerializer.flush();
        }
        catch (Exception e) {
            Log.debug("Error delivering packet" + "\n" + this.toString(), e);
            errorDelivering = true;
        }
        finally {
            if (allowedToWrite) {
                releaseWriting();
            }
        }
        if (errorDelivering) {
            close();
            // Retry sending the packet again. Most probably if the packet is a
            // Message it will be stored offline
            backupDeliverer.deliver(packet);
        }
        else {
            session.incrementServerPacketCount();
        }
    }
}
 
Example 29
Source Project: Openfire   Source File: ComponentStanzaHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void processPresence(Presence packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Presence reply = new Presence();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processPresence(packet);
}
 
Example 30
Source Project: Openfire   Source File: ComponentStanzaHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void processMessage(Message packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Message reply = new Message();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processMessage(packet);
}