001/**
002 *
003 * Copyright © 2009 Jonas Ådahl, 2011-2014 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.caps;
018
019import org.jivesoftware.smack.AbstractConnectionListener;
020import org.jivesoftware.smack.SmackException.NoResponseException;
021import org.jivesoftware.smack.SmackException.NotConnectedException;
022import org.jivesoftware.smack.XMPPConnection;
023import org.jivesoftware.smack.ConnectionCreationListener;
024import org.jivesoftware.smack.Manager;
025import org.jivesoftware.smack.StanzaListener;
026import org.jivesoftware.smack.XMPPConnectionRegistry;
027import org.jivesoftware.smack.XMPPException.XMPPErrorException;
028import org.jivesoftware.smack.packet.IQ;
029import org.jivesoftware.smack.packet.Stanza;
030import org.jivesoftware.smack.packet.ExtensionElement;
031import org.jivesoftware.smack.packet.Presence;
032import org.jivesoftware.smack.filter.NotFilter;
033import org.jivesoftware.smack.filter.StanzaFilter;
034import org.jivesoftware.smack.filter.AndFilter;
035import org.jivesoftware.smack.filter.StanzaTypeFilter;
036import org.jivesoftware.smack.filter.StanzaExtensionFilter;
037import org.jivesoftware.smack.util.StringUtils;
038import org.jivesoftware.smack.util.stringencoder.Base64;
039import org.jivesoftware.smackx.caps.cache.EntityCapsPersistentCache;
040import org.jivesoftware.smackx.caps.packet.CapsExtension;
041import org.jivesoftware.smackx.disco.AbstractNodeInformationProvider;
042import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
043import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
044import org.jivesoftware.smackx.disco.packet.DiscoverInfo.Feature;
045import org.jivesoftware.smackx.disco.packet.DiscoverInfo.Identity;
046import org.jivesoftware.smackx.xdata.FormField;
047import org.jivesoftware.smackx.xdata.packet.DataForm;
048import org.jxmpp.util.cache.LruCache;
049
050import java.util.Comparator;
051import java.util.HashMap;
052import java.util.LinkedList;
053import java.util.List;
054import java.util.Locale;
055import java.util.Map;
056import java.util.Queue;
057import java.util.SortedSet;
058import java.util.TreeSet;
059import java.util.WeakHashMap;
060import java.util.concurrent.ConcurrentLinkedQueue;
061import java.util.logging.Level;
062import java.util.logging.Logger;
063import java.security.MessageDigest;
064import java.security.NoSuchAlgorithmException;
065
066/**
067 * Keeps track of entity capabilities.
068 * 
069 * @author Florian Schmaus
070 * @see <a href="http://www.xmpp.org/extensions/xep-0115.html">XEP-0115: Entity Capabilities</a>
071 */
072public class EntityCapsManager extends Manager {
073    private static final Logger LOGGER = Logger.getLogger(EntityCapsManager.class.getName());
074
075    public static final String NAMESPACE = CapsExtension.NAMESPACE;
076    public static final String ELEMENT = CapsExtension.ELEMENT;
077
078    private static final Map<String, MessageDigest> SUPPORTED_HASHES = new HashMap<String, MessageDigest>();
079
080    /**
081     * The default hash. Currently 'sha-1'.
082     */
083    private static final String DEFAULT_HASH = StringUtils.SHA1;
084
085    private static String DEFAULT_ENTITY_NODE = "http://www.igniterealtime.org/projects/smack";
086
087    protected static EntityCapsPersistentCache persistentCache;
088
089    private static boolean autoEnableEntityCaps = true;
090
091    private static Map<XMPPConnection, EntityCapsManager> instances = new WeakHashMap<>();
092
093    private static final StanzaFilter PRESENCES_WITH_CAPS = new AndFilter(new StanzaTypeFilter(Presence.class), new StanzaExtensionFilter(
094                    ELEMENT, NAMESPACE));
095    private static final StanzaFilter PRESENCES_WITHOUT_CAPS = new AndFilter(new StanzaTypeFilter(Presence.class), new NotFilter(new StanzaExtensionFilter(
096                    ELEMENT, NAMESPACE)));
097    private static final StanzaFilter PRESENCES = StanzaTypeFilter.PRESENCE;
098
099    /**
100     * Map of "node + '#' + hash" to DiscoverInfo data
101     */
102    private static final LruCache<String, DiscoverInfo> CAPS_CACHE = new LruCache<String, DiscoverInfo>(1000);
103
104    /**
105     * Map of Full JID -&gt; DiscoverInfo/null. In case of c2s connection the
106     * key is formed as user@server/resource (resource is required) In case of
107     * link-local connection the key is formed as user@host (no resource) In
108     * case of a server or component the key is formed as domain
109     */
110    private static final LruCache<String, NodeVerHash> JID_TO_NODEVER_CACHE = new LruCache<String, NodeVerHash>(10000);
111
112    static {
113        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
114            public void connectionCreated(XMPPConnection connection) {
115                getInstanceFor(connection);
116            }
117        });
118
119        try {
120            MessageDigest sha1MessageDigest = MessageDigest.getInstance(DEFAULT_HASH);
121            SUPPORTED_HASHES.put(DEFAULT_HASH, sha1MessageDigest);
122        } catch (NoSuchAlgorithmException e) {
123            // Ignore
124        }
125    }
126
127    /**
128     * Set the default entity node that will be used for new EntityCapsManagers
129     *
130     * @param entityNode
131     */
132    public static void setDefaultEntityNode(String entityNode) {
133        DEFAULT_ENTITY_NODE = entityNode;
134    }
135
136    /**
137     * Add DiscoverInfo to the database.
138     * 
139     * @param nodeVer
140     *            The node and verification String (e.g.
141     *            "http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w=").
142     * @param info
143     *            DiscoverInfo for the specified node.
144     */
145    public static void addDiscoverInfoByNode(String nodeVer, DiscoverInfo info) {
146        CAPS_CACHE.put(nodeVer, info);
147
148        if (persistentCache != null)
149            persistentCache.addDiscoverInfoByNodePersistent(nodeVer, info);
150    }
151
152    /**
153     * Get the Node version (node#ver) of a JID. Returns a String or null if
154     * EntiyCapsManager does not have any information.
155     * 
156     * @param jid
157     *            the user (Full JID)
158     * @return the node version (node#ver) or null
159     */
160    public static String getNodeVersionByJid(String jid) {
161        NodeVerHash nvh = JID_TO_NODEVER_CACHE.get(jid);
162        if (nvh != null) {
163            return nvh.nodeVer;
164        } else {
165            return null;
166        }
167    }
168
169    public static NodeVerHash getNodeVerHashByJid(String jid) {
170        return JID_TO_NODEVER_CACHE.get(jid);
171    }
172
173    /**
174     * Get the discover info given a user name. The discover info is returned if
175     * the user has a node#ver associated with it and the node#ver has a
176     * discover info associated with it.
177     * 
178     * @param user
179     *            user name (Full JID)
180     * @return the discovered info
181     */
182    public static DiscoverInfo getDiscoverInfoByUser(String user) {
183        NodeVerHash nvh = JID_TO_NODEVER_CACHE.get(user);
184        if (nvh == null)
185            return null;
186
187        return getDiscoveryInfoByNodeVer(nvh.nodeVer);
188    }
189
190    /**
191     * Retrieve DiscoverInfo for a specific node.
192     * 
193     * @param nodeVer
194     *            The node name (e.g.
195     *            "http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w=").
196     * @return The corresponding DiscoverInfo or null if none is known.
197     */
198    public static DiscoverInfo getDiscoveryInfoByNodeVer(String nodeVer) {
199        DiscoverInfo info = CAPS_CACHE.get(nodeVer);
200
201        // If it was not in CAPS_CACHE, try to retrieve the information from persistentCache
202        if (info == null && persistentCache != null) {
203            info = persistentCache.lookup(nodeVer);
204            // Promote the information to CAPS_CACHE if one was found
205            if (info != null) {
206                CAPS_CACHE.put(nodeVer, info);
207            }
208        }
209
210        // If we were able to retrieve information from one of the caches, copy it before returning
211        if (info != null)
212            info = new DiscoverInfo(info);
213
214        return info;
215    }
216
217    /**
218     * Set the persistent cache implementation
219     * 
220     * @param cache
221     */
222    public static void setPersistentCache(EntityCapsPersistentCache cache) {
223        persistentCache = cache;
224    }
225
226    /**
227     * Sets the maximum cache sizes
228     *
229     * @param maxJidToNodeVerSize
230     * @param maxCapsCacheSize
231     */
232    public static void setMaxsCacheSizes(int maxJidToNodeVerSize, int maxCapsCacheSize) {
233        JID_TO_NODEVER_CACHE.setMaxCacheSize(maxJidToNodeVerSize);
234        CAPS_CACHE.setMaxCacheSize(maxCapsCacheSize);
235    }
236
237    /**
238     * Clears the memory cache.
239     */
240    public static void clearMemoryCache() {
241        JID_TO_NODEVER_CACHE.clear();
242        CAPS_CACHE.clear();
243    }
244
245    private static void addCapsExtensionInfo(String from, CapsExtension capsExtension) {
246        String capsExtensionHash = capsExtension.getHash();
247        String hashInUppercase = capsExtensionHash.toUpperCase(Locale.US);
248        // SUPPORTED_HASHES uses the format of MessageDigest, which is uppercase, e.g. "SHA-1" instead of "sha-1"
249        if (!SUPPORTED_HASHES.containsKey(hashInUppercase))
250            return;
251        String hash = capsExtensionHash.toLowerCase(Locale.US);
252
253        String node = capsExtension.getNode();
254        String ver = capsExtension.getVer();
255
256        JID_TO_NODEVER_CACHE.put(from, new NodeVerHash(node, ver, hash));
257    }
258
259    private final Queue<CapsVersionAndHash> lastLocalCapsVersions = new ConcurrentLinkedQueue<>();
260
261    private final ServiceDiscoveryManager sdm;
262
263    private boolean entityCapsEnabled;
264    private CapsVersionAndHash currentCapsVersion;
265    private boolean presenceSend = false;
266
267    /**
268     * The entity node String used by this EntityCapsManager instance.
269     */
270    private String entityNode = DEFAULT_ENTITY_NODE;
271
272    private EntityCapsManager(XMPPConnection connection) {
273        super(connection);
274        this.sdm = ServiceDiscoveryManager.getInstanceFor(connection);
275        instances.put(connection, this);
276
277        connection.addConnectionListener(new AbstractConnectionListener() {
278            @Override
279            public void connected(XMPPConnection connection) {
280                // It's not clear when a server would report the caps stream
281                // feature, so we try to process it after we are connected and
282                // once after we are authenticated.
283                processCapsStreamFeatureIfAvailable(connection);
284            }
285            @Override
286            public void authenticated(XMPPConnection connection, boolean resumed) {
287                // It's not clear when a server would report the caps stream
288                // feature, so we try to process it after we are connected and
289                // once after we are authenticated.
290                processCapsStreamFeatureIfAvailable(connection);
291
292                // Reset presenceSend when the connection was not resumed
293                if (!resumed) {
294                    presenceSend = false;
295                }
296            }
297            private void processCapsStreamFeatureIfAvailable(XMPPConnection connection) {
298                CapsExtension capsExtension = connection.getFeature(
299                                CapsExtension.ELEMENT, CapsExtension.NAMESPACE);
300                if (capsExtension == null) {
301                    return;
302                }
303                String from = connection.getServiceName();
304                addCapsExtensionInfo(from, capsExtension);
305            }
306        });
307
308        // This calculates the local entity caps version
309        updateLocalEntityCaps();
310
311        if (autoEnableEntityCaps)
312            enableEntityCaps();
313
314        connection.addAsyncStanzaListener(new StanzaListener() {
315            // Listen for remote presence stanzas with the caps extension
316            // If we receive such a stanza, record the JID and nodeVer
317            @Override
318            public void processPacket(Stanza packet) {
319                if (!entityCapsEnabled())
320                    return;
321
322                CapsExtension capsExtension = CapsExtension.from(packet);
323                String from = packet.getFrom();
324                addCapsExtensionInfo(from, capsExtension);
325            }
326
327        }, PRESENCES_WITH_CAPS);
328
329        connection.addAsyncStanzaListener(new StanzaListener() {
330            @Override
331            public void processPacket(Stanza packet) {
332                // always remove the JID from the map, even if entityCaps are
333                // disabled
334                String from = packet.getFrom();
335                JID_TO_NODEVER_CACHE.remove(from);
336            }
337        }, PRESENCES_WITHOUT_CAPS);
338
339        connection.addPacketSendingListener(new StanzaListener() {
340            @Override
341            public void processPacket(Stanza packet) {
342                presenceSend = true;
343            }
344        }, PRESENCES);
345
346        // Intercept presence packages and add caps data when intended.
347        // XEP-0115 specifies that a client SHOULD include entity capabilities
348        // with every presence notification it sends.
349        StanzaListener packetInterceptor = new StanzaListener() {
350            public void processPacket(Stanza packet) {
351                if (!entityCapsEnabled)
352                    return;
353                CapsVersionAndHash capsVersionAndHash = getCapsVersionAndHash();
354                CapsExtension caps = new CapsExtension(entityNode, capsVersionAndHash.version, capsVersionAndHash.hash);
355                packet.addExtension(caps);
356            }
357        };
358        connection.addPacketInterceptor(packetInterceptor, PRESENCES);
359        // It's important to do this as last action. Since it changes the
360        // behavior of the SDM in some ways
361        sdm.setEntityCapsManager(this);
362    }
363
364    public static synchronized EntityCapsManager getInstanceFor(XMPPConnection connection) {
365        if (SUPPORTED_HASHES.size() <= 0)
366            throw new IllegalStateException("No supported hashes for EntityCapsManager");
367
368        EntityCapsManager entityCapsManager = instances.get(connection);
369
370        if (entityCapsManager == null) {
371            entityCapsManager = new EntityCapsManager(connection);
372        }
373
374        return entityCapsManager;
375    }
376
377    public synchronized void enableEntityCaps() {
378        // Add Entity Capabilities (XEP-0115) feature node.
379        sdm.addFeature(NAMESPACE);
380        updateLocalEntityCaps();
381        entityCapsEnabled = true;
382    }
383
384    public synchronized void disableEntityCaps() {
385        entityCapsEnabled = false;
386        sdm.removeFeature(NAMESPACE);
387    }
388
389    public boolean entityCapsEnabled() {
390        return entityCapsEnabled;
391    }
392
393    public void setEntityNode(String entityNode) throws NotConnectedException {
394        this.entityNode = entityNode;
395        updateLocalEntityCaps();
396    }
397
398    /**
399     * Remove a record telling what entity caps node a user has.
400     * 
401     * @param user
402     *            the user (Full JID)
403     */
404    public void removeUserCapsNode(String user) {
405        JID_TO_NODEVER_CACHE.remove(user);
406    }
407
408    /**
409     * Get our own caps version. The version depends on the enabled features. A
410     * caps version looks like '66/0NaeaBKkwk85efJTGmU47vXI='
411     * 
412     * @return our own caps version
413     */
414    public CapsVersionAndHash getCapsVersionAndHash() {
415        return currentCapsVersion;
416    }
417
418    /**
419     * Returns the local entity's NodeVer (e.g.
420     * "http://www.igniterealtime.org/projects/smack/#66/0NaeaBKkwk85efJTGmU47vXI=
421     * )
422     * 
423     * @return the local NodeVer
424     */
425    public String getLocalNodeVer() {
426        CapsVersionAndHash capsVersionAndHash = getCapsVersionAndHash();
427        if (capsVersionAndHash == null) {
428            return null;
429        }
430        return entityNode + '#' + capsVersionAndHash.version;
431    }
432
433    /**
434     * Returns true if Entity Caps are supported by a given JID
435     * 
436     * @param jid
437     * @return true if the entity supports Entity Capabilities.
438     * @throws XMPPErrorException 
439     * @throws NoResponseException 
440     * @throws NotConnectedException 
441     */
442    public boolean areEntityCapsSupported(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException {
443        return sdm.supportsFeature(jid, NAMESPACE);
444    }
445
446    /**
447     * Returns true if Entity Caps are supported by the local service/server
448     * 
449     * @return true if the user's server supports Entity Capabilities.
450     * @throws XMPPErrorException 
451     * @throws NoResponseException 
452     * @throws NotConnectedException 
453     */
454    public boolean areEntityCapsSupportedByServer() throws NoResponseException, XMPPErrorException, NotConnectedException  {
455        return areEntityCapsSupported(connection().getServiceName());
456    }
457
458    /**
459     * Updates the local user Entity Caps information with the data provided
460     *
461     * If we are connected and there was already a presence send, another
462     * presence is send to inform others about your new Entity Caps node string.
463     *
464     */
465    public void updateLocalEntityCaps() {
466        XMPPConnection connection = connection();
467
468        DiscoverInfo discoverInfo = new DiscoverInfo();
469        discoverInfo.setType(IQ.Type.result);
470        sdm.addDiscoverInfoTo(discoverInfo);
471
472        // getLocalNodeVer() will return a result only after currentCapsVersion is set. Therefore
473        // set it first and then call getLocalNodeVer()
474        currentCapsVersion = generateVerificationString(discoverInfo);
475        final String localNodeVer = getLocalNodeVer();
476        discoverInfo.setNode(localNodeVer);
477        addDiscoverInfoByNode(localNodeVer, discoverInfo);
478        if (lastLocalCapsVersions.size() > 10) {
479            CapsVersionAndHash oldCapsVersion = lastLocalCapsVersions.poll();
480            sdm.removeNodeInformationProvider(entityNode + '#' + oldCapsVersion.version);
481        }
482        lastLocalCapsVersions.add(currentCapsVersion);
483
484        if (connection != null)
485            JID_TO_NODEVER_CACHE.put(connection.getUser(), new NodeVerHash(entityNode, currentCapsVersion));
486
487        final List<Identity> identities = new LinkedList<Identity>(ServiceDiscoveryManager.getInstanceFor(connection).getIdentities());
488        sdm.setNodeInformationProvider(localNodeVer, new AbstractNodeInformationProvider() {
489            List<String> features = sdm.getFeatures();
490            List<ExtensionElement> packetExtensions = sdm.getExtendedInfoAsList();
491            @Override
492            public List<String> getNodeFeatures() {
493                return features;
494            }
495            @Override
496            public List<Identity> getNodeIdentities() {
497                return identities;
498            }
499            @Override
500            public List<ExtensionElement> getNodePacketExtensions() {
501                return packetExtensions;
502            }
503        });
504
505        // Send an empty presence, and let the packet interceptor
506        // add a <c/> node to it.
507        // See http://xmpp.org/extensions/xep-0115.html#advertise
508        // We only send a presence packet if there was already one send
509        // to respect ConnectionConfiguration.isSendPresence()
510        if (connection != null && connection.isAuthenticated() && presenceSend) {
511            Presence presence = new Presence(Presence.Type.available);
512            try {
513                connection.sendStanza(presence);
514            }
515            catch (NotConnectedException e) {
516                LOGGER.log(Level.WARNING, "Could could not update presence with caps info", e);
517            }
518        }
519    }
520
521    /**
522     * Verify DisoverInfo and Caps Node as defined in XEP-0115 5.4 Processing
523     * Method
524     * 
525     * @see <a href="http://xmpp.org/extensions/xep-0115.html#ver-proc">XEP-0115
526     *      5.4 Processing Method</a>
527     * 
528     * @param ver
529     * @param hash
530     * @param info
531     * @return true if it's valid and should be cache, false if not
532     */
533    public static boolean verifyDiscoverInfoVersion(String ver, String hash, DiscoverInfo info) {
534        // step 3.3 check for duplicate identities
535        if (info.containsDuplicateIdentities())
536            return false;
537
538        // step 3.4 check for duplicate features
539        if (info.containsDuplicateFeatures())
540            return false;
541
542        // step 3.5 check for well-formed packet extensions
543        if (verifyPacketExtensions(info))
544            return false;
545
546        String calculatedVer = generateVerificationString(info, hash).version;
547
548        if (!ver.equals(calculatedVer))
549            return false;
550
551        return true;
552    }
553
554    /**
555     * 
556     * @param info
557     * @return true if the stanza(/packet) extensions is ill-formed
558     */
559    protected static boolean verifyPacketExtensions(DiscoverInfo info) {
560        List<FormField> foundFormTypes = new LinkedList<FormField>();
561        for (ExtensionElement pe : info.getExtensions()) {
562            if (pe.getNamespace().equals(DataForm.NAMESPACE)) {
563                DataForm df = (DataForm) pe;
564                for (FormField f : df.getFields()) {
565                    if (f.getVariable().equals("FORM_TYPE")) {
566                        for (FormField fft : foundFormTypes) {
567                            if (f.equals(fft))
568                                return true;
569                        }
570                        foundFormTypes.add(f);
571                    }
572                }
573            }
574        }
575        return false;
576    }
577
578    protected static CapsVersionAndHash generateVerificationString(DiscoverInfo discoverInfo) {
579        return generateVerificationString(discoverInfo, null);
580    }
581
582    /**
583     * Generates a XEP-115 Verification String
584     * 
585     * @see <a href="http://xmpp.org/extensions/xep-0115.html#ver">XEP-115
586     *      Verification String</a>
587     * 
588     * @param discoverInfo
589     * @param hash
590     *            the used hash function, if null, default hash will be used
591     * @return The generated verification String or null if the hash is not
592     *         supported
593     */
594    protected static CapsVersionAndHash generateVerificationString(DiscoverInfo discoverInfo, String hash) {
595        if (hash == null) {
596            hash = DEFAULT_HASH;
597        }
598        // SUPPORTED_HASHES uses the format of MessageDigest, which is uppercase, e.g. "SHA-1" instead of "sha-1"
599        MessageDigest md = SUPPORTED_HASHES.get(hash.toUpperCase(Locale.US));
600        if (md == null)
601            return null;
602        // Then transform the hash to lowercase, as this value will be put on the wire within the caps element's hash
603        // attribute. I'm not sure if the standard is case insensitive here, but let's assume that even it is, there could
604        // be "broken" implementation in the wild, so we *always* transform to lowercase.
605        hash = hash.toLowerCase(Locale.US);
606
607        DataForm extendedInfo =  DataForm.from(discoverInfo);
608
609        // 1. Initialize an empty string S ('sb' in this method).
610        StringBuilder sb = new StringBuilder(); // Use StringBuilder as we don't
611                                                // need thread-safe StringBuffer
612
613        // 2. Sort the service discovery identities by category and then by
614        // type and then by xml:lang
615        // (if it exists), formatted as CATEGORY '/' [TYPE] '/' [LANG] '/'
616        // [NAME]. Note that each slash is included even if the LANG or
617        // NAME is not included (in accordance with XEP-0030, the category and
618        // type MUST be included.
619        SortedSet<DiscoverInfo.Identity> sortedIdentities = new TreeSet<DiscoverInfo.Identity>();
620
621        for (DiscoverInfo.Identity i : discoverInfo.getIdentities())
622            sortedIdentities.add(i);
623
624        // 3. For each identity, append the 'category/type/lang/name' to S,
625        // followed by the '<' character.
626        for (DiscoverInfo.Identity identity : sortedIdentities) {
627            sb.append(identity.getCategory());
628            sb.append("/");
629            sb.append(identity.getType());
630            sb.append("/");
631            sb.append(identity.getLanguage() == null ? "" : identity.getLanguage());
632            sb.append("/");
633            sb.append(identity.getName() == null ? "" : identity.getName());
634            sb.append("<");
635        }
636
637        // 4. Sort the supported service discovery features.
638        SortedSet<String> features = new TreeSet<String>();
639        for (Feature f : discoverInfo.getFeatures())
640            features.add(f.getVar());
641
642        // 5. For each feature, append the feature to S, followed by the '<'
643        // character
644        for (String f : features) {
645            sb.append(f);
646            sb.append("<");
647        }
648
649        // only use the data form for calculation is it has a hidden FORM_TYPE
650        // field
651        // see XEP-0115 5.4 step 3.6
652        if (extendedInfo != null && extendedInfo.hasHiddenFormTypeField()) {
653            synchronized (extendedInfo) {
654                // 6. If the service discovery information response includes
655                // XEP-0128 data forms, sort the forms by the FORM_TYPE (i.e.,
656                // by the XML character data of the <value/> element).
657                SortedSet<FormField> fs = new TreeSet<FormField>(new Comparator<FormField>() {
658                    public int compare(FormField f1, FormField f2) {
659                        return f1.getVariable().compareTo(f2.getVariable());
660                    }
661                });
662
663                FormField ft = null;
664
665                for (FormField f : extendedInfo.getFields()) {
666                    if (!f.getVariable().equals("FORM_TYPE")) {
667                        fs.add(f);
668                    } else {
669                        ft = f;
670                    }
671                }
672
673                // Add FORM_TYPE values
674                if (ft != null) {
675                    formFieldValuesToCaps(ft.getValues(), sb);
676                }
677
678                // 7. 3. For each field other than FORM_TYPE:
679                // 1. Append the value of the "var" attribute, followed by the
680                // '<' character.
681                // 2. Sort values by the XML character data of the <value/>
682                // element.
683                // 3. For each <value/> element, append the XML character data,
684                // followed by the '<' character.
685                for (FormField f : fs) {
686                    sb.append(f.getVariable());
687                    sb.append("<");
688                    formFieldValuesToCaps(f.getValues(), sb);
689                }
690            }
691        }
692        // 8. Ensure that S is encoded according to the UTF-8 encoding (RFC
693        // 3269).
694        // 9. Compute the verification string by hashing S using the algorithm
695        // specified in the 'hash' attribute (e.g., SHA-1 as defined in RFC
696        // 3174).
697        // The hashed data MUST be generated with binary output and
698        // encoded using Base64 as specified in Section 4 of RFC 4648
699        // (note: the Base64 output MUST NOT include whitespace and MUST set
700        // padding bits to zero).
701        byte[] digest;
702        synchronized(md) {
703            digest = md.digest(sb.toString().getBytes());
704        }
705        String version = Base64.encodeToString(digest);
706        return new CapsVersionAndHash(version, hash);
707    }
708
709    private static void formFieldValuesToCaps(List<String> i, StringBuilder sb) {
710        SortedSet<String> fvs = new TreeSet<String>();
711        for (String s : i) {
712            fvs.add(s);
713        }
714        for (String fv : fvs) {
715            sb.append(fv);
716            sb.append("<");
717        }
718    }
719
720    public static class NodeVerHash {
721        private String node;
722        private String hash;
723        private String ver;
724        private String nodeVer;
725
726        NodeVerHash(String node, CapsVersionAndHash capsVersionAndHash) {
727            this(node, capsVersionAndHash.version, capsVersionAndHash.hash);
728        }
729
730        NodeVerHash(String node, String ver, String hash) {
731            this.node = node;
732            this.ver = ver;
733            this.hash = hash;
734            nodeVer = node + "#" + ver;
735        }
736
737        public String getNodeVer() {
738            return nodeVer;
739        }
740
741        public String getNode() {
742            return node;
743        }
744
745        public String getHash() {
746            return hash;
747        }
748
749        public String getVer() {
750            return ver;
751        }
752    }
753}