001/** 002 * 003 * Copyright 2005-2008 Jive Software. 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 */ 017 018package org.jivesoftware.smackx.commands; 019 020import java.lang.reflect.InvocationTargetException; 021import java.util.ArrayList; 022import java.util.Collection; 023import java.util.List; 024import java.util.Map; 025import java.util.WeakHashMap; 026import java.util.concurrent.ConcurrentHashMap; 027import java.util.logging.Level; 028import java.util.logging.Logger; 029 030import org.jivesoftware.smack.ConnectionCreationListener; 031import org.jivesoftware.smack.Manager; 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.XMPPConnectionRegistry; 037import org.jivesoftware.smack.XMPPException; 038import org.jivesoftware.smack.XMPPException.XMPPErrorException; 039import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler; 040import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode; 041import org.jivesoftware.smack.packet.IQ; 042import org.jivesoftware.smack.packet.StanzaError; 043import org.jivesoftware.smack.util.StringUtils; 044 045import org.jivesoftware.smackx.commands.AdHocCommand.Action; 046import org.jivesoftware.smackx.commands.AdHocCommand.Status; 047import org.jivesoftware.smackx.commands.packet.AdHocCommandData; 048import org.jivesoftware.smackx.disco.AbstractNodeInformationProvider; 049import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; 050import org.jivesoftware.smackx.disco.packet.DiscoverInfo; 051import org.jivesoftware.smackx.disco.packet.DiscoverItems; 052import org.jivesoftware.smackx.xdata.Form; 053 054import org.jxmpp.jid.Jid; 055 056/** 057 * An AdHocCommandManager is responsible for keeping the list of available 058 * commands offered by a service and for processing commands requests. 059 * 060 * Pass in an XMPPConnection instance to 061 * {@link #getAddHocCommandsManager(XMPPConnection)} in order to 062 * get an instance of this class. 063 * 064 * @author Gabriel Guardincerri 065 */ 066public final class AdHocCommandManager extends Manager { 067 public static final String NAMESPACE = "http://jabber.org/protocol/commands"; 068 069 private static final Logger LOGGER = Logger.getLogger(AdHocCommandManager.class.getName()); 070 071 /** 072 * The session time out in seconds. 073 */ 074 private static final int SESSION_TIMEOUT = 2 * 60; 075 076 /** 077 * Map an XMPPConnection with it AdHocCommandManager. This map have a key-value 078 * pair for every active connection. 079 */ 080 private static final Map<XMPPConnection, AdHocCommandManager> instances = new WeakHashMap<>(); 081 082 /** 083 * Register the listener for all the connection creations. When a new 084 * connection is created a new AdHocCommandManager is also created and 085 * related to that connection. 086 */ 087 static { 088 XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { 089 @Override 090 public void connectionCreated(XMPPConnection connection) { 091 getAddHocCommandsManager(connection); 092 } 093 }); 094 } 095 096 /** 097 * Returns the <code>AdHocCommandManager</code> related to the 098 * <code>connection</code>. 099 * 100 * @param connection the XMPP connection. 101 * @return the AdHocCommandManager associated with the connection. 102 */ 103 public static synchronized AdHocCommandManager getAddHocCommandsManager(XMPPConnection connection) { 104 AdHocCommandManager ahcm = instances.get(connection); 105 if (ahcm == null) { 106 ahcm = new AdHocCommandManager(connection); 107 instances.put(connection, ahcm); 108 } 109 return ahcm; 110 } 111 112 /** 113 * Map a command node with its AdHocCommandInfo. Note: Key=command node, 114 * Value=command. Command node matches the node attribute sent by command 115 * requesters. 116 */ 117 private final Map<String, AdHocCommandInfo> commands = new ConcurrentHashMap<>(); 118 119 /** 120 * Map a command session ID with the instance LocalCommand. The LocalCommand 121 * is the an objects that has all the information of the current state of 122 * the command execution. Note: Key=session ID, Value=LocalCommand. Session 123 * ID matches the sessionid attribute sent by command responders. 124 */ 125 private final Map<String, LocalCommand> executingCommands = new ConcurrentHashMap<>(); 126 127 private final ServiceDiscoveryManager serviceDiscoveryManager; 128 129 /** 130 * Thread that reaps stale sessions. 131 */ 132 // FIXME The session sweeping is horrible implemented. The thread will never stop running. A different approach must 133 // be implemented. For example one that does stop reaping sessions and the thread if there are no more, and restarts 134 // the reaping process on demand. Or for every command a scheduled task should be created that removes the session 135 // if it's timed out. See SMACK-624. 136 private Thread sessionsSweeper; 137 138 private AdHocCommandManager(XMPPConnection connection) { 139 super(connection); 140 this.serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); 141 142 // Add the feature to the service discovery manage to show that this 143 // connection supports the AdHoc-Commands protocol. 144 // This information will be used when another client tries to 145 // discover whether this client supports AdHoc-Commands or not. 146 ServiceDiscoveryManager.getInstanceFor(connection).addFeature( 147 NAMESPACE); 148 149 // Set the NodeInformationProvider that will provide information about 150 // which AdHoc-Commands are registered, whenever a disco request is 151 // received 152 ServiceDiscoveryManager.getInstanceFor(connection) 153 .setNodeInformationProvider(NAMESPACE, 154 new AbstractNodeInformationProvider() { 155 @Override 156 public List<DiscoverItems.Item> getNodeItems() { 157 158 List<DiscoverItems.Item> answer = new ArrayList<>(); 159 Collection<AdHocCommandInfo> commandsList = getRegisteredCommands(); 160 161 for (AdHocCommandInfo info : commandsList) { 162 DiscoverItems.Item item = new DiscoverItems.Item( 163 info.getOwnerJID()); 164 item.setName(info.getName()); 165 item.setNode(info.getNode()); 166 answer.add(item); 167 } 168 169 return answer; 170 } 171 }); 172 173 // The packet listener and the filter for processing some AdHoc Commands 174 // Packets 175 connection.registerIQRequestHandler(new AbstractIqRequestHandler(AdHocCommandData.ELEMENT, 176 AdHocCommandData.NAMESPACE, IQ.Type.set, Mode.async) { 177 @Override 178 public IQ handleIQRequest(IQ iqRequest) { 179 AdHocCommandData requestData = (AdHocCommandData) iqRequest; 180 try { 181 return processAdHocCommand(requestData); 182 } 183 catch (InterruptedException | NoResponseException | NotConnectedException e) { 184 LOGGER.log(Level.INFO, "processAdHocCommand threw exception", e); 185 return null; 186 } 187 } 188 }); 189 190 sessionsSweeper = null; 191 } 192 193 /** 194 * Registers a new command with this command manager, which is related to a 195 * connection. The <tt>node</tt> is an unique identifier of that command for 196 * the connection related to this command manager. The <tt>name</tt> is the 197 * human readable name of the command. The <tt>class</tt> is the class of 198 * the command, which must extend {@link LocalCommand} and have a default 199 * constructor. 200 * 201 * @param node the unique identifier of the command. 202 * @param name the human readable name of the command. 203 * @param clazz the class of the command, which must extend {@link LocalCommand}. 204 */ 205 public void registerCommand(String node, String name, final Class<? extends LocalCommand> clazz) { 206 registerCommand(node, name, new LocalCommandFactory() { 207 @Override 208 public LocalCommand getInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { 209 return clazz.getConstructor().newInstance(); 210 } 211 }); 212 } 213 214 /** 215 * Registers a new command with this command manager, which is related to a 216 * connection. The <tt>node</tt> is an unique identifier of that 217 * command for the connection related to this command manager. The <tt>name</tt> 218 * is the human readable name of the command. The <tt>factory</tt> generates 219 * new instances of the command. 220 * 221 * @param node the unique identifier of the command. 222 * @param name the human readable name of the command. 223 * @param factory a factory to create new instances of the command. 224 */ 225 public void registerCommand(String node, final String name, LocalCommandFactory factory) { 226 AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection().getUser(), factory); 227 228 commands.put(node, commandInfo); 229 // Set the NodeInformationProvider that will provide information about 230 // the added command 231 serviceDiscoveryManager.setNodeInformationProvider(node, 232 new AbstractNodeInformationProvider() { 233 @Override 234 public List<String> getNodeFeatures() { 235 List<String> answer = new ArrayList<>(); 236 answer.add(NAMESPACE); 237 // TODO: check if this service is provided by the 238 // TODO: current connection. 239 answer.add("jabber:x:data"); 240 return answer; 241 } 242 @Override 243 public List<DiscoverInfo.Identity> getNodeIdentities() { 244 List<DiscoverInfo.Identity> answer = new ArrayList<>(); 245 DiscoverInfo.Identity identity = new DiscoverInfo.Identity( 246 "automation", name, "command-node"); 247 answer.add(identity); 248 return answer; 249 } 250 }); 251 } 252 253 /** 254 * Discover the commands of an specific JID. The <code>jid</code> is a 255 * full JID. 256 * 257 * @param jid the full JID to retrieve the commands for. 258 * @return the discovered items. 259 * @throws XMPPException if the operation failed for some reason. 260 * @throws SmackException if there was no response from the server. 261 * @throws InterruptedException 262 */ 263 public DiscoverItems discoverCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { 264 return serviceDiscoveryManager.discoverItems(jid, NAMESPACE); 265 } 266 267 /** 268 * Publish the commands to an specific JID. 269 * 270 * @param jid the full JID to publish the commands to. 271 * @throws XMPPException if the operation failed for some reason. 272 * @throws SmackException if there was no response from the server. 273 * @throws InterruptedException 274 * @deprecated This method uses no longer existent XEP-0030 features and will be removed. 275 */ 276 @SuppressWarnings("deprecation") 277 @Deprecated 278 // TODO: Remove in Smack 4.4. 279 public void publishCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { 280 // Collects the commands to publish as items 281 DiscoverItems discoverItems = new DiscoverItems(); 282 Collection<AdHocCommandInfo> xCommandsList = getRegisteredCommands(); 283 284 for (AdHocCommandInfo info : xCommandsList) { 285 DiscoverItems.Item item = new DiscoverItems.Item(info.getOwnerJID()); 286 item.setName(info.getName()); 287 item.setNode(info.getNode()); 288 discoverItems.addItem(item); 289 } 290 291 serviceDiscoveryManager.publishItems(jid, NAMESPACE, discoverItems); 292 } 293 294 /** 295 * Returns a command that represents an instance of a command in a remote 296 * host. It is used to execute remote commands. The concept is similar to 297 * RMI. Every invocation on this command is equivalent to an invocation in 298 * the remote command. 299 * 300 * @param jid the full JID of the host of the remote command 301 * @param node the identifier of the command 302 * @return a local instance equivalent to the remote command. 303 */ 304 public RemoteCommand getRemoteCommand(Jid jid, String node) { 305 return new RemoteCommand(connection(), node, jid); 306 } 307 308 /** 309 * Process the AdHoc-Command stanza that request the execution of some 310 * action of a command. If this is the first request, this method checks, 311 * before executing the command, if: 312 * <ul> 313 * <li>The requested command exists</li> 314 * <li>The requester has permissions to execute it</li> 315 * <li>The command has more than one stage, if so, it saves the command and 316 * session ID for further use</li> 317 * </ul> 318 * 319 * <br> 320 * <br> 321 * If this is not the first request, this method checks, before executing 322 * the command, if: 323 * <ul> 324 * <li>The session ID of the request was stored</li> 325 * <li>The session life do not exceed the time out</li> 326 * <li>The action to execute is one of the available actions</li> 327 * </ul> 328 * 329 * @param requestData 330 * the stanza to process. 331 * @throws NotConnectedException 332 * @throws NoResponseException 333 * @throws InterruptedException 334 */ 335 private IQ processAdHocCommand(AdHocCommandData requestData) throws NoResponseException, NotConnectedException, InterruptedException { 336 // Creates the response with the corresponding data 337 AdHocCommandData response = new AdHocCommandData(); 338 response.setTo(requestData.getFrom()); 339 response.setStanzaId(requestData.getStanzaId()); 340 response.setNode(requestData.getNode()); 341 response.setId(requestData.getTo()); 342 343 String sessionId = requestData.getSessionID(); 344 String commandNode = requestData.getNode(); 345 346 if (sessionId == null) { 347 // A new execution request has been received. Check that the 348 // command exists 349 if (!commands.containsKey(commandNode)) { 350 // Requested command does not exist so return 351 // item_not_found error. 352 return respondError(response, StanzaError.Condition.item_not_found); 353 } 354 355 // Create new session ID 356 sessionId = StringUtils.randomString(15); 357 358 try { 359 // Create a new instance of the command with the 360 // corresponding sessionid 361 LocalCommand command; 362 try { 363 command = newInstanceOfCmd(commandNode, sessionId); 364 } 365 catch (InstantiationException | IllegalAccessException | IllegalArgumentException 366 | InvocationTargetException | NoSuchMethodException | SecurityException e) { 367 StanzaError.Builder xmppError = StanzaError.getBuilder().setCondition(StanzaError.Condition.internal_server_error).setDescriptiveEnText(e.getMessage()); 368 return respondError(response, xmppError); 369 } 370 371 response.setType(IQ.Type.result); 372 command.setData(response); 373 374 // Check that the requester has enough permission. 375 // Answer forbidden error if requester permissions are not 376 // enough to execute the requested command 377 if (!command.hasPermission(requestData.getFrom())) { 378 return respondError(response, StanzaError.Condition.forbidden); 379 } 380 381 Action action = requestData.getAction(); 382 383 // If the action is unknown then respond an error. 384 if (action != null && action.equals(Action.unknown)) { 385 return respondError(response, StanzaError.Condition.bad_request, 386 AdHocCommand.SpecificErrorCondition.malformedAction); 387 } 388 389 // If the action is not execute, then it is an invalid action. 390 if (action != null && !action.equals(Action.execute)) { 391 return respondError(response, StanzaError.Condition.bad_request, 392 AdHocCommand.SpecificErrorCondition.badAction); 393 } 394 395 // Increase the state number, so the command knows in witch 396 // stage it is 397 command.incrementStage(); 398 // Executes the command 399 command.execute(); 400 401 if (command.isLastStage()) { 402 // If there is only one stage then the command is completed 403 response.setStatus(Status.completed); 404 } 405 else { 406 // Else it is still executing, and is registered to be 407 // available for the next call 408 response.setStatus(Status.executing); 409 executingCommands.put(sessionId, command); 410 // See if the session reaping thread is started. If not, start it. 411 if (sessionsSweeper == null) { 412 sessionsSweeper = new Thread(new Runnable() { 413 @Override 414 public void run() { 415 while (true) { 416 for (String sessionId : executingCommands.keySet()) { 417 LocalCommand command = executingCommands.get(sessionId); 418 // Since the command could be removed in the meanwhile 419 // of getting the key and getting the value - by a 420 // processed packet. We must check if it still in the 421 // map. 422 if (command != null) { 423 long creationStamp = command.getCreationDate(); 424 // Check if the Session data has expired (default is 425 // 10 minutes) 426 // To remove it from the session list it waits for 427 // the double of the of time out time. This is to 428 // let 429 // the requester know why his execution request is 430 // not accepted. If the session is removed just 431 // after the time out, then whe the user request to 432 // continue the execution he will received an 433 // invalid session error and not a time out error. 434 if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000 * 2) { 435 // Remove the expired session 436 executingCommands.remove(sessionId); 437 } 438 } 439 } 440 try { 441 Thread.sleep(1000); 442 } 443 catch (InterruptedException ie) { 444 // Ignore. 445 } 446 } 447 } 448 449 }); 450 sessionsSweeper.setDaemon(true); 451 sessionsSweeper.start(); 452 } 453 } 454 455 // Sends the response packet 456 return response; 457 458 } 459 catch (XMPPErrorException e) { 460 // If there is an exception caused by the next, complete, 461 // prev or cancel method, then that error is returned to the 462 // requester. 463 StanzaError error = e.getStanzaError(); 464 465 // If the error type is cancel, then the execution is 466 // canceled therefore the status must show that, and the 467 // command be removed from the executing list. 468 if (StanzaError.Type.CANCEL.equals(error.getType())) { 469 response.setStatus(Status.canceled); 470 executingCommands.remove(sessionId); 471 } 472 return respondError(response, StanzaError.getBuilder(error)); 473 } 474 } 475 else { 476 LocalCommand command = executingCommands.get(sessionId); 477 478 // Check that a command exists for the specified sessionID 479 // This also handles if the command was removed in the meanwhile 480 // of getting the key and the value of the map. 481 if (command == null) { 482 return respondError(response, StanzaError.Condition.bad_request, 483 AdHocCommand.SpecificErrorCondition.badSessionid); 484 } 485 486 // Check if the Session data has expired (default is 10 minutes) 487 long creationStamp = command.getCreationDate(); 488 if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000) { 489 // Remove the expired session 490 executingCommands.remove(sessionId); 491 492 // Answer a not_allowed error (session-expired) 493 return respondError(response, StanzaError.Condition.not_allowed, 494 AdHocCommand.SpecificErrorCondition.sessionExpired); 495 } 496 497 /* 498 * Since the requester could send two requests for the same 499 * executing command i.e. the same session id, all the execution of 500 * the action must be synchronized to avoid inconsistencies. 501 */ 502 synchronized (command) { 503 Action action = requestData.getAction(); 504 505 // If the action is unknown the respond an error 506 if (action != null && action.equals(Action.unknown)) { 507 return respondError(response, StanzaError.Condition.bad_request, 508 AdHocCommand.SpecificErrorCondition.malformedAction); 509 } 510 511 // If the user didn't specify an action or specify the execute 512 // action then follow the actual default execute action 513 if (action == null || Action.execute.equals(action)) { 514 action = command.getExecuteAction(); 515 } 516 517 // Check that the specified action was previously 518 // offered 519 if (!command.isValidAction(action)) { 520 return respondError(response, StanzaError.Condition.bad_request, 521 AdHocCommand.SpecificErrorCondition.badAction); 522 } 523 524 try { 525 // TODO: Check that all the required fields of the form are 526 // TODO: filled, if not throw an exception. This will simplify the 527 // TODO: construction of new commands 528 529 // Since all errors were passed, the response is now a 530 // result 531 response.setType(IQ.Type.result); 532 533 // Set the new data to the command. 534 command.setData(response); 535 536 if (Action.next.equals(action)) { 537 command.incrementStage(); 538 command.next(new Form(requestData.getForm())); 539 if (command.isLastStage()) { 540 // If it is the last stage then the command is 541 // completed 542 response.setStatus(Status.completed); 543 } 544 else { 545 // Otherwise it is still executing 546 response.setStatus(Status.executing); 547 } 548 } 549 else if (Action.complete.equals(action)) { 550 command.incrementStage(); 551 command.complete(new Form(requestData.getForm())); 552 response.setStatus(Status.completed); 553 // Remove the completed session 554 executingCommands.remove(sessionId); 555 } 556 else if (Action.prev.equals(action)) { 557 command.decrementStage(); 558 command.prev(); 559 } 560 else if (Action.cancel.equals(action)) { 561 command.cancel(); 562 response.setStatus(Status.canceled); 563 // Remove the canceled session 564 executingCommands.remove(sessionId); 565 } 566 567 return response; 568 } 569 catch (XMPPErrorException e) { 570 // If there is an exception caused by the next, complete, 571 // prev or cancel method, then that error is returned to the 572 // requester. 573 StanzaError error = e.getStanzaError(); 574 575 // If the error type is cancel, then the execution is 576 // canceled therefore the status must show that, and the 577 // command be removed from the executing list. 578 if (StanzaError.Type.CANCEL.equals(error.getType())) { 579 response.setStatus(Status.canceled); 580 executingCommands.remove(sessionId); 581 } 582 return respondError(response, StanzaError.getBuilder(error)); 583 } 584 } 585 } 586 } 587 588 /** 589 * Responds an error with an specific condition. 590 * 591 * @param response the response to send. 592 * @param condition the condition of the error. 593 * @throws NotConnectedException 594 */ 595 private static IQ respondError(AdHocCommandData response, 596 StanzaError.Condition condition) { 597 return respondError(response, StanzaError.getBuilder(condition)); 598 } 599 600 /** 601 * Responds an error with an specific condition. 602 * 603 * @param response the response to send. 604 * @param condition the condition of the error. 605 * @param specificCondition the adhoc command error condition. 606 * @throws NotConnectedException 607 */ 608 private static IQ respondError(AdHocCommandData response, StanzaError.Condition condition, 609 AdHocCommand.SpecificErrorCondition specificCondition) { 610 StanzaError.Builder error = StanzaError.getBuilder(condition).addExtension(new AdHocCommandData.SpecificError(specificCondition)); 611 return respondError(response, error); 612 } 613 614 /** 615 * Responds an error with an specific error. 616 * 617 * @param response the response to send. 618 * @param error the error to send. 619 * @throws NotConnectedException 620 */ 621 private static IQ respondError(AdHocCommandData response, StanzaError.Builder error) { 622 response.setType(IQ.Type.error); 623 response.setError(error); 624 return response; 625 } 626 627 /** 628 * Creates a new instance of a command to be used by a new execution request 629 * 630 * @param commandNode the command node that identifies it. 631 * @param sessionID the session id of this execution. 632 * @return the command instance to execute. 633 * @throws XMPPErrorException if there is problem creating the new instance. 634 * @throws SecurityException 635 * @throws NoSuchMethodException 636 * @throws InvocationTargetException 637 * @throws IllegalArgumentException 638 * @throws IllegalAccessException 639 * @throws InstantiationException 640 */ 641 private LocalCommand newInstanceOfCmd(String commandNode, String sessionID) 642 throws XMPPErrorException, InstantiationException, IllegalAccessException, IllegalArgumentException, 643 InvocationTargetException, NoSuchMethodException, SecurityException { 644 AdHocCommandInfo commandInfo = commands.get(commandNode); 645 LocalCommand command = commandInfo.getCommandInstance(); 646 command.setSessionID(sessionID); 647 command.setName(commandInfo.getName()); 648 command.setNode(commandInfo.getNode()); 649 650 return command; 651 } 652 653 /** 654 * Returns the registered commands of this command manager, which is related 655 * to a connection. 656 * 657 * @return the registered commands. 658 */ 659 private Collection<AdHocCommandInfo> getRegisteredCommands() { 660 return commands.values(); 661 } 662 663 /** 664 * Stores ad-hoc command information. 665 */ 666 private static final class AdHocCommandInfo { 667 668 private String node; 669 private String name; 670 private final Jid ownerJID; 671 private LocalCommandFactory factory; 672 673 private AdHocCommandInfo(String node, String name, Jid ownerJID, 674 LocalCommandFactory factory) { 675 this.node = node; 676 this.name = name; 677 this.ownerJID = ownerJID; 678 this.factory = factory; 679 } 680 681 public LocalCommand getCommandInstance() throws InstantiationException, 682 IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { 683 return factory.getInstance(); 684 } 685 686 public String getName() { 687 return name; 688 } 689 690 public String getNode() { 691 return node; 692 } 693 694 public Jid getOwnerJID() { 695 return ownerJID; 696 } 697 } 698}