public DataForm getExtendedInfo(String name, String node, JID senderJID) {
    // Mark that offline messages shouldn't be sent when the user becomes available
    stopOfflineFlooding(senderJID);

    final DataForm dataForm = new DataForm(DataForm.Type.result);

    final FormField field1 = dataForm.addField();
    field1.setVariable("FORM_TYPE");
    field1.setType(FormField.Type.hidden);
    field1.addValue(NAMESPACE);

    final FormField field2 = dataForm.addField();
    field2.setVariable("number_of_messages");
    field2.addValue(String.valueOf(messageStore.getMessages(senderJID.getNode(), false).size()));

    return dataForm;
  }
  private void notifySubscribers(HashMap<String, String> configuration)
      throws NodeStoreException, InterruptedException {
    ResultSet<NodeSubscription> subscribers = channelManager.getNodeSubscriptionListeners(node);
    Document document = getDocumentHelper();
    Element message = document.addElement("message");
    message.addAttribute("remote-server-discover", "false");
    Element event = message.addElement("event");
    Element configurationElement = event.addElement("configuration");
    configurationElement.addAttribute("node", node);
    event.addNamespace("", Event.NAMESPACE);
    message.addAttribute("from", request.getTo().toString());
    message.addAttribute("type", "headline");
    Message rootElement = new Message(message);

    Element dataForm = configurationElement.addElement("x");
    dataForm.addAttribute("type", "result");
    dataForm.addNamespace("", DataForm.NAMESPACE);
    DataForm df = new DataForm(dataForm);

    FormField field;
    for (Map.Entry<String, String> entry : configuration.entrySet()) {
      String key = entry.getKey();
      Object value = entry.getValue();
      field = df.addField(key, null, null);
      field.addValue(value);
      // ...
    }

    for (NodeSubscription subscriber : subscribers) {
      Message notification = rootElement.createCopy();
      notification.setTo(subscriber.getListener());
      outQueue.put(notification);
    }

    Collection<JID> admins = getAdminUsers();
    for (JID admin : admins) {
      Message notification = rootElement.createCopy();
      notification.setTo(admin);
      outQueue.put(notification);
    }
  }
Exemplo n.º 3
0
  /**
   * Handles packets that includes a data form. The data form was sent using an element with name
   * "x" and namespace "jabber:x:data".
   *
   * @param senderRole the role of the user that sent the data form.
   * @param formElement the element that contains the data form specification.
   * @throws ForbiddenException if the user does not have enough privileges.
   * @throws ConflictException If the room was going to lose all of its owners.
   */
  private void handleDataFormElement(MUCRole senderRole, Element formElement)
      throws ForbiddenException, ConflictException {
    DataForm completedForm = new DataForm(formElement);

    switch (completedForm.getType()) {
      case cancel:
        // If the room was just created (i.e. is locked) and the owner cancels the configuration
        // form then destroy the room
        if (room.isLocked()) {
          room.destroyRoom(null, null);
        }
        break;

      case submit:
        // The owner is requesting an instant room
        if (completedForm.getFields().isEmpty()) {
          // Do nothing
        }
        // The owner is requesting a reserved room or is changing the current configuration
        else {
          processConfigurationForm(completedForm, senderRole);
        }
        // If the room was locked, unlock it and send to the owner the "room is now unlocked"
        // message
        if (room.isLocked() && !room.isManuallyLocked()) {
          room.unlock(senderRole);
        }
        if (!room.isDestroyed) {
          // Let other cluster nodes that the room has been updated
          CacheFactory.doClusterTask(new RoomUpdatedEvent(room));
        }
        break;

      default:
        Log.warn("cannot handle data form element: " + formElement.asXML());
        break;
    }
  }
Exemplo n.º 4
0
  private void init() {
    Element element =
        DocumentHelper.createElement(QName.get("query", "http://jabber.org/protocol/muc#owner"));

    configurationForm = new DataForm(DataForm.Type.form);
    configurationForm.setTitle(LocaleUtils.getLocalizedString("muc.form.conf.title"));
    List<String> params = new ArrayList<String>();
    params.add(room.getName());
    configurationForm.addInstruction(
        LocaleUtils.getLocalizedString("muc.form.conf.instruction", params));

    configurationForm
        .addField("FORM_TYPE", null, Type.hidden)
        .addValue("http://jabber.org/protocol/muc#roomconfig");

    configurationForm.addField(
        "muc#roomconfig_roomname",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomname"),
        Type.text_single);

    configurationForm.addField(
        "muc#roomconfig_roomdesc",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomdesc"),
        Type.text_single);

    configurationForm.addField(
        "muc#roomconfig_changesubject",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_changesubject"),
        Type.boolean_type);

    final FormField maxUsers =
        configurationForm.addField(
            "muc#roomconfig_maxusers",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_maxusers"),
            Type.list_single);
    maxUsers.addOption("10", "10");
    maxUsers.addOption("20", "20");
    maxUsers.addOption("30", "30");
    maxUsers.addOption("40", "40");
    maxUsers.addOption("50", "50");
    maxUsers.addOption(LocaleUtils.getLocalizedString("muc.form.conf.none"), "0");

    final FormField broadcast =
        configurationForm.addField(
            "muc#roomconfig_presencebroadcast",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_presencebroadcast"),
            Type.list_multi);
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.moderator"), "moderator");
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.participant"), "participant");
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.visitor"), "visitor");

    configurationForm.addField(
        "muc#roomconfig_publicroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_publicroom"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_persistentroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_persistentroom"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_moderatedroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_moderatedroom"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_membersonly",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_membersonly"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.allowinvitesfixed"));

    configurationForm.addField(
        "muc#roomconfig_allowinvites",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_allowinvites"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_passwordprotectedroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_passwordprotectedroom"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomsecretfixed"));

    configurationForm.addField(
        "muc#roomconfig_roomsecret",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomsecret"),
        Type.text_private);

    final FormField whois =
        configurationForm.addField(
            "muc#roomconfig_whois",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_whois"),
            Type.list_single);
    whois.addOption(LocaleUtils.getLocalizedString("muc.form.conf.moderator"), "moderators");
    whois.addOption(LocaleUtils.getLocalizedString("muc.form.conf.anyone"), "anyone");

    configurationForm.addField(
        "muc#roomconfig_enablelogging",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_enablelogging"),
        Type.boolean_type);

    configurationForm.addField(
        "x-muc#roomconfig_reservednick",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_reservednick"),
        Type.boolean_type);

    configurationForm.addField(
        "x-muc#roomconfig_canchangenick",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_canchangenick"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.owner_registration"));

    configurationForm.addField(
        "x-muc#roomconfig_registration",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_registration"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomadminsfixed"));

    configurationForm.addField(
        "muc#roomconfig_roomadmins",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomadmins"),
        Type.jid_multi);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomownersfixed"));

    configurationForm.addField(
        "muc#roomconfig_roomowners",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomowners"),
        Type.jid_multi);

    // Create the probeResult and add the basic info together with the configuration form
    probeResult = element;
    probeResult.add(configurationForm.getElement());
  }
Exemplo n.º 5
0
  private void refreshConfigurationFormValues() {
    room.lock.readLock().lock();
    try {
      FormField field = configurationForm.getField("muc#roomconfig_roomname");
      field.clearValues();
      field.addValue(room.getNaturalLanguageName());

      field = configurationForm.getField("muc#roomconfig_roomdesc");
      field.clearValues();
      field.addValue(room.getDescription());

      field = configurationForm.getField("muc#roomconfig_changesubject");
      field.clearValues();
      field.addValue((room.canOccupantsChangeSubject() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_maxusers");
      field.clearValues();
      field.addValue(Integer.toString(room.getMaxUsers()));

      field = configurationForm.getField("muc#roomconfig_presencebroadcast");
      field.clearValues();
      for (String roleToBroadcast : room.getRolesToBroadcastPresence()) {
        field.addValue(roleToBroadcast);
      }

      field = configurationForm.getField("muc#roomconfig_publicroom");
      field.clearValues();
      field.addValue((room.isPublicRoom() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_persistentroom");
      field.clearValues();
      field.addValue((room.isPersistent() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_moderatedroom");
      field.clearValues();
      field.addValue((room.isModerated() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_membersonly");
      field.clearValues();
      field.addValue((room.isMembersOnly() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_allowinvites");
      field.clearValues();
      field.addValue((room.canOccupantsInvite() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_passwordprotectedroom");
      field.clearValues();
      field.addValue((room.isPasswordProtected() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_roomsecret");
      field.clearValues();
      field.addValue(room.getPassword());

      field = configurationForm.getField("muc#roomconfig_whois");
      field.clearValues();
      field.addValue((room.canAnyoneDiscoverJID() ? "anyone" : "moderators"));

      field = configurationForm.getField("muc#roomconfig_enablelogging");
      field.clearValues();
      field.addValue((room.isLogEnabled() ? "1" : "0"));

      field = configurationForm.getField("x-muc#roomconfig_reservednick");
      field.clearValues();
      field.addValue((room.isLoginRestrictedToNickname() ? "1" : "0"));

      field = configurationForm.getField("x-muc#roomconfig_canchangenick");
      field.clearValues();
      field.addValue((room.canChangeNickname() ? "1" : "0"));

      field = configurationForm.getField("x-muc#roomconfig_registration");
      field.clearValues();
      field.addValue((room.isRegistrationEnabled() ? "1" : "0"));

      field = configurationForm.getField("muc#roomconfig_roomadmins");
      field.clearValues();
      for (JID jid : room.getAdmins()) {
        field.addValue(jid.toString());
      }

      field = configurationForm.getField("muc#roomconfig_roomowners");
      field.clearValues();
      for (JID jid : room.getOwners()) {
        field.addValue(jid.toString());
      }

      // Remove the old element
      probeResult.remove(probeResult.element(QName.get("x", "jabber:x:data")));
      // Add the new representation of configurationForm as an element
      probeResult.add(configurationForm.getElement());

    } finally {
      room.lock.readLock().unlock();
    }
  }
Exemplo n.º 6
0
  /**
   * Processes the completed form sent by an owner of the room. This will modify the room's
   * configuration as well as the list of owners and admins.
   *
   * @param completedForm the completed form sent by an owner of the room.
   * @param senderRole the role of the user that sent the completed form.
   * @throws ForbiddenException if the user does not have enough privileges.
   * @throws ConflictException If the room was going to lose all of its owners.
   */
  private void processConfigurationForm(DataForm completedForm, MUCRole senderRole)
      throws ForbiddenException, ConflictException {
    List<String> values;
    String booleanValue;
    FormField field;

    // Get the new list of admins
    field = completedForm.getField("muc#roomconfig_roomadmins");
    boolean adminsSent = field != null;
    List<JID> admins = new ArrayList<JID>();
    if (field != null) {
      for (String value : field.getValues()) {
        // XEP-0045: "Affiliations are granted, revoked, and
        // maintained based on the user's bare JID, (...)"
        if (value != null && value.trim().length() != 0) {
          admins.add(new JID(value.trim()).asBareJID());
        }
      }
    }

    // Get the new list of owners
    field = completedForm.getField("muc#roomconfig_roomowners");
    boolean ownersSent = field != null;
    List<JID> owners = new ArrayList<JID>();
    if (field != null) {
      for (String value : field.getValues()) {
        // XEP-0045: "Affiliations are granted, revoked, and
        // maintained based on the user's bare JID, (...)"
        if (value != null && value.trim().length() != 0) {
          owners.add(new JID(value.trim()).asBareJID());
        }
      }
    }

    // Answer a conflic error if all the current owners will be removed
    if (ownersSent && owners.isEmpty()) {
      throw new ConflictException();
    }

    // Keep a registry of the updated presences
    List<Presence> presences = new ArrayList<Presence>(admins.size() + owners.size());

    field = completedForm.getField("muc#roomconfig_roomname");
    if (field != null) {
      final String value = field.getFirstValue();
      room.setNaturalLanguageName((value != null ? value : " "));
    }

    field = completedForm.getField("muc#roomconfig_roomdesc");
    if (field != null) {
      final String value = field.getFirstValue();
      room.setDescription((value != null ? value : " "));
    }

    field = completedForm.getField("muc#roomconfig_changesubject");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setCanOccupantsChangeSubject(("1".equals(booleanValue)));
    }

    field = completedForm.getField("muc#roomconfig_maxusers");
    if (field != null) {
      final String value = field.getFirstValue();
      room.setMaxUsers((value != null ? Integer.parseInt(value) : 30));
    }

    field = completedForm.getField("muc#roomconfig_presencebroadcast");
    if (field != null) {
      values = new ArrayList<String>(field.getValues());
      room.setRolesToBroadcastPresence(values);
    }

    field = completedForm.getField("muc#roomconfig_publicroom");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setPublicRoom(("1".equals(booleanValue)));
    }

    field = completedForm.getField("muc#roomconfig_persistentroom");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      boolean isPersistent = ("1".equals(booleanValue));
      // Delete the room from the DB if it's no longer persistent
      if (room.isPersistent() && !isPersistent) {
        MUCPersistenceManager.deleteFromDB(room);
      }
      room.setPersistent(isPersistent);
    }

    field = completedForm.getField("muc#roomconfig_moderatedroom");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setModerated(("1".equals(booleanValue)));
    }

    field = completedForm.getField("muc#roomconfig_membersonly");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      presences.addAll(room.setMembersOnly(("1".equals(booleanValue))));
    }

    field = completedForm.getField("muc#roomconfig_allowinvites");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setCanOccupantsInvite(("1".equals(booleanValue)));
    }

    field = completedForm.getField("muc#roomconfig_passwordprotectedroom");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      boolean isPasswordProtected = "1".equals(booleanValue);
      if (isPasswordProtected) {
        // The room is password protected so set the new password
        field = completedForm.getField("muc#roomconfig_roomsecret");
        if (field != null) {
          final String secret = completedForm.getField("muc#roomconfig_roomsecret").getFirstValue();
          room.setPassword(secret);
        }
      } else {
        // The room is not password protected so remove any previous password
        room.setPassword(null);
      }
    }

    field = completedForm.getField("muc#roomconfig_whois");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setCanAnyoneDiscoverJID(("anyone".equals(booleanValue)));
    }

    field = completedForm.getField("muc#roomconfig_enablelogging");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setLogEnabled(("1".equals(booleanValue)));
    }

    field = completedForm.getField("x-muc#roomconfig_reservednick");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setLoginRestrictedToNickname(("1".equals(booleanValue)));
    }

    field = completedForm.getField("x-muc#roomconfig_canchangenick");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setChangeNickname(("1".equals(booleanValue)));
    }

    field = completedForm.getField("x-muc#roomconfig_registration");
    if (field != null) {
      final String value = field.getFirstValue();
      booleanValue = ((value != null ? value : "1"));
      room.setRegistrationEnabled(("1".equals(booleanValue)));
    }

    // Update the modification date to reflect the last time when the room's configuration
    // was modified
    room.setModificationDate(new Date());

    if (room.isPersistent()) {
      room.saveToDB();
    }

    // Set the new owners and admins of the room
    presences.addAll(room.addOwners(owners, senderRole));
    presences.addAll(room.addAdmins(admins, senderRole));

    if (ownersSent) {
      // Change the affiliation to "member" for the current owners that won't be neither
      // owner nor admin (if the form included the owners field)
      List<JID> ownersToRemove = new ArrayList<JID>(room.owners);
      ownersToRemove.removeAll(admins);
      ownersToRemove.removeAll(owners);
      for (JID jid : ownersToRemove) {
        presences.addAll(room.addMember(jid, null, senderRole));
      }
    }

    if (adminsSent) {
      // Change the affiliation to "member" for the current admins that won't be neither
      // owner nor admin (if the form included the admins field)
      List<JID> adminsToRemove = new ArrayList<JID>(room.admins);
      adminsToRemove.removeAll(admins);
      adminsToRemove.removeAll(owners);
      for (JID jid : adminsToRemove) {
        presences.addAll(room.addMember(jid, null, senderRole));
      }
    }

    // Destroy the room if the room is no longer persistent and there are no occupants in
    // the room
    if (!room.isPersistent() && room.getOccupantsCount() == 0) {
      room.destroyRoom(null, null);
    }

    // Send the updated presences to the room occupants
    for (Object presence : presences) {
      room.send((Presence) presence);
    }
  }
Exemplo n.º 7
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);
    }
  }
Exemplo n.º 8
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);
  }
Exemplo n.º 9
0
  /**
   * Returns a data form with the subscription configuration. The data form can be used to edit the
   * subscription configuration.
   *
   * @return data form used by the subscriber to edit the subscription configuration.
   */
  public DataForm getConfigurationForm() {
    DataForm form = new DataForm(DataForm.Type.form);
    form.setTitle(LocaleUtils.getLocalizedString("pubsub.form.subscription.title"));
    List<String> params = new ArrayList<String>();
    params.add(node.getNodeID());
    form.addInstruction(
        LocaleUtils.getLocalizedString("pubsub.form.subscription.instruction", params));
    // Add the form fields and configure them for edition
    FormField formField = form.addField();
    formField.setVariable("FORM_TYPE");
    formField.setType(FormField.Type.hidden);
    formField.addValue("http://jabber.org/protocol/pubsub#subscribe_options");

    formField = form.addField();
    formField.setVariable("pubsub#deliver");
    formField.setType(FormField.Type.boolean_type);
    formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.deliver"));
    formField.addValue(deliverNotifications);

    formField = form.addField();
    formField.setVariable("pubsub#digest");
    formField.setType(FormField.Type.boolean_type);
    formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.digest"));
    formField.addValue(usingDigest);

    formField = form.addField();
    formField.setVariable("pubsub#digest_frequency");
    formField.setType(FormField.Type.text_single);
    formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.digest_frequency"));
    formField.addValue(digestFrequency);

    formField = form.addField();
    formField.setVariable("pubsub#expire");
    formField.setType(FormField.Type.text_single);
    formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.expire"));
    if (expire != null) {
      formField.addValue(fastDateFormat.format(expire));
    }

    formField = form.addField();
    formField.setVariable("pubsub#include_body");
    formField.setType(FormField.Type.boolean_type);
    formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.include_body"));
    formField.addValue(includingBody);

    formField = form.addField();
    formField.setVariable("pubsub#show-values");
    formField.setType(FormField.Type.list_multi);
    formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.show-values"));
    formField.addOption(null, Presence.Show.away.name());
    formField.addOption(null, Presence.Show.chat.name());
    formField.addOption(null, Presence.Show.dnd.name());
    formField.addOption(null, "online");
    formField.addOption(null, Presence.Show.xa.name());
    for (String value : presenceStates) {
      formField.addValue(value);
    }

    if (node.isCollectionNode()) {
      formField = form.addField();
      formField.setVariable("pubsub#subscription_type");
      formField.setType(FormField.Type.list_single);
      formField.setLabel(
          LocaleUtils.getLocalizedString("pubsub.form.subscription.subscription_type"));
      formField.addOption(null, Type.items.name());
      formField.addOption(null, Type.nodes.name());
      formField.addValue(type);

      formField = form.addField();
      formField.setVariable("pubsub#subscription_depth");
      formField.setType(FormField.Type.list_single);
      formField.setLabel(
          LocaleUtils.getLocalizedString("pubsub.form.subscription.subscription_depth"));
      formField.addOption(null, "1");
      formField.addOption(null, "all");
      formField.addValue(depth == 1 ? "1" : "all");
    }

    if (!node.isCollectionNode() || type == Type.items) {
      formField = form.addField();
      formField.setVariable("x-pubsub#keywords");
      formField.setType(FormField.Type.text_single);
      formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.subscription.keywords"));
      if (keyword != null) {
        formField.addValue(keyword);
      }
    }

    return form;
  }
Exemplo n.º 10
0
  void configure(DataForm options) {
    List<String> values;
    String booleanValue;

    boolean wasUsingPresence = !presenceStates.isEmpty();

    // Remove this field from the form
    options.removeField("FORM_TYPE");
    // Process and remove specific collection node fields
    FormField collectionField = options.getField("pubsub#subscription_type");
    if (collectionField != null) {
      values = collectionField.getValues();
      if (values.size() > 0) {
        type = Type.valueOf(values.get(0));
      }
      options.removeField("pubsub#subscription_type");
    }
    collectionField = options.getField("pubsub#subscription_depth");
    if (collectionField != null) {
      values = collectionField.getValues();
      depth = "all".equals(values.get(0)) ? 0 : 1;
      options.removeField("pubsub#subscription_depth");
    }
    // If there are more fields in the form then process them and set that
    // the subscription has been configured
    for (FormField field : options.getFields()) {
      boolean fieldExists = true;
      if ("pubsub#deliver".equals(field.getVariable())) {
        values = field.getValues();
        booleanValue = (values.size() > 0 ? values.get(0) : "1");
        deliverNotifications = "1".equals(booleanValue);
      } else if ("pubsub#digest".equals(field.getVariable())) {
        values = field.getValues();
        booleanValue = (values.size() > 0 ? values.get(0) : "1");
        usingDigest = "1".equals(booleanValue);
      } else if ("pubsub#digest_frequency".equals(field.getVariable())) {
        values = field.getValues();
        digestFrequency = values.size() > 0 ? Integer.parseInt(values.get(0)) : 86400000;
      } else if ("pubsub#expire".equals(field.getVariable())) {
        values = field.getValues();
        synchronized (dateFormat) {
          try {
            expire = dateFormat.parse(values.get(0));
          } catch (ParseException e) {
            Log.error("Error parsing date", e);
          }
        }
      } else if ("pubsub#include_body".equals(field.getVariable())) {
        values = field.getValues();
        booleanValue = (values.size() > 0 ? values.get(0) : "1");
        includingBody = "1".equals(booleanValue);
      } else if ("pubsub#show-values".equals(field.getVariable())) {
        // Get the new list of presence states for which an entity wants to
        // receive notifications
        presenceStates = new ArrayList<String>();
        for (String value : field.getValues()) {
          try {
            presenceStates.add(value);
          } catch (Exception e) {
            // Do nothing
          }
        }
      } else if ("x-pubsub#keywords".equals(field.getVariable())) {
        values = field.getValues();
        keyword = values.isEmpty() ? null : values.get(0);
      } else {
        fieldExists = false;
      }
      if (fieldExists) {
        // Subscription has been configured so set the next state
        if (node.getAccessModel().isAuthorizationRequired() && !node.isAdmin(owner)) {
          state = State.pending;
        } else {
          state = State.subscribed;
        }
      }
    }
    if (savedToDB) {
      // Update the subscription in the backend store
      PubSubPersistenceManager.saveSubscription(service, node, this, false);
    }
    // Check if the service needs to subscribe or unsubscribe from the owner presence
    if (!node.isPresenceBasedDelivery() && wasUsingPresence != !presenceStates.isEmpty()) {
      if (presenceStates.isEmpty()) {
        service.presenceSubscriptionNotRequired(node, owner);
      } else {
        service.presenceSubscriptionRequired(node, owner);
      }
    }
  }