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