001/** 002 * 003 * Copyright 2012-2017 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.Map; 020import java.util.Set; 021import java.util.WeakHashMap; 022import java.util.concurrent.CopyOnWriteArraySet; 023import java.util.concurrent.Executors; 024import java.util.concurrent.ScheduledExecutorService; 025import java.util.concurrent.ScheduledFuture; 026import java.util.concurrent.TimeUnit; 027import java.util.logging.Level; 028import java.util.logging.Logger; 029 030import org.jivesoftware.smack.AbstractConnectionClosedListener; 031import org.jivesoftware.smack.SmackException; 032import org.jivesoftware.smack.SmackException.NoResponseException; 033import org.jivesoftware.smack.SmackException.NotConnectedException; 034import org.jivesoftware.smack.XMPPConnection; 035import org.jivesoftware.smack.ConnectionCreationListener; 036import org.jivesoftware.smack.Manager; 037import org.jivesoftware.smack.XMPPConnectionRegistry; 038import org.jivesoftware.smack.XMPPException; 039import org.jivesoftware.smack.XMPPException.XMPPErrorException; 040import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler; 041import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode; 042import org.jivesoftware.smack.packet.IQ; 043import org.jivesoftware.smack.packet.IQ.Type; 044import org.jivesoftware.smack.util.SmackExecutorThreadFactory; 045import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; 046import org.jivesoftware.smackx.ping.packet.Ping; 047import org.jxmpp.jid.Jid; 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 final 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 @Override 070 public void connectionCreated(XMPPConnection connection) { 071 getInstanceFor(connection); 072 } 073 }); 074 } 075 076 /** 077 * Retrieves a {@link PingManager} for the specified {@link XMPPConnection}, creating one if it doesn't already 078 * exist. 079 * 080 * @param connection 081 * The connection the manager is attached to. 082 * @return The new or existing manager. 083 */ 084 public synchronized static PingManager getInstanceFor(XMPPConnection connection) { 085 PingManager pingManager = INSTANCES.get(connection); 086 if (pingManager == null) { 087 pingManager = new PingManager(connection); 088 INSTANCES.put(connection, pingManager); 089 } 090 return pingManager; 091 } 092 093 /** 094 * The default ping interval in seconds used by new PingManager instances. The default is 30 minutes. 095 */ 096 private static int defaultPingInterval = 60 * 30; 097 098 /** 099 * Set the default ping interval which will be used for new connections. 100 * 101 * @param interval the interval in seconds 102 */ 103 public static void setDefaultPingInterval(int interval) { 104 defaultPingInterval = interval; 105 } 106 107 private final Set<PingFailedListener> pingFailedListeners = new CopyOnWriteArraySet<>(); 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, "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(Jid)} 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 * @throws InterruptedException 159 */ 160 public boolean ping(Jid jid, long pingTimeout) throws NotConnectedException, NoResponseException, InterruptedException { 161 final XMPPConnection connection = connection(); 162 // Packet collector for IQs needs an connection that was at least authenticated once, 163 // otherwise the client JID will be null causing an NPE 164 if (!connection.isAuthenticated()) { 165 throw new NotConnectedException(); 166 } 167 Ping ping = new Ping(jid); 168 try { 169 connection.createStanzaCollectorAndSend(ping).nextResultOrThrow(pingTimeout); 170 } 171 catch (XMPPException exc) { 172 return jid.equals(connection.getXMPPServiceDomain()); 173 } 174 return true; 175 } 176 177 /** 178 * Same as calling {@link #ping(Jid, long)} with the defaultpacket reply 179 * timeout. 180 * 181 * @param jid The id of the entity the ping is being sent to 182 * @return true if a reply was received from the entity, false otherwise. 183 * @throws NotConnectedException 184 * @throws NoResponseException if there was no response from the jid. 185 * @throws InterruptedException 186 */ 187 public boolean ping(Jid jid) throws NotConnectedException, NoResponseException, InterruptedException { 188 return ping(jid, connection().getReplyTimeout()); 189 } 190 191 /** 192 * Query the specified entity to see if it supports the Ping protocol (XEP-0199). 193 * 194 * @param jid The id of the entity the query is being sent to 195 * @return true if it supports ping, false otherwise. 196 * @throws XMPPErrorException An XMPP related error occurred during the request 197 * @throws NoResponseException if there was no response from the jid. 198 * @throws NotConnectedException 199 * @throws InterruptedException 200 */ 201 public boolean isPingSupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 202 return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, Ping.NAMESPACE); 203 } 204 205 /** 206 * Pings the server. This method will return true if the server is reachable. It 207 * is the equivalent of calling <code>ping</code> with the XMPP domain. 208 * <p> 209 * Unlike the {@link #ping(Jid)} case, this method will return true even if 210 * {@link #isPingSupported(Jid)} is false. 211 * 212 * @return true if a reply was received from the server, false otherwise. 213 * @throws NotConnectedException 214 * @throws InterruptedException 215 */ 216 public boolean pingMyServer() throws NotConnectedException, InterruptedException { 217 return pingMyServer(true); 218 } 219 220 /** 221 * Pings the server. This method will return true if the server is reachable. It 222 * is the equivalent of calling <code>ping</code> with the XMPP domain. 223 * <p> 224 * Unlike the {@link #ping(Jid)} case, this method will return true even if 225 * {@link #isPingSupported(Jid)} is false. 226 * 227 * @param notifyListeners Notify the PingFailedListener in case of error if true 228 * @return true if the user's server could be pinged. 229 * @throws NotConnectedException 230 * @throws InterruptedException 231 */ 232 public boolean pingMyServer(boolean notifyListeners) throws NotConnectedException, InterruptedException { 233 return pingMyServer(notifyListeners, connection().getReplyTimeout()); 234 } 235 236 /** 237 * Pings the server. This method will return true if the server is reachable. It 238 * is the equivalent of calling <code>ping</code> with the XMPP domain. 239 * <p> 240 * Unlike the {@link #ping(Jid)} case, this method will return true even if 241 * {@link #isPingSupported(Jid)} is false. 242 * 243 * @param notifyListeners Notify the PingFailedListener in case of error if true 244 * @param pingTimeout The time to wait for a reply in milliseconds 245 * @return true if the user's server could be pinged. 246 * @throws NotConnectedException 247 * @throws InterruptedException 248 */ 249 public boolean pingMyServer(boolean notifyListeners, long pingTimeout) throws NotConnectedException, InterruptedException { 250 boolean res; 251 try { 252 res = ping(connection().getXMPPServiceDomain(), pingTimeout); 253 } 254 catch (NoResponseException e) { 255 res = false; 256 } 257 if (!res && notifyListeners) { 258 for (PingFailedListener l : pingFailedListeners) 259 l.pingFailed(); 260 } 261 return res; 262 } 263 264 /** 265 * Set the interval in seconds between a automated server ping is send. A negative value disables automatic server 266 * pings. All settings take effect immediately. If there is an active scheduled server ping it will be canceled and, 267 * if <code>pingInterval</code> is positive, a new one will be scheduled in pingInterval seconds. 268 * <p> 269 * If the ping fails after 3 attempts waiting the connections reply timeout for an answer, then the ping failed 270 * listeners will be invoked. 271 * </p> 272 * 273 * @param pingInterval the interval in seconds between the automated server pings 274 */ 275 public void setPingInterval(int pingInterval) { 276 this.pingInterval = pingInterval; 277 maybeSchedulePingServerTask(); 278 } 279 280 /** 281 * Get the current ping interval. 282 * 283 * @return the interval between pings in seconds 284 */ 285 public int getPingInterval() { 286 return pingInterval; 287 } 288 289 /** 290 * Register a new PingFailedListener. 291 * 292 * @param listener the listener to invoke 293 */ 294 public void registerPingFailedListener(PingFailedListener listener) { 295 pingFailedListeners.add(listener); 296 } 297 298 /** 299 * Unregister a PingFailedListener. 300 * 301 * @param listener the listener to remove 302 */ 303 public void unregisterPingFailedListener(PingFailedListener listener) { 304 pingFailedListeners.remove(listener); 305 } 306 307 private void maybeSchedulePingServerTask() { 308 maybeSchedulePingServerTask(0); 309 } 310 311 /** 312 * Cancels any existing periodic ping task if there is one and schedules a new ping task if 313 * pingInterval is greater then zero. 314 * 315 * @param delta the delta to the last received stanza in seconds 316 */ 317 private synchronized void maybeSchedulePingServerTask(int delta) { 318 maybeStopPingServerTask(); 319 if (pingInterval > 0) { 320 int nextPingIn = pingInterval - delta; 321 LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval=" 322 + pingInterval + ", delta=" + delta + ")"); 323 nextAutomaticPing = executorService.schedule(pingServerRunnable, nextPingIn, TimeUnit.SECONDS); 324 } 325 } 326 327 private void maybeStopPingServerTask() { 328 if (nextAutomaticPing != null) { 329 nextAutomaticPing.cancel(true); 330 nextAutomaticPing = null; 331 } 332 } 333 334 /** 335 * Ping the server if deemed necessary because automatic server pings are 336 * enabled ({@link #setPingInterval(int)}) and the ping interval has expired. 337 */ 338 public synchronized void pingServerIfNecessary() { 339 final int DELTA = 1000; // 1 seconds 340 final int TRIES = 3; // 3 tries 341 final XMPPConnection connection = connection(); 342 if (connection == null) { 343 // connection has been collected by GC 344 // which means we can stop the thread by breaking the loop 345 return; 346 } 347 if (pingInterval <= 0) { 348 // Ping has been disabled 349 return; 350 } 351 long lastStanzaReceived = connection.getLastStanzaReceived(); 352 if (lastStanzaReceived > 0) { 353 long now = System.currentTimeMillis(); 354 // Delta since the last stanza was received 355 int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000); 356 // If the delta is small then the ping interval, then we can defer the ping 357 if (deltaInSeconds < pingInterval) { 358 maybeSchedulePingServerTask(deltaInSeconds); 359 return; 360 } 361 } 362 if (connection.isAuthenticated()) { 363 boolean res = false; 364 365 for (int i = 0; i < TRIES; i++) { 366 if (i != 0) { 367 try { 368 Thread.sleep(DELTA); 369 } catch (InterruptedException e) { 370 // We received an interrupt 371 // This only happens if we should stop pinging 372 return; 373 } 374 } 375 try { 376 res = pingMyServer(false); 377 } 378 catch (InterruptedException | SmackException e) { 379 // Note that we log the connection here, so that it is not GC'ed between the call to isAuthenticated 380 // a few lines above and the usage of the connection within pingMyServer(). In order to prevent: 381 // https://community.igniterealtime.org/thread/59369 382 LOGGER.log(Level.WARNING, "Exception while pinging server of " + connection, e); 383 res = false; 384 } 385 // stop when we receive a pong back 386 if (res) { 387 break; 388 } 389 } 390 if (!res) { 391 for (PingFailedListener l : pingFailedListeners) { 392 l.pingFailed(); 393 } 394 } else { 395 // Ping was successful, wind-up the periodic task again 396 maybeSchedulePingServerTask(); 397 } 398 } else { 399 LOGGER.warning("XMPPConnection was not authenticated"); 400 } 401 } 402 403 private final Runnable pingServerRunnable = new Runnable() { 404 @Override 405 public void run() { 406 LOGGER.fine("ServerPingTask run()"); 407 pingServerIfNecessary(); 408 } 409 }; 410 411 @Override 412 protected void finalize() throws Throwable { 413 LOGGER.fine("finalizing PingManager: Shutting down executor service"); 414 try { 415 executorService.shutdown(); 416 } catch (Throwable t) { 417 LOGGER.log(Level.WARNING, "finalize() threw throwable", t); 418 } 419 finally { 420 super.finalize(); 421 } 422 } 423}