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.XMPPError; 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 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<String, AdHocCommandInfo>(); 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<String, LocalCommand>(); 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<DiscoverItems.Item>(); 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 exceptino", 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 { 209 try { 210 return clazz.getConstructor().newInstance(); 211 } 212 catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException 213 | SecurityException e) { 214 // TODO: Throw those method in Smack 4.3. 215 throw new IllegalStateException(e); 216 } 217 } 218 }); 219 } 220 221 /** 222 * Registers a new command with this command manager, which is related to a 223 * connection. The <tt>node</tt> is an unique identifier of that 224 * command for the connection related to this command manager. The <tt>name</tt> 225 * is the human readeale name of the command. The <tt>factory</tt> generates 226 * new instances of the command. 227 * 228 * @param node the unique identifier of the command. 229 * @param name the human readable name of the command. 230 * @param factory a factory to create new instances of the command. 231 */ 232 public void registerCommand(String node, final String name, LocalCommandFactory factory) { 233 AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection().getUser(), factory); 234 235 commands.put(node, commandInfo); 236 // Set the NodeInformationProvider that will provide information about 237 // the added command 238 serviceDiscoveryManager.setNodeInformationProvider(node, 239 new AbstractNodeInformationProvider() { 240 @Override 241 public List<String> getNodeFeatures() { 242 List<String> answer = new ArrayList<String>(); 243 answer.add(NAMESPACE); 244 // TODO: check if this service is provided by the 245 // TODO: current connection. 246 answer.add("jabber:x:data"); 247 return answer; 248 } 249 @Override 250 public List<DiscoverInfo.Identity> getNodeIdentities() { 251 List<DiscoverInfo.Identity> answer = new ArrayList<DiscoverInfo.Identity>(); 252 DiscoverInfo.Identity identity = new DiscoverInfo.Identity( 253 "automation", name, "command-node"); 254 answer.add(identity); 255 return answer; 256 } 257 }); 258 } 259 260 /** 261 * Discover the commands of an specific JID. The <code>jid</code> is a 262 * full JID. 263 * 264 * @param jid the full JID to retrieve the commands for. 265 * @return the discovered items. 266 * @throws XMPPException if the operation failed for some reason. 267 * @throws SmackException if there was no response from the server. 268 * @throws InterruptedException 269 */ 270 public DiscoverItems discoverCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { 271 return serviceDiscoveryManager.discoverItems(jid, NAMESPACE); 272 } 273 274 /** 275 * Publish the commands to an specific JID. 276 * 277 * @param jid the full JID to publish the commands to. 278 * @throws XMPPException if the operation failed for some reason. 279 * @throws SmackException if there was no response from the server. 280 * @throws InterruptedException 281 * @deprecated This method uses no longer existent XEP-0030 features and will be removed. 282 */ 283 @SuppressWarnings("deprecation") 284 @Deprecated 285 // TODO: Remove in Smack 4.4. 286 public void publishCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { 287 // Collects the commands to publish as items 288 DiscoverItems discoverItems = new DiscoverItems(); 289 Collection<AdHocCommandInfo> xCommandsList = getRegisteredCommands(); 290 291 for (AdHocCommandInfo info : xCommandsList) { 292 DiscoverItems.Item item = new DiscoverItems.Item(info.getOwnerJID()); 293 item.setName(info.getName()); 294 item.setNode(info.getNode()); 295 discoverItems.addItem(item); 296 } 297 298 serviceDiscoveryManager.publishItems(jid, NAMESPACE, discoverItems); 299 } 300 301 /** 302 * Returns a command that represents an instance of a command in a remote 303 * host. It is used to execute remote commands. The concept is similar to 304 * RMI. Every invocation on this command is equivalent to an invocation in 305 * the remote command. 306 * 307 * @param jid the full JID of the host of the remote command 308 * @param node the identifier of the command 309 * @return a local instance equivalent to the remote command. 310 */ 311 public RemoteCommand getRemoteCommand(Jid jid, String node) { 312 return new RemoteCommand(connection(), node, jid); 313 } 314 315 /** 316 * Process the AdHoc-Command stanza(/packet) that request the execution of some 317 * action of a command. If this is the first request, this method checks, 318 * before executing the command, if: 319 * <ul> 320 * <li>The requested command exists</li> 321 * <li>The requester has permissions to execute it</li> 322 * <li>The command has more than one stage, if so, it saves the command and 323 * session ID for further use</li> 324 * </ul> 325 * 326 * <br> 327 * <br> 328 * If this is not the first request, this method checks, before executing 329 * the command, if: 330 * <ul> 331 * <li>The session ID of the request was stored</li> 332 * <li>The session life do not exceed the time out</li> 333 * <li>The action to execute is one of the available actions</li> 334 * </ul> 335 * 336 * @param requestData 337 * the stanza(/packet) to process. 338 * @throws NotConnectedException 339 * @throws NoResponseException 340 * @throws InterruptedException 341 */ 342 private IQ processAdHocCommand(AdHocCommandData requestData) throws NoResponseException, NotConnectedException, InterruptedException { 343 // Creates the response with the corresponding data 344 AdHocCommandData response = new AdHocCommandData(); 345 response.setTo(requestData.getFrom()); 346 response.setStanzaId(requestData.getStanzaId()); 347 response.setNode(requestData.getNode()); 348 response.setId(requestData.getTo()); 349 350 String sessionId = requestData.getSessionID(); 351 String commandNode = requestData.getNode(); 352 353 if (sessionId == null) { 354 // A new execution request has been received. Check that the 355 // command exists 356 if (!commands.containsKey(commandNode)) { 357 // Requested command does not exist so return 358 // item_not_found error. 359 return respondError(response, XMPPError.Condition.item_not_found); 360 } 361 362 // Create new session ID 363 sessionId = StringUtils.randomString(15); 364 365 try { 366 // Create a new instance of the command with the 367 // corresponding sessioid 368 LocalCommand command = newInstanceOfCmd(commandNode, sessionId); 369 370 response.setType(IQ.Type.result); 371 command.setData(response); 372 373 // Check that the requester has enough permission. 374 // Answer forbidden error if requester permissions are not 375 // enough to execute the requested command 376 if (!command.hasPermission(requestData.getFrom())) { 377 return respondError(response, XMPPError.Condition.forbidden); 378 } 379 380 Action action = requestData.getAction(); 381 382 // If the action is unknown then respond an error. 383 if (action != null && action.equals(Action.unknown)) { 384 return respondError(response, XMPPError.Condition.bad_request, 385 AdHocCommand.SpecificErrorCondition.malformedAction); 386 } 387 388 // If the action is not execute, then it is an invalid action. 389 if (action != null && !action.equals(Action.execute)) { 390 return respondError(response, XMPPError.Condition.bad_request, 391 AdHocCommand.SpecificErrorCondition.badAction); 392 } 393 394 // Increase the state number, so the command knows in witch 395 // stage it is 396 command.incrementStage(); 397 // Executes the command 398 command.execute(); 399 400 if (command.isLastStage()) { 401 // If there is only one stage then the command is completed 402 response.setStatus(Status.completed); 403 } 404 else { 405 // Else it is still executing, and is registered to be 406 // available for the next call 407 response.setStatus(Status.executing); 408 executingCommands.put(sessionId, command); 409 // See if the session reaping thread is started. If not, start it. 410 if (sessionsSweeper == null) { 411 sessionsSweeper = new Thread(new Runnable() { 412 @Override 413 public void run() { 414 while (true) { 415 for (String sessionId : executingCommands.keySet()) { 416 LocalCommand command = executingCommands.get(sessionId); 417 // Since the command could be removed in the meanwhile 418 // of getting the key and getting the value - by a 419 // processed packet. We must check if it still in the 420 // map. 421 if (command != null) { 422 long creationStamp = command.getCreationDate(); 423 // Check if the Session data has expired (default is 424 // 10 minutes) 425 // To remove it from the session list it waits for 426 // the double of the of time out time. This is to 427 // let 428 // the requester know why his execution request is 429 // not accepted. If the session is removed just 430 // after the time out, then whe the user request to 431 // continue the execution he will recieved an 432 // invalid session error and not a time out error. 433 if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000 * 2) { 434 // Remove the expired session 435 executingCommands.remove(sessionId); 436 } 437 } 438 } 439 try { 440 Thread.sleep(1000); 441 } 442 catch (InterruptedException ie) { 443 // Ignore. 444 } 445 } 446 } 447 448 }); 449 sessionsSweeper.setDaemon(true); 450 sessionsSweeper.start(); 451 } 452 } 453 454 // Sends the response packet 455 return response; 456 457 } 458 catch (XMPPErrorException e) { 459 // If there is an exception caused by the next, complete, 460 // prev or cancel method, then that error is returned to the 461 // requester. 462 XMPPError error = e.getXMPPError(); 463 464 // If the error type is cancel, then the execution is 465 // canceled therefore the status must show that, and the 466 // command be removed from the executing list. 467 if (XMPPError.Type.CANCEL.equals(error.getType())) { 468 response.setStatus(Status.canceled); 469 executingCommands.remove(sessionId); 470 } 471 return respondError(response, XMPPError.getBuilder(error)); 472 } 473 } 474 else { 475 LocalCommand command = executingCommands.get(sessionId); 476 477 // Check that a command exists for the specified sessionID 478 // This also handles if the command was removed in the meanwhile 479 // of getting the key and the value of the map. 480 if (command == null) { 481 return respondError(response, XMPPError.Condition.bad_request, 482 AdHocCommand.SpecificErrorCondition.badSessionid); 483 } 484 485 // Check if the Session data has expired (default is 10 minutes) 486 long creationStamp = command.getCreationDate(); 487 if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000) { 488 // Remove the expired session 489 executingCommands.remove(sessionId); 490 491 // Answer a not_allowed error (session-expired) 492 return respondError(response, XMPPError.Condition.not_allowed, 493 AdHocCommand.SpecificErrorCondition.sessionExpired); 494 } 495 496 /* 497 * Since the requester could send two requests for the same 498 * executing command i.e. the same session id, all the execution of 499 * the action must be synchronized to avoid inconsistencies. 500 */ 501 synchronized (command) { 502 Action action = requestData.getAction(); 503 504 // If the action is unknown the respond an error 505 if (action != null && action.equals(Action.unknown)) { 506 return respondError(response, XMPPError.Condition.bad_request, 507 AdHocCommand.SpecificErrorCondition.malformedAction); 508 } 509 510 // If the user didn't specify an action or specify the execute 511 // action then follow the actual default execute action 512 if (action == null || Action.execute.equals(action)) { 513 action = command.getExecuteAction(); 514 } 515 516 // Check that the specified action was previously 517 // offered 518 if (!command.isValidAction(action)) { 519 return respondError(response, XMPPError.Condition.bad_request, 520 AdHocCommand.SpecificErrorCondition.badAction); 521 } 522 523 try { 524 // TODO: Check that all the required fields of the form are 525 // TODO: filled, if not throw an exception. This will simplify the 526 // TODO: construction of new commands 527 528 // Since all errors were passed, the response is now a 529 // result 530 response.setType(IQ.Type.result); 531 532 // Set the new data to the command. 533 command.setData(response); 534 535 if (Action.next.equals(action)) { 536 command.incrementStage(); 537 command.next(new Form(requestData.getForm())); 538 if (command.isLastStage()) { 539 // If it is the last stage then the command is 540 // completed 541 response.setStatus(Status.completed); 542 } 543 else { 544 // Otherwise it is still executing 545 response.setStatus(Status.executing); 546 } 547 } 548 else if (Action.complete.equals(action)) { 549 command.incrementStage(); 550 command.complete(new Form(requestData.getForm())); 551 response.setStatus(Status.completed); 552 // Remove the completed session 553 executingCommands.remove(sessionId); 554 } 555 else if (Action.prev.equals(action)) { 556 command.decrementStage(); 557 command.prev(); 558 } 559 else if (Action.cancel.equals(action)) { 560 command.cancel(); 561 response.setStatus(Status.canceled); 562 // Remove the canceled session 563 executingCommands.remove(sessionId); 564 } 565 566 return response; 567 } 568 catch (XMPPErrorException e) { 569 // If there is an exception caused by the next, complete, 570 // prev or cancel method, then that error is returned to the 571 // requester. 572 XMPPError error = e.getXMPPError(); 573 574 // If the error type is cancel, then the execution is 575 // canceled therefore the status must show that, and the 576 // command be removed from the executing list. 577 if (XMPPError.Type.CANCEL.equals(error.getType())) { 578 response.setStatus(Status.canceled); 579 executingCommands.remove(sessionId); 580 } 581 return respondError(response, XMPPError.getBuilder(error)); 582 } 583 } 584 } 585 } 586 587 /** 588 * Responds an error with an specific condition. 589 * 590 * @param response the response to send. 591 * @param condition the condition of the error. 592 * @throws NotConnectedException 593 */ 594 private static IQ respondError(AdHocCommandData response, 595 XMPPError.Condition condition) { 596 return respondError(response, XMPPError.getBuilder(condition)); 597 } 598 599 /** 600 * Responds an error with an specific condition. 601 * 602 * @param response the response to send. 603 * @param condition the condition of the error. 604 * @param specificCondition the adhoc command error condition. 605 * @throws NotConnectedException 606 */ 607 private static IQ respondError(AdHocCommandData response, XMPPError.Condition condition, 608 AdHocCommand.SpecificErrorCondition specificCondition) 609 { 610 XMPPError.Builder error = XMPPError.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, XMPPError.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 */ 635 @SuppressWarnings("deprecation") 636 private LocalCommand newInstanceOfCmd(String commandNode, String sessionID) throws XMPPErrorException 637 { 638 AdHocCommandInfo commandInfo = commands.get(commandNode); 639 LocalCommand command; 640 try { 641 command = commandInfo.getCommandInstance(); 642 command.setSessionID(sessionID); 643 command.setName(commandInfo.getName()); 644 command.setNode(commandInfo.getNode()); 645 } 646 catch (InstantiationException e) { 647 throw new XMPPErrorException(XMPPError.getBuilder( 648 XMPPError.Condition.internal_server_error)); 649 } 650 catch (IllegalAccessException e) { 651 throw new XMPPErrorException(XMPPError.getBuilder( 652 XMPPError.Condition.internal_server_error)); 653 } 654 return command; 655 } 656 657 /** 658 * Returns the registered commands of this command manager, which is related 659 * to a connection. 660 * 661 * @return the registered commands. 662 */ 663 private Collection<AdHocCommandInfo> getRegisteredCommands() { 664 return commands.values(); 665 } 666 667 /** 668 * Stores ad-hoc command information. 669 */ 670 private static class AdHocCommandInfo { 671 672 private String node; 673 private String name; 674 private final Jid ownerJID; 675 private LocalCommandFactory factory; 676 677 public AdHocCommandInfo(String node, String name, Jid ownerJID, 678 LocalCommandFactory factory) 679 { 680 this.node = node; 681 this.name = name; 682 this.ownerJID = ownerJID; 683 this.factory = factory; 684 } 685 686 public LocalCommand getCommandInstance() throws InstantiationException, 687 IllegalAccessException 688 { 689 return factory.getInstance(); 690 } 691 692 public String getName() { 693 return name; 694 } 695 696 public String getNode() { 697 return node; 698 } 699 700 public Jid getOwnerJID() { 701 return ownerJID; 702 } 703 } 704}