aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/ssh/ProtocolProviderServiceSSHImpl.java
blob: a4b16e6b5224a65624484a0116ade5d0048a8aab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.impl.protocol.ssh;

import java.io.*;

import javax.swing.*;

import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.Logger;

import org.osgi.framework.*;

import com.jcraft.jsch.*;

/**
 * A SSH implementation of the ProtocolProviderService.
 *
 * @author Shobhit Jindal
 */
public class ProtocolProviderServiceSSHImpl
        extends AbstractProtocolProviderService
{
    private static final Logger logger
            = Logger.getLogger(ProtocolProviderServiceSSHImpl.class);

    /**
     * The name of this protocol.
     */
    public static final String SSH_PROTOCOL_NAME = ProtocolNames.SSH;

//    /**
//     * The identifier for SSH Stack
//     * Java Secure Channel JSch
//     */
//    JSch jsch = new JSch();

    /**
     * The test command given after each command to determine the reply length
     * of the command
     */
    //private final String testCommand =
    //    Resources.getString("testCommand");

    /**
     * A reference to the protocol provider of UIService
     */
    private static ServiceReference ppUIServiceRef;

    /**
     * Connection timeout to a remote server in milliseconds
     */
    private static int connectionTimeout = 30000;

    /**
     * A reference to UI Service
     */
    private static UIService uiService;

    /**
     * The id of the account that this protocol provider represents.
     */
    private AccountID accountID = null;

    /**
     * We use this to lock access to initialization.
     */
    private final Object initializationLock = new Object();

    private OperationSetBasicInstantMessagingSSHImpl basicInstantMessaging;

    private OperationSetFileTransferSSHImpl fileTranfer;

    /**
     * Indicates whether or not the provider is initialized and ready for use.
     */
    private boolean isInitialized = false;

    /**
     * The logo corresponding to the ssh protocol.
     */
    private ProtocolIconSSHImpl sshIcon
            = new ProtocolIconSSHImpl();

    /**
     * The registration state of SSH Provider is taken to be registered by
     * default as it doesn't correspond to the state on remote server
     */
    private RegistrationState currentRegistrationState
            = RegistrationState.REGISTERED;

    /**
     * The default constructor for the SSH protocol provider.
     */
    public ProtocolProviderServiceSSHImpl()
    {
        if (logger.isTraceEnabled())
            logger.trace("Creating a ssh provider.");

        try
        {
            // converting to milliseconds
            connectionTimeout = Integer.parseInt(Resources.getString(
                                    "connectionTimeout")) * 1000;
        }
        catch(NumberFormatException ex)
        {
            logger.error("Connection Timeout set to 30 seconds");
        }
    }

    /**
     * Initializes the service implementation, and puts it in a sate where it
     * could interoperate with other services. It is strongly recomended that
     * properties in this Map be mapped to property names as specified by
     * <tt>AccountProperties</tt>.
     *
     * @param userID the user id of the ssh account we're currently
     * initializing
     * @param accountID the identifier of the account that this protocol
     * provider represents.
     *
     * @see net.java.sip.communicator.service.protocol.AccountID
     */
    protected void initialize(
            String userID,
            AccountID accountID)
    {
        synchronized(initializationLock)
        {
            this.accountID = accountID;

            //initialize the presence operationset
            OperationSetPersistentPresenceSSHImpl persistentPresence =
                    new OperationSetPersistentPresenceSSHImpl(this);

            addSupportedOperationSet(
                OperationSetPersistentPresence.class,
                persistentPresence);
            //register it once again for those that simply need presence and
            //won't be smart enough to check for a persistent presence
            //alternative
            addSupportedOperationSet(
                OperationSetPresence.class,
                persistentPresence);

            //initialize the IM operation set
            basicInstantMessaging = new
                OperationSetBasicInstantMessagingSSHImpl(
                    this);
            addSupportedOperationSet(
                OperationSetBasicInstantMessaging.class,
                basicInstantMessaging);

            //initialze the file transfer operation set
            fileTranfer = new OperationSetFileTransferSSHImpl(this);
            addSupportedOperationSet(
                OperationSetFileTransfer.class,
                fileTranfer);

            isInitialized = true;
        }
    }

    /**
     * Determines whether a vaild session exists for the contact of remote
     * machine.
     *
     * @param sshContact ID of SSH Contact
     *
     * @return <tt>true</tt> if the session is connected
     *         <tt>false</tt> otherwise
     */
    public boolean isSessionValid(ContactSSH sshContact)
    {
        Session sshSession = sshContact.getSSHSession();
        if( sshSession != null)
            if(sshSession.isConnected())
                return true;

        // remove reference to an unconnected SSH Session, if any
        sshContact.setSSHSession(null);
        return false;
    }

    /**
     * Determines whether the contact is connected to shell of remote machine
     * as a precheck for any further operation
     *
     * @param sshContact ID of SSH Contact
     *
     * @return <tt>true</tt> if the contact is connected
     *         <tt>false</tt> if the contact is not connected
     */
    public boolean isShellConnected(ContactSSH sshContact)
    {
        // a test command may also be run here

        if(isSessionValid(sshContact))
        {
            return(sshContact.getShellChannel() != null);
        }

        /*
         * Above should be return(sshContact.getShellChannel() != null
         *                     && sshContact.getShellChannel().isConnected());
         *
         * but incorrect reply from stack for isConnected()
         */

        return false;
    }

    /**
     * Creates a shell channel to the remote machine
     * a new jsch session is also created if the current one is invalid
     *
     * @param sshContact the contact of the remote machine
     * @param firstMessage the first message
     */
    public void connectShell(
            final ContactSSH sshContact,
            final Message firstMessage)
    {
        sshContact.setConnectionInProgress(true);

        final Thread newConnection = new Thread((new Runnable()
        {
            public void run()
            {
                OperationSetPersistentPresenceSSHImpl persistentPresence
                        = (OperationSetPersistentPresenceSSHImpl)sshContact
                        .getParentPresenceOperationSet();

                persistentPresence.changeContactPresenceStatus(
                        sshContact,
                        SSHStatusEnum.CONNECTING);

                try
                {
                    if(!isSessionValid(sshContact))
                        createSSHSessionAndLogin(sshContact);

                    createShellChannel(sshContact);

                    //initializing the reader and writers of ssh contact

                    persistentPresence.changeContactPresenceStatus(
                            sshContact,
                            SSHStatusEnum.CONNECTED);

                    showWelcomeMessage(sshContact);

                    sshContact.setMessageType(ContactSSH
                            .CONVERSATION_MESSAGE_RECEIVED);

                    sshContact.setConnectionInProgress(false);

                    Thread.sleep(1500);

                    sshContact.setCommandSent(true);

                    basicInstantMessaging.sendInstantMessage(
                            sshContact,
                            firstMessage);
                }
                // rigorous Exception Checking in future
                catch (Exception ex)
                {
                    persistentPresence.changeContactPresenceStatus(
                            sshContact,
                            SSHStatusEnum.NOT_AVAILABLE);

                    ex.printStackTrace();
                }
                finally
                {
                    sshContact.setConnectionInProgress(false);
                }
            }
        }));

        newConnection.start();
    }

    /**
     * Creates a channel for shell type in the current session
     * channel types = shell, sftp, exec(X forwarding),
     *                 direct-tcpip(stream forwarding) etc
     *
     * @param sshContact ID of SSH Contact
     * @throws IOException if the shell channel cannot be created
     */
    public void createShellChannel(ContactSSH sshContact)
        throws IOException
    {
        try
        {
            Channel shellChannel = sshContact.getSSHSession()
                .openChannel("shell");

            //initalizing the reader and writers of ssh contact
            sshContact.initializeShellIO(shellChannel.getInputStream(),
                    shellChannel.getOutputStream());

            ((ChannelShell)shellChannel).setPtyType(
                    sshContact.getSSHConfigurationForm().getTerminalType());

            //initializing the shell
            shellChannel.connect(1000);

            sshContact.setShellChannel(shellChannel);

            sshContact.sendLine("export PS1=");
        }
        catch (JSchException ex)
        {
            sshContact.setSSHSession(null);
            throw new IOException("Unable to create shell channel to remote" +
                    " server");
        }
    }

    /**
     * Closes the Shell channel are associated IO Streams
     *
     * @param sshContact ID of SSH Contact
     * @throws JSchException if something went wrong in JSch
     * @throws IOException if I/O exception occurred
     */
    public void closeShellChannel(ContactSSH sshContact) throws
            JSchException,
            IOException
    {
        sshContact.closeShellIO();
        sshContact.getShellChannel().disconnect();
        sshContact.setShellChannel(null);
    }

    /**
     * Creates a SSH Session with a remote machine and tries to login
     * according to the details specified by Contact
     * An appropriate message is shown to the end user in case the login fails
     *
     * @param sshContact ID of SSH Contact
     *
     * @throws JSchException if a JSch is unable to create a SSH Session with
     * the remote machine
     * @throws InterruptedException if the thread is interrupted before session
     *         connected or is timed out
     * @throws OperationFailedException if not of above reasons :-)
     */
    public void createSSHSessionAndLogin(ContactSSH sshContact) throws
            JSchException,
            OperationFailedException,
            InterruptedException
    {
        if (logger.isInfoEnabled())
            logger.info("Creating a new SSH Session to "
                + sshContact.getHostName());

        // creating a new JSch Stack identifier for contact
        JSch jsch = new JSch();

        String knownHosts =
            accountID.getAccountPropertyString("KNOWN_HOSTS_FILE");

        if(!knownHosts.equals("Optional"))
            jsch.setKnownHosts(knownHosts);

        String identitiyKey =
            accountID.getAccountPropertyString("IDENTITY_FILE");

        String userName = sshContact.getUserName();

        // use the name of system user if the contact has not supplied SSH
        // details
        if(userName.equals(""))
            userName = System.getProperty("user.name");

        if(!identitiyKey.equals("Optional"))
            jsch.addIdentity(identitiyKey);

        // creating a new session for the contact
        Session session = jsch.getSession(
                userName,
                sshContact.getHostName(),
                sshContact.getSSHConfigurationForm().getPort());

        /**
         * Creating and associating User Info with the session
         * User Info passes authentication from sshContact to SSH Stack
         */
        SSHUserInfo sshUserInfo = new SSHUserInfo(sshContact);

        session.setUserInfo(sshUserInfo);

        /**
         * initializing the session
         */
        session.connect(connectionTimeout);

        int count = 0;

        // wait for session to get connected
        while(!session.isConnected() && count<=30000)
        {
            Thread.sleep(1000);
            count += 1000;
            if (logger.isTraceEnabled())
                logger.trace("SSH:" + sshContact.getHostName()
                    + ": Sleep zzz .. " );
        }

        // if timeout have exceeded
        if(count>30000)
        {
            sshContact.setSSHSession(null);
            JOptionPane.showMessageDialog(
                    null,
                    "SSH Connection attempt to "
                    + sshContact.getHostName() + " timed out");

            // error codes are not defined yet
            throw new OperationFailedException("SSH Connection attempt to " +
                    sshContact.getHostName() + " timed out", 2);
        }

        sshContact.setJSch(jsch);
        sshContact.setSSHSession(session);

        if (logger.isInfoEnabled())
            logger.info("A new SSH Session to " + sshContact.getHostName()
                + " Created");
    }

    /**
     * Closes the SSH Session associated with the contact
     *
     * @param sshContact ID of SSH Contact
     */
    void closeSSHSession(ContactSSH sshContact)
    {
        sshContact.getSSHSession().disconnect();
        sshContact.setSSHSession(null);
    }

    /**
     * Presents the login welcome message to user
     *
     * @param sshContact ID of SSH Contact
     * @throws IOException if I/O exception occurred
     */
    public void showWelcomeMessage(ContactSSH sshContact)
        throws IOException
    {
/*      //sending the command
        sshContact.sendLine(testCommand);

        String reply = "", line = "";

        // message is extracted until the test Command ie echoed back
        while(line.indexOf(testCommand) == -1)
        {
            reply += line + "\n";
            line = sshContact.getLine();
        }

        uiService.getPopupDialog().showMessagePopupDialog
                (reply,"Message from " + sshContact.getDisplayName(),
                uiService.getPopupDialog().INFORMATION_MESSAGE);

        if(line.startsWith(testCommand))
            while(!sshContact.getLine().contains(testCommand));

        //one line output of testCommand
        sshContact.getLine();
*/
        if (logger.isDebugEnabled())
            logger.debug("SSH: Welcome message shown");
    }

    /**
     * Returns a reference to UIServce for accessing UI related services
     *
     * @return uiService a reference to UIService
     */
    public static UIService getUIService()
    {
        return uiService;
    }

    /**
     * Returns the AccountID that uniquely identifies the account represented
     * by this instance of the ProtocolProviderService.
     *
     * @return the id of the account represented by this provider.
     */
    public AccountID getAccountID()
    {
        return accountID;
    }

    /**
     * Returns the short name of the protocol that the implementation of this
     * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for
     * example).
     *
     * @return a String containing the short name of the protocol this
     *   service is implementing (most often that would be a name in
     *   ProtocolNames).
     */
    public String getProtocolName()
    {
        return SSH_PROTOCOL_NAME;
    }

    /**
     * Returns the state of the registration of this protocol provider with
     * the corresponding registration service.
     *
     * @return ProviderRegistrationState
     */
    public RegistrationState getRegistrationState()
    {
        return currentRegistrationState;
    }

    /**
     * Starts the registration process.
     *
     * @param authority the security authority that will be used for
     *   resolving any security challenges that may be returned during the
     *   registration or at any moment while wer're registered.
     * @throws OperationFailedException with the corresponding code it the
     *   registration fails for some reason (e.g. a networking error or an
     *   implementation problem).
     */
    public void register(SecurityAuthority authority)
    throws OperationFailedException
    {
        RegistrationState oldState = currentRegistrationState;
        currentRegistrationState = RegistrationState.REGISTERED;

        //get a reference to UI Service via its Service Reference
        ppUIServiceRef = SSHActivator.getBundleContext()
            .getServiceReference(UIService.class.getName());

        uiService = (UIService)SSHActivator.getBundleContext()
            .getService(ppUIServiceRef);

        fireRegistrationStateChanged(
                oldState
                , currentRegistrationState
                , RegistrationStateChangeEvent.REASON_USER_REQUEST
                , null);

    }

    /**
     * Makes the service implementation close all open sockets and release
     * any resources that it might have taken and prepare for
     * shutdown/garbage collection.
     */
    public void shutdown()
    {
        if(!isInitialized)
        {
            return;
        }
        if (logger.isTraceEnabled())
            logger.trace("Killing the SSH Protocol Provider.");

        if(isRegistered())
        {
            try
            {
                //do the unregistration
                unregister();
            }
            catch (OperationFailedException ex)
            {
                //we're shutting down so we need to silence the exception here
                logger.error(
                        "Failed to properly unregister before shutting down. "
                        + getAccountID()
                        , ex);
            }
        }

        isInitialized = false;
    }

    /**
     * Ends the registration of this protocol provider with the current
     * registration service.
     *
     * @throws OperationFailedException with the corresponding code it the
     *   registration fails for some reason (e.g. a networking error or an
     *   implementation problem).
     */
    public void unregister()
    throws OperationFailedException
    {
        RegistrationState oldState = currentRegistrationState;
        currentRegistrationState = RegistrationState.UNREGISTERED;

        fireRegistrationStateChanged(
                oldState
                , currentRegistrationState
                , RegistrationStateChangeEvent.REASON_USER_REQUEST
                , null);
    }

    /*
     * (non-Javadoc)
     *
     * @see net.java.sip.communicator.service.protocol.ProtocolProviderService#
     * isSignallingTransportSecure()
     */
    public boolean isSignalingTransportSecure()
    {
        return false;
    }

    /**
     * Returns the "transport" protocol of this instance used to carry the
     * control channel for the current protocol service.
     *
     * @return The "transport" protocol of this instance: TCP.
     */
    public TransportProtocol getTransportProtocol()
    {
        return TransportProtocol.TCP;
    }

    /**
     * Returns the ssh protocol icon.
     * @return the ssh protocol icon
     */
    public ProtocolIcon getProtocolIcon()
    {
        return sshIcon;
    }
}