public void processDiscoItemsResponse(JID from, List<Element> items) throws ComponentException {

    for (Element item : items) {
      Attribute name = item.attribute("name");
      if (name != null && name.getStringValue().equals(BUDDYCLOUD_SERVER)) {
        remoteChannelDiscoveryStatus.put(from.toString(), DISCOVERED);
        setDiscoveredServer(from.toString(), item.attributeValue("jid"));
        sendFederatedRequests(from.toString());
        return;
      }
    }
    IQ infoRequest = new IQ(IQ.Type.get);
    infoRequest.setFrom(localServer);
    infoRequest.getElement().addElement("query", JabberPubsub.NS_DISCO_INFO);

    remoteServerItemsToProcess.put(from.toString(), items.size());
    String infoRequestId;
    for (Element item : items) {
      infoRequestId = getId() + ":info";
      infoRequest.setTo(item.attributeValue("jid"));
      infoRequest.setID(infoRequestId);
      remoteServerInfoRequestIds.put(infoRequestId, from.toString());
      component.sendPacket(infoRequest.createCopy());
    }
    remoteChannelDiscoveryStatus.put(from.toString(), DISCO_INFO);
  }
  @Override
  public IQ createServiceRequest(Object object, String fromNode, String toNode) {
    if (object instanceof JingleIQ) {
      final IQ request = new IQ(IQ.Type.set);
      if (toNode.indexOf("00") == 0) {
        toNode = "+" + toNode.substring(2);
      }
      final JID to = JIDFactory.getInstance().getJID(null, creditService, null);
      final JID from =
          JIDFactory.getInstance().getJID(fromNode, this.getComponentJID().getDomain(), null);
      final JingleIQ jingleIQ = (JingleIQ) object;
      request.setTo(to);
      request.setFrom(from);
      request.setChildElement(requestElement.createCopy());
      final String toBareJid =
          JIDFactory.getInstance().getJID(toNode, creditService, null).toBareJID();

      final Element e = request.getChildElement();
      e.addAttribute("initiator", from.toBareJID());
      e.addAttribute("responder", toBareJid);
      e.addAttribute("sid", jingleIQ.getJingle().getSid());
      log.debug("createCreditRequest: " + request.toXML());
      return request;
    }
    return null;
  }
Exemple #3
0
  private void processIQ(Element doc) {
    log.debug("processIQ()...");
    IQ packet;
    try {
      packet = getIQ(doc);
    } catch (IllegalArgumentException e) {
      log.debug("Rejecting packet. JID malformed", e);
      IQ reply = new IQ();
      if (!doc.elements().isEmpty()) {
        reply.setChildElement(((Element) doc.elements().get(0)).createCopy());
      }
      reply.setID(doc.attributeValue("id"));
      reply.setTo(session.getAddress());
      String to = doc.attributeValue("to");
      if (to != null) {
        reply.getElement().addAttribute("from", to);
      }
      reply.setError(PacketError.Condition.jid_malformed);
      session.process(reply);
      return;
    }

    //        if (packet.getID() == null) {
    //            // IQ packets MUST have an 'id' attribute
    //            StreamError error = new StreamError(
    //                    StreamError.Condition.invalid_xml);
    //            session.deliverRawText(error.toXML());
    //            session.close();
    //            return;
    //        }

    packet.setFrom(session.getAddress());
    router.route(packet);
    session.incrementClientPacketCount();
  }
  /**
   * The packet is a typical 'set' or 'get' update targeted at the server. Notice that the set could
   * be a roster removal in which case we have to generate a local roster removal update as well as
   * a new roster removal to send to the the roster item's owner.
   *
   * @param packet The packet that triggered this update
   * @return Either a response to the roster update or null if the packet is corrupt and the session
   *     was closed down
   */
  private IQ manageRoster(org.xmpp.packet.Roster packet)
      throws UnauthorizedException, UserAlreadyExistsException, SharedGroupException {

    IQ returnPacket = null;
    JID sender = packet.getFrom();
    IQ.Type type = packet.getType();

    try {
      if ((sender.getNode() == null
              || !RosterManager.isRosterServiceEnabled()
              || !userManager.isRegisteredUser(sender.getNode()))
          && IQ.Type.get == type) {
        // If anonymous user asks for his roster or roster service is disabled then
        // return an empty roster
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement("query", "jabber:iq:roster");
        return reply;
      }
      if (!localServer.isLocal(sender)) {
        // Sender belongs to a remote server so discard this IQ request
        Log.warn("Discarding IQ roster packet of remote user: " + packet);
        return null;
      }

      Roster cachedRoster = userManager.getUser(sender.getNode()).getRoster();
      if (IQ.Type.get == type) {
        returnPacket = cachedRoster.getReset();
        returnPacket.setType(IQ.Type.result);
        returnPacket.setTo(sender);
        returnPacket.setID(packet.getID());
        // Force delivery of the response because we need to trigger
        // a presence probe from all contacts
        deliverer.deliver(returnPacket);
        returnPacket = null;
      } else if (IQ.Type.set == type) {

        for (org.xmpp.packet.Roster.Item item : packet.getItems()) {
          if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.remove) {
            removeItem(cachedRoster, packet.getFrom(), item);
          } else {
            if (cachedRoster.isRosterItem(item.getJID())) {
              // existing item
              RosterItem cachedItem = cachedRoster.getRosterItem(item.getJID());
              cachedItem.setAsCopyOf(item);
              cachedRoster.updateRosterItem(cachedItem);
            } else {
              // new item
              cachedRoster.createRosterItem(item);
            }
          }
        }
        returnPacket = IQ.createResultIQ(packet);
      }
    } catch (UserNotFoundException e) {
      throw new UnauthorizedException(e);
    }

    return returnPacket;
  }
  public void process(Presence packet) {
    // Ignore unavailable presences
    if (Presence.Type.unavailable == packet.getType()) {
      return;
    }

    // Examine the packet and check if it has caps info,
    // if not -- do nothing by returning.
    Element capsElement = packet.getChildElement("c", "http://jabber.org/protocol/caps");
    if (capsElement == null) {
      return;
    }

    // Examine the packet and check if it's in legacy format (pre version 1.4
    // of XEP-0115). If so, do nothing by returning.
    // TODO: if this packet is in legacy format, we SHOULD check the 'node',
    // 'ver', and 'ext' combinations as specified in the archived version
    // 1.3 of the specification, and cache the results. See JM-1447
    final String hashAttribute = capsElement.attributeValue("hash");
    if (hashAttribute == null || hashAttribute.trim().length() == 0) {
      return;
    }

    // Examine the packet and check if it has and a 'ver' hash
    // if not -- do nothing by returning.
    final String newVerAttribute = capsElement.attributeValue("ver");
    if (newVerAttribute == null || newVerAttribute.trim().length() == 0) {
      return;
    }

    // Check to see if the 'ver' hash is already in our cache.
    if (isInCapsCache(newVerAttribute)) {
      // The 'ver' hash is in the cache already, so let's update the
      // entityCapabilitiesUserMap for the user that sent the caps
      // packet.
      entityCapabilitiesUserMap.put(packet.getFrom(), newVerAttribute);
    } else {
      // The 'ver' hash is not in the cache so send out a disco#info query
      // so that we may begin recognizing this 'ver' hash.
      IQ iq = new IQ(IQ.Type.get);
      iq.setTo(packet.getFrom());

      String serverName = XmppServer.getInstance().getServerInfo().getXMPPDomain();
      iq.setFrom(serverName);

      iq.setChildElement("query", "http://jabber.org/protocol/disco#info");

      String packetId = iq.getID();

      final EntityCapabilities caps = new EntityCapabilities();
      caps.setHashAttribute(hashAttribute);
      caps.setVerAttribute(newVerAttribute);
      verAttributes.put(packetId, caps);

      final IQRouter iqRouter = XmppServer.getInstance().getIQRouter();
      iqRouter.addIQResultListener(packetId, this);
      iqRouter.route(iq);
    }
  }
  protected IQ error(Packet packet, PacketError.Condition condition) {
    IQ reply;

    reply = new IQ(IQ.Type.error, packet.getID());
    reply.setFrom(packet.getTo());
    reply.setTo(packet.getFrom());
    reply.setError(condition);
    return reply;
  }
 private void discoverRemoteChannelServer(String remoteDomain, String id)
     throws ComponentException {
   logger.info("Attemping to discover remote server " + remoteDomain);
   IQ discover = new IQ(IQ.Type.get);
   discover.setFrom(localServer);
   discover.setTo(remoteDomain);
   discover.setID(id);
   discover.getElement().addElement("query", JabberPubsub.NS_DISCO_ITEMS);
   component.sendPacket(discover);
   remoteChannelDiscoveryStatus.put(remoteDomain, DISCO_ITEMS);
 }
 /**
  * Send a disco#info request to the new component. If the component provides information then it
  * will be added to the list of discoverable server items.
  *
  * @param component the new component that was added to this manager.
  * @param componentJID the XMPP address of the new component.
  */
 private void checkDiscoSupport(Component component, JID componentJID) {
   // Build a disco#info request that will be sent to the component
   IQ iq = new IQ(IQ.Type.get);
   iq.setFrom(getAddress());
   iq.setTo(componentJID);
   iq.setChildElement("query", "http://jabber.org/protocol/disco#info");
   // Send the disco#info request to the component. The reply (if any) will be processed in
   // #process(Packet)
   //        sendPacket(component, iq);
   component.processPacket(iq);
 }
  public ServerRequestIQ(
      JID fromAddress,
      JID toAddress,
      String method,
      String action,
      Map<String, String> headerMap,
      String bodyText) {
    super(IQ.Type.set);

    if (fromAddress != null) super.setFrom(fromAddress);
    if (toAddress != null) super.setTo(toAddress);

    addOpenHomeElement(method, action, headerMap, bodyText);
  }
  /**
   * Creates an error response for a given IQ request.
   *
   * @param request
   * @param message
   * @param condition
   * @param type
   * @return
   */
  public static IQ createErrorResponse(
      final IQ request, final String message, Condition condition, Type type) {
    final IQ result = request.createCopy();
    result.setID(request.getID());
    result.setFrom(request.getTo());
    result.setTo(request.getFrom());

    PacketError e = new PacketError(condition, type);
    if (message != null) {
      e.setText(message);
    }
    result.setError(e);

    return result;
  }
 private void makeRemoteRequests(IQ request, Set<String> remoteDomains) throws Exception {
   for (String remoteDomain : remoteDomains) {
     IQ remoteRequest = request.createCopy();
     remoteRequest.getElement().addAttribute("remote-server-discover", "false");
     remoteRequest.setTo(remoteDomain);
     Element actor =
         remoteRequest
             .getElement()
             .element("query")
             .element("remove")
             .addElement("actor", Buddycloud.NS);
     actor.addText(request.getFrom().toBareJID());
     outQueue.put(remoteRequest);
   }
 }
  public void passResponseToRequester(IQ packet) throws Exception {
    if (!sentRemotePackets.containsKey(packet.getID())) {
      throw new UnknownFederatedPacketException(
          "Can not find original requesting packet! (ID:" + packet.getID() + ")");
    }

    String uniqueId = packet.getID();
    packet.setID(idMap.get(uniqueId));
    packet.setTo((JID) sentRemotePackets.get(uniqueId));
    packet.setFrom(localServer);
    sentRemotePackets.remove(packet.getID());
    idMap.remove(uniqueId);

    component.sendPacket(packet);
  }
  /**
   * Broadcasts a newly created notification message to all connected users.
   *
   * @param apiKey the API key
   * @param title the title
   * @param message the message details
   * @param uri the uri
   */
  public void sendBroadcast(String apiKey, String title, String message, String uri) {
    log.debug("sendBroadcast()...");

    List<User> users = userService.getUsers();
    for (User user : users) {
      ClientSession session = sessionManager.getSession(user.getUsername());
      Random random = new Random();
      String id = Integer.toHexString(random.nextInt());
      IQ notificationIQ = createNotificationIQ(id, apiKey, title, message, uri);
      if (session != null && session.getPresence().isAvailable()) {
        notificationIQ.setTo(session.getAddress());
        session.deliver(notificationIQ);
      }

      saveNotification(id, apiKey, user.getUsername(), title, message, uri);
    }
  }
Exemple #14
0
  public void executeSet(IQ packet, Workgroup workgroup) {
    IQ reply = null;
    Element iq = packet.getChildElement();

    try {
      JID from = packet.getFrom();
      String bareJID = from.toBareJID();
      if (!isOwner(bareJID, workgroup)) {
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(new PacketError(PacketError.Condition.forbidden));
        workgroup.send(reply);
        return;
      }

      // Verify that an agent is requesting this information.
      WorkgroupManager workgroupManager = WorkgroupManager.getInstance();
      if (iq.element("makeOwner") != null) {
        String sessionID = iq.element("makeOwner").attributeValue("sessionID");
        final String serviceName = workgroupManager.getMUCServiceName();
        final String roomName = sessionID + "@" + serviceName;
        // final String roomJID = roomName + "/" + workgroup.getJID().getNode();

        IQ iqPacket = new IQ(IQ.Type.set);
        iqPacket.setTo(roomName);
        iqPacket.setFrom(workgroup.getFullJID());

        Element query = iqPacket.setChildElement("query", "http://jabber.org/protocol/muc#admin");
        Element item = query.addElement("item");
        item.addAttribute("affiliation", "owner");
        item.addAttribute("jid", packet.getFrom().toBareJID());
        workgroup.send(iqPacket);
      }

      reply = IQ.createResultIQ(packet);
    } catch (Exception e) {
      reply = IQ.createResultIQ(packet);
      reply.setChildElement(packet.getChildElement().createCopy());
      reply.setError(new PacketError(PacketError.Condition.item_not_found));
    }
    workgroup.send(reply);
  }
  /**
   * Sends an IQ packet to the Clearspace external component and returns the IQ packet returned by
   * CS or <tt>null</tt> if no answer was received before the specified timeout.
   *
   * @param packet IQ packet to send.
   * @param timeout milliseconds to wait before timing out.
   * @return IQ packet returned by Clearspace responsing the packet we sent.
   */
  public IQ query(final IQ packet, int timeout) {
    // Complain if FROM is empty
    if (packet.getFrom() == null) {
      throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace");
    }
    // If CS is not connected then return null
    if (clearspaces.isEmpty()) {
      return null;
    }
    // Set the target address to the IQ packet. Roate list so we distribute load
    String component;
    synchronized (clearspaces) {
      component = clearspaces.get(0);
      Collections.rotate(clearspaces, 1);
    }
    packet.setTo(component);
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
    final IQRouter router = XMPPServer.getInstance().getIQRouter();
    router.addIQResultListener(
        packet.getID(),
        new IQResultListener() {
          public void receivedAnswer(IQ packet) {
            answer.offer(packet);
          }

          public void answerTimeout(String packetId) {
            Log.warn("No answer from Clearspace was received for IQ stanza: " + packet);
          }
        });
    XMPPServer.getInstance().getIQRouter().route(packet);
    IQ reply = null;
    try {
      reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }
    return reply;
  }
  public void testProcessPacket_When_IQ_Packet_Send_To_Service() throws Exception {

    // Arrange
    final IQ packet = new IQ();
    packet.setTo(serviceJid);
    groupService.initialize(serviceJid, null);
    new NonStrictExpectations() {
      {
        final IQDispatcher dispatcher = getField(groupService, "iqDispatcher");
        new NonStrictExpectations(dispatcher) {
          {
            dispatcher.dispatch(packet);
            times = 1;
          }
        };
      }
    };

    // Act
    groupService.processPacket(packet);

    // Assert
  }
 /**
  * If the Connection Manager or the Client requested to close the connection then just do nothing.
  * But if the server originated the request to close the connection then we need to send to the
  * Connection Manager a packet letting him know that the Client Session needs to be terminated.
  */
 @Override
 public void closeVirtualConnection() {
   // Figure out who requested the connection to be closed
   String streamID = session.getStreamID().getID();
   if (multiplexerManager.getClientSession(connectionManagerName, streamID) == null) {
     // Client or Connection manager requested to close the session
     // Do nothing since it has already been removed and closed
   } else {
     ConnectionMultiplexerSession multiplexerSession =
         multiplexerManager.getMultiplexerSession(connectionManagerName, streamID);
     if (multiplexerSession != null) {
       // Server requested to close the client session so let the connection manager
       // know that he has to finish the client session
       IQ closeRequest = new IQ(IQ.Type.set);
       closeRequest.setFrom(serverName);
       closeRequest.setTo(connectionManagerName);
       Element child =
           closeRequest.setChildElement("session", "http://jabber.org/protocol/connectionmanager");
       child.addAttribute("id", streamID);
       child.addElement("close");
       multiplexerSession.process(closeRequest);
     }
   }
 }
  /**
   * Sends a newly created notification message to the specific user.
   *
   * @param apiKey the API key
   * @param title the title
   * @param message the message details
   * @param uri the uri
   */
  public void sendNotifcationToUser(
      String apiKey, String username, String title, String message, String uri, boolean save) {
    log.debug("sendNotifcationToUser()...");
    Random random = new Random();
    String id = Integer.toHexString(random.nextInt());
    IQ notificationIQ = createNotificationIQ(id, apiKey, title, message, uri);
    ClientSession session = sessionManager.getSession(username);
    if (session != null) {
      if (session.getPresence().isAvailable()) {
        notificationIQ.setTo(session.getAddress());
        session.deliver(notificationIQ);
      }
    }

    try {
      User user = userService.getUserByUsername(username);
      if (user != null && save) {
        saveNotification(id, apiKey, username, title, message, uri);
      }
    } catch (UserNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Handles the received IQ packet.
   *
   * @param packet the packet
   * @return the response to send back
   * @throws UnauthorizedException if the user is not authorized
   */
  public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ reply = null;

    ClientSession session = sessionManager.getSession(packet.getFrom());
    if (session == null) {
      log.error("Session not found for key " + packet.getFrom());
      reply = IQ.createResultIQ(packet);
      reply.setChildElement(packet.getChildElement().createCopy());
      reply.setError(PacketError.Condition.internal_server_error);
      return reply;
    }

    try {
      Element iq = packet.getElement();
      Element query = iq.element("query");
      Element queryResponse = probeResponse.createCopy();

      if (IQ.Type.get == packet.getType()) { // get query
        String username = query.elementText("username");
        if (username != null) {
          queryResponse.element("username").setText(username);
        }
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(queryResponse);
        if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
          reply.setTo((JID) null);
        }
      } else { // set query
        String resource = query.elementText("resource");
        String username = query.elementText("username");
        String password = query.elementText("password");
        String digest = null;
        if (query.element("digest") != null) {
          digest = query.elementText("digest").toLowerCase();
        }

        // Verify the resource
        if (resource != null) {
          try {
            resource = JID.resourceprep(resource);
          } catch (StringprepException e) {
            throw new UnauthorizedException("Invalid resource: " + resource, e);
          }
        } else {
          throw new IllegalArgumentException("Invalid resource (empty or null).");
        }

        // Verify the username
        if (username == null || username.trim().length() == 0) {
          throw new UnauthorizedException("Invalid username (empty or null).");
        }
        try {
          Stringprep.nodeprep(username);
        } catch (StringprepException e) {
          throw new UnauthorizedException("Invalid username: " + username, e);
        }
        username = username.toLowerCase();

        // Verify that username and password are correct
        AuthToken token = null;
        if (password != null && AuthManager.isPlainSupported()) {
          token = AuthManager.authenticate(username, password);
        } else if (digest != null && AuthManager.isDigestSupported()) {
          token = AuthManager.authenticate(username, session.getStreamID().toString(), digest);
        }

        if (token == null) {
          throw new UnauthenticatedException();
        }

        // Set the session authenticated successfully
        session.setAuthToken(token, resource);
        packet.setFrom(session.getAddress());
        reply = IQ.createResultIQ(packet);
      }
    } catch (Exception ex) {
      log.error(ex);
      reply = IQ.createResultIQ(packet);
      reply.setChildElement(packet.getChildElement().createCopy());
      if (ex instanceof IllegalArgumentException) {
        reply.setError(PacketError.Condition.not_acceptable);
      } else if (ex instanceof UnauthorizedException) {
        reply.setError(PacketError.Condition.not_authorized);
      } else if (ex instanceof UnauthenticatedException) {
        reply.setError(PacketError.Condition.not_authorized);
      } else {
        reply.setError(PacketError.Condition.internal_server_error);
      }
    }

    // Send the response directly to the session
    if (reply != null) {
      session.process(reply);
    }
    return null;
  }