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