/*
   * Create the SessionCredit
   * the information retrieved from the iq
   */
  protected SessionCredit getSessionCredit(final IQ iq) {
    String maxseconds = null;
    String type = null;
    SessionCredit sessionCredit = new SessionCredit(SessionCredit.RouteType.ip);
    sessionCredit.setMaxDurationInSeconds(0);

    log.debug("Get Credit Value Received: " + iq.toXML());

    final Element e = iq.getChildElement();
    maxseconds = e.attributeValue("maxseconds");
    type = e.attributeValue("type");
    if (maxseconds != null && type != null) {
      try {
        final int seconds = Integer.parseInt(maxseconds);
        sessionCredit.setMaxDurationInSeconds(seconds);

        final SessionCredit.RouteType rt = SessionCredit.RouteType.valueOf(type);
        sessionCredit.setRouteType(rt);

      } catch (IllegalFormatException ife) {
        log.error("Invalid Credit Value Received: " + iq.toXML(), ife);
      } catch (IllegalArgumentException ife) {
        log.error("Invalid Route Type Value Received: " + iq.toXML(), ife);
      }
    } else {
      log.debug("Call Initialized with Default Credits: " + iq.toXML());
    }

    return sessionCredit;
  }
Example #2
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);
    }
  }
  /**
   * 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);
  }
  @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;
  }
  public void featureNotImplementedSuccess()
      throws IOException, InterruptedException, DocumentException {
    IQ request = readStanzaAsIq("/iq/featureNotImplemented/request.stanza");
    String expectedReply = readStanzaAsString("/iq/featureNotImplemented/reply.stanza");

    TestHelper helper = new TestHelper();

    helper.getInQueue().put(request);

    IQ replyIQ = (IQ) helper.getOutQueue().poll(1000, TimeUnit.MILLISECONDS);

    Assert.assertNotNull(replyIQ);
    Assert.assertEquals(expectedReply, replyIQ.toXML());
  }
  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;
      }
    }
  }
  /**
   * 用户申请入群
   *
   * @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);
    }
  }
Example #8
0
 /**
  * Processes the packet in another thread if the packet has not been rejected.
  *
  * @param packet the received packet.
  */
 protected void processIQ(final IQ packet) throws UnauthorizedException {
   try {
     packetReceived(packet);
     // Process the packet in another thread
     threadPool.execute(
         new Runnable() {
           public void run() {
             try {
               ServerSocketReader.super.processIQ(packet);
             } catch (UnauthorizedException e) {
               Log.error("Error processing packet", e);
             }
           }
         });
   } catch (PacketRejectedException e) {
     Log.debug("IQ rejected: " + packet.toXML(), e);
   }
 }
  /**
   * 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);
    }
  }