This file is indexed.

/usr/share/pyshared/x2go/session.py is in python-x2go 0.1.1.8-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
# -*- coding: utf-8 -*-

# Copyright (C) 2010-2011 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# Python X2go 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 3 of the License, or
# (at your option) any later version.
#
# Python X2go 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.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

"""\
X2goSession class - a public API of Python X2go, handling standalone X2go 
sessions.

This class is normally embedded into the context of an L{X2goClient}
instance, but it is also possible to address L{X2goSession}s directly via this
class.

"""
__NAME__ = 'x2gosession-pylib'

import os
import copy
import types
import uuid
import time
import threading
import gevent

# Python X2go modules
import log
import utils
import session
from x2go_exceptions import *

from x2go.backends.control import X2goControlSession as _X2goControlSession
from x2go.backends.terminal import X2goTerminalSession as _X2goTerminalSession
from x2go.backends.info import X2goServerSessionInfo as _X2goServerSessionInfo
from x2go.backends.info import X2goServerSessionList as _X2goServerSessionList
from x2go.backends.proxy import X2goProxy as _X2goProxy
from x2go.backends.profiles import X2goSessionProfiles as _X2goSessionProfiles
from x2go.backends.settings import X2goClientSettings as _X2goClientSettings
from x2go.backends.printing import X2goClientPrinting as _X2goClientPrinting

from defaults import LOCAL_HOME as _LOCAL_HOME
from defaults import X2GO_CLIENT_ROOTDIR as _X2GO_CLIENT_ROOTDIR
from defaults import X2GO_SESSIONS_ROOTDIR as _X2GO_SESSIONS_ROOTDIR
from defaults import X2GO_SSH_ROOTDIR as _X2GO_SSH_ROOTDIR

from defaults import SUPPORTED_SOUND, SUPPORTED_PRINTING, SUPPORTED_FOLDERSHARING, SUPPORTED_MIMEBOX

# options of the paramiko.SSHClient().connect()
_X2GO_SESSION_PARAMS = ('geometry', 'depth', 'link', 'pack',
                        'cache_type', 'kblayout', 'kbtype',
                        'session_type', 'snd_system', 'snd_port',
                        'cmd',
                        'rdp_server', 'rdp_options',
                        'xdmcp_server',
                        'rootdir', 'loglevel', 'profile_name', 'profile_id',
                        'print_action', 'print_action_args',
                        'convert_encoding', 'client_encoding', 'server_encoding',
                        'proxy_options', 
                        'logger',
                        'control_backend', 'terminal_backend', 'proxy_backend',
                        'profiles_backend', 'settings_backend', 'printing_backend',
                       )
"""A list of allowed X2go session parameters."""
_X2GO_SSHPROXY_PARAMS = ('sshproxy_host', 'sshproxy_user', 'sshproxy_password',
                         'sshproxy_key_filename', 'sshproxy_pkey', 'sshproxy_tunnel',
                        )
"""A list of allowed X2go SSH proxy parameters."""


class X2goSession(object):
    """\
    Public API class for launching X2go sessions. Recommended is to manage X2go sessions from
    within an L{X2goClient} instance. However, Python X2go is designed in a way that it also
    allows the management of singel L{X2goSession} instance.

    Thus, you can use the L{X2goSession} class to manually set up X2go sessions without 
    L{X2goClient} context (session registry, session list cache, auto-registration of new
    sessions etc.).

    """
    def __init__(self, server=None, control_session=None,
                 use_sshproxy=False,
                 profile_id=None, profile_name='UNKNOWN',
                 session_name=None,
                 printing=False,
                 allow_mimebox=False,
                 mimebox_extensions=[],
                 mimebox_action='OPEN',
                 allow_share_local_folders=False,
                 share_local_folders=[],
                 control_backend=_X2goControlSession,
                 terminal_backend=_X2goTerminalSession,
                 info_backend=_X2goServerSessionInfo,
                 list_backend=_X2goServerSessionList,
                 proxy_backend=_X2goProxy,
                 settings_backend=_X2goClientSettings,
                 printing_backend=_X2goClientPrinting,
                 client_rootdir=os.path.join(_LOCAL_HOME, _X2GO_CLIENT_ROOTDIR),
                 sessions_rootdir=os.path.join(_LOCAL_HOME, _X2GO_SESSIONS_ROOTDIR),
                 ssh_rootdir=os.path.join(_LOCAL_HOME, _X2GO_SSH_ROOTDIR),
                 keep_controlsession_alive=False,
                 add_to_known_hosts=False,
                 known_hosts=None,
                 logger=None, loglevel=log.loglevel_DEFAULT,
                 connected=False, virgin=True, running=None, suspended=None, terminated=None, faulty=None,
                 client_instance=None,
                 **params):
        """\
        @param server: hostname of X2go server
        @type server: C{str}
        @param control_session: an already initialized C{X2goControlSession*} instance
        @type control_session: C{X2goControlSession*} instance
        @param use_sshproxy: for communication with X2go server use an SSH proxy host
        @type use_sshproxy: C{bool}
        @param profile_id: profile ID
        @type profile_id: C{str}
        @param profile_name: profile name
        @type profile_name: C{str}
        @param session_name: session name (if available)
        @type session_name: C{str}
        @param printing: enable X2go printing
        @type printing: C{bool}
        @param allow_mimebox: enable X2go MIME box support
        @type allow_mimebox: C{bool}
        @param mimebox_extensions: whitelist of allowed X2go MIME box extensions
        @type mimebox_extensions: C{list}
        @param mimebox_action: action for incoming X2go MIME box files
        @type mimebox_action: C{X2goMimeBoxAction*} or C{str}
        @param allow_share_local_folders: enable local folder sharing support
        @type allow_share_local_folders: C{bool}
        @param share_local_folders: list of local folders to share with the remote X2go session
        @type share_local_folders: C{list}
        @param control_backend: X2go control session backend to use
        @type control_backend: C{class}
        @param terminal_backend: X2go terminal session backend to use
        @type terminal_backend: C{class}
        @param info_backend: X2go session info backend to use
        @type info_backend: C{class}
        @param list_backend: X2go session list backend to use
        @type list_backend: C{class}
        @param proxy_backend: X2go proxy backend to use
        @type proxy_backend: C{class}
        @param settings_backend: X2go client settings backend to use
        @type settings_backend: C{class}
        @param printing_backend: X2go client printing backend to use
        @type printing_backend: C{class}
        @param client_rootdir: client base dir (default: ~/.x2goclient)
        @type client_rootdir: C{str}
        @param sessions_rootdir: sessions base dir (default: ~/.x2go)
        @type sessions_rootdir: C{str}
        @param ssh_rootdir: ssh base dir (default: ~/.ssh)
        @type ssh_rootdir: C{str}
        @param keep_controlsession_alive: On last L{X2goSession.disconnect()} keep the associated C{X2goControlSession*} instance alive?
        @ŧype keep_controlsession_alive: C{bool}
        @param add_to_known_hosts: Auto-accept server host validity?
        @type add_to_known_hosts: C{bool}
        @param known_hosts: the underlying Paramiko/SSH systems C{known_hosts} file
        @type known_hosts: C{str}
        @param connected: manipulate session state »connected« by giving a pre-set value
        @type connected: C{bool}
        @param virgin: manipulate session state »virgin« by giving a pre-set value
        @type virgin: C{bool}
        @param running: manipulate session state »running« by giving a pre-set value
        @type running: C{bool}
        @param suspended: manipulate session state »suspended« by giving a pre-set value
        @type suspended: C{bool}
        @param terminated: manipulate session state »terminated« by giving a pre-set value
        @type terminated: C{bool}
        @param faulty: manipulate session state »faulty« by giving a pre-set value
        @type faulty: C{bool}
        @param client_instance: if available, the underlying L{X2goClient} instance
        @type client_instance: C{X2goClient} instance
        @param params: further control session, terminal session and SSH proxy class options
        @type params: C{dict}

        """
        if logger is None:
            self.logger = log.X2goLogger(loglevel=loglevel)
        else:
            self.logger = copy.deepcopy(logger)
        self.logger.tag = __NAME__

        self._keep = None

        self.uuid = uuid.uuid1()
        self.connected = connected

        self.virgin = virgin
        self.running = running
        self.suspended = suspended
        self.terminated = terminated
        self.faulty = faulty
        self.keep_controlsession_alive = keep_controlsession_alive

        self.profile_id = profile_id
        self.profile_name = profile_name
        self.session_name = session_name
        self.server = server

        self._last_status = None

        self.locked = False

        self.printing = printing
        self.allow_share_local_folders = allow_share_local_folders
        self.share_local_folders = share_local_folders
        self.allow_mimebox = allow_mimebox
        self.mimebox_extensions = mimebox_extensions
        self.mimebox_action = mimebox_action
        self.control_backend = control_backend
        self.terminal_backend = terminal_backend
        self.info_backend = info_backend
        self.list_backend = list_backend
        self.proxy_backend = proxy_backend
        self.settings_backend = settings_backend
        self.printing_backend = printing_backend
        self.client_rootdir = client_rootdir
        self.sessions_rootdir = sessions_rootdir
        self.ssh_rootdir = ssh_rootdir
        self.control_session = control_session

        self.control_params = {}
        self.terminal_params = {}
        self.sshproxy_params = {}
        self.update_params(params)
        self.shared_folders = []

        self.session_environment = {}

        try: del self.control_params['server']
        except: pass

        self.client_instance = client_instance

        if self.logger.get_loglevel() & log.loglevel_DEBUG:
            self.logger('X2go control session parameters for profile %s:' % profile_name, loglevel=log.loglevel_DEBUG)
            for p in self.control_params:
                self.logger('    %s: %s' % (p, self.control_params[p]), log.loglevel_DEBUG)
            self.logger('X2go terminal session parameters for profile %s:' % profile_name, loglevel=log.loglevel_DEBUG)
            for p in self.terminal_params:
                self.logger('    %s: %s' % (p,self.terminal_params[p]), log.loglevel_DEBUG)
            self.logger('X2go sshproxy parameters for profile %s:' % profile_name, loglevel=log.loglevel_DEBUG)
            for p in self.sshproxy_params:
                self.logger('    %s: %s' % (p,self.sshproxy_params[p]), loglevel=log.loglevel_DEBUG)

        self.add_to_known_hosts = add_to_known_hosts
        self.known_hosts = known_hosts
        self.use_sshproxy = use_sshproxy

        self._current_status = {
            'timestamp': time.time(),
            'server': self.server,
            'virgin': self.virgin,
            'connected': self.connected,
            'running': self.running,
            'suspended': self.suspended,
            'terminated': self.terminated,
            'faulty': self.faulty,
        }

        self._SUPPORTED_SOUND = SUPPORTED_SOUND
        self._SUPPORTED_PRINTING = SUPPORTED_PRINTING
        self._SUPPORTED_MIMEBOX = SUPPORTED_MIMEBOX
        self._SUPPORTED_FOLDERSHARING = SUPPORTED_FOLDERSHARING

        self.init_control_session()
        self.terminal_session = None

    def HOOK_session_startup_failed(self):
        """\
        HOOK method: called if the startup of a session failed.

        """
        if self.client_instance:
            self.client_instance.HOOK_session_startup_failed(profile_name=self.profile_name)
        else:
            self.logger('HOOK_session_startup_failed: session startup for session profile ,,%s'' failed.' % self.profile_name, loglevel=log.loglevel_WARN)

    def HOOK_rforward_request_denied(self, server_port=0):
        """\
        HOOK method: called if a reverse port forwarding request has been denied.

        @param server_port: remote server port (starting point of reverse forwarding tunnel)
        @type server_port: C{str}

        """
        if self.client_instance:
            self.client_instance.HOOK_rforward_request_denied(profile_name=self.profile_name, session_name=self.session_name, server_port=server_port)
        else:
            self.logger('HOOK_rforward_request_denied: TCP port (reverse) forwarding request for session %s to server port %s has been denied by server %s. This is a common issue with SSH, it might help to restart the server\'s SSH daemon.' % (self.session_name, server_port, self.profile_name), loglevel=log.loglevel_WARN)

    def HOOK_forwarding_tunnel_setup_failed(self, chain_host='UNKNOWN', chain_port=0):
        """\
        HOOK method: called if a port forwarding tunnel setup failed.

        @param chain_host: hostname of chain host (forwarding tunnel end point)
        @type chain_host: C{str}
        @param chain_port: port of chain host (forwarding tunnel end point)
        @type chain_port: C{str}

        """
        # mark session as faulty
        self.faulty = True

        if self.client_instance:
            self.client_instance.HOOK_forwarding_tunnel_setup_failed(profile_name=self.profile_name, session_name=self.session_name, chain_host=chain_host, chain_port=chain_port)
        else:
            self.logger('HOOK_forwarding_tunnel_setup_failed: Forwarding tunnel request to [%s]:%s for session %s (%s) was denied by remote X2go/SSH server. Session startup failed.' % (chain_host, chain_port, self.session_name, self.profile_name), loglevel=log.loglevel_WARN)

        # get rid of the faulty session...
        self.terminate()

    def HOOK_check_host_dialog(self, host, port, fingerprint='no fingerprint', fingerprint_type='RSA'):
        """\
        HOOK method: called if a host check is requested. This hook has to either return C{True} (default) or C{False}.

        @param host: SSH server name to validate
        @type host: C{str}
        @param port: SSH server port to validate
        @type port: C{int}
        @param fingerprint: the server's fingerprint
        @type fingerprint: C{str}
        @param fingerprint_type: finger print type (like RSA, DSA, ...)
        @type fingerprint_type: C{str}
        @return: if host validity is verified, this hook method should return C{True}
        @rtype: C{bool}

        """
        if self.client_instance:
            return self.client_instance.HOOK_check_host_dialog(profile_name=self.profile_name, host=host, port=port, fingerprint=fingerprint, fingerprint_type=fingerprint_type)
        else:
            self.logger('HOOK_check_host_dialog: host check requested for [%s]:%s with %s fingerprint: ,,%s.\'\'. Automatically adding host as known host.' % (host, port, fingerprint_type, fingerprint), loglevel=log.loglevel_WARN)
            return True

    def init_control_session(self):
        """\
        Initialize a new control session (C{X2goControlSession*}).

        """
        if self.control_session is None:
            self.logger('initializing X2goControlSession', loglevel=log.loglevel_DEBUG)
            self.control_session = self.control_backend(profile_name=self.profile_name,
                                                        add_to_known_hosts=self.add_to_known_hosts,
                                                        known_hosts=self.known_hosts,
                                                        terminal_backend=self.terminal_backend,
                                                        info_backend=self.info_backend,
                                                        list_backend=self.list_backend,
                                                        proxy_backend=self.proxy_backend,
                                                        client_rootdir=self.client_rootdir,
                                                        sessions_rootdir=self.sessions_rootdir,
                                                        ssh_rootdir=self.ssh_rootdir,
                                                        logger=self.logger)

    def set_server(self, server):
        """\
        Modify server name after L{X2goSession} has already been initialized.

        @param server: new server name
        @type server: C{str}

        """
        self.server = server

    def set_profile_name(self, profile_name):
        """\
        Modify session profile name after L{X2goSession} has already been initialized.

        @param profile_name: new session profile name
        @type profile_name: C{str}

        """
        self.profile_name = profile_name
        self.control_session.set_profile_name(profile_name)

    def __str__(self):
        return self.__get_uuid()

    def __repr__(self):
        result = 'X2goSession('
        for p in dir(self):
            if '__' in p or not p in self.__dict__ or type(p) is types.InstanceType: continue
            result += p + '=' + str(self.__dict__[p]) + ', '
        return result + ')'

    def __call__(self):
        return self.__get_uuid()

    def __del__(self):
        """\
        Class destructor.

        """
        if self.has_control_session() and self.has_terminal_session():
            self.get_control_session().dissociate(self.get_terminal_session())

        if self.has_control_session():
            if self.keep_controlsession_alive:
                # regenerate this session instance for re-usage if this is the last session for a certain session profile
                # and keep_controlsession_alive is set to True...
                self.virgin = True
                self.connected = self.is_connected()
                self.running = None
                self.suspended = None
                self.terminated = None
                self._current_status = {
                    'timestamp': time.time(),
                    'server': self.server,
                    'virgin': self.virgin,
                    'connected': self.connected,
                    'running': self.running,
                    'suspended': self.suspended,
                    'terminated': self.terminated,
                    'faulty': self.faulty,
                }
                self._last_status = None
                self.session_name = None

            else:
                self.get_control_session().__del__()
                self.control_session = None

        if self.has_terminal_session():
            self.get_terminal_session().__del__()
            self.terminal_session = None

    def update_params(self, params):
        """\
        This method can be used to modify L{X2goSession} parameters after the
        L{X2goSession} instance has already been initialized.

        @param params: a Python dictionary with L{X2goSession} parameters
        @type params: C{dict}

        """
        try: del params['server'] 
        except KeyError: pass
        try: del params['profile_name']
        except KeyError: pass
        try: del params['profile_id'] 
        except KeyError: pass
        try:
            self.printing = params['printing']
            del params['printing'] 
        except KeyError: pass
        try: 
            self.allow_share_local_folders = params['allow_share_local_folders']
            del params['allow_share_local_folders']
        except KeyError: pass
        try:
            self.share_local_folders = params['share_local_folders']
            del params['share_local_folders'] 
        except KeyError: pass
        try:
            self.allow_mimebox = params['allow_mimebox']
            del params['allow_mimebox']
        except KeyError: pass
        try:
            self.mimebox_extensions = params['mimebox_extensions']
            del params['mimebox_extensions']
        except KeyError: pass
        try: 
            self.mimebox_action = params['mimebox_action']
            del params['mimebox_action']
        except KeyError: pass
        try:
            self.use_sshproxy = params['use_sshproxy']
            del params['use_sshproxy']
        except KeyError: pass

        _terminal_params = copy.deepcopy(params)
        _control_params = copy.deepcopy(params)
        _sshproxy_params = copy.deepcopy(params)
        for p in params.keys():
            if p in session._X2GO_SESSION_PARAMS:
                del _control_params[p]
                del _sshproxy_params[p]
            elif p in session._X2GO_SSHPROXY_PARAMS:
                del _control_params[p]
                del _terminal_params[p]
            else:
                del _sshproxy_params[p]
                del _terminal_params[p]

        self.control_params.update(_control_params)
        self.terminal_params.update(_terminal_params)
        self.sshproxy_params.update(_sshproxy_params)

    def get_uuid(self):
        """\
        Retrieve session UUID hash for this L{X2goSession}.

        """
        return str(self.uuid)
    __get_uuid = get_uuid

    def get_username(self):
        """\
        After a session has been set up you can query the
        username the sessions runs as.

        @return: the remote username the X2go session runs as
        @rtype: C{str}

        """
        # try to retrieve the username from the control session, if already connected
        try:
            return self.control_session.get_transport().get_username()
        except AttributeError:
            return self.control_params['username']
    __get_username = get_username


    def user_is_x2gouser(self, username=None):
        """\
        Check if a given user is valid server-side X2go user.

        @param username: username to check validity for
        @type username: C{str}
        @return: return C{True} if the username is allowed to launch X2go sessions
        @rtype: C{bool}

        """
        if username is None:
            username = self.__get_username()
        return self.control_session.is_x2gouser(username)
    __user_is_x2gouser = user_is_x2gouser

    def get_password(self):
        """\
        After a session has been setup up you can query the
        username's password from the session.

        @return: the username's password
        @rtype: C{str}

        """
        return self.control_session._session_password
    __get_password = get_password

    def get_server_peername(self):
        """\
        After a session has been setup up you can query the
        peername of the host this session is connected to (or
        about to connect to).

        @return: the address of the server the X2go session is
            connected to (as an C{(addr,port)} tuple)
        @rtype: C{tuple}

        """
        return self.control_session.get_transport().getpeername()
    __get_server_peername = get_server_peername

    def get_server_hostname(self):
        """\
        After a session has been setup up you can query the
        hostname of the host this session is connected to (or
        about to connect to).

        @return: the hostname of the server the X2go session is
            connected to / about to connect to
        @rtype: C{str}

        """
        self.server = self.control_session.hostname
        return self.server
    __get_server_hostname = get_server_hostname

    def get_server_port(self):
        """\
        After a session has been setup up you can query the
        IP socket port used for connecting the remote X2go server.

        @return: the server-side IP socket port that is used by the X2go session to
            connect to the server
        @rtype: C{str}

        """
        return self.control_session.port
    __get_server_port = get_server_port

    def get_session_name(self):
        """\
        Retrieve the server-side X2go session name for this session.

        @return: X2go session name
        @rtype: C{str}

        """
        return self.session_name
    __get_session_name = get_session_name

    def get_session_cmd(self):
        """\
        Retrieve the server-side command that is used to start a session
        on the remote X2go server.

        @return: server-side session command
        @rtype: C{str}

        """
        if self.terminal_params.has_key('cmd'):
            return self.terminal_params['cmd']
        return None
    __get_session_cmd = get_session_cmd

    def get_control_session(self):
        """\
        Retrieve the control session (C{X2goControlSession*} backend) of this L{X2goSession}.

        @return: the L{X2goSession}'s control session
        @rtype: C{X2goControlSession*} instance
        """
        return self.control_session
    __get_control_session = get_control_session

    def has_control_session(self):
        """\
        Check if this L{X2goSession} instance has an associated control session.

        @return: returns C{True} if this L{X2goSession} has a control session associated to itself
        @rtype: C{bool}

        """
        return self.control_session is not None
    __has_control_session = has_control_session

    def get_terminal_session(self):
        """\
        Retrieve the terminal session (C{X2goTerminalSession*} backend) of this L{X2goSession}.

        @return: the L{X2goSession}'s terminal session
        @rtype: C{X2goControlTerminal*} instance

        """
        if self.terminal_session == 'PENDING':
            return None
        return self.terminal_session
    __get_terminal_session = get_terminal_session

    def has_terminal_session(self):
        """\
        Check if this L{X2goSession} instance has an associated terminal session.

        @return: returns C{True} if this L{X2goSession} has a terminal session associated to itself
        @rtype: C{bool}


        """
        return self.terminal_session not in (None, 'PENDING')
    __has_terminal_session = has_terminal_session

    def check_host(self):
        """\
        Provide a host check mechanism. This method basically calls the L{HOOK_check_host_dialog()} method
        which by itself calls the L{X2goClient.HOOK_check_host_dialog()} method. Make sure you
        override any of these to enable user interaction on X2go server validity checks.

        @return: returns C{True} if an X2go server host is valid for authentication
        @rtype: C{bool}

        """
        if self.connected:
            return True

        _port = self.control_params['port']
        (_valid, _host, _port, _fingerprint, _fingerprint_type) = self.control_session.check_host(self.server, port=_port)
        return _valid or self.HOOK_check_host_dialog(host=_host, port=_port, fingerprint=_fingerprint, fingerprint_type=_fingerprint_type)
    __check_host = check_host

    def uses_sshproxy(self):
        """\
        Check if a session is configured to use an intermediate SSH proxy server.

        @return: returns C{True} if the session is configured to use an SSH proxy, C{False} otherwise.
        @rtype: C{bool}

        """
        return self.use_sshproxy

    def can_sshproxy_auto_connect(self):
        """\
        Check if a session's SSH proxy (if used) is configured adequately to be able to auto-connect
        to the SSH proxy server (e.g. by public key authentication).

        @return: returns C{True} if the session's SSH proxy can auto-connect, C{False} otherwise, C{None}
            if no SSH proxy is used for this session, C{None} is returned.
        @rtype: C{bool}

        """
        if self.use_sshproxy:
            if self.sshproxy_params.has_key('sshproxy_key_filename') and self.sshproxy_params['sshproxy_key_filename'] and os.path.exists(os.path.normpath(self.sshproxy_params['sshproxy_key_filename'])):
                return True
            elif self.sshproxy_params.has_key('sshproxy_pkey') and self.sshproxy_params['sshproxy_pkey']:
                return True
            else:
                return False
        else:
            return None
    __can_sshproxy_auto_connect = can_sshproxy_auto_connect

    def can_auto_connect(self):
        """\
        Check if a session is configured adequately to be able to auto-connect to the X2go
        server (e.g. public key authentication).

        @return: returns C{True} if the session can auto-connect, C{False} otherwise, C{None}
            if no control session has been set up yet.
        @rtype: C{bool}

        """
        if self.control_session is None:
            return None

        # do we have a key file passed as control parameter?
        if self.control_params.has_key('key_filename') and self.control_params['key_filename'] and os.path.exists(os.path.normpath(self.control_params['key_filename'])):
            _can_sshproxy_auto_connect = self.can_sshproxy_auto_connect()
            if _can_sshproxy_auto_connect is not None:
                return _can_sshproxy_auto_connect
            else:
                return True

        # or a private key?
        elif self.control_params.has_key('pkey') and self.control_params['pkey']:
            _can_sshproxy_auto_connect = self.can_sshproxy_auto_connect()
            if _can_sshproxy_auto_connect is not None:
                return _can_sshproxy_auto_connect
            else:
                return True

        else:
            return False
    __can_auto_connect = can_auto_connect

    def connect(self, username='', password='', add_to_known_hosts=False, force_password_auth=False,
                use_sshproxy=False, sshproxy_user='', sshproxy_password=''):
        """\
        Connects to the L{X2goSession}'s server host. This method basically wraps around 
        the C{X2goControlSession*.connect()} method.

        @param username: the username for the X2go server that is going to be
            connected to (as a last minute way of changing the session username)
        @type username: C{str}
        @param password: the user's password for the X2go server that is going to be
            connected to
        @type password: C{str}
        @param add_to_known_hosts: non-paramiko option, if C{True} paramiko.AutoAddPolicy()
            is used as missing-host-key-policy. If set to C{False} paramiko.RejectPolicy()
            is used
        @type add_to_known_hosts: C{bool}
        @param force_password_auth: disable SSH pub/priv key authentication mechanisms
            completely
        @type force_password_auth: C{bool}
        @param use_sshproxy: use an SSH proxy host for connecting the target X2go server
        @type use_sshproxy: C{bool}
        @param sshproxy_user: username for authentication against the SSH proxy host
        @type sshproxy_user: C{str}
        @param sshproxy_password: password for authentication against the SSH proxy host
        @type sshproxy_password: C{str}

        @return: returns C{True} is the connection to the X2go server has been successful
        @rtype C{bool}

        """
        if self.control_session and self.control_session.is_connected():
            self.logger('control session is already connected, skipping authentication', loglevel=log.loglevel_DEBUG)
            self.connected = True
        else:
            if username:
                self.control_params['username'] = username
            if add_to_known_hosts is not None:
                self.control_params['add_to_known_hosts'] = add_to_known_hosts
            if force_password_auth is not None:
                self.control_params['force_password_auth'] = force_password_auth
            if sshproxy_user:
                self.sshproxy_params['sshproxy_user'] = sshproxy_user
            if sshproxy_password:
                self.sshproxy_params['sshproxy_password'] = sshproxy_password
            self.control_params['password'] = password

            _params = {}
            _params.update(self.control_params)
            _params.update(self.sshproxy_params)

            try:
                self.connected = self.control_session.connect(self.server,
                                                              use_sshproxy=self.use_sshproxy, 
                                                              session_instance=self, 
                                                              **_params)
            except X2goControlSessionException, e:
                raise X2goSessionException(str(e))
            except X2goRemoteHomeException, e:
                self.disconnect()
                raise e
            except:
                # remove credentials immediately
                self.control_params['password'] = ''
                if self.sshproxy_params and self.sshproxy_params.has_key('sshproxy_password'):
                    del self.sshproxy_params['sshproxy_password']
                raise
            finally:
                # remove credentials immediately
                self.control_params['password'] = ''
                if self.sshproxy_params and self.sshproxy_params.has_key('sshproxy_password'):
                    del self.sshproxy_params['sshproxy_password']

            if not self.connected:
                # then tidy up...
                self.disconnect()

            _dummy = self.get_server_hostname()

        if self.connected:
            self.update_status()

        return self.connected
    __connect = connect

    def disconnect(self):
        """\
        Disconnect this L{X2goSession} instance.

        @return: returns C{True} if the disconnect operation has been successful
        @rtype: C{bool}

        """
        self.connected = False
        self.running = None
        self.suspended = None
        self.terminated = None
        self.faults = None
        try:
            self.update_status(force_update=True)
        except X2goControlSessionException:
            pass
        retval = self.control_session.disconnect()
        return retval
    __disconnect = disconnect

    def set_print_action(self, print_action, **kwargs):
        """\
        If X2go client-side printing is enable within this X2go session you can use
        this method to alter the way how incoming print spool jobs are handled/processed.

        For further information, please refer to the documentation of the L{X2goClient.set_session_print_action()}
        method.

        @param print_action: one of the named above print actions, either as string or class instance
        @type print_action: C{str} or C{instance}
        @param kwargs: additional information for the given print action (print 
            action arguments), for possible print action arguments and their values see each individual
            print action class
        @type kwargs: C{dict}

        """
        if type(print_action) is not types.StringType:
            return False
        self.terminal_session.set_print_action(print_action, **kwargs)
    __set_print_action = set_print_action

    def is_alive(self):
        """\
        Find out if this X2go session is still alive (that is: connected to the server).

        @return: returns C{True} if the server connection is still alive
        @rtype: C{bool}

        """
        self.connected = self.control_session.is_alive()
        if not self.connected:
            self._X2goSession__disconnect()
        return self.connected
    __is_alive = is_alive

    def clean_sessions(self, destroy_terminals=True):
        """\
        Clean all running sessions for the authenticated user on the remote X2go server.

        """
        if self.is_alive():
            self.control_session.clean_sessions(destroy_terminals=destroy_terminals)
        else:
            self._X2goSession__disconnect()
    __clean_sessions = clean_sessions

    def list_sessions(self, raw=False):
        """\
        List all sessions on the remote X2go server that are owned by the authenticated user 

        @param raw: if C{True} the output of this method equals
            the output of the server-side C{x2golistsessions} command
        @type raw: C{bool}

        @return: a session list (as data object or list of strings when called with C{raw=True} option)
        @rtype: C{X2goServerSessionList*} instance or C{list}

        """
        try:
            return self.control_session.list_sessions(raw=raw)
        except X2goControlSessionException:
            self._X2goSession__disconnect()
            return None
    __list_sessions = list_sessions

    def list_desktops(self, raw=False):
        """\
        List X2go desktops sessions available for desktop sharing on the remote X2go server.

        @param raw: if C{True} the output of this method equals
            the output of the server-side C{x2golistdesktops} command
        @type raw: C{bool}

        @return: a list of strings representing available desktop sessions
        @rtype: C{list}

        """
        try:
            return self.control_session.list_desktops(raw=raw)
        except X2goDesktopSharingException:
            if raw:
                return ('','')
            else:
                return []
        except X2goControlSessionException:
            self._X2goSession__disconnect()
            return None
    __list_desktops = list_desktops

    def update_status(self, session_list=None, force_update=False):
        """\
        Update the current session status. The L{X2goSession} instance uses an internal
        session status cache that allows to query the session status without the need
        of retrieving data from the remote X2go server for each query.

        The session status (if initialized properly with the L{X2goClient} constructor gets
        updated in regularly intervals.

        In case you use the L{X2goSession} class in standalone instances (that is: without
        being embedded into an L{X2goSession} context) then run this method in regular
        intervals to make sure the L{X2goSession}'s internal status cache information
        is always up-to-date.

        @param session_list: provide an C{X2goServerSessionList*} that refers to X2go sessions we want to update.
            This option is mainly for reducing server/client traffic.
        @type session_list: C{X2goServerSessionList*} instance
        @param force_update: force a session status update, if if the last update is less then 1 second ago
        @type force_update: C{bool}

        """
        if not force_update and self._last_status is not None:
            _status_update_timedelta = time.time() - self._last_status['timestamp']

            # skip this session status update if not longer than a second ago...
            if  _status_update_timedelta < 1:
                self.logger('status update interval too short (%s), skipping status update this time...' % _status_update_timedelta, loglevel=log.loglevel_DEBUG)
                return False

        e = None
        self._last_status = copy.deepcopy(self._current_status)
        if session_list is None:
            try:
                session_list = self.control_session.list_sessions()
                self.connected = True
            except X2goControlSessionException, e:
                self.connected = False
                self.running = None
                self.suspended = None
                self.terminated = None
                self.faulty = None

        if self.connected:
            try:
                _session_name = self.get_session_name()
                _session_info = session_list[_session_name]
                self.running = _session_info.is_running()
                self.suspended = _session_info.is_suspended()
                if not self.virgin:
                    self.terminated = not (self.running or self.suspended)
                else:
                    self.terminated = None
            except KeyError:
                self.running = False
                self.suspended = False
                if not self.virgin:
                    self.terminated = True
            self.faulty = not (self.running or self.suspended or self.terminated or self.virgin)


        self._current_status = {
            'timestamp': time.time(),
            'server': self.server,
            'virgin': self.virgin,
            'connected': self.connected,
            'running': self.running,
            'suspended': self.suspended,
            'terminated': self.terminated,
            'faulty': self.faulty,
        }

        if (not self.connected or self.faulty) and e:
            raise e

        return True

    __update_status = update_status

    def resume(self, session_name=None):
        """\
        Resume or continue a suspended / running X2go session on the
        remote X2go server.

        @param session_name: the server-side name of an X2go session
        @type session_name: C{str}

        @return: returns C{True} if resuming the session has been successful, C{False} otherwise
        @rtype: C{bool}

        """
        self.terminal_session = 'PENDING'
        _new_session = False
        if self.session_name is None:
            self.session_name = session_name

        if self.is_alive():
            _control = self.control_session

            # FIXME: normally this part gets called if you suspend a session that is associated to another client
            # we do not have a possibility to really check if SSH has released port forwarding channels or
            # sockets, thus  we plainly have to wait a while
            if self.is_running():
                self.suspend()
                gevent.sleep(10)

            self.terminal_session = _control.resume(session_name=self.session_name,
                                                    session_instance=self,
                                                    logger=self.logger, **self.terminal_params)

            if self.session_name is None:
                _new_session = True
                try:
                    self.session_name = self.terminal_session.session_info.name
                except AttributeError:
                    self.HOOK_session_startup_failed()
                    return False

            if self.has_terminal_session() and not self.faulty:

                # only run the session startup command if we do not resume...
                if _new_session:
                    self.terminal_session.run_command(env=self.session_environment)

                if self._SUPPORTED_SOUND and self.terminal_session.params.snd_system is not 'none':
                    self.terminal_session and not self.faulty and self.terminal_session.start_sound()
                else:
                    self._SUPPORTED_SOUND = False

                try:
                    if (self._SUPPORTED_PRINTING and self.printing) or \
                       (self._SUPPORTED_MIMEBOX and self.allow_mimebox) or \
                       (self._SUPPORTED_FOLDERSHARING and self.allow_share_local_folders):
                        self.terminal_session and not self.faulty and self.terminal_session.start_sshfs()
                except X2goUserException, e:
                    self.logger('%s' % str(e), loglevel=log.loglevel_WARN)
                    # TODO: handle this exception as a notification hook method...
                    self._SUPPORTED_PRINTING = False
                    self._SUPPORTED_MIMEBOX = False
                    self._SUPPORTED_FOLDERSHARING = False

                try:
                    if SUPPORTED_PRINTING and self.printing:
                        self.terminal_session and not self.faulty and self.terminal_session.start_printing()
                        self.terminal_session and not self.faulty and self.session_environment.update({'X2GO_SPOOLDIR': self.terminal_session.get_printing_spooldir(), })
                except X2goUserException, e:
                    self.logger('%s' % str(e), loglevel=log.loglevel_WARN)
                    # TODO: handle this exception as a notification hook method...
                    self._SUPPORTED_PRINTING = False

                if self._SUPPORTED_MIMEBOX and self.allow_mimebox:
                    self.terminal_session and not self.faulty and self.terminal_session.start_mimebox(mimebox_extensions=self.mimebox_extensions, mimebox_action=self.mimebox_action)
                    self.terminal_session and self.session_environment.update({'X2GO_MIMEBOX': self.terminal_session.get_mimebox_spooldir(), })

                if self.share_local_folders and self.terminal_session and not self.faulty and self.is_folder_sharing_available():
                    if _control.get_transport().reverse_tunnels[self.terminal_session.get_session_name()]['sshfs'][1] is not None:
                        for _folder in self.share_local_folders:
                            self.share_local_folder(_folder)

                self.virgin = False
                self.suspended = False
                self.running = True
                self.terminated = False
                self.faulty = False

                return True

            else:
                self.terminal_session = None
                return False

            return self.running
        else:
            self._X2goSession__disconnect()
            return False

    __resume = resume

    def start(self):
        """\
        Start a new X2go session on the remote X2go server.

        @return: returns C{True} if starting the session has been successful, C{False} otherwise
        @rtype: C{bool}

        """
        self.session_name = None
        return self.resume()
    __start = start

    def share_desktop(self, desktop=None, user=None, display=None, share_mode=0, check_desktop_list=True):
        """\
        Share an already running X2go session on the remote X2go server locally. The shared session may be either
        owned by the same user or by a user that grants access to his/her desktop session by the local user.

        @param desktop: desktop ID of a sharable desktop in format <user>@<display>
        @type desktop: C{str}
        @param user: user name and display number can be given separately, here give the
            name of the user who wants to share a session with you.
        @type user: C{str}
        @param display: user name and display number can be given separately, here give the
            number of the display that a user allows you to be shared with.
        @type display: C{str}
        @param share_mode: desktop sharing mode, 0 is VIEW-ONLY, 1 is FULL-ACCESS.
        @type share_mode: C{int}
        @param check_desktop_list: check if the given desktop is available on the X2go server; handle with care as
            the server-side C{x2golistdesktops} command might block client I/O.
        @type check_desktop_list: C{bool}

        @return: returns C{True} if starting the session has been successful, C{False} otherwise
        @rtype: C{bool}

        """
        self.terminal_session = 'PENDING'

        _desktop = desktop or '%s@%s' % (user, display)
        if check_desktop_list:
            if not _desktop in self._X2goSession__list_desktops():
                _orig_desktop = _desktop
                _desktop = '%s.0' % _desktop
                if not _desktop in self._X2GoSession__list_desktops():
                    raise X2goDesktopSharingException('No such desktop ID: %s' % _orig_desktop)

        _session_owner = _desktop.split('@')[0]
        _display = _desktop.split('@')[1]

        if self.is_alive():
            if self.get_username() != _session_owner:
                self.logger('waiting for user ,,%s\'\' to interactively grant you access to his/her desktop session...' % _session_owner, loglevel=log.loglevel_NOTICE)
                self.logger('THIS MAY TAKE A WHILE!', loglevel=log.loglevel_NOTICE)

            _control = self.control_session
            try:
                self.terminal_session = _control.share_desktop(desktop=_desktop, share_mode=share_mode,
                                                               logger=self.logger, **self.terminal_params)
            except ValueError:
                # x2gostartagent output parsing will result in a ValueError. This one we will catch
                # here and change it into an X2goSessionException
                raise X2goSessionException('the session on desktop %s is seemingly dead' % _desktop)

            if self.has_terminal_session():
                self.session_name = self.terminal_session.session_info.name

                # shared desktop sessions get their startup command set by the control
                # session, run this pre-set command now...
                self.terminal_session.run_command(env=self.session_environment)

                self.virgin = False
                self.suspended = False
                self.running = True
                self.terminated = False
                self.faulty = False

                return self.running
            else:
                self.terminal_session = None

        else:
            self._X2goSession__disconnect()

        return False
    __share_desktop = share_desktop

    def suspend(self):
        """\
        Suspend this X2go session.

        @return: returns C{True} if suspending the session has been successful, C{False} otherwise
        @rtype: C{bool}

        """
        if self.is_alive():
            if self.has_terminal_session():

                if self.terminal_session.suspend():

                    self.running = False
                    self.suspended = True
                    self.terminated = False
                    self.faults = False
                    self.session_cleanup()
                    return True

            elif self.has_control_session() and self.session_name:
                if self.control_session.suspend(session_name=self.session_name):

                    self.running = False
                    self.suspended = True
                    self.terminated = False
                    self.faulty = False
                    self.session_cleanup()
                    return True

            else:
                raise X2goClientException('cannot suspend session')

        else:
            self._X2goSession__disconnect()

        return False
    __suspend = suspend

    def terminate(self):
        """\
        Terminate this X2go session.

        @return: returns C{True} if terminating the session has been successful, C{False} otherwise
        @rtype: C{bool}

        """
        if self.is_alive():
            if self.has_terminal_session():

                if self.terminal_session.terminate():
                    self.running = False
                    self.suspended = False
                    self.terminated = True
                    self.faulty = False
                    self.session_cleanup()
                    return True

            elif self.has_control_session() and self.session_name:
                if self.control_session.terminate(session_name=self.session_name):

                    self.running = False
                    self.suspended = False
                    self.terminated = True
                    self.faulty = False
                    self.session_cleanup()
                    return True
            else:
                raise X2goClientException('cannot terminate session')

        else:
            self._X2goSession__disconnect()

        return False
    __terminate = terminate

    def get_profile_name(self):
        """\
        Retrieve the profile name of this L{X2goSession} instance.

        @return: X2go client profile name of the session
        @rtype: C{str}

        """
        return self.profile_name
    __get_profile_name = get_profile_name

    def get_profile_id(self):
        """\
        Retrieve the profile ID of this L{X2goSession} instance.

        @return: the session profile's id
        @rtype: C{str}

        """
        return self.profile_id
    __get_profile_id = get_profile_id

    ###
    ### QUERYING INFORMATION
    ###

    def session_ok(self):
        """\
        Test if this C{X2goSession} is
        in a healthy state.

        @return: C{BTrue} if session is ok, C{False} otherwise
        @rtype: C{bool}

        """
        if self.has_terminal_session():
            return self.terminal_session.ok()
        return False
    __session_ok = session_ok

    def color_depth_from_session_name(self):
        """\
        Extract color depth from session name.

        @return: the session's color depth (as found in the session name)
        @rtype: C{str}

        """
        return int(self.get_session_name().split('_')[2][2:])
    __color_depth_from_session_name = color_depth_from_session_name

    def is_color_depth_ok(self):
        """\
        Check if this session will display properly with the local screen's color depth.

        @return: C{True} if the session will display on this client screen, False otherwise. If no terminal session is yet registered with this session, C{None} is returned.
        @rtype C{bool}

        """
        return utils.is_color_depth_ok(depth_session=self.color_depth_from_session_name(), depth_local=utils.local_color_depth())
        __is_color_depth_ok = is_color_depth_ok

    def is_connected(self):
        """\
        Test if the L{X2goSession}'s control session is connected to the 
        remote X2go server.

        @return: C{True} if session is connected, C{False} otherwise
        @rtype: C{bool}

        """
        self.connected = bool(self.control_session and self.control_session.is_connected())
        if not self.connected:
            self.running = None
            self.suspended = None
            self.terminated = None
            self.faulty = None
        return self.connected
    __is_connected = is_connected

    def is_running(self):
        """\
        Test if the L{X2goSession}'s terminal session is up and running.

        @return: C{True} if session is running, C{False} otherwise
        @rtype: C{bool}

        """
        if self.is_connected():
            self.running = self.control_session.is_running(self.get_session_name())
            if self.running:
                self.suspended = False
                self.terminated = False
                self.faulty = False
            if self.virgin and not self.running:
                self.running = None
        return self.running
    __is_running = is_running

    def is_suspended(self):
        """\
        Test if the L{X2goSession}'s terminal session is in suspended state.

        @return: C{True} if session is suspended, C{False} otherwise
        @rtype: C{bool}

        """
        if self.is_connected():
            self.suspended = self.control_session.is_suspended(self.get_session_name())
            if self.suspended:
                self.running = False
                self.terminated = False
                self.faulty = False
            if self.virgin and not self.suspended:
                self.suspended = None
        return self.suspended
    __is_suspended = is_suspended

    def has_terminated(self):
        """\
        Test if the L{X2goSession}'s terminal session has terminated.

        @return: C{True} if session has terminated, C{False} otherwise
        @rtype: C{bool}

        """
        if self.is_connected():
            self.terminated = not self.virgin and self.control_session.has_terminated(self.get_session_name())
            if self.terminated:
                self.running = False
                self.suspended = False
                self.faulty = False
            if self.virgin and not self.terminated:
                self.terminated = None
        return self.terminated
    __has_terminated = has_terminated

    def is_folder_sharing_available(self):
        """\
        Test if the remote session allows sharing of local folders with the session.

        @return: returns C{True} if local folder sharing is available in the remote session
        @rtype: C{bool}

        """
        if self._SUPPORTED_FOLDERSHARING and self.allow_share_local_folders:
            if self.is_connected():
                return self.control_session.is_folder_sharing_available()
        else:
            self.logger('local folder sharing is disabled for this session profile', loglevel=log.loglevel_WARN)

    def share_local_folder(self, local_path=None, folder_name=None):
        """\
        Share a local folder with this registered X2go session.

        @param local_path: the full path to an existing folder on the local
            file system
        @type local_path: C{str}
        @param folder_name: synonymous to C{local_path}
        @type folder_name: C{str}

        @return: returns C{True} if the local folder has been successfully mounted within
            this X2go session
        @rtype: C{bool}

        """
        # compat for Python-X2go (<=0.1.1.6)
        if folder_name: local_path=folder_name

        if self.has_terminal_session():
            if self._SUPPORTED_FOLDERSHARING and self.allow_share_local_folders:
                if self.terminal_session.share_local_folder(local_path=local_path):
                    self.shared_folders.append(local_path)
                    return True
                return False
            else:
                self.logger('local folder sharing is disabled for this session profile', loglevel=log.loglevel_WARN)
        else:
            raise X2goSessionException('this X2goSession object does not have any associated terminal')
    __share_local_folder = share_local_folder

    def unshare_all_local_folders(self, force_all=False):
        """\
        Unshare all local folders mounted within this X2go session.

        @param force_all: Really unmount _all_ shared folders, including the print spool folder and
            the MIME box spool dir (not recommended).
        @type force_all: C{bool}

        @return: returns C{True} if all local folders could be successfully unmounted
            inside this X2go session
        @rtype: C{bool}

        """
        if self.has_terminal_session():
            if self._SUPPORTED_FOLDERSHARING and self.allow_share_local_folders:
                if force_all:
                    self.shared_folders = []
                    return self.terminal_session.unshare_all_local_folders()
                else:
                    retval = 0
                    for _shared_folder in self.shared_folders:
                        retval = retval | self.terminal_session.unshare_local_folder(_shared_folder)
                    self.shared_folders = []
                    return retval
            else:
                self.logger('local folder sharing is disabled for this session profile', loglevel=log.loglevel_WARN)
        else:
            raise X2goSessionException('this X2goSession object does not have any associated terminal')
        return False
    __unshare_all_local_folders = unshare_all_local_folders

    def unshare_local_folder(self, local_path=None):
        """\
        Unshare a local folder that is mounted within this X2go session.

        @param local_path: the full path to an existing folder on the local
            file system that is mounted in this X2go session and shall be
            unmounted
        @type local_path: C{str}
        @return: returns C{True} if all local folders could be successfully unmounted
            inside this X2go session
        @rtype: C{bool}

        """
        if self.has_terminal_session():
            if self._SUPPORTED_FOLDERSHARING and self.allow_share_local_folders and local_path in self.shared_folders:
                self.shared_folders.remove(local_path)
                return self.terminal_session.unshare_local_folder(local_path=local_path)
            else:
                self.logger('local folder sharing is disabled for this session profile', loglevel=log.loglevel_WARN)
        else:
            raise X2goSessionException('this X2goSession object does not have any associated terminal')
    __unshare_local_folder = unshare_local_folder

    def get_shared_folders(self):
        """\
        Get a list of local folders mounted within this X2go session from this client.

        @return: returns a C{list} of those folder names that are mounted with this X2go session.
        @rtype: C{list}

        """
        return self.shared_folders
    __get_shared_folders = get_shared_folders

    def is_locked(self):
        """\
        Query session if it is locked by some command being processed.

        @return: return C{True} is the session is locked, C{False} if not; returns None, if there is no
            control session yet.
        @rtype: C{bool}

        """
        if self.control_session is not None:
            return self.control_session.locked or self.locked
        return None

    def session_cleanup(self):
        """\
        Clean up X2go session.

        """
        # release terminal session's proxy
        if self.has_terminal_session():
            self.terminal_session.release_proxy()

        # unmount shared folders
        try:
            self.unshare_all_local_folders()
        except X2goSessionException:
            pass

        # remove client-side session cache
        if self.terminated and self.has_terminal_session():
            self.terminal_session.post_terminate_cleanup()

        # destroy terminal session
        if self.has_terminal_session():
            self.terminal_session.__del__()

        self.terminal_session = None