/**
   * Processes an IQ-register request that is expressing the wish to deregister from a gateway.
   *
   * @param packet the IQ-register stanza.
   */
  private void handleDeregister(final IQ packet) {
    final IQ result = IQ.createResultIQ(packet);

    if (packet.getChildElement().elements().size() != 1) {
      Log.debug(
          "Cannot process this stanza - exactly one"
              + " childelement of <remove> expected:"
              + packet.toXML());
      final IQ error = IQ.createResultIQ(packet);
      error.setError(Condition.bad_request);
      parent.sendPacket(error);
      return;
    }

    final JID from = packet.getFrom();
    final JID to = packet.getTo();

    // Tell the end user the transport went byebye.
    final Presence unavailable = new Presence(Presence.Type.unavailable);
    unavailable.setTo(from);
    unavailable.setFrom(to);
    this.parent.sendPacket(unavailable);

    try {
      deleteRegistration(from);
    } catch (UserNotFoundException e) {
      Log.debug("Error cleaning up contact list of: " + from);
      result.setError(Condition.registration_required);
    }
    parent.sendPacket(result);
  }
示例#2
0
  /**
   * 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;
  }
示例#3
0
  private void processIQ(IQ iq) {
    long start = System.currentTimeMillis();
    Element childElement = iq.getChildElement();
    String namespace = childElement.getNamespaceURI();

    // 构造返回dom
    IQ reply = IQ.createResultIQ(iq);
    Element childElementCopy = childElement.createCopy();
    reply.setChildElement(childElementCopy);

    if (XConstants.PROTOCOL_DISCO_INFO.equals(namespace)) {
      generateDisco(childElementCopy); // 构造disco反馈信息
      if (LOG.isInfoEnabled()) {
        LOG.info(
            "[spend time:{}ms],reqId: {},IRComponent服务发现,response:{}",
            System.currentTimeMillis() - start,
            iq.getID(),
            reply.toXML());
      }
    }

    try {
      ComponentManagerFactory.getComponentManager().sendPacket(this, reply);
    } catch (Throwable t) {
      LOG.error(
          "[spend time:{}ms],reqId: {},IRComponent IQ处理异常! iq:{},replay:{}",
          System.currentTimeMillis() - start,
          iq.getID(),
          reply.toXML(),
          t);
    }
  }
  public void process(Element elm, JID actorJID, IQ reqIQ, Element rsm) throws Exception {
    element = elm;
    response = IQ.createResultIQ(reqIQ);
    request = reqIQ;
    actor = actorJID;
    node = element.attributeValue("node");

    if (null == actor) {
      actor = request.getFrom();
    }
    if (!channelManager.isLocalNode(node)) {
      makeRemoteRequest();
      return;
    }
    try {
      if (!nodeProvided() || !nodeExists() || !actorCanModify()) {
        outQueue.put(response);
        return;
      }
    } catch (NodeStoreException e) {
      LOGGER.error(e);
      setErrorCondition(PacketError.Type.cancel, PacketError.Condition.internal_server_error);
      outQueue.put(response);
      return;
    }
    setNodeConfiguration();
  }
示例#5
0
  public void executeGet(IQ packet, Workgroup workgroup) {
    IQ reply = IQ.createResultIQ(packet);

    JID from = packet.getFrom();
    String bareJID = from.toBareJID();

    boolean isMonitor = false;

    // Retrieve the sound settings.
    String monitors = workgroup.getProperties().getProperty("monitors");
    if (monitors != null) {
      StringTokenizer tkn = new StringTokenizer(monitors, ",");
      while (tkn.hasMoreTokens()) {
        String agent = tkn.nextToken();
        if (agent.equalsIgnoreCase(bareJID)) {
          isMonitor = true;
        }
      }
    }

    Element monitorElement =
        reply.setChildElement("monitor", "http://jivesoftware.com/protocol/workgroup");

    if (!isMonitor) {
      monitorElement.addElement("isMonitor").setText("false");
    } else {
      monitorElement.addElement("isMonitor").setText("true");
    }

    workgroup.send(reply);
  }
  public void completeRegistration(TransportSession session) {
    final IQ result = IQ.createResultIQ(session.getRegistrationPacket());
    if (!session.getFailureStatus().equals(ConnectionFailureReason.NO_ISSUE)) {
      // Ooh there was a connection issue, we're going to report that back!
      if (session
          .getFailureStatus()
          .equals(ConnectionFailureReason.USERNAME_OR_PASSWORD_INCORRECT)) {
        result.setError(Condition.not_authorized);
      } else if (session.getFailureStatus().equals(ConnectionFailureReason.CAN_NOT_CONNECT)) {
        result.setError(Condition.service_unavailable);
      } else if (session.getFailureStatus().equals(ConnectionFailureReason.LOCKED_OUT)) {
        result.setError(Condition.forbidden);
      } else {
        result.setError(Condition.undefined_condition);
      }
      result.setType(IQ.Type.error);
    }
    parent.sendPacket(result);

    session.setRegistrationPacket(null);

    // Lets ask them what their presence is, maybe log them in immediately.
    final Presence p = new Presence(Presence.Type.probe);
    p.setTo(session.getJID());
    p.setFrom(parent.getJID());
    parent.sendPacket(p);
  }
示例#7
0
  /**
   * Configures the subscription based on the sent {@link DataForm} included in the IQ packet sent
   * by the subscriber. If the subscription was pending of configuration then the last published
   * item is going to be sent to the subscriber.
   *
   * <p>The originalIQ parameter may be <tt>null</tt> when using this API internally. When no IQ
   * packet was sent then no IQ result will be sent to the sender. The rest of the functionality is
   * the same.
   *
   * @param originalIQ the IQ packet sent by the subscriber to configure his subscription or null
   *     when using this API internally.
   * @param options the data form containing the new subscription configuration.
   */
  public void configure(IQ originalIQ, DataForm options) {
    boolean wasUnconfigured = isConfigurationPending();
    // Change the subscription configuration based on the completed form
    configure(options);
    if (originalIQ != null) {
      // Return success response
      service.send(IQ.createResultIQ(originalIQ));
    }

    if (wasUnconfigured) {
      // If subscription is pending then send notification to node owners
      // asking to approve the now configured subscription
      if (isAuthorizationPending()) {
        sendAuthorizationRequest();
      }

      // Send last published item (if node is leaf node and subscription status is ok)
      if (node.isSendItemSubscribe() && isActive()) {
        PublishedItem lastItem = node.getLastPublishedItem();
        if (lastItem != null) {
          sendLastPublishedItem(lastItem);
        }
      }
    }
  }
 /**
  * 退出群
  *
  * @param iq
  * @return
  */
 private IQ quitGroup(IQ iq) {
   String member_jid = iq.getFrom().toBareJID();
   JID group = iq.getTo();
   IQ reply = IQ.createResultIQ(iq);
   long group_id = -1;
   LocalGroup localGroup = null;
   try {
     group_id = Long.parseLong(group.getNode());
     localGroup = service.getGroup(group_id);
   } catch (Exception e) {
     reply.setError(PacketError.Condition.bad_request);
     return reply;
   }
   // 删除群成员
   try {
     Map<String, LocalGroupRole> members = localGroup.getGroupMembers();
     if (members != null && !members.isEmpty()) {
       int delete = groupDbManager.deleteGroupMember(group_id, member_jid);
       // 有记录被删除,通知群成员
       if (delete > 0) {
         // 如果群主退出,删除群
         if (localGroup.isOwner(member_jid)) groupDbManager.deleteGroupById(group_id);
         // 发送消息
         sendPacket(members.keySet(), packetUtil.createQuitPresence(member_jid, group_id));
       }
     }
     localGroup.removeMember(member_jid);
   } catch (SQLException e) {
     reply.setError(PacketError.Condition.internal_server_error);
     return reply;
   }
   return null;
 }
  private void sendRemoteChannelServerNotFoundErrorResponses(String server)
      throws ComponentException {

    List<Packet> queued = waitingStanzas.get(server);
    if (queued == null) {
      return;
    }
    Element noRemoteServer =
        new DOMElement("text", new Namespace("", JabberPubsub.NS_PUBSUB_ERROR));
    noRemoteServer.setText("No pubsub channel service discovered for " + server);
    Element itemNotFound =
        new DOMElement(
            PacketError.Condition.item_not_found.toXMPP(),
            new Namespace("", JabberPubsub.NS_XMPP_STANZAS));
    Element error = new DOMElement("error");
    error.addAttribute("type", PacketError.Type.cancel.toXMPP());
    error.add(itemNotFound);
    error.add(noRemoteServer);
    IQ response;
    for (Packet packet : queued) {
      response = IQ.createResultIQ((IQ) packet);
      response.setFrom(localServer);
      response.setType(IQ.Type.error);
      response.setChildElement(error);
      component.sendPacket(response);
    }
  }
 private void fail(IQ request, Condition condition, org.xmpp.packet.PacketError.Type type)
     throws InterruptedException {
   IQ reply = IQ.createResultIQ(request);
   reply.setType(Type.error);
   PacketError pe = new PacketError(condition, type);
   reply.setError(pe);
   outQueue.put(reply);
 }
  private void unregister(IQ request, JID actorJID, boolean isRemote) throws Exception {
    LOGGER.debug("Processing unregister request from " + request.getFrom());

    if (!validateSingleChildElement(request)) {
      failBadRequest(request);
      return;
    }
    if (!isRemote && !userRegistered(actorJID)) {
      failRegistrationRequired(request);
      return;
    }

    Transaction t = null;
    try {
      t = channelManager.beginTransaction();

      List<Packet> notifications = new LinkedList<Packet>();
      Set<String> remoteDomains = getRemoteDomains();

      ResultSet<NodeMembership> userMemberships = channelManager.getUserMemberships(actorJID);
      for (NodeMembership userMembership : userMemberships) {
        String nodeId = userMembership.getNodeId();
        if (isPersonal(nodeId) || isSingleOwner(nodeId, actorJID)) {
          channelManager.deleteNode(nodeId);
          if (Configuration.getInstance().isLocalNode(nodeId)) {
            addDeleteNodeNotifications(nodeId, notifications);
          }
        }
        if (!isRemote) {
          addUnsubscribeFromNodeNotifications(actorJID, userMembership.getNodeId(), notifications);
        }
      }

      ResultSet<NodeItem> userItems = channelManager.getUserPublishedItems(actorJID);
      for (NodeItem userItem : userItems) {
        if (Configuration.getInstance().isLocalNode(userItem.getNodeId())) {
          addDeleteItemNotifications(userItem.getNodeId(), userItem.getId(), notifications);
        }
      }

      channelManager.deleteUserItems(actorJID);
      channelManager.deleteUserSubscriptions(actorJID);
      channelManager.deleteUserAffiliations(actorJID);

      outQueue.put(IQ.createResultIQ(request));
      if (!isRemote) {
        makeRemoteRequests(request, remoteDomains);
      }
      sendNotifications(notifications);

      t.commit();
    } finally {
      if (t != null) {
        t.close();
      }
    }
  }
示例#12
0
 /**
  * 审批入群申请
  *
  * @param iq
  * @return
  */
 private IQ processGroupApply(IQ iq) {
   IQ reply = IQ.createResultIQ(iq);
   // 发送者
   String creator = iq.getFrom().toBareJID();
   Element query = iq.getChildElement();
   // 申请人
   String applier = query.elementText("applier");
   // 审批结果
   String result = query.elementText("result");
   if (result == null
       || applier == null
       || (!GroupApply.STATUS_ACCEPT.equals(result) && !GroupApply.STATUS_DENIED.equals(result))) {
     reply.setError(PacketError.Condition.bad_request);
     return reply;
   }
   long group_id = -1;
   LocalGroup localGroup = null;
   try {
     group_id = Long.parseLong(iq.getTo().getNode());
     localGroup = service.getGroup(group_id);
   } catch (Exception e) {
     reply.setError(PacketError.Condition.bad_request);
     return reply;
   }
   try {
     // 检查是否已经处理过这条请求
     GroupApply apply = groupDbManager.getGroupApplyByUserGroupId(group_id, applier);
     if (apply == null && !localGroup.isOwner(creator)) {
       reply.setError(PacketError.Condition.bad_request);
       return reply;
     }
     // 处理请求
     apply.setStatus(result);
     groupDbManager.processGroupApply(apply);
     // 如果申请人在线,发送消息通知
     Message applier_msg =
         packetUtil.createGroupApplyResponseMessage(apply, localGroup.getGroup());
     boolean sent = sendPacketIfOnline(applier_msg, apply.getApply_user());
     // 未发送,保存到数据库
     if (!sent) {
       GroupSysMessage sysMessage =
           new GroupSysMessage(apply.getApply_user(), applier_msg.toXML());
       groupDbManager.insertGroupSysMessage(sysMessage);
     }
     // 如果是同意,发送presence给群成员
     if (GroupApply.STATUS_ACCEPT.equals(apply.getStatus())) {
       // 发送消息
       sendPacket(
           localGroup.getGroupMembers().keySet(), packetUtil.createNewMemberPresence(apply));
     }
     // 处理完成
   } catch (SQLException e) {
     reply.setError(PacketError.Condition.internal_server_error);
   }
   return reply;
 }
示例#13
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);
  }
示例#14
0
  /**
   * Handles the IQ packet sent by an owner of the room. Possible actions are:
   *
   * <ul>
   *   <li>Return the list of owners
   *   <li>Return the list of admins
   *   <li>Change user's affiliation to owner
   *   <li>Change user's affiliation to admin
   *   <li>Change user's affiliation to member
   *   <li>Change user's affiliation to none
   *   <li>Destroy the room
   *   <li>Return the room configuration within a dataform
   *   <li>Update the room configuration based on the sent dataform
   * </ul>
   *
   * @param packet the IQ packet sent by an owner of the room.
   * @param role the role of the user that sent the packet.
   * @throws ForbiddenException if the user does not have enough permissions (ie. is not an owner).
   * @throws ConflictException If the room was going to lose all of its owners.
   */
  @SuppressWarnings("unchecked")
  public void handleIQ(IQ packet, MUCRole role)
      throws ForbiddenException, ConflictException, CannotBeInvitedException {
    // Only owners can send packets with the namespace "http://jabber.org/protocol/muc#owner"
    if (MUCRole.Affiliation.owner != role.getAffiliation()) {
      throw new ForbiddenException();
    }

    IQ reply = IQ.createResultIQ(packet);
    Element element = packet.getChildElement();

    // Analyze the action to perform based on the included element
    Element formElement = element.element(QName.get("x", "jabber:x:data"));
    if (formElement != null) {
      handleDataFormElement(role, formElement);
    } else {
      Element destroyElement = element.element("destroy");
      if (destroyElement != null) {
        if (((MultiUserChatServiceImpl) room.getMUCService()).getMUCDelegate() != null) {
          if (!((MultiUserChatServiceImpl) room.getMUCService())
              .getMUCDelegate()
              .destroyingRoom(room.getName(), role.getUserAddress())) {
            // Delegate said no, reject destroy request.
            throw new ForbiddenException();
          }
        }

        JID alternateJID = null;
        final String jid = destroyElement.attributeValue("jid");
        if (jid != null) {
          alternateJID = new JID(jid);
        }
        room.destroyRoom(alternateJID, destroyElement.elementTextTrim("reason"));
      } else {
        // If no element was included in the query element then answer the
        // configuration form
        if (!element.elementIterator().hasNext()) {
          refreshConfigurationFormValues();
          reply.setChildElement(probeResult.createCopy());
        }
        // An unknown and possibly incorrect element was included in the query
        // element so answer a BAD_REQUEST error
        else {
          reply.setChildElement(packet.getChildElement().createCopy());
          reply.setError(PacketError.Condition.bad_request);
        }
      }
    }
    if (reply.getTo() != null) {
      // Send a reply only if the sender of the original packet was from a real JID. (i.e. not
      // a packet generated locally)
      router.route(reply);
    }
  }
示例#15
0
  /**
   * Handles all roster queries. There are two major types of queries:
   *
   * <ul>
   *   <li>Roster remove - A forced removal of items from a roster. Roster removals are the only
   *       roster queries allowed to directly affect the roster from another user.
   *   <li>Roster management - A local user looking up or updating their roster.
   * </ul>
   *
   * @param packet The update packet
   * @return The reply or null if no reply
   */
  public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    try {
      IQ returnPacket = null;
      org.xmpp.packet.Roster roster = (org.xmpp.packet.Roster) packet;

      JID recipientJID = packet.getTo();

      // The packet is bound for the server and must be roster management
      if (recipientJID == null
          || recipientJID.getNode() == null
          || !UserManager.getInstance().isRegisteredUser(recipientJID.getNode())) {
        returnPacket = manageRoster(roster);
      }
      // The packet must be a roster removal from a foreign domain user.
      else {
        removeRosterItem(roster);
      }
      return returnPacket;
    } catch (SharedGroupException e) {
      IQ result = IQ.createResultIQ(packet);
      result.setChildElement(packet.getChildElement().createCopy());
      result.setError(PacketError.Condition.not_acceptable);
      return result;
    } catch (Exception e) {
      if (e.getCause() instanceof IDNAException) {
        Log.warn(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.jid_malformed);
        return result;
      } else {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
      }
    }
  }
示例#16
0
  public void process(IQ packet) throws UnauthorizedException, PacketException {

    // sanitize the input
    if (packet == null) {
      throw new IllegalArgumentException("Argument 'packet' cannot be null.");
    }

    final String xmlns;
    final Element child = (packet).getChildElement();
    if (child != null) {
      xmlns = child.getNamespaceURI();
    } else {
      xmlns = null;
    }

    if (xmlns == null) {
      // No namespace defined.
      Log.debug("Cannot process this stanza, as it has no namespace:" + packet.toXML());
      final IQ error = IQ.createResultIQ(packet);
      error.setError(Condition.bad_request);
      parent.sendPacket(error);
      return;
    }

    // done sanitizing, start processing.
    final Element remove = packet.getChildElement().element("remove");
    if (remove != null) {
      // User wants to unregister. =(
      // this.convinceNotToLeave() ... kidding.
      handleDeregister(packet);
    } else {
      // handle the request
      switch (packet.getType()) {
        case get:
          // client requests registration form
          getRegistrationForm(packet);
          break;

        case set:
          // client is providing (filled out) registration form
          setRegistrationForm(packet);
          break;

        default:
          // ignore result and error stanzas.
          break;
      }
    }
  }
示例#17
0
  /**
   * 用户申请入群
   *
   * @param iq
   * @return
   */
  private IQ applyUserGroup(IQ iq) {
    JID from = iq.getFrom();
    JID to = iq.getTo();
    long group_id = -1;
    // 取群id
    try {
      group_id = Long.parseLong(to.getNode());
    } catch (Exception e) {
      return packetUtil.createErrorIq(iq, GroupError.Condition.bad_request);
    }
    try {
      // 申请理由
      String reason = iq.getChildElement().elementText("reason");
      // 申请人
      String member_jid = from.toBareJID();
      Group group = groupDbManager.getGroupById(group_id);
      // 群不存在
      if (group == null) return packetUtil.createErrorIq(iq, GroupError.Condition.group_not_exsist);
      // 已经是群成员
      if (groupDbManager.isGroupMember(group_id, member_jid))
        return packetUtil.createErrorIq(iq, GroupError.Condition.alread_in_group);
      // 已经提交了申请
      if (groupDbManager.getGroupApplyByUserGroupId(group_id, member_jid) != null)
        return packetUtil.createErrorIq(iq, GroupError.Condition.alread_applied);

      // 新建入群申请
      GroupApply apply = new GroupApply(group_id, member_jid);
      groupDbManager.insertGroupApply(apply);

      // 生成需要发送给群主的消息
      IQ to_admin = packetUtil.createGroupApplyMessage(group, member_jid, reason);
      // 插入系统消息
      GroupSysMessage sysMessage =
          new GroupSysMessage(group_id, member_jid, group.getCreator(), to_admin.toXML());
      groupDbManager.insertGroupSysMessage(sysMessage);

      // 如果群主在线,发送审核消息
      sendPacketIfOnline(to_admin, group.getCreator());

      return IQ.createResultIQ(iq);

    } catch (SQLException e) {
      e.printStackTrace();
      return packetUtil.createErrorIq(iq, GroupError.Condition.server_error);
    }
  }
  public void process(Packet packet) throws ComponentException {

    logger.debug("Packet payload " + packet.toXML() + " going to federation.");

    String to = packet.getTo().toString();

    String uniqueId = generateUniqueId(packet);
    idMap.put(uniqueId, packet.getID());
    packet.setID(uniqueId);

    sentRemotePackets.put(uniqueId, packet.getFrom());
    try {
      extractNodeDetails(packet);
      // Do we have a map already?
      if (discoveredServers.containsKey(to)) {
        packet.setTo(new JID(discoveredServers.get(to)));
        sendPacket(packet.createCopy());
        return;
      }
      // Are we already discovering a remote server?
      if (!remoteChannelDiscoveryStatus.containsKey(to)) {
        discoverRemoteChannelServer(to, packet.getID());
      } else if (remoteChannelDiscoveryStatus.get(to).equals(NO_CHANNEL_SERVER)) {
        logger.error("No remote channel server for " + to);
        IQ reply = IQ.createResultIQ((IQ) packet);
        reply.setError(
            new PacketError(
                PacketError.Condition.remote_server_not_found, PacketError.Type.cancel));
        component.sendPacket(reply);
        return;
      }
      // Add packet to list
      if (!waitingStanzas.containsKey(to)) {
        waitingStanzas.put(to, new ArrayList<Packet>());
      }
      waitingStanzas.get(to).add(packet);
      logger.debug(
          "Adding packet to waiting stanza list for "
              + to
              + " (size "
              + waitingStanzas.get(to).size()
              + ")");
    } catch (Exception e) {
      logger.error(e);
    }
  }
  @Override
  public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ reply = IQ.createResultIQ(packet);
    Element offlineRequest = packet.getChildElement();

    JID from = packet.getFrom();
    if (offlineRequest.element("purge") != null) {
      // User requested to delete all offline messages
      messageStore.deleteMessages(from.getNode());
    } else if (offlineRequest.element("fetch") != null) {
      // Mark that offline messages shouldn't be sent when the user becomes available
      stopOfflineFlooding(from);
      // User requested to receive all offline messages
      for (OfflineMessage offlineMessage : messageStore.getMessages(from.getNode(), false)) {
        sendOfflineMessage(from, offlineMessage);
      }
    } else {
      for (Iterator it = offlineRequest.elementIterator("item"); it.hasNext(); ) {
        Element item = (Element) it.next();
        Date creationDate = null;
        try {
          creationDate = xmppDateTime.parseString(item.attributeValue("node"));
        } catch (ParseException e) {
          Log.error("Error parsing date", e);
        }
        if ("view".equals(item.attributeValue("action"))) {
          // User requested to receive specific message
          OfflineMessage offlineMsg = messageStore.getMessage(from.getNode(), creationDate);
          if (offlineMsg != null) {
            sendOfflineMessage(from, offlineMsg);
          }
        } else if ("remove".equals(item.attributeValue("action"))) {
          // User requested to delete specific message
          if (messageStore.getMessage(from.getNode(), creationDate) != null) {
            messageStore.deleteMessage(from.getNode(), creationDate);
          } else {
            // If the requester is authorized but the node does not exist, the server MUST return a
            // <item-not-found/> error.
            reply.setError(PacketError.Condition.item_not_found);
          }
        }
      }
    }
    return reply;
  }
  private void createExtendedErrorReply(
      Type type, Condition condition, String additionalElement, String additionalNamespace) {

    if (null == response) {
      response = IQ.createResultIQ(request);
    }
    response.setType(IQ.Type.error);
    Element standardError =
        new DOMElement(
            condition.toXMPP(), new org.dom4j.Namespace("", JabberPubsub.NS_XMPP_STANZAS));
    Element extraError =
        new DOMElement(additionalElement, new org.dom4j.Namespace("", additionalNamespace));
    Element error = new DOMElement("error");
    error.addAttribute("type", type.toXMPP());
    error.add(standardError);
    error.add(extraError);
    response.setChildElement(error);
  }
示例#21
0
 /**
  * Sends the current subscription status to the user that tried to create a subscription to the
  * node. The subscription status is sent to the subsciber after the subscription was created or if
  * the subscriber tries to subscribe many times and the node does not support multpiple
  * subscriptions.
  *
  * @param originalRequest the IQ packet sent by the subscriber to create the subscription.
  */
 void sendSubscriptionState(IQ originalRequest) {
   IQ result = IQ.createResultIQ(originalRequest);
   Element child = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
   Element entity = child.addElement("subscription");
   if (!node.isRootCollectionNode()) {
     entity.addAttribute("node", node.getNodeID());
   }
   entity.addAttribute("jid", getJID().toString());
   if (node.isMultipleSubscriptionsEnabled()) {
     entity.addAttribute("subid", getID());
   }
   entity.addAttribute("subscription", getState().name());
   Element subscribeOptions = entity.addElement("subscribe-options");
   if (node.isSubscriptionConfigurationRequired() && isConfigurationPending()) {
     subscribeOptions.addElement("required");
   }
   // Send the result
   service.send(result);
 }
示例#22
0
  @Override
  public IQ handleIQ(IQ packet) throws UnauthorizedException {
    Log.debug("handling IQ packet " + packet);
    IQ reply = IQ.createResultIQ(packet);
    Element iq = packet.getChildElement();
    String method = iq.attributeValue("name");
    List<String> args = new ArrayList<String>();

    // TODO Don't look this up each time
    // We currently do this to avoid problems during development
    // from reloading Jive - later we probably want to move this to
    // constructor
    XMPPMethods methods = EJBUtil.defaultLookup(XMPPMethods.class);
    SimpleAnnotatedInvoker xmppInvoker =
        new SimpleAnnotatedInvoker(XMPPRemoted.class, methods, new PersonArgumentPrepender());

    for (Object argObj : iq.elements()) {
      Node arg = (Node) argObj;
      Log.debug("parsing expected arg node " + arg);
      if (arg.getNodeType() == Node.ELEMENT_NODE) {
        String argValue = arg.getText();
        Log.debug("Adding arg value" + argValue);
        args.add(argValue);
      }
    }

    try {
      Log.debug(
          "invoking method "
              + method
              + " with ("
              + args.size()
              + ") args "
              + Arrays.toString(args.toArray()));
      @SuppressWarnings("unused")
      String replyStr = xmppInvoker.invoke(method, args, packet.getFrom());
      // Don't do anything with this yet
    } catch (Exception e) {
      Log.debug("Caught exception during client method invocation", e);
    }
    return reply;
  }
示例#23
0
 public void process(Packet packet) {
   // Check that the requested packet can be processed
   if (canProcess(packet)) {
     // Perform the actual processing of the packet. This usually implies sending
     // the packet to the entity
     try {
       // Invoke the interceptors before we send the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, this, false, false);
       deliver(packet);
       // Invoke the interceptors after we have sent the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, this, false, true);
     } catch (PacketRejectedException e) {
       // An interceptor rejected the packet so do nothing
     } catch (Exception e) {
       Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
     }
   } else {
     // http://xmpp.org/extensions/xep-0016.html#protocol-error
     if (packet instanceof Message) {
       // For message stanzas, the server SHOULD return an error, which SHOULD be
       // <service-unavailable/>.
       Message message = (Message) packet;
       Message result = message.createCopy();
       result.setTo(message.getFrom());
       result.setError(PacketError.Condition.service_unavailable);
       XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true);
     } else if (packet instanceof IQ) {
       // For IQ stanzas of type "get" or "set", the server MUST return an error, which SHOULD be
       // <service-unavailable/>.
       // IQ stanzas of other types MUST be silently dropped by the server.
       IQ iq = (IQ) packet;
       if (iq.getType() == IQ.Type.get || iq.getType() == IQ.Type.set) {
         IQ result = IQ.createResultIQ(iq);
         result.setError(PacketError.Condition.service_unavailable);
         XMPPServer.getInstance().getRoutingTable().routePacket(iq.getFrom(), result, true);
       }
     }
   }
 }
  @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;
  }
示例#25
0
  @Override
  public void process(IQ packet) {
    Paging<GroupInfo> paging;
    try {
      /* 分页查询圈子数据 */
      RSMPacketExtension rsm = QueryInfo.getRSM(packet);
      paging = groupManager.search(QueryInfo.getQuery(packet), rsm.getIndex(0), rsm.getMax(10));
    } catch (Exception e) {
      handleException(e, "搜索圈子失败");
      replyError(packet, PacketError.Condition.internal_server_error);
      return;
    }

    /* 构建分页数据包 */
    PagingPacket pagingPacket =
        new PagingPacket(
            SEARCH_NAMESPACE,
            paging,
            new GroupSummaryProcessDelegate(groupService.getServiceDomain()));

    IQ reply = IQ.createResultIQ(packet);
    reply.setChildElement(pagingPacket.getElement());
    routePacket(reply);
  }
示例#26
0
  /**
   * Handles a IQ-register 'get' request, which is to be interpreted as a request for a registration
   * form template. The template will be prefilled with data, if the requestee has a current
   * registration with the gateway.
   *
   * @param packet the IQ-register 'get' stanza.
   * @throws UnauthorizedException if the user is not allowed to make use of the gateway.
   */
  private void getRegistrationForm(IQ packet) throws UnauthorizedException {
    final JID from = packet.getFrom();
    final IQ result = IQ.createResultIQ(packet);

    // search for existing registrations
    String curUsername = null;
    String curPassword = null;
    String curNickname = null;
    Boolean registered = false;
    final Collection<Registration> registrations =
        RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
    if (registrations.iterator().hasNext()) {
      Registration registration = registrations.iterator().next();
      curUsername = registration.getUsername();
      curPassword = registration.getPassword();
      curNickname = registration.getNickname();
      registered = true;
    }

    // Verify that the user is allowed to make use of the gateway.
    if (!registered && !parent.permissionManager.hasAccess(from)) {
      // User does not have permission to register with transport.
      // We want to allow them to change settings if they are already
      // registered.
      throw new UnauthorizedException(
          LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyacls", "kraken"));
    }

    // generate a template registration form.
    final Element response =
        DocumentHelper.createElement(QName.get("query", NameSpace.IQ_REGISTER));
    final DataForm form = new DataForm(DataForm.Type.form);
    form.addInstruction(parent.getTerminologyRegistration());

    final FormField usernameField = form.addField();
    usernameField.setLabel(parent.getTerminologyUsername());
    usernameField.setVariable("username");
    usernameField.setType(FormField.Type.text_single);
    if (curUsername != null) {
      usernameField.addValue(curUsername);
    }

    final FormField passwordField = form.addField();
    passwordField.setLabel(parent.getTerminologyPassword());
    passwordField.setVariable("password");
    passwordField.setType(FormField.Type.text_private);
    if (curPassword != null) {
      passwordField.addValue(curPassword);
    }

    final String nicknameTerm = parent.getTerminologyNickname();
    if (nicknameTerm != null) {
      FormField nicknameField = form.addField();
      nicknameField.setLabel(nicknameTerm);
      nicknameField.setVariable("nick");
      nicknameField.setType(FormField.Type.text_single);
      if (curNickname != null) {
        nicknameField.addValue(curNickname);
      }
    }

    response.add(form.getElement());
    response.addElement("instructions").addText(parent.getTerminologyRegistration());

    // prefill the template with existing data if a registration already
    // exists.
    if (registered) {
      response.addElement("registered");
      response.addElement("username").addText(curUsername);
      if (curPassword == null) {
        response.addElement("password");
      } else {
        response.addElement("password").addText(curPassword);
      }
      if (nicknameTerm != null) {
        if (curNickname == null) {
          response.addElement("nick");
        } else {
          response.addElement("nick").addText(curNickname);
        }
      }
    } else {
      response.addElement("username");
      response.addElement("password");
      if (nicknameTerm != null) {
        response.addElement("nick");
      }
    }

    // Add special indicator for rosterless gateway handling.
    response.addElement("x").addNamespace("", NameSpace.IQ_GATEWAY_REGISTER);

    result.setChildElement(response);

    parent.sendPacket(result);
  }
 /**
  * @param iq
  * @param userJid
  * @param notificationSettings
  * @return
  */
 private IQ createResponse(IQ iq, String userJid, NotificationSettings notificationSettings) {
   IQ result = IQ.createResultIQ(iq);
   Element queryElement = result.getElement().addElement("query", getNamespace());
   NotificationUtils.appendXML(queryElement, notificationSettings);
   return result;
 }
 protected void setErrorCondition(Type type, Condition condition) {
   if (null == response) response = IQ.createResultIQ(request);
   response.setType(IQ.Type.error);
   PacketError error = new PacketError(condition, type);
   response.setError(error);
 }
示例#29
0
  /**
   * Handles a IQ-register 'set' request, which is to be interpreted as a request to create a new
   * registration.
   *
   * @param packet the IQ-register 'set' stanza.
   * @throws UnauthorizedException if the user isn't allowed to register.
   */
  private void setRegistrationForm(IQ packet) throws UnauthorizedException {
    final JID from = packet.getFrom();

    final boolean registered;
    Collection<Registration> registrations =
        RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
    if (registrations.iterator().hasNext()) {
      registered = true;
    } else {
      registered = false;
    }

    if (!registered && !parent.permissionManager.hasAccess(from)) {
      // User does not have permission to register with transport.
      // We want to allow them to change settings if they are already
      // registered.
      throw new UnauthorizedException(
          LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyacls", "kraken"));
    }

    // Parse the input variables
    String username = null;
    String password = null;
    String nickname = null;
    try {
      if (packet.getChildElement().element("x") != null) {
        final DataForm form = new DataForm(packet.getChildElement().element("x"));
        final List<FormField> fields = form.getFields();
        for (final FormField field : fields) {
          final String var = field.getVariable();
          if (var.equals("username")) {
            username = field.getValues().get(0);
          } else if (var.equals("password")) {
            password = field.getValues().get(0);
          } else if (var.equals("nick")) {
            nickname = field.getValues().get(0);
          }
        }
      }
    }
    // TODO: This shouldn't be done by catching an Exception - check for the
    // existence of elements instead. If we insist doing this with an
    // exception handler, prevent catching a generic Exception (catch more
    // specific subclasses instead).
    catch (Exception ex) {
      // No with data form apparently
      Log.info("Most likely, no dataform was present " + "in the IQ-register request.", ex);
    }

    // input variables could also exist in the non-extended elements
    final Element userEl = packet.getChildElement().element("username");
    final Element passEl = packet.getChildElement().element("password");
    final Element nickEl = packet.getChildElement().element("nick");
    if (userEl != null) {
      username = userEl.getTextTrim();
    }
    if (passEl != null) {
      password = passEl.getTextTrim();
    }
    if (nickEl != null) {
      nickname = nickEl.getTextTrim();
    }

    username = (username == null || username.equals("")) ? null : username;
    password = (password == null || password.equals("")) ? null : password;
    nickname = (nickname == null || nickname.equals("")) ? null : nickname;

    // verify that we've got wat we need.
    if (username == null
        || (parent.isPasswordRequired() && password == null)
        || (parent.isNicknameRequired() && nickname == null)) {
      // Invalid information from stanza, lets yell.
      Log.info(
          "Cannot process IQ register request, as it "
              + "fails to provide all data that's required: "
              + packet.toXML());
      final IQ result = IQ.createResultIQ(packet);
      result.setError(Condition.bad_request);
      parent.sendPacket(result);
      return;
    }

    // Check if the client supports our proprietary 'rosterless' mode.
    final boolean rosterlessMode;
    final Element x = packet.getChildElement().element("x");
    if (x != null
        && x.getNamespaceURI() != null
        && x.getNamespaceURI().equals(NameSpace.IQ_GATEWAY_REGISTER)) {
      rosterlessMode = true;
      Log.info("Registering " + packet.getFrom() + " as " + username + " in rosterless mode.");
    } else {
      rosterlessMode = false;
      Log.info(
          "Registering "
              + packet.getFrom()
              + " as "
              + username
              + " (without making use of rosterless mode).");
    }

    // Here's where the true magic lies: create the registration!
    try {
      addNewRegistration(from, username, password, nickname, rosterlessMode);

      registrations =
          RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
      Registration registration = registrations.iterator().next();
      TransportSession session =
          parent.registrationLoggedIn(registration, from, PresenceType.available, "", -1);
      session.setRegistrationPacket(packet);
      session.detachSession();
      parent.getSessionManager().storeSession(from, session);

      // final IQ result = IQ.createResultIQ(packet);
      // I believe this shouldn't be included. Leaving it around just in
      // case.
      // Element response =
      // DocumentHelper.createElement(QName.get("query", IQ_REGISTER));
      // result.setChildElement(response);
      // parent.sendPacket(result);
    } catch (UserNotFoundException e) {
      Log.warn(
          "Someone attempted to register with the gateway "
              + "who is not registered with the server: "
              + from);
      final IQ eresult = IQ.createResultIQ(packet);
      eresult.setError(Condition.forbidden);
      parent.sendPacket(eresult);
      final Message em = new Message();
      em.setType(Message.Type.error);
      em.setTo(packet.getFrom());
      em.setFrom(packet.getTo());
      em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniednoacct", "kraken"));
      parent.sendPacket(em);
    } catch (IllegalAccessException e) {
      Log.warn(
          "Someone who is not a user of this server "
              + "tried to register with the transport: "
              + from);
      final IQ eresult = IQ.createResultIQ(packet);
      eresult.setError(Condition.forbidden);
      parent.sendPacket(eresult);
      final Message em = new Message();
      em.setType(Message.Type.error);
      em.setTo(packet.getFrom());
      em.setFrom(packet.getTo());
      em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyhost", "kraken"));
      parent.sendPacket(em);
    } catch (IllegalArgumentException e) {
      Log.warn(
          "Someone attempted to register with the " + "gateway with an invalid username: "******"gateway.base.registrationdeniedbadusername", "kraken"));
      parent.sendPacket(em);
    }
  }
 /*
  * @see
  * org.jivesoftware.openfire.handler.IQHandler#handleIQ(org.xmpp.packet.IQ)
  */
 @Override
 public IQ handleIQ(IQ packet) {
   return IQ.createResultIQ(packet);
 }