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