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