File: sshmasterconnection.cpp

package info (click to toggle)
x2goclient 3.99.2.1-5
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,596 kB
  • sloc: cpp: 21,625; perl: 512; makefile: 129; sh: 17
file content (944 lines) | stat: -rw-r--r-- 29,444 bytes parent folder | download
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944

/***************************************************************************
 *   Copyright (C) 2005-2012 by Oleksandr Shneyder                         *
 *   oleksandr.shneyder@obviously-nice.de                                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "x2goclientconfig.h"
#include "x2gologdebug.h"
#include "sshmasterconnection.h"
#include <stdlib.h>
#include <stdio.h>
#include "sshprocess.h"

#include <QStringList>
#include <QFile>
#include <QDir>
#include <QTemporaryFile>
#ifndef Q_OS_WIN
#include <arpa/inet.h>
#endif
#include <math.h>

#ifndef Q_OS_WIN
#include <arpa/inet.h>
#include <netinet/tcp.h>
#endif


#include "onmainwindow.h"

#undef DEBUG
//#define DEBUG

//#define SSH_DEBUG
#undef SSH_DEBUG

static bool isLibSshInited=false;


SshMasterConnection::SshMasterConnection ( QString host, int port, bool acceptUnknownServers, QString user,
        QString pass, QString key,bool autologin, bool krblogin, QObject* parent ) : QThread ( parent )
{
#if defined ( Q_OS_DARWIN )
    // Mac OS X provides only 512KB stack space for secondary threads.
    // As we put a 512KB buffer on the stack later on, we need a bigger stack space.
    setStackSize (sizeof (char) * 1024 * 1024 * 2);
#endif
    this->host=host;
    this->port=port;
    this->user=user;
    this->pass=pass;
    this->key=key;
    this->autologin=autologin;
    this->acceptUnknownServers=acceptUnknownServers;
    reverseTunnel=false;
    mainWnd=(ONMainWindow*) parent;
    kerberos=krblogin;
#ifdef DEBUG
    if (kerberos)
        x2goDebug<<"starting ssh connection with kerberos authentication"<<endl;
    else
        x2goDebug<<"starting ssh connection without kerberos authentication"<<endl;
#endif
    kerberos=false;
}

SshMasterConnection::SshMasterConnection ( QString host, int port, bool acceptUnknownServers, QString user,
        QString pass, QString key, bool autologin,
        int remotePort, QString localHost, int localPort, SshProcess* creator,
        QObject* parent, ONMainWindow* mwd ) : QThread ( parent )
{
#if defined ( Q_OS_DARWIN )
    setStackSize (sizeof (char) * 1024 * 1024 * 2);
#endif
    this->host=host;
    this->port=port;
    this->user=user;
    this->pass=pass;
    this->key=key;
    this->autologin=autologin;
    this->acceptUnknownServers=acceptUnknownServers;
    reverseTunnelLocalHost=localHost;
    reverseTunnelLocalPort=localPort;
    reverseTunnelCreator=creator;
    reverseTunnel=true;
    reverseTunnelRemotePort=remotePort;
    mainWnd=mwd;
}

SshMasterConnection* SshMasterConnection::reverseTunnelConnection ( SshProcess* creator,
        int remotePort, QString localHost, int localPort )
{
    SshMasterConnection* con=new SshMasterConnection ( host,port,acceptUnknownServers,user,pass,
            key,autologin, remotePort,localHost,
            localPort,creator,this, mainWnd);
    con->kerberos=kerberos;

    connect ( con,SIGNAL ( ioErr ( SshProcess*,QString,QString ) ),this,SIGNAL ( ioErr ( SshProcess*,QString,QString ) ) );
    connect ( con,SIGNAL ( stdErr ( SshProcess*,QByteArray ) ),this,SIGNAL ( stdErr ( SshProcess*,QByteArray ) ) );
    connect ( con,SIGNAL ( reverseListenOk ( SshProcess* ) ), this, SIGNAL ( reverseListenOk ( SshProcess* ) ) );
    con->start();
    reverseTunnelConnectionsMutex.lock();
    reverseTunnelConnections.append ( con );
    reverseTunnelConnectionsMutex.unlock();
    return con;
}

void SshMasterConnection::run()
{
    disconnectSessionFlag=false;
    if ( !isLibSshInited )
    {
#ifdef DEBUG
        x2goDebug<<"libSsh not inited yet, initting\n";
#endif
        if ( ssh_init() !=0 )
        {
            QString err=tr ( "Can not initialize libssh" );
            x2goDebug<<err<<endl;
            emit connectionError ( err,"" );
            quit();
            return;
        }
        isLibSshInited=true;
    }
#ifdef DEBUG
    else
    {
        x2goDebug<<"already inited\n";
    }
#endif

#ifdef SSH_DEBUG
    int verbosity=SSH_LOG_PACKET;
#else
    int verbosity=SSH_LOG_NOLOG;
#endif

    long timeout = 60;

    my_ssh_session = ssh_new();
    if ( my_ssh_session == NULL )
    {
        QString err=tr ( "Can not create ssh session" );
        x2goDebug<<err<<endl;
        emit connectionError ( err,"" );
        if ( reverseTunnel )
            emit ioErr ( reverseTunnelCreator,err,"" );
        quit();
        return;
    }
#ifdef Q_OS_WIN
    ssh_options_set ( my_ssh_session, SSH_OPTIONS_SSH_DIR, (mainWnd->getHomeDirectory()+"/ssh").toAscii());
#endif
    ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);

    ssh_options_set(my_ssh_session, SSH_OPTIONS_TIMEOUT, &timeout);

    if ( !sshConnect() )
    {
        QString err=ssh_get_error ( my_ssh_session );
        QString message=tr ( "Can not connect to " ) +host+QString::number ( port );
        x2goDebug<<message<<" - "<<err;
        emit connectionError ( message, err );
        if ( reverseTunnel )
            emit ioErr ( reverseTunnelCreator,message,err );
        ssh_free ( my_ssh_session );
        quit();
        return;
    }
    QString errMsg;
    int state=serverAuth ( errMsg );
    if ( state != SSH_SERVER_KNOWN_OK )
    {
        emit serverAuthError ( state,errMsg );
        ssh_disconnect ( my_ssh_session );
        ssh_free ( my_ssh_session );
        quit();
        return;
    }

    ssh_options_set ( my_ssh_session, SSH_OPTIONS_USER, user.toAscii() );
#ifdef Q_OS_WIN
    ssh_options_set ( my_ssh_session, SSH_OPTIONS_SSH_DIR, (mainWnd->getHomeDirectory()+"/ssh").toAscii());

#ifdef DEBUG
    x2goDebug<<"setting SSH DIR to "<<mainWnd->getHomeDirectory()+"/ssh";
#endif
#endif

    if ( userAuth() )
    {
#ifdef DEBUG
        x2goDebug<<"user auth OK\n";
#endif
        emit connectionOk(host);
    }
    else
    {
        QString err;
        if (!kerberos)
            err=ssh_get_error ( my_ssh_session );
        QString message=tr ( "Authentication failed" );
        x2goDebug<<message<<" - "<<err;
        emit userAuthError ( authErrors.join ( "\n" ) );
        if ( reverseTunnel )
            emit ioErr ( reverseTunnelCreator,message,err );
        ssh_disconnect ( my_ssh_session );
        ssh_free ( my_ssh_session );
        quit();
        return;
    }


#ifndef Q_OS_WIN
    const int y=1;
#else
    const char y=1;
#endif
    socket_t session_sock=ssh_get_fd(my_ssh_session);
    setsockopt(session_sock, IPPROTO_TCP, TCP_NODELAY,&y, sizeof(int));


    if ( reverseTunnel )
    {
        if ( channel_forward_listen ( my_ssh_session, NULL, reverseTunnelRemotePort,  NULL ) !=SSH_OK )
        {
            QString err=ssh_get_error ( my_ssh_session );
            QString message=tr ( "channel_forward_listen failed" );
            x2goDebug<<message<<" - "<<err;
            emit ioErr ( reverseTunnelCreator, message, err );
            ssh_disconnect ( my_ssh_session );
            ssh_free ( my_ssh_session );
            quit();
            return;
        }
        emit reverseListenOk ( reverseTunnelCreator );

#ifdef DEBUG
        x2goDebug<<"channel_forward_listen ok\n ";
#endif
    }
    channelLoop();
}


SshMasterConnection::~SshMasterConnection()
{
    /*    ssh_disconnect(my_ssh_session);
        ssh_free(my_ssh_session);*/
}


void SshMasterConnection::finalizeLibSsh()
{
    if ( !isLibSshInited )
    {
#ifdef DEBUG
        x2goDebug<<"libssh not inited yet\n";
#endif
        return;
    }

    ssh_finalize();
#ifdef DEBUG
    x2goDebug<<"libssh finalized\n";
#endif
}

bool SshMasterConnection::sshConnect()
{
    int rc;
    QByteArray tmpBA = host.toLocal8Bit();
    ssh_options_set ( my_ssh_session, SSH_OPTIONS_HOST, tmpBA.data() );
    ssh_options_set ( my_ssh_session, SSH_OPTIONS_PORT, &port );
    rc = ssh_connect ( my_ssh_session );
    if ( rc != SSH_OK )
        return false;
    return true;

}



int SshMasterConnection::serverAuth ( QString& errorMsg )
{
#ifdef DEBUG
    x2goDebug<<"cserverAuth\n ";
#endif

    int state, hlen;
    unsigned char *hash = NULL;
    char *hexa;

    state = ssh_is_server_known ( my_ssh_session );
    hlen = ssh_get_pubkey_hash ( my_ssh_session, &hash );


    if ( hlen < 0 )
        return SSH_SERVER_ERROR;

#ifdef DEBUG
    x2goDebug<<"state: "<<state<<endl;
#endif


    switch ( state )
    {
    case SSH_SERVER_KNOWN_OK:
        break; /* ok */

    case SSH_SERVER_KNOWN_CHANGED:
        hexa = ssh_get_hexa ( hash, hlen );
        errorMsg=hexa;
        free ( hexa );
        break;
    case SSH_SERVER_FOUND_OTHER:
        break;
    case SSH_SERVER_FILE_NOT_FOUND:
    case SSH_SERVER_NOT_KNOWN:
        if ( !acceptUnknownServers )
        {
            hexa = ssh_get_hexa ( hash, hlen );
            errorMsg=hexa;
            free ( hexa );
            break;
        }
        ssh_write_knownhost ( my_ssh_session );
        state=SSH_SERVER_KNOWN_OK;
        break;

    case SSH_SERVER_ERROR:
        errorMsg=ssh_get_error ( my_ssh_session );
        break;
    }
    free ( hash );
    return state;
}


bool SshMasterConnection::userAuthWithPass()
{
    int rc = ssh_userauth_password ( my_ssh_session, NULL, pass.toAscii() );
    if ( rc != SSH_AUTH_SUCCESS )
    {
        QString err=ssh_get_error ( my_ssh_session );
        authErrors<<err;
#ifdef DEBUG
        x2goDebug<<"userAuthWithPass failed:" <<err<<endl;
#endif
        return false;
    }
    return true;
}


bool SshMasterConnection::userAuthAuto()
{
    int rc = ssh_userauth_autopubkey ( my_ssh_session, NULL );
    if ( rc != SSH_AUTH_SUCCESS )
    {
        QString err=ssh_get_error ( my_ssh_session );
        authErrors<<err;
#ifdef DEBUG
        x2goDebug<<"userAuthAuto failed:" <<err<<endl;
#endif
        return false;
    }
    return true;
}

bool SshMasterConnection::userAuthWithKey()
{
#ifdef DEBUG
    x2goDebug<<"try authenticate user with private key" <<endl;
#endif
    QString keyName=key;
    bool autoRemove=false;
    if ( key.indexOf ( "PRIVATE KEY" ) !=-1 )
    {
        QDir dr;
        QString keyPath=mainWnd->getHomeDirectory() +"/.x2go/ssh/gen";
        dr.mkpath ( keyPath );
        QTemporaryFile fl ( keyPath+"/key" );
        fl.open();
        keyName=fl.fileName();
        fl.setAutoRemove ( false );
        QTextStream out ( &fl );
        out<<key;
        fl.close();
        autoRemove=true;
#ifdef DEBUG
        x2goDebug<<"temporary save key in "<<keyName<<endl;
#endif
    }

    ssh_private_key prkey=privatekey_from_file(my_ssh_session, keyName.toAscii(), 0, pass.toAscii());
    if (!prkey)
    {
#ifdef DEBUG
        x2goDebug<<"Failed to get private key from "<<keyName<<endl;
#endif
        if ( autoRemove )
            QFile::remove ( keyName );
        return false;
    }
    ssh_public_key pubkey=publickey_from_privatekey(prkey);
    if (!prkey)
    {
#ifdef DEBUG
        x2goDebug<<"Failed to get public key from private key"<<endl;
#endif
        privatekey_free(prkey);
        if ( autoRemove )
            QFile::remove ( keyName );
        return false;
    }

    ssh_string pubkeyStr=publickey_to_string(pubkey);
    publickey_free(pubkey);

    //not implemented before libssh 0.5
    /*	int rc = ssh_userauth_privatekey_file ( my_ssh_session,NULL,
    	                                        keyName.toAscii(),
    	                                        pass.toAscii() );*/

    int rc=ssh_userauth_pubkey(my_ssh_session, NULL, pubkeyStr, prkey);
    privatekey_free(prkey);
    string_free(pubkeyStr);

#ifdef DEBUG
    x2goDebug<<"auth with key: "<<rc<<endl;
#endif

    if ( autoRemove )
        QFile::remove ( keyName );
    if ( rc != SSH_AUTH_SUCCESS )
    {
        QString err=ssh_get_error ( my_ssh_session );
        authErrors<<err;

#ifdef DEBUG
        x2goDebug<<"userAuthWithKey failed:" <<err<<endl;
#endif

        return false;
    }
    return true;
}


bool SshMasterConnection::userAuth()
{
    if ( autologin )
        if ( userAuthAuto() )
            return true;
    if ( key!="" )
    {
        if ( userAuthWithKey() )
            return true;
    }
    return userAuthWithPass();
}


void SshMasterConnection::addChannelConnection ( SshProcess* creator, int sock, QString forwardHost, int forwardPort,
        QString localHost, int localPort, void* channel )
{
    ChannelConnection con;
    con.channel= ( ssh_channel ) channel;
    con.sock=sock;
    con.creator=creator;
    con.forwardHost=forwardHost;
    con.forwardPort=forwardPort;
    con.localHost=localHost;
    con.localPort=localPort;

    channelConnectionsMutex.lock();
    channelConnections<<con;
    channelConnectionsMutex.unlock();
}


void SshMasterConnection::addChannelConnection ( SshProcess* creator, QString cmd )
{
    ChannelConnection con;
    con.channel=NULL;
    con.sock=-1;
    con.creator=creator;
    con.command=cmd;

    channelConnectionsMutex.lock();
    channelConnections<<con;
    channelConnectionsMutex.unlock();
}


void SshMasterConnection::addCopyRequest ( SshProcess* creator, QString src, QString dst )
{
    CopyRequest req;
    req.src=src;
    req.dst=dst;
    req.creator=creator;
    copyRequestMutex.lock();
    copyRequests<<req;
    copyRequestMutex.unlock();
}

void SshMasterConnection::disconnectSession()
{
    disconnectFlagMutex.lock();
    disconnectSessionFlag=true;
    disconnectFlagMutex.unlock();
}

void SshMasterConnection::copy()
{

    for ( int i=copyRequests.size()-1;i>=0;--i )
    {
        QStringList lst=copyRequests[i].dst.split ( "/" );
        QString dstFile=lst.last();
        lst.removeLast();
        QString dstPath=lst.join ( "/" );
#ifdef DEBUG
        x2goDebug<<"dst path:"<<dstPath<<" file:"<<dstFile<<endl;
#endif
        ssh_scp scp=ssh_scp_new ( my_ssh_session, SSH_SCP_WRITE|SSH_SCP_RECURSIVE, dstPath.toAscii() );
        if ( scp == NULL )
        {
            x2goDebug<<"Error allocating scp session: "<< ssh_get_error ( my_ssh_session ) <<endl;
            return;
        }
        int rc = ssh_scp_init ( scp );
        if ( rc != SSH_OK )
        {
            x2goDebug<<"Error initializing scp session: "<< ssh_get_error ( my_ssh_session ) <<endl;
            ssh_scp_free ( scp );
            return;
        }
        QFile file ( copyRequests[i].src );
        if ( !file.open ( QIODevice::ReadOnly ) )
        {
            QString errMsg=tr ( "Can not open file " ) +copyRequests[i].src;
            emit copyErr ( copyRequests[i].creator, errMsg, "" );
            copyRequests.removeAt ( i );
            ssh_scp_close ( scp );
            ssh_scp_free ( scp );
            continue;
        }
        QByteArray arr=file.readAll();
        file.close();
        rc=ssh_scp_push_file ( scp,dstFile.toAscii(),arr.size(), 0600 );
        if ( rc != SSH_OK )
        {
            QString errMsg=tr ( "Can not create remote file " ) +copyRequests[i].dst;
            QString serr=ssh_get_error ( my_ssh_session );
            x2goDebug<<errMsg<<" - "<<serr<<endl;
            emit copyErr ( copyRequests[i].creator, errMsg, serr );
            copyRequests.removeAt ( i );
            ssh_scp_close ( scp );
            ssh_scp_free ( scp );
            continue;
        }
        rc=ssh_scp_write ( scp,arr.data(),arr.size() );
        if ( rc != SSH_OK )
        {
            QString serr=ssh_get_error ( my_ssh_session );
            QString errMsg=tr ( "Can not write to remote file " ) +copyRequests[i].dst;
            x2goDebug<<errMsg<<" - "<<serr<<endl;
            emit copyErr ( copyRequests[i].creator, errMsg, serr );
            copyRequests.removeAt ( i );
            ssh_scp_close ( scp );
            ssh_scp_free ( scp );
            continue;
        }
        emit copyOk ( copyRequests[i].creator );
#ifdef DEBUG
        x2goDebug<<"scp ok: "<<copyRequests[i].src<<" -> "<<user<<"@"<<host<<":"<<copyRequests[i].dst<<endl;
#endif
        copyRequests.removeAt ( i );
        ssh_scp_close ( scp );
        ssh_scp_free ( scp );
    }
}

void SshMasterConnection::channelLoop()
{
    forever
    {
        copyRequestMutex.lock();
        if ( copyRequests.size() >0 )
            copy();
        copyRequestMutex.unlock();
        if ( reverseTunnel )
        {
            ssh_channel newChan=channel_forward_accept ( my_ssh_session,0 );
            if ( newChan )
            {
#ifdef DEBUG
                x2goDebug<<"new forward connection"<<endl;
#endif
                int sock=socket ( AF_INET, SOCK_STREAM,0 );
#ifndef Q_OS_WIN
                const int y=1;
#else
                const char y=1;
#endif
                setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,&y, sizeof(int));

                struct sockaddr_in address;
                address.sin_family=AF_INET;
                address.sin_port=htons ( reverseTunnelLocalPort );
#ifdef DEBUG
                x2goDebug<<"connecting to "<<reverseTunnelLocalHost<<":"<<reverseTunnelLocalPort<<endl;
#endif
#ifndef Q_OS_WIN
                inet_aton ( reverseTunnelLocalHost.toAscii(), &address.sin_addr );
#else
                address.sin_addr.s_addr=inet_addr (
                                            reverseTunnelLocalHost.toAscii() );
#endif

                if ( ::connect ( sock, ( struct sockaddr * ) &address,sizeof ( address ) ) !=0 )
                {
                    QString errMsg=tr ( "can not connect to " ) +
                                   reverseTunnelLocalHost+":"+QString::number ( reverseTunnelLocalPort );
                    x2goDebug<<errMsg<<endl;
                    emit ioErr ( reverseTunnelCreator, errMsg, "" );
                    continue;
                }
#ifdef DEBUG
                x2goDebug<<"creating new channel connection"<<endl;
#endif
                ChannelConnection con;
                con.channel=newChan;
                con.sock=sock;
                con.creator=reverseTunnelCreator;
                channelConnectionsMutex.lock();
                channelConnections<<con;
                channelConnectionsMutex.unlock();
            }
        }

        char buffer[1024*512]; //512K buffer
        int nbytes;
        fd_set rfds;

        struct timeval tv;

        tv.tv_sec = 0;
        tv.tv_usec = 500;

        int retval;
        int maxsock=-1;

        disconnectFlagMutex.lock();
        bool disconnect=disconnectSessionFlag;
        disconnectFlagMutex.unlock();

        if ( disconnect )
        {
#ifdef DEBUG
            if ( !reverseTunnel )
                x2goDebug<<"Disconnecting..."<<endl;
#endif
            reverseTunnelConnectionsMutex.lock();
            for ( int i=0;i<reverseTunnelConnections.size();++i )
            {
                reverseTunnelConnections[i]->disconnectSession();
                reverseTunnelConnections[i]->wait ( 10000 );

            }
            reverseTunnelConnectionsMutex.unlock();

            channelConnectionsMutex.lock();
            for ( int i=0;i<channelConnections.size();++i )
            {
                finalize ( i );
            }
            channelConnectionsMutex.unlock();

            ssh_disconnect ( my_ssh_session );
            ssh_free ( my_ssh_session );
#ifdef DEBUG
            if ( !reverseTunnel )
                x2goDebug<<"All channels closed, session disconnected, quiting session loop"<<endl;
#endif
            quit();
            return;
        }


        channelConnectionsMutex.lock();
        if ( channelConnections.size() <=0 )
        {
//             x2goDebug<<"no channel connections, waiting\n";
            channelConnectionsMutex.unlock();
            usleep ( 500 );
            continue;
        }
        ssh_channel* read_chan=new ssh_channel[channelConnections.size() +1];
        ssh_channel* out_chan=new ssh_channel[channelConnections.size() +1];
        read_chan[channelConnections.size() ]=NULL;

        FD_ZERO ( &rfds );

        for ( int i=0;i<channelConnections.size();++i )
        {
            int tcpSocket=channelConnections.at ( i ).sock;
            if ( tcpSocket>0 )
                FD_SET ( tcpSocket, &rfds );
            if ( channelConnections.at ( i ).channel==0l )
            {
#ifdef DEBUG
                x2goDebug<<"creating new channel"<<endl;
#endif
                ssh_channel channel=channel_new ( my_ssh_session );
#ifdef DEBUG
                x2goDebug<<"new channel:"<<channel<<endl;
#endif
                channelConnections[i].channel=channel;
                if ( tcpSocket>0 )
                {
#ifdef DEBUG
                    x2goDebug<<"forwarding new channel, local port: "<<channelConnections.at ( i ).localPort<<endl;
#endif
                    if ( channel_open_forward ( channel,
                                                channelConnections.at ( i ).forwardHost.toAscii(),
                                                channelConnections.at ( i ).forwardPort,
                                                channelConnections.at ( i ).localHost.toAscii(),
                                                channelConnections.at ( i ).localPort ) != SSH_OK )
                    {
                        QString err=ssh_get_error ( my_ssh_session );
                        QString errorMsg=tr ( "channel_open_forward failed" );
                        emit ioErr ( channelConnections[i].creator, errorMsg, err );
                        x2goDebug<<errorMsg<<": "<<err<<endl;
                    }
#ifdef DEBUG
                    else
                    {
                        x2goDebug<<" new channel forwarded"<<endl;
                    }
#endif
                }
                else
                {
#ifdef DEBUG
                    x2goDebug<<"executing remote: "<<channelConnections.at ( i ).command<<endl;
#endif
                    if ( channel_open_session ( channel ) !=SSH_OK )
                    {
                        QString err=ssh_get_error ( my_ssh_session );
                        QString errorMsg=tr ( "channel_open_session failed" );
                        emit ioErr ( channelConnections[i].creator, errorMsg, err );
                        x2goDebug<<errorMsg<<": "<<err<<endl;
                    }
                    else if ( channel_request_exec ( channel, channelConnections[i].command.toAscii() ) != SSH_OK )
                    {
                        QString err=ssh_get_error ( my_ssh_session );
                        QString errorMsg=tr ( "channel_request_exec failed" );
                        emit ioErr ( channelConnections[i].creator, errorMsg, err );
                        x2goDebug<<errorMsg<<": "<<err<<endl;
                    }
#ifdef DEBUG
                    else
                    {
                        x2goDebug<<" new exec channel created"<<endl;
                    }
#endif
                }

            }
            read_chan[i]=channelConnections.at ( i ).channel;
            if ( tcpSocket>maxsock )
                maxsock=tcpSocket;
        }
        channelConnectionsMutex.unlock();
        retval=ssh_select ( read_chan,out_chan,maxsock+1,&rfds,&tv );
        delete [] read_chan;
        delete [] out_chan;

        if ( retval == -1 )
        {
            x2goDebug<<"select error\n";
            continue;
        }

//         x2goDebug<<"select exited"<<endl;

        channelConnectionsMutex.lock();
        for ( int i=channelConnections.size()-1;i>=0;--i )
        {
            int tcpSocket=channelConnections.at ( i ).sock;
            ssh_channel channel=channelConnections.at ( i ).channel;
            if ( channel==0l )
                continue;
            if ( channel_poll ( channel,1 ) >0 )
            {
//              x2goDebug<<"read err data from channel\n";
                nbytes = channel_read ( channel, buffer, sizeof ( buffer )-1, 1 );
                emit stdErr ( channelConnections[i].creator, QByteArray ( buffer,nbytes ) );
//              x2goDebug<<nbytes<<" err from channel"<<endl;
            }
            int rez=channel_poll ( channel,0 );
            if ( rez==SSH_EOF )
            {
#ifdef DEBUG
                x2goDebug<<"EOF ON CHANNEL "<<channel<<endl;
#endif
                //////Finished////////
                finalize ( i );
                continue;
            }
            if ( rez>0 )
            {
//                  x2goDebug<<"read data from channel "<<channel<<endl;
                nbytes = channel_read ( channel, buffer, sizeof ( buffer )-1, 0 );
//                  x2goDebug<<nbytes<<" from channel "<<channel<<endl;
                if ( nbytes > 0 )
                {
                    if ( tcpSocket>0 )
                    {
                        if ( send ( tcpSocket,buffer, nbytes,0 ) != nbytes )
                        {
                            QString errMsg=tr ( "error writing to socket" );
                            x2goDebug<<"error writing "<<nbytes<<" to tcp socket"<<tcpSocket<<endl;
                            emit ioErr ( channelConnections[i].creator,errMsg,"" );
                            finalize ( i );
                            continue;
                        }
//                      x2goDebug<<"wrote "<<nbytes<<" to tcp socket "<<tcpSocket<<endl;
                    }
                    else
                    {
                        emit stdOut ( channelConnections[i].creator, QByteArray ( buffer,nbytes ) );
                    }
                }

                if ( nbytes < 0 )
                {
                    //////ERROR!!!!!////////
                    QString err=ssh_get_error ( my_ssh_session );
                    QString errorMsg=tr ( "error reading channel" );
                    emit ioErr ( channelConnections[i].creator, errorMsg, err );
                    x2goDebug<<errorMsg<<" - "<<err<<endl;
                    finalize ( i );
                    continue;
                }

                if ( channel_is_eof ( channel ) )
                {
#ifdef DEBUG
                    x2goDebug<<"EOF ON CHANNEL "<<channel<<endl;
#endif
                    //////Finished////////
                    finalize ( i );
                    continue;
                }
            }
            if ( tcpSocket<=0 )
            {
                continue;
            }
            if ( FD_ISSET ( tcpSocket,&rfds ) )
            {
                nbytes = recv ( tcpSocket, buffer, sizeof ( buffer )-1,0 );
//                  x2goDebug<<nbytes<<" bytes from tcp socket "<<tcpSocket<<endl;
                if ( nbytes > 0 )
                {
                    if ( channel_write ( channel, buffer, nbytes ) !=nbytes )
                    {
                        QString err=ssh_get_error ( my_ssh_session );
                        QString errorMsg=tr ( "channel_write failed" );
                        emit ioErr ( channelConnections[i].creator, errorMsg, err );
                        x2goDebug<<errorMsg<<" - "<<err<<endl;
                        finalize ( i );
                        continue;
                    }
//                      x2goDebug<<nbytes<<" bytes wrote to channel"<<channel<<endl;
                }
                if ( nbytes < 0 )
                {
                    //////ERROR!!!!!////////
                    QString err="";
                    QString errorMsg=tr ( "error reading tcp socket" );
                    emit ioErr ( channelConnections[i].creator, errorMsg, err );
                    x2goDebug<<errorMsg<<" - "<<err<<endl;
                    finalize ( i );
                    continue;
                }
                if ( nbytes==0 )
                {
#ifdef DEBUG
                    x2goDebug<<"socket closed "<<tcpSocket<<endl;
#endif
                    finalize ( i );
                    continue;
                }
            }
        }
        channelConnectionsMutex.unlock();
    }
}

void SshMasterConnection::finalize ( int item )
{
    int tcpSocket=channelConnections.at ( item ).sock;
    ssh_channel channel=channelConnections.at ( item ).channel;
    if ( channel )
    {
        channel_send_eof ( channel );
#ifdef DEBUG
        x2goDebug<<"eof sent\n";
#endif
        channel_close ( channel );
#ifdef DEBUG
        x2goDebug<<"channel closed\n";
#endif
        channel_free ( channel );
    }
    if ( tcpSocket>0 )
    {
        close ( tcpSocket );
    }
    SshProcess* proc=channelConnections[item].creator;
    channelConnections.removeAt ( item );
    emit channelClosed ( proc );
}