001/**
002 *
003 * Copyright 2012-2015 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.ping;
018
019import java.util.Collections;
020import java.util.HashSet;
021import java.util.Map;
022import java.util.Set;
023import java.util.WeakHashMap;
024import java.util.concurrent.Executors;
025import java.util.concurrent.ScheduledExecutorService;
026import java.util.concurrent.ScheduledFuture;
027import java.util.concurrent.TimeUnit;
028import java.util.logging.Level;
029import java.util.logging.Logger;
030
031import org.jivesoftware.smack.AbstractConnectionClosedListener;
032import org.jivesoftware.smack.SmackException;
033import org.jivesoftware.smack.SmackException.NoResponseException;
034import org.jivesoftware.smack.SmackException.NotConnectedException;
035import org.jivesoftware.smack.XMPPConnection;
036import org.jivesoftware.smack.ConnectionCreationListener;
037import org.jivesoftware.smack.Manager;
038import org.jivesoftware.smack.XMPPConnectionRegistry;
039import org.jivesoftware.smack.XMPPException;
040import org.jivesoftware.smack.XMPPException.XMPPErrorException;
041import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
042import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
043import org.jivesoftware.smack.packet.IQ;
044import org.jivesoftware.smack.packet.IQ.Type;
045import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
046import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
047import org.jivesoftware.smackx.ping.packet.Ping;
048
049/**
050 * Implements the XMPP Ping as defined by XEP-0199. The XMPP Ping protocol allows one entity to
051 * ping any other entity by simply sending a ping to the appropriate JID. PingManger also
052 * periodically sends XMPP pings to the server to avoid NAT timeouts and to test
053 * the connection status.
054 * <p>
055 * The default server ping interval is 30 minutes and can be modified with
056 * {@link #setDefaultPingInterval(int)} and {@link #setPingInterval(int)}.
057 * </p>
058 * 
059 * @author Florian Schmaus
060 * @see <a href="http://www.xmpp.org/extensions/xep-0199.html">XEP-0199:XMPP Ping</a>
061 */
062public class PingManager extends Manager {
063    private static final Logger LOGGER = Logger.getLogger(PingManager.class.getName());
064
065    private static final Map<XMPPConnection, PingManager> INSTANCES = new WeakHashMap<XMPPConnection, PingManager>();
066
067    static {
068        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
069            public void connectionCreated(XMPPConnection connection) {
070                getInstanceFor(connection);
071            }
072        });
073    }
074
075    /**
076     * Retrieves a {@link PingManager} for the specified {@link XMPPConnection}, creating one if it doesn't already
077     * exist.
078     * 
079     * @param connection
080     * The connection the manager is attached to.
081     * @return The new or existing manager.
082     */
083    public synchronized static PingManager getInstanceFor(XMPPConnection connection) {
084        PingManager pingManager = INSTANCES.get(connection);
085        if (pingManager == null) {
086            pingManager = new PingManager(connection);
087            INSTANCES.put(connection, pingManager);
088        }
089        return pingManager;
090    }
091
092    /**
093     * The default ping interval in seconds used by new PingManager instances. The default is 30 minutes.
094     */
095    private static int defaultPingInterval = 60 * 30;
096
097    /**
098     * Set the default ping interval which will be used for new connections.
099     *
100     * @param interval the interval in seconds
101     */
102    public static void setDefaultPingInterval(int interval) {
103        defaultPingInterval = interval;
104    }
105
106    private final Set<PingFailedListener> pingFailedListeners = Collections
107                    .synchronizedSet(new HashSet<PingFailedListener>());
108
109    private final ScheduledExecutorService executorService;
110
111    /**
112     * The interval in seconds between pings are send to the users server.
113     */
114    private int pingInterval = defaultPingInterval;
115
116    private ScheduledFuture<?> nextAutomaticPing;
117
118    private PingManager(XMPPConnection connection) {
119        super(connection);
120        executorService = Executors.newSingleThreadScheduledExecutor(
121                        new SmackExecutorThreadFactory(connection.getConnectionCounter(), "Ping"));
122        ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
123        sdm.addFeature(Ping.NAMESPACE);
124
125        connection.registerIQRequestHandler(new AbstractIqRequestHandler(Ping.ELEMENT, Ping.NAMESPACE, Type.get, Mode.async) {
126            @Override
127            public IQ handleIQRequest(IQ iqRequest) {
128                Ping ping = (Ping) iqRequest;
129                return ping.getPong();
130            }
131        });
132        connection.addConnectionListener(new AbstractConnectionClosedListener() {
133            @Override
134            public void authenticated(XMPPConnection connection, boolean resumed) {
135                maybeSchedulePingServerTask();
136            }
137            @Override
138            public void connectionTerminated() {
139                maybeStopPingServerTask();
140            }
141        });
142        maybeSchedulePingServerTask();
143    }
144
145    /**
146     * Pings the given jid. This method will return false if an error occurs.  The exception 
147     * to this, is a server ping, which will always return true if the server is reachable, 
148     * event if there is an error on the ping itself (i.e. ping not supported).
149     * <p>
150     * Use {@link #isPingSupported(String)} to determine if XMPP Ping is supported 
151     * by the entity.
152     * 
153     * @param jid The id of the entity the ping is being sent to
154     * @param pingTimeout The time to wait for a reply in milliseconds
155     * @return true if a reply was received from the entity, false otherwise.
156     * @throws NoResponseException if there was no response from the jid.
157     * @throws NotConnectedException 
158     */
159    public boolean ping(String jid, long pingTimeout) throws NotConnectedException, NoResponseException {
160        final XMPPConnection connection = connection();
161        // Packet collector for IQs needs an connection that was at least authenticated once,
162        // otherwise the client JID will be null causing an NPE
163        if (!connection.isAuthenticated()) {
164            throw new NotConnectedException();
165        }
166        Ping ping = new Ping(jid);
167        try {
168            connection.createPacketCollectorAndSend(ping).nextResultOrThrow(pingTimeout);
169        }
170        catch (XMPPException exc) {
171            return jid.equals(connection.getServiceName());
172        }
173        return true;
174    }
175
176    /**
177     * Same as calling {@link #ping(String, long)} with the defaultpacket reply 
178     * timeout.
179     * 
180     * @param jid The id of the entity the ping is being sent to
181     * @return true if a reply was received from the entity, false otherwise.
182     * @throws NotConnectedException
183     * @throws NoResponseException if there was no response from the jid.
184     */
185    public boolean ping(String jid) throws NotConnectedException, NoResponseException {
186        return ping(jid, connection().getPacketReplyTimeout());
187    }
188
189    /**
190     * Query the specified entity to see if it supports the Ping protocol (XEP-0199)
191     * 
192     * @param jid The id of the entity the query is being sent to
193     * @return true if it supports ping, false otherwise.
194     * @throws XMPPErrorException An XMPP related error occurred during the request 
195     * @throws NoResponseException if there was no response from the jid.
196     * @throws NotConnectedException 
197     */
198    public boolean isPingSupported(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException  {
199        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, Ping.NAMESPACE);
200    }
201
202    /**
203     * Pings the server. This method will return true if the server is reachable.  It
204     * is the equivalent of calling <code>ping</code> with the XMPP domain.
205     * <p>
206     * Unlike the {@link #ping(String)} case, this method will return true even if 
207     * {@link #isPingSupported(String)} is false.
208     * 
209     * @return true if a reply was received from the server, false otherwise.
210     * @throws NotConnectedException
211     */
212    public boolean pingMyServer() throws NotConnectedException {
213        return pingMyServer(true);
214    }
215
216    /**
217     * Pings the server. This method will return true if the server is reachable.  It
218     * is the equivalent of calling <code>ping</code> with the XMPP domain.
219     * <p>
220     * Unlike the {@link #ping(String)} case, this method will return true even if
221     * {@link #isPingSupported(String)} is false.
222     *
223     * @param notifyListeners Notify the PingFailedListener in case of error if true
224     * @return true if the user's server could be pinged.
225     * @throws NotConnectedException
226     */
227    public boolean pingMyServer(boolean notifyListeners) throws NotConnectedException {
228        return pingMyServer(notifyListeners, connection().getPacketReplyTimeout());
229    }
230
231    /**
232     * Pings the server. This method will return true if the server is reachable.  It
233     * is the equivalent of calling <code>ping</code> with the XMPP domain.
234     * <p>
235     * Unlike the {@link #ping(String)} case, this method will return true even if
236     * {@link #isPingSupported(String)} is false.
237     *
238     * @param notifyListeners Notify the PingFailedListener in case of error if true
239     * @param pingTimeout The time to wait for a reply in milliseconds
240     * @return true if the user's server could be pinged.
241     * @throws NotConnectedException
242     */
243    public boolean pingMyServer(boolean notifyListeners, long pingTimeout) throws NotConnectedException {
244        boolean res;
245        try {
246            res = ping(connection().getServiceName(), pingTimeout);
247        }
248        catch (NoResponseException e) {
249            res = false;
250        }
251        if (!res && notifyListeners) {
252            for (PingFailedListener l : pingFailedListeners)
253                l.pingFailed();
254        }
255        return res;
256    }
257
258    /**
259     * Set the interval in seconds between a automated server ping is send. A negative value disables automatic server
260     * pings. All settings take effect immediately. If there is an active scheduled server ping it will be canceled and,
261     * if <code>pingInterval</code> is positive, a new one will be scheduled in pingInterval seconds.
262     * <p>
263     * If the ping fails after 3 attempts waiting the connections reply timeout for an answer, then the ping failed
264     * listeners will be invoked.
265     * </p>
266     *
267     * @param pingInterval the interval in seconds between the automated server pings
268     */
269    public void setPingInterval(int pingInterval) {
270        this.pingInterval = pingInterval;
271        maybeSchedulePingServerTask();
272    }
273
274    /**
275     * Get the current ping interval.
276     *
277     * @return the interval between pings in seconds
278     */
279    public int getPingInterval() {
280        return pingInterval;
281    }
282
283    /**
284     * Register a new PingFailedListener
285     *
286     * @param listener the listener to invoke
287     */
288    public void registerPingFailedListener(PingFailedListener listener) {
289        pingFailedListeners.add(listener);
290    }
291
292    /**
293     * Unregister a PingFailedListener
294     *
295     * @param listener the listener to remove
296     */
297    public void unregisterPingFailedListener(PingFailedListener listener) {
298        pingFailedListeners.remove(listener);
299    }
300
301    private void maybeSchedulePingServerTask() {
302        maybeSchedulePingServerTask(0);
303    }
304
305    /**
306     * Cancels any existing periodic ping task if there is one and schedules a new ping task if
307     * pingInterval is greater then zero.
308     *
309     * @param delta the delta to the last received stanza in seconds
310     */
311    private synchronized void maybeSchedulePingServerTask(int delta) {
312        maybeStopPingServerTask();
313        if (pingInterval > 0) {
314            int nextPingIn = pingInterval - delta;
315            LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval="
316                            + pingInterval + ", delta=" + delta + ")");
317            nextAutomaticPing = executorService.schedule(pingServerRunnable, nextPingIn, TimeUnit.SECONDS);
318        }
319    }
320
321    private void maybeStopPingServerTask() {
322        if (nextAutomaticPing != null) {
323            nextAutomaticPing.cancel(true);
324            nextAutomaticPing = null;
325        }
326    }
327
328    /**
329     * Ping the server if deemed necessary because automatic server pings are
330     * enabled ({@link #setPingInterval(int)}) and the ping interval has expired.
331     */
332    public synchronized void pingServerIfNecessary() {
333        final int DELTA = 1000; // 1 seconds
334        final int TRIES = 3; // 3 tries
335        final XMPPConnection connection = connection();
336        if (connection == null) {
337            // connection has been collected by GC
338            // which means we can stop the thread by breaking the loop
339            return;
340        }
341        if (pingInterval <= 0) {
342            // Ping has been disabled
343            return;
344        }
345        long lastStanzaReceived = connection.getLastStanzaReceived();
346        if (lastStanzaReceived > 0) {
347            long now = System.currentTimeMillis();
348            // Delta since the last stanza was received
349            int deltaInSeconds = (int)  ((now - lastStanzaReceived) / 1000);
350            // If the delta is small then the ping interval, then we can defer the ping
351            if (deltaInSeconds < pingInterval) {
352                maybeSchedulePingServerTask(deltaInSeconds);
353                return;
354            }
355        }
356        if (connection.isAuthenticated()) {
357            boolean res = false;
358
359            for (int i = 0; i < TRIES; i++) {
360                if (i != 0) {
361                    try {
362                        Thread.sleep(DELTA);
363                    } catch (InterruptedException e) {
364                        // We received an interrupt
365                        // This only happens if we should stop pinging
366                        return;
367                    }
368                }
369                try {
370                    res = pingMyServer(false);
371                }
372                catch (SmackException e) {
373                    LOGGER.log(Level.WARNING, "SmackError while pinging server", e);
374                    res = false;
375                }
376                // stop when we receive a pong back
377                if (res) {
378                    break;
379                }
380            }
381            if (!res) {
382                for (PingFailedListener l : pingFailedListeners) {
383                    l.pingFailed();
384                }
385            } else {
386                // Ping was successful, wind-up the periodic task again
387                maybeSchedulePingServerTask();
388            }
389        } else {
390            LOGGER.warning("XMPPConnection was not authenticated");
391        }
392    }
393
394    private final Runnable pingServerRunnable = new Runnable() {
395        public void run() {
396            LOGGER.fine("ServerPingTask run()");
397            pingServerIfNecessary();
398        }
399    };
400
401    @Override
402    protected void finalize() throws Throwable {
403        LOGGER.fine("finalizing PingManager: Shutting down executor service");
404        try {
405            executorService.shutdown();
406        } catch (Throwable t) {
407            LOGGER.log(Level.WARNING, "finalize() threw throwable", t);
408        }
409        finally {
410            super.finalize();
411        }
412    }
413}