private void makeRemoteRequests(IQ request, Set<String> remoteDomains) throws Exception {
   for (String remoteDomain : remoteDomains) {
     IQ remoteRequest = request.createCopy();
     remoteRequest.getElement().addAttribute("remote-server-discover", "false");
     remoteRequest.setTo(remoteDomain);
     Element actor =
         remoteRequest
             .getElement()
             .element("query")
             .element("remove")
             .addElement("actor", Buddycloud.NS);
     actor.addText(request.getFrom().toBareJID());
     outQueue.put(remoteRequest);
   }
 }
  public void processDiscoItemsResponse(JID from, List<Element> items) throws ComponentException {

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

    remoteServerItemsToProcess.put(from.toString(), items.size());
    String infoRequestId;
    for (Element item : items) {
      infoRequestId = getId() + ":info";
      infoRequest.setTo(item.attributeValue("jid"));
      infoRequest.setID(infoRequestId);
      remoteServerInfoRequestIds.put(infoRequestId, from.toString());
      component.sendPacket(infoRequest.createCopy());
    }
    remoteChannelDiscoveryStatus.put(from.toString(), DISCO_INFO);
  }
Exemplo n.º 3
0
  private void processIQ(Element doc) {
    log.debug("processIQ()...");
    IQ packet;
    try {
      packet = getIQ(doc);
    } catch (IllegalArgumentException e) {
      log.debug("Rejecting packet. JID malformed", e);
      IQ reply = new IQ();
      if (!doc.elements().isEmpty()) {
        reply.setChildElement(((Element) doc.elements().get(0)).createCopy());
      }
      reply.setID(doc.attributeValue("id"));
      reply.setTo(session.getAddress());
      String to = doc.attributeValue("to");
      if (to != null) {
        reply.getElement().addAttribute("from", to);
      }
      reply.setError(PacketError.Condition.jid_malformed);
      session.process(reply);
      return;
    }

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

    packet.setFrom(session.getAddress());
    router.route(packet);
    session.incrementClientPacketCount();
  }
Exemplo n.º 4
0
  /**
   * Reads a post signer request off the wire, sends it to the WS with a new callback for returning
   * the response.
   *
   * @param request the post signer request
   * @param responseCallback the callback to send the response back
   */
  void processPostSignerRequest(final IQ request, final PacketCallback responseCallback) {
    Element item = null, signatureElement = null;
    Element pubsubRequest = request.getElement().element("pubsub");
    Element publish = pubsubRequest.element("publish");
    if (publish != null) {
      item = publish.element("item");
      if (item != null) {
        signatureElement = item.element("signature");
      }
    }

    if (publish == null
        || item == null
        || signatureElement == null
        || signatureElement.attribute("domain") == null
        || signatureElement.attribute("algorithm") == null
        || signatureElement.element("certificate") == null) {
      responseCallback.error(FederationErrors.badRequest("Malformed post signer request"));
      return;
    }

    ProtocolSignerInfo signer;
    try {
      signer = XmppUtil.xmlToProtocolSignerInfo(signatureElement);
    } catch (UnknownSignerType e) {
      responseCallback.error(
          FederationErrors.badRequest("Could not understand signer algorithm: " + e));
      return;
    }

    WaveletFederationProvider.PostSignerInfoResponseListener listener =
        new WaveletFederationProvider.PostSignerInfoResponseListener() {
          @Override
          public void onFailure(FederationError error) {
            responseCallback.error(error);
          }

          @Override
          public void onSuccess() {
            IQ response = IQ.createResultIQ(request);

            Element pubsub = response.setChildElement("pubsub", XmppNamespace.NAMESPACE_PUBSUB);
            Element item = pubsub.addElement("publish").addElement("item");

            item.addAttribute("node", "signer");
            item.addElement("signature-response", XmppNamespace.NAMESPACE_WAVE_SERVER);

            responseCallback.run(response);
          }
        };

    // TODO(thorogood,arb): This field is a Bad Idea; it could be faked and not
    // be a provider we host on this instance. Instead, we should infer from the
    // "To:" JID.
    String targetDomain = signatureElement.attributeValue("domain");

    // The first argument is the domain we intend to send this information to.
    waveletProvider.postSignerInfo(targetDomain, signer, listener);
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.buddycloud.pusher.handler.AbstractQueryHandler#handleQuery(org.xmpp
  * .packet.IQ)
  */
 @Override
 protected IQ handleQuery(IQ iq) {
   String userJid = iq.getFrom().toBareJID();
   Element queryElement = iq.getElement().element("query");
   Element typeEl = queryElement.element("type");
   NotificationSettings notificationSettings =
       NotificationUtils.getNotificationSettingsByType(userJid, typeEl.getText(), getDataSource());
   return createResponse(iq, userJid, notificationSettings);
 }
  @SuppressWarnings("unchecked")
  @Test
  @Ignore
  public void testCanControlGatheredEntriesUsingRsm() throws Exception {

    NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "node1:1", new Date(0), "<entry>item1</entry>");
    NodeItem item2 = new NodeItemImpl(TEST_NODE_2, "node2:1", new Date(10), "<entry>item2</entry>");
    NodeItem item3 = new NodeItemImpl(TEST_NODE_1, "node1:2", new Date(20), "<entry>item3</entry>");
    NodeItem item4 = new NodeItemImpl(TEST_NODE_1, "node1:3", new Date(30), "<entry>item4</entry>");

    ArrayList<NodeItem> results = new ArrayList<NodeItem>();
    results.add(item1);
    results.add(item2);
    results.add(item3);
    results.add(item4);

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(results.iterator()));
    Mockito.when(
            channelManager.getCountUserFeedItems(
                Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyBoolean()))
        .thenReturn(results.size());

    Element rsm = request.getElement().addElement("rsm");
    rsm.addNamespace("", PubSubElementProcessorAbstract.NS_RSM);
    rsm.addElement("max").addText("2");
    rsm.addElement("after").addText("node1:1");

    userItemsGet.process(element, jid, request, null);
    IQ response = (IQ) queue.poll();

    Assert.assertEquals(IQ.Type.result, response.getType());
    Element pubsub = response.getChildElement();
    Assert.assertEquals("pubsub", pubsub.getName());
    Assert.assertEquals(JabberPubsub.NAMESPACE_URI, pubsub.getNamespaceURI());

    List<Element> items = pubsub.elements("items");
    Assert.assertEquals(2, items.size());

    Assert.assertEquals(TEST_NODE_2, items.get(0).attributeValue("node"));
    Assert.assertEquals(TEST_NODE_1, items.get(1).attributeValue("node"));
    Assert.assertEquals(1, items.get(0).elements("item").size());
    Assert.assertEquals(1, items.get(1).elements("item").size());

    Element rsmResult = pubsub.element("set");
    Assert.assertEquals("2", rsmResult.element("count").getText());
    Assert.assertEquals("node2:1", rsmResult.element("first").getText());
    Assert.assertEquals("node1:2", rsmResult.element("last").getText());
  }
 private void discoverRemoteChannelServer(String remoteDomain, String id)
     throws ComponentException {
   logger.info("Attemping to discover remote server " + remoteDomain);
   IQ discover = new IQ(IQ.Type.get);
   discover.setFrom(localServer);
   discover.setTo(remoteDomain);
   discover.setID(id);
   discover.getElement().addElement("query", JabberPubsub.NS_DISCO_ITEMS);
   component.sendPacket(discover);
   remoteChannelDiscoveryStatus.put(remoteDomain, DISCO_ITEMS);
 }
  @Override
  public void process(IQ request) throws Exception {
    JID actorJID = null;
    Element removeEl = request.getElement().element("query").element("remove");
    Element actorEl = removeEl.element("actor");
    boolean isRemote = actorEl != null;

    if (isRemote) {
      actorJID = new JID(actorEl.getTextTrim());
      if (!checkDomain(request, actorJID)) {
        return;
      }
    } else {
      actorJID = new JID(request.getFrom().toBareJID());
    }

    unregister(request, actorJID, isRemote);
  }
  @Override
  public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
      throws PacketRejectedException {
    if (!processed && incoming) {
      if (packet instanceof IQ) {
        Log.debug(
            "Incomping unprocessed package i might be interested in. Package: \n"
                + packet.toString()
                + "\n");
        IQ myPacket = (IQ) packet;
        if (myPacket.getFrom() == null || myPacket.getTo() == null) {
          /*
           * If getTo() == null this is maybe a roster update from the
           * Client to the Server, check if we should mirror this
           * package to external component
           */
          if (myPacket.getFrom() != null
              && myPacket.getType().equals(IQ.Type.set)
              && myPacket.getTo() == null) {
            if (XpathHelper.findNodesInDocument(
                        myPacket.getChildElement().getDocument(), "//roster:item")
                    .size()
                > 0) {
              _packetProcessor.get("clientToComponentUpdate").process(myPacket);
            }
          }
          return;
        }
        @SuppressWarnings("unused")
        String to = myPacket.getTo().toString();
        String from = myPacket.getFrom().toString();

        if (myPacket.getType().equals(IQ.Type.get) && from.equals(_mySubdomain)) {
          if (XpathHelper.findNodesInDocument(myPacket.getElement().getDocument(), "//roster:*")
                  .size()
              == 1) {
            // This Package is a roster request by remote component
            _packetProcessor.get("sendRoster").process(packet);
          }
        } else if (myPacket.getType().equals(IQ.Type.set) && from.equals(_mySubdomain)) {
          if (XpathHelper.findNodesInDocument(myPacket.getElement().getDocument(), "//roster:item")
                  .size()
              >= 1) {
            // Component sends roster update
            _packetProcessor.get("receiveChanges").process(packet);
          }
        } else if (myPacket.getType().equals(IQ.Type.get)
            && myPacket.toString().contains("http://jabber.org/protocol/disco#info")
            && myPacket.getTo().toString().equals(_mySubdomain)) {
          /*
           * modify the disco#info for spark clients if enabled in
           * admin panel
           */
          _packetProcessor.get("sparkIQRegistered").process(packet);
        } else if (myPacket.getType().equals(IQ.Type.set)
            && myPacket.getTo().toString().equals(_mySubdomain)) {
          System.out.println("war das ein remove an mich????");
          _packetProcessor.get("handleCleanUp").process(packet);
        }
      }
      // else if (packet instanceof Presence) {
      // if (packet.getFrom().toString().equals(_mySubdomain)
      // &&
      // !JiveGlobals.getBooleanProperty("plugin.remoteroster.persistent",
      // false)) {
      // System.out.println("MACH EIN CLEANUP!!!!!!");
      // _packetProcessor.get("handleCleanUp").process(packet);
      // }
      // }
    }
  }
Exemplo n.º 10
0
 public void writeExternal(ObjectOutput out) throws IOException {
   ExternalizableUtil.getInstance().writeSerializable(out, (DefaultElement) iq.getElement());
 }
 private boolean validateSingleChildElement(IQ request) {
   return request.getElement().element("query").elements().size() == 1;
 }
 /**
  * @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;
 }
Exemplo n.º 13
0
  /**
   * Handles a submit request from a foreign wave remote. Sends it to the wave server, sets up a
   * callback to send the response.
   *
   * @param request the submit request
   * @param responseCallback the callback to send the response back
   */
  void processSubmitRequest(final IQ request, final PacketCallback responseCallback) {
    Element item = null, submitRequest = null, deltaElement = null;
    Element pubsubRequest = request.getElement().element("pubsub");
    // TODO: check for correct elements.
    Element publish = pubsubRequest.element("publish");
    if (publish != null) {
      item = publish.element("item");
      if (item != null) {
        submitRequest = item.element("submit-request");
        if (submitRequest != null) {
          deltaElement = submitRequest.element("delta");
        }
      }
    }
    if (publish == null
        || item == null
        || submitRequest == null
        || deltaElement == null
        || deltaElement.attribute("wavelet-name") == null
        || deltaElement.getText() == null) {
      responseCallback.error(FederationErrors.badRequest("Malformed submit request"));
      return;
    }

    final WaveletName waveletName;
    try {
      waveletName =
          XmppUtil.waveletNameCodec.uriToWaveletName(deltaElement.attributeValue("wavelet-name"));
    } catch (EncodingException e) {
      responseCallback.error(
          FederationErrors.badRequest(
              "Malformed wavelet name: " + deltaElement.attributeValue("wavelet-name")));
      return;
    }

    final ProtocolSignedDelta delta;
    try {
      delta = ProtocolSignedDelta.parseFrom(Base64Util.decode(deltaElement.getText()));
    } catch (InvalidProtocolBufferException e) {
      responseCallback.error(
          FederationErrors.badRequest("Malformed delta, not a valid protocol buffer"));
      return;
    }

    // Construct a submit result listener inline.
    WaveletFederationProvider.SubmitResultListener listener =
        new WaveletFederationProvider.SubmitResultListener() {
          @Override
          public void onFailure(FederationError error) {
            responseCallback.error(error);
          }

          @Override
          public void onSuccess(int operations, ProtocolHashedVersion version, long timestamp) {
            IQ response = IQ.createResultIQ(request);

            Element pubsub = response.setChildElement("pubsub", XmppNamespace.NAMESPACE_PUBSUB);
            Element submitResponse =
                pubsub
                    .addElement("publish")
                    .addElement("item")
                    .addElement("submit-response", XmppNamespace.NAMESPACE_WAVE_SERVER);

            submitResponse.addAttribute("application-timestamp", String.valueOf(timestamp));
            submitResponse.addAttribute("operations-applied", String.valueOf(operations));

            Element hashedVersion = submitResponse.addElement("hashed-version");
            hashedVersion.addAttribute("history-hash", Base64Util.encode(version.getHistoryHash()));
            hashedVersion.addAttribute("version", String.valueOf(version.getVersion()));

            responseCallback.run(response);
          }
        };

    // Hand off the submit request to the wavelet provider.
    waveletProvider.submitRequest(waveletName, delta, listener);
  }
Exemplo n.º 14
0
  /**
   * Reads a history request off the wire, sends it to the WS with a new callback for returning the
   * response.
   *
   * @param request the history request
   * @param responseCallback the callback to send the response back
   */
  void processHistoryRequest(final IQ request, final PacketCallback responseCallback) {
    Element items = null, historyDelta = null;
    Element pubsubRequest = request.getElement().element("pubsub");
    if (pubsubRequest != null) {
      items = pubsubRequest.element("items");
      if (items != null) {
        historyDelta = items.element("delta-history");
      }
    }
    if (items == null
        || historyDelta == null
        || historyDelta.attribute("start-version") == null
        || historyDelta.attribute("start-version-hash") == null
        || historyDelta.attribute("end-version") == null
        || historyDelta.attribute("end-version-hash") == null
        || historyDelta.attribute("wavelet-name") == null) {
      responseCallback.error(FederationErrors.badRequest("Malformed history request"));
      return;
    }

    final ProtocolHashedVersion startVersion;
    try {
      startVersion =
          parseFromUnsafe(
              historyDelta.attributeValue("start-version"),
              historyDelta.attributeValue("start-version-hash"));
    } catch (IllegalArgumentException e) {
      responseCallback.error(FederationErrors.badRequest("Invalid format of start version"));
      return;
    }

    final ProtocolHashedVersion endVersion;
    try {
      endVersion =
          parseFromUnsafe(
              historyDelta.attributeValue("end-version"),
              historyDelta.attributeValue("end-version-hash"));
    } catch (IllegalArgumentException e) {
      responseCallback.error(FederationErrors.badRequest("Invalid format of end version"));
      return;
    }

    final long responseLengthLimit;
    if (historyDelta.attribute("response-length-limit") != null) {
      try {
        responseLengthLimit = Long.parseLong(historyDelta.attributeValue("response-length-limit"));
      } catch (NumberFormatException e) {
        responseCallback.error(FederationErrors.badRequest("Invalid response length limit"));
        return;
      }
    } else {
      responseLengthLimit = 0;
    }

    final WaveletName waveletName;
    try {
      waveletName =
          XmppUtil.waveletNameCodec.uriToWaveletName(historyDelta.attributeValue("wavelet-name"));
    } catch (EncodingException e) {
      responseCallback.error(
          FederationErrors.badRequest(
              "Malformed wavelet name: " + historyDelta.attributeValue("wavelet-name")));
      return;
    }

    // Construct a new response listener inline.
    WaveletFederationProvider.HistoryResponseListener listener =
        new WaveletFederationProvider.HistoryResponseListener() {
          @Override
          public void onFailure(FederationError error) {
            responseCallback.error(error);
          }

          @Override
          public void onSuccess(
              List<ByteString> appliedDeltaSet,
              ProtocolHashedVersion lastCommittedVersion,
              long versionTruncatedAt) {
            IQ response = IQ.createResultIQ(request);

            Element pubsub = response.setChildElement("pubsub", XmppNamespace.NAMESPACE_PUBSUB);
            Element items = pubsub.addElement("items");

            // Add each delta to the outgoing response.
            for (ByteString appliedDelta : appliedDeltaSet) {
              items
                  .addElement("item")
                  .addElement("applied-delta", XmppNamespace.NAMESPACE_WAVE_SERVER)
                  .addCDATA(Base64Util.encode(appliedDelta.toByteArray()));
            }

            // Set the LCV history-hash, if provided.
            // TODO(thorogood): We don't set the hashed version, which is wrong,
            // but it's not part of the current spec (Feb 2010).
            if (lastCommittedVersion != null && lastCommittedVersion.hasVersion()) {
              String version = String.valueOf(lastCommittedVersion.getVersion());
              items
                  .addElement("item")
                  .addElement("commit-notice", XmppNamespace.NAMESPACE_WAVE_SERVER)
                  .addAttribute("version", version);
            }

            // Set the version truncated at, if provided.
            if (versionTruncatedAt > 0) {
              String version = String.valueOf(versionTruncatedAt);
              items
                  .addElement("item")
                  .addElement("history-truncated", XmppNamespace.NAMESPACE_WAVE_SERVER)
                  .addAttribute("version", version);
            }

            // Send the message to the source.
            responseCallback.run(response);
          }
        };

    // Hand off a history request to the waveletProvider.
    // TODO(thorogood,arb): Note that the following remote domain is going to be
    // the Wave component JID (e.g. wave.foo.com), and *not* the actual remote domain.
    String remoteDomain = request.getFrom().getDomain();
    waveletProvider.requestHistory(
        waveletName, remoteDomain, startVersion, endVersion, responseLengthLimit, listener);
  }
  /**
   * Handles the received IQ packet.
   *
   * @param packet the packet
   * @return the response to send back
   * @throws UnauthorizedException if the user is not authorized
   */
  public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ reply = null;

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

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

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

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

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

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

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

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

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