Welcome to mirror list, hosted at ThFree Co, Russian Federation.

remmina_ssh.c « src - gitlab.com/Remmina/Remmina.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7d904b129594c25fc445422293aac88b3046aba4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
/*
 * Remmina - The GTK+ Remote Desktop Client
 * Copyright (C) 2009-2011 Vic Lee
 * Copyright (C) 2014-2015 Antenore Gatta, Fabio Castelli, Giovanni Panozzo
 * Copyright (C) 2016-2019 Antenore Gatta, Giovanni Panozzo
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of portions of this program with the
 *  OpenSSL library under certain conditions as described in each
 *  individual source file, and distribute linked combinations
 *  including the two.
 *  You must obey the GNU General Public License in all respects
 *  for all of the code used other than OpenSSL. *  If you modify
 *  file(s) with this exception, you may extend this exception to your
 *  version of the file(s), but you are not obligated to do so. *  If you
 *  do not wish to do so, delete this exception statement from your
 *  version. *  If you delete this exception statement from all source
 *  files in the program, then also delete it here.
 *
 */

#include "config.h"

#ifdef HAVE_LIBSSH

/* Define this before stdlib.h to have posix_openpt */
#define _XOPEN_SOURCE 600

#define LIBSSH_STATIC 1
#include <libssh/libssh.h>
#include <gdk/gdkx.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <pthread.h>
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_PTY_H
#include <pty.h>
#endif
#include "remmina_public.h"
#include "remmina/types.h"
#include "remmina_file.h"
#include "remmina_log.h"
#include "remmina_pref.h"
#include "remmina_ssh.h"
#include "remmina_masterthread_exec.h"
#include "remmina/remmina_trace_calls.h"


#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>

#if defined(__FreeBSD__) || defined(__OpenBSD__)
#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif
#endif

#endif


/*-----------------------------------------------------------------------------*
*                           SSH Base                                          *
*-----------------------------------------------------------------------------*/

#define LOCK_SSH(ssh) pthread_mutex_lock(&REMMINA_SSH(ssh)->ssh_mutex);
#define UNLOCK_SSH(ssh) pthread_mutex_unlock(&REMMINA_SSH(ssh)->ssh_mutex);

static const gchar *common_identities[] =
{
	".ssh/id_ed25519",
	".ssh/id_rsa",
	".ssh/id_dsa",
	".ssh/identity",
	NULL
};

gchar *
remmina_ssh_identity_path(const gchar *id)
{
	TRACE_CALL(__func__);
	if (id == NULL) return NULL;
	if (id[0] == '/') return g_strdup(id);
	return g_strdup_printf("%s/%s", g_get_home_dir(), id);
}

gchar *
remmina_ssh_find_identity(void)
{
	TRACE_CALL(__func__);
	gchar *path;
	gint i;

	for (i = 0; common_identities[i]; i++) {
		path = remmina_ssh_identity_path(common_identities[i]);
		if (g_file_test(path, G_FILE_TEST_IS_REGULAR | G_FILE_TEST_EXISTS))
			return path;
		g_free(path);
	}
	return NULL;
}

void
remmina_ssh_set_error(RemminaSSH *ssh, const gchar *fmt)
{
	TRACE_CALL(__func__);
	const gchar *err;

	err = ssh_get_error(ssh->session);
	ssh->error = g_strdup_printf(fmt, err);
}

void
remmina_ssh_set_application_error(RemminaSSH *ssh, const gchar *fmt, ...)
{
	TRACE_CALL(__func__);
	va_list args;

	va_start(args, fmt);
	ssh->error = g_strdup_vprintf(fmt, args);
	va_end(args);
}

static gint
remmina_ssh_auth_interactive(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	gint ret;
	gint n;
	gint i;

	ret = SSH_AUTH_ERROR;
	if (ssh->authenticated) return 1;
	if (ssh->password == NULL) return -1;

	while ((ret = ssh_userauth_kbdint(ssh->session, NULL, NULL)) == SSH_AUTH_INFO) {
		n = ssh_userauth_kbdint_getnprompts(ssh->session);
		for (i = 0; i < n; i++)
			ssh_userauth_kbdint_setanswer(ssh->session, i, ssh->password);
	}

	if (ret != SSH_AUTH_SUCCESS)
		return 0;       // Generic error

	ssh->authenticated = TRUE;
	return 1;
}

static gint
remmina_ssh_auth_password(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	gint ret;

	ret = SSH_AUTH_ERROR;
	if (ssh->authenticated) return 1;
	if (ssh->password == NULL) return -1;

	ret = ssh_userauth_password(ssh->session, NULL, ssh->password);
	if (ret != SSH_AUTH_SUCCESS) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not authenticate with SSH password. %s"));
		return 0;
	}

	ssh->authenticated = TRUE;
	return 1;
}

static gint
remmina_ssh_auth_pubkey(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);

	ssh_key key = NULL;
	gchar pubkey[132] = { 0 }; // +".pub"
	gint ret;

	if (ssh->authenticated) return 1;

	if (ssh->privkeyfile == NULL) {
		// TRANSLATORS: The placeholder %s is an error message
		ssh->error = g_strdup_printf(_("Could not authenticate with public SSH key. %s"),
					     _("SSH Key file not yet set."));
		return 0;
	}

	g_snprintf(pubkey, sizeof(pubkey), "%s.pub", ssh->privkeyfile);

	/*G_FILE_TEST_EXISTS*/
	if (g_file_test(pubkey, G_FILE_TEST_EXISTS)) {
		ret = ssh_pki_import_pubkey_file(pubkey, &key);
		if (ret != SSH_OK) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(ssh, _("Public SSH key cannot be imported. %s"));
			return 0;
		}
		ssh_key_free(key);
	}


	if (ssh_pki_import_privkey_file(ssh->privkeyfile, (ssh->passphrase ? ssh->passphrase : ""),
					NULL, NULL, &key) != SSH_OK) {
		if (ssh->passphrase == NULL || ssh->passphrase[0] == '\0') return -1;

		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not authenticate with public SSH key. %s"));
		return 0;
	}

	ret = ssh_userauth_publickey(ssh->session, NULL, key);
	ssh_key_free(key);

	if (ret != SSH_AUTH_SUCCESS) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not authenticate with public SSH key. %s"));
		return 0;
	}

	ssh->authenticated = TRUE;
	return 1;
}

static gint
remmina_ssh_auth_auto_pubkey(RemminaSSH *ssh, RemminaProtocolWidget *gp, RemminaFile *remminafile)
{
	TRACE_CALL(__func__);

	gboolean disablepasswordstoring;
	gboolean save_password;
	gchar *pwd;
	gint ret;

	if (!ssh->passphrase) {
		disablepasswordstoring = remmina_file_get_int(remminafile, "disablepasswordstoring", FALSE);

		ret = remmina_protocol_widget_panel_auth(gp, (disablepasswordstoring ? 0 : REMMINA_MESSAGE_PANEL_FLAG_SAVEPASSWORD),
							 _("SSH credentials"), NULL,
							 remmina_file_get_string(remminafile, "ssh_passphrase"),
							 NULL,
							 _("SSH private key passphrase"));
		if (ret == GTK_RESPONSE_OK) {
			pwd = remmina_protocol_widget_get_password(gp);
			save_password = remmina_protocol_widget_get_savepassword(gp);
			if (save_password)
				remmina_file_set_string(remminafile, "ssh_passphrase", pwd);
			else
				remmina_file_set_string(remminafile, "ssh_passphrase", NULL);
		} else {
			return -1;
		}
		ssh->passphrase = pwd;
	}
	ret = ssh_userauth_publickey_auto(ssh->session, NULL, ssh->passphrase);

	if (ret != SSH_AUTH_SUCCESS) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not authenticate automatically with public SSH key. %s"));
		return -1;
	}

	ssh->authenticated = TRUE;
	return 1;
}

static gint
remmina_ssh_auth_agent(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	gint ret;
	ret = ssh_userauth_agent(ssh->session, NULL);

	if (ret != SSH_AUTH_SUCCESS) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not authenticate with public SSH key using SSH agent. %s"));
		return 0;
	}

	ssh->authenticated = TRUE;
	return 1;
}

static gint
remmina_ssh_auth_gssapi(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	gint ret;

	if (ssh->authenticated) return 1;

	ret = ssh_userauth_gssapi(ssh->session);

	if (ret != SSH_AUTH_SUCCESS) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not authenticate with SSH Kerberos/GSSAPI. %s"));
		return 0;
	}

	ssh->authenticated = TRUE;
	return 1;
}

gint
remmina_ssh_auth(RemminaSSH *ssh, const gchar *password, RemminaProtocolWidget *gp, RemminaFile *remminafile)
{
	TRACE_CALL(__func__);
	gint method;

	/* Check known host again to ensure it’s still the original server when user forks
	 * a new session from existing one */
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 9, 0)
	/* TODO: Add error checking
	 * SSH_KNOWN_HOSTS_OK: The server is known and has not changed.
	 *SSH_KNOWN_HOSTS_CHANGED: The server key has changed. Either you are under attack or the administrator changed the key. You HAVE to warn the user about a possible attack.
	 *SSH_KNOWN_HOSTS_OTHER: The server gave use a key of a type while we had an other type recorded. It is a possible attack.
	 *SSH_KNOWN_HOSTS_UNKNOWN: The server is unknown. User should confirm the public key hash is correct.
	 *SSH_KNOWN_HOSTS_NOT_FOUND: The known host file does not exist. The host is thus unknown. File will be created if host key is accepted.
	 *SSH_KNOWN_HOSTS_ERROR: There had been an error checking the host.
	 */
	if (ssh_session_is_known_server(ssh->session) != SSH_KNOWN_HOSTS_OK) {
#else
	if (ssh_is_server_known(ssh->session) != SSH_SERVER_KNOWN_OK) {
#endif
		remmina_ssh_set_application_error(ssh, _("The public SSH key changed!"));
		return 0;
	}

	if (password) {
		g_free(ssh->password);
		g_free(ssh->passphrase);
		ssh->password = g_strdup(password);
		ssh->passphrase = g_strdup(password);
	}

	/** @todo Here we should call
	 * gint method;
	 * method = ssh_userauth_list(ssh->session, NULL);
	 *
	 * SSH_AUTH_METHOD_PASSWORD
	 * SSH_AUTH_METHOD_PUBLICKEY
	 * SSH_AUTH_METHOD_HOSTBASED
	 * SSH_AUTH_METHOD_INTERACTIVE
	 *
	 * And than test both the method and the option selected by the user
	 */
	ssh_userauth_none (ssh->session, NULL);
	method = ssh_userauth_list(ssh->session, NULL);
	g_debug ("[SSH] method: %d", method);
	switch (ssh->auth) {
	case SSH_AUTH_PASSWORD:
		g_debug ("[SSH] ssh->auth: SSH_AUTH_PASSWORD (%d)", ssh->auth);
		if (ssh->authenticated)
			return 1;
		if (method & SSH_AUTH_METHOD_PASSWORD)
			if (remmina_ssh_auth_password(ssh) <= 0) {
				g_debug ("SSH using remmina_ssh_auth_password");
				return -1;              // Re-prompt password
			}
		if (method & SSH_AUTH_METHOD_INTERACTIVE) {
			/* SSH server is requesting us to do interactive auth.
			 * But we just send the saved password */
			if (remmina_ssh_auth_interactive(ssh) <= 0) {
				g_debug ("SSH using remmina_ssh_auth_interactive");
				return -1;      // Re-prompt password
			}
		}
		return 1;

	case SSH_AUTH_PUBLICKEY:
		g_debug ("[SSH] ssh->auth: SSH_AUTH_PUBLICKEY (%d)", ssh->auth);
		if (method & SSH_AUTH_METHOD_PUBLICKEY)
			return remmina_ssh_auth_pubkey(ssh);

	case SSH_AUTH_AGENT:
		g_debug ("[SSH] ssh->auth: SSH_AUTH_AGENT (%d)", ssh->auth);
		return remmina_ssh_auth_agent(ssh);

	case SSH_AUTH_AUTO_PUBLICKEY:
		g_debug ("[SSH] ssh->auth: SSH_AUTH_AUTO_PUBLICKEY (%d)", ssh->auth);
		/* ssh_agent or none */
		return remmina_ssh_auth_auto_pubkey(ssh, gp, remminafile);

#if 0
	/* Not yet supported by libssh */
	case SSH_AUTH_HOSTBASED:
		if (method & SSH_AUTH_METHOD_HOSTBASED)
			//return remmina_ssh_auth_hostbased;
			return 0;
#endif

	case SSH_AUTH_GSSAPI:
		g_debug ("[SSH] ssh->auth: SSH_AUTH_GSSAPI (%d)", ssh->auth);
		if (method & SSH_AUTH_METHOD_GSSAPI_MIC)
			return remmina_ssh_auth_gssapi(ssh);

	default:
		g_debug ("[SSH] ssh->auth: UNKNOWN (%d)", ssh->auth);
		return 0;
	}
}

gint
remmina_ssh_auth_gui(RemminaSSH *ssh, RemminaProtocolWidget *gp, RemminaFile *remminafile)
{
	TRACE_CALL(__func__);
	gchar *keyname;
	gchar *pwdtype;
	gchar *message;
	gint ret;
	size_t len;
	guchar *pubkey;
	ssh_key server_pubkey;
	gboolean disablepasswordstoring;
	gboolean save_password;

	/* Check if the server’s public key is known */
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 9, 0)
	/* TODO: Add error checking
	 * SSH_KNOWN_HOSTS_OK: The server is known and has not changed.
	 * SSH_KNOWN_HOSTS_CHANGED: The server key has changed. Either you are under attack or the administrator changed the key. You HAVE to warn the user about a possible attack.
	 * SSH_KNOWN_HOSTS_OTHER: The server gave use a key of a type while we had an other type recorded. It is a possible attack.
	 * SSH_KNOWN_HOSTS_UNKNOWN: The server is unknown. User should confirm the public key hash is correct.
	 * SSH_KNOWN_HOSTS_NOT_FOUND: The known host file does not exist. The host is thus unknown. File will be created if host key is accepted.
	 * SSH_KNOWN_HOSTS_ERROR: There had been an error checking the host.
	 */
	ret = ssh_session_is_known_server(ssh->session);
	switch (ret) {
	case SSH_KNOWN_HOSTS_OK:
		break;                          /* ok */

	/*  TODO: These are all wrong, we should deal with each of them */
	case SSH_KNOWN_HOSTS_CHANGED:
	case SSH_KNOWN_HOSTS_OTHER:
	case SSH_KNOWN_HOSTS_UNKNOWN:
	case SSH_KNOWN_HOSTS_NOT_FOUND:
#else
	ret = ssh_is_server_known(ssh->session);
	switch (ret) {
	case SSH_SERVER_KNOWN_OK:
		break;                          /* ok */

	/*  fallback to SSH_SERVER_NOT_KNOWN behavior */
	case SSH_SERVER_KNOWN_CHANGED:
	case SSH_SERVER_FOUND_OTHER:
	case SSH_SERVER_NOT_KNOWN:
	case SSH_SERVER_FILE_NOT_FOUND:
#endif
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 8, 6)
		if (ssh_get_server_publickey(ssh->session, &server_pubkey) != SSH_OK) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(ssh, _("Could not fetch the server\'s public SSH key. %s"));
			g_debug ("ssh_get_server_publickey() has failed");
			return 0;
		}
#else
		if (ssh_get_publickey(ssh->session, &server_pubkey) != SSH_OK) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(ssh, _("Could not fetch public SSH key. %s"));
			g_debug ("ssh_get_publickey() has failed");
			return 0;
		}
#endif
		if (ssh_get_publickey_hash(server_pubkey, SSH_PUBLICKEY_HASH_MD5, &pubkey, &len) != 0) {
			ssh_key_free(server_pubkey);
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(ssh, _("Could not fetch checksum for public SSH key. %s"));
			g_debug ("ssh_get_publickey_hash() has failed");
			return 0;
		}
		ssh_key_free(server_pubkey);
		keyname = ssh_get_hexa(pubkey, len);

#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 9, 0)
		if (ret == SSH_KNOWN_HOSTS_UNKNOWN || ret == SSH_KNOWN_HOSTS_NOT_FOUND) {
#else
		if (ret == SSH_SERVER_NOT_KNOWN || ret == SSH_SERVER_FILE_NOT_FOUND) {
#endif
			message = g_strdup_printf("%s\n%s\n\n%s",
						  _("The server is unknown. The public key fingerprint is:"),
						  keyname,
						  _("Do you trust the new public key?"));
		} else {
			message = g_strdup_printf("%s\n%s\n\n%s",
						  _("Warning: The server has changed its public key. This means either you are under attack,\n"
						    "or the administrator has changed the key. The new public key fingerprint is:"),
						  keyname,
						  _("Do you trust the new public key?"));
		}

		ret = remmina_protocol_widget_panel_question_yesno(gp, message);
		g_free(message);

		ssh_string_free_char(keyname);
		ssh_clean_pubkey_hash(&pubkey);
		if (ret != GTK_RESPONSE_YES) return -1;
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 9, 0)
		ssh_session_update_known_hosts(ssh->session);
#else
		ssh_write_knownhost(ssh->session);
#endif
		break;
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 9, 0)
	case SSH_KNOWN_HOSTS_ERROR:
#else
	case SSH_SERVER_ERROR:
#endif
	default:
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not check list of known SSH hosts. %s"));
		g_debug ("Could not check list of known SSH hosts");
		return 0;
	}

	switch (ssh->auth) {
	case SSH_AUTH_PASSWORD:
		keyname = _("SSH password");
		pwdtype = "ssh_password";
		break;
	case SSH_AUTH_PUBLICKEY:
	case SSH_AUTH_AGENT:
	case SSH_AUTH_AUTO_PUBLICKEY:
		keyname = _("SSH private key passphrase");
		pwdtype = "ssh_passphrase";
		break;
	case SSH_AUTH_GSSAPI:
		keyname = _("SSH Kerberos/GSSAPI");
		pwdtype = "kerberos_token";
		break;
	default:
		return FALSE;
	}
	/* Try empty password or existing password/passphrase first */
	ret = remmina_ssh_auth(ssh, remmina_file_get_string(remminafile, pwdtype), gp, remminafile);
	if (ret > 0) return 1;

	/* Requested for a non-empty password */
	if (ret < 0) {
		gchar *pwd;

		disablepasswordstoring = remmina_file_get_int(remminafile, "disablepasswordstoring", FALSE);

		if (g_strcmp0(pwdtype, "ssh_passphrase") == 0) {
			ret = remmina_protocol_widget_panel_auth(gp,
					(disablepasswordstoring ? 0 :
					 REMMINA_MESSAGE_PANEL_FLAG_SAVEPASSWORD),
					_("SSH credentials"), NULL,
					remmina_file_get_string(remminafile, "ssh_passphrase"),
					NULL,
					_("SSH private key passphrase"));
			if (ret == GTK_RESPONSE_OK) {
				pwd = remmina_protocol_widget_get_password(gp);
				save_password = remmina_protocol_widget_get_savepassword(gp);
				if (save_password)
					remmina_file_set_string(remminafile, "ssh_passphrase", pwd);
				else
					remmina_file_set_string(remminafile, "ssh_passphrase", NULL);
				g_free(pwd);
			} else {
				return -1;
			}
		} else if (g_strcmp0(pwdtype, "ssh_password") == 0) {
			ret = remmina_protocol_widget_panel_auth(gp,
					(disablepasswordstoring ? 0 : REMMINA_MESSAGE_PANEL_FLAG_SAVEPASSWORD)
					| REMMINA_MESSAGE_PANEL_FLAG_USERNAME,
					_("SSH credentials"),
					remmina_file_get_string(remminafile, "ssh_username"),
					remmina_file_get_string(remminafile, "ssh_password"),
					NULL,
					NULL);
			if (ret == GTK_RESPONSE_OK) {
				pwd = remmina_protocol_widget_get_username(gp);
				remmina_file_set_string(remminafile, "ssh_username", pwd);
				g_free(pwd);
				pwd = remmina_protocol_widget_get_password(gp);
				save_password = remmina_protocol_widget_get_savepassword(gp);
				if (save_password)
					remmina_file_set_string(remminafile, "ssh_password", pwd);
				else
					remmina_file_set_string(remminafile, "ssh_password", NULL);
				g_free(pwd);
			} else {
				return -1;
			}
		} else {
			/* ??? */
			ret = remmina_protocol_widget_panel_auth(gp, (disablepasswordstoring ? 0 : REMMINA_MESSAGE_PANEL_FLAG_SAVEPASSWORD) | REMMINA_MESSAGE_PANEL_FLAG_USERNAME,
								 _("SSH authentication"),
								 remmina_file_get_string(remminafile, "Username"),
								 remmina_file_get_string(remminafile, "Password"),
								 NULL,
								 NULL);
			if (ret == GTK_RESPONSE_OK) {
				pwd = remmina_protocol_widget_get_username(gp);
				remmina_file_set_string(remminafile, "Username", pwd);
				g_free(pwd);
				pwd = remmina_protocol_widget_get_password(gp);
				save_password = remmina_protocol_widget_get_savepassword(gp);
				if (save_password)
					remmina_file_set_string(remminafile, "Password", pwd);
				else
					remmina_file_set_string(remminafile, "Password", NULL);
				g_free(pwd);
			} else {
				return -1;
			}
		}

		pwd = remmina_protocol_widget_get_password(gp);
		ret = remmina_ssh_auth(ssh, pwd, gp, remminafile);
		g_free(pwd);
	}

	if (ret <= 0) {
		g_debug ("SSH Authentication failed");
		return 0;
	}

	return 1;
}

void
remmina_ssh_log_callback(ssh_session session, int priority, const char *message, void *userdata)
{
	TRACE_CALL(__func__);
	remmina_log_printf("[SSH] %s\n", message);
}

gboolean
remmina_ssh_init_session(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	gint verbosity;
	gint rc;
#ifdef HAVE_NETINET_TCP_H
	socket_t sshsock;
	gint optval;
#endif

	ssh->callback = g_new0(struct ssh_callbacks_struct, 1);

	/* Init & startup the SSH session */
	ssh->session = ssh_new();
	ssh_options_set(ssh->session, SSH_OPTIONS_HOST, ssh->server);
	ssh_options_set(ssh->session, SSH_OPTIONS_PORT, &ssh->port);
	if (*ssh->user != 0)
		ssh_options_set(ssh->session, SSH_OPTIONS_USER, ssh->user);
	if (ssh->privkeyfile && *ssh->privkeyfile != 0) {
		rc = ssh_options_set(ssh->session, SSH_OPTIONS_IDENTITY, ssh->privkeyfile);
		if (rc == 0)
			remmina_log_printf("[SSH] SSH_OPTIONS_IDENTITY is now %s\n", ssh->privkeyfile);
		else
			remmina_log_printf("[SSH] SSH_OPTIONS_IDENTITY is not set, by default the files \"identity\", \"id_dsa\" and \"id_rsa\" are used.\n");
	}

#ifdef SNAP_BUILD
	ssh_options_set(ssh->session, SSH_OPTIONS_SSH_DIR, g_strdup_printf("%s/.ssh", g_getenv("SNAP_USER_COMMON")));
#endif
	rc = ssh_options_set(ssh->session, SSH_OPTIONS_KEY_EXCHANGE, ssh->kex_algorithms);
	if (rc == 0)
		remmina_log_printf("[SSH] SSH_OPTIONS_KEY_EXCHANGE is now %s\n", ssh->kex_algorithms);
	else
		remmina_log_printf("[SSH] SSH_OPTIONS_KEY_EXCHANGE does not have a valid value. %s\n", ssh->kex_algorithms);
	rc = ssh_options_set(ssh->session, SSH_OPTIONS_CIPHERS_C_S, ssh->ciphers);
	if (rc == 0)
		remmina_log_printf("[SSH] SSH_OPTIONS_CIPHERS_C_S has been set to %s\n", ssh->ciphers);
	else
		remmina_log_printf("[SSH] SSH_OPTIONS_CIPHERS_C_S does not have a valid value. %s\n", ssh->ciphers);
	rc = ssh_options_set(ssh->session, SSH_OPTIONS_HOSTKEYS, ssh->hostkeytypes);
	if (rc == 0)
		remmina_log_printf("[SSH] SSH_OPTIONS_HOSTKEYS is now %s\n", ssh->hostkeytypes);
	else
		remmina_log_printf("[SSH] SSH_OPTIONS_HOSTKEYS does not have a valid value. %s\n", ssh->hostkeytypes);
	rc = ssh_options_set(ssh->session, SSH_OPTIONS_PROXYCOMMAND, ssh->proxycommand);
	if (rc == 0)
		remmina_log_printf("[SSH] SSH_OPTIONS_PROXYCOMMAND is now %s\n", ssh->proxycommand);
	else
		remmina_log_printf("[SSH] SSH_OPTIONS_PROXYCOMMAND does not have a valid value. %s\n", ssh->proxycommand);
	rc = ssh_options_set(ssh->session, SSH_OPTIONS_STRICTHOSTKEYCHECK, &ssh->stricthostkeycheck);
	if (rc == 0)
		remmina_log_printf("[SSH] SSH_OPTIONS_STRICTHOSTKEYCHECK is now %d\n", ssh->stricthostkeycheck);
	else
		remmina_log_printf("[SSH] SSH_OPTIONS_STRICTHOSTKEYCHECK does not have a valid value. %d\n", ssh->stricthostkeycheck);
	rc = ssh_options_set(ssh->session, SSH_OPTIONS_COMPRESSION, ssh->compression);
	if (rc == 0)
		remmina_log_printf("[SSH] SSH_OPTIONS_COMPRESSION is now %s\n", ssh->compression);
	else
		remmina_log_printf("[SSH] SSH_OPTIONS_COMPRESSION does not have a valid value. %s\n", ssh->compression);

	ssh_callbacks_init(ssh->callback);
	if (remmina_log_running()) {
		verbosity = remmina_pref.ssh_loglevel;
		ssh_options_set(ssh->session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
		ssh->callback->log_function = remmina_ssh_log_callback;
		/* Reset libssh legacy userdata. This is a workaround for a libssh bug */
		ssh_set_log_userdata(ssh->session);
	}
	ssh->callback->userdata = ssh;
	ssh_set_callbacks(ssh->session, ssh->callback);

	/* As the latest parse the ~/.ssh/config file */
	if (remmina_pref.ssh_parseconfig)
		ssh_options_parse_config(ssh->session, NULL);

	if (ssh_connect(ssh->session)) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(ssh, _("Could not start SSH session. %s"));
		return FALSE;
	}

#ifdef HAVE_NETINET_TCP_H
	/* Set keepalive on SSH socket, so we can keep firewalls awaken and detect
	 * when we loss the tunnel */
	sshsock = ssh_get_fd(ssh->session);
	if (sshsock >= 0) {
		optval = 1;
		if (setsockopt(sshsock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0)
			remmina_log_printf("[SSH] TCP KeepAlive not set\n");
		else
			remmina_log_printf("[SSH] TCP KeepAlive enabled\n");

#ifdef TCP_KEEPIDLE
		optval = remmina_pref.ssh_tcp_keepidle;
		if (setsockopt(sshsock, IPPROTO_TCP, TCP_KEEPIDLE, &optval, sizeof(optval)) < 0)
			remmina_log_printf("[SSH] TCP_KEEPIDLE not set\n");
		else
			remmina_log_printf("[SSH] TCP_KEEPIDLE set to %i\n", optval);

#endif
#ifdef TCP_KEEPCNT
		optval = remmina_pref.ssh_tcp_keepcnt;
		if (setsockopt(sshsock, IPPROTO_TCP, TCP_KEEPCNT, &optval, sizeof(optval)) < 0)
			remmina_log_printf("[SSH] TCP_KEEPCNT not set\n");
		else
			remmina_log_printf("[SSH] TCP_KEEPCNT set to %i\n", optval);

#endif
#ifdef TCP_KEEPINTVL
		optval = remmina_pref.ssh_tcp_keepintvl;
		if (setsockopt(sshsock, IPPROTO_TCP, TCP_KEEPINTVL, &optval, sizeof(optval)) < 0)
			remmina_log_printf("[SSH] TCP_KEEPINTVL not set\n");
		else
			remmina_log_printf("[SSH] TCP_KEEPINTVL set to %i\n", optval);

#endif
#ifdef TCP_USER_TIMEOUT
		optval = remmina_pref.ssh_tcp_usrtimeout;
		if (setsockopt(sshsock, IPPROTO_TCP, TCP_USER_TIMEOUT, &optval, sizeof(optval)) < 0)
			remmina_log_printf("[SSH] TCP_USER_TIMEOUT not set\n");
		else
			remmina_log_printf("[SSH] TCP_USER_TIMEOUT set to %i\n", optval);

#endif
	}
#endif

	/* Try the "none" authentication */
	if (ssh_userauth_none(ssh->session, NULL) == SSH_AUTH_SUCCESS)
		ssh->authenticated = TRUE;
	return TRUE;
}

gboolean
remmina_ssh_init_from_file(RemminaSSH *ssh, RemminaFile *remminafile)
{
	TRACE_CALL(__func__);
	const gchar *ssh_server;
	const gchar *ssh_username;
	const gchar *ssh_privatekey;
	const gchar *server;
	gchar *s;

	ssh->session = NULL;
	ssh->callback = NULL;
	ssh->authenticated = FALSE;
	ssh->error = NULL;
	ssh->passphrase = NULL;
	pthread_mutex_init(&ssh->ssh_mutex, NULL);

	/* Parse the address and port */
	ssh_server = remmina_file_get_string(remminafile, "ssh_server");
	ssh_username = remmina_file_get_string(remminafile, "ssh_username");
	ssh_privatekey = remmina_file_get_string(remminafile, "ssh_privatekey");
	server = remmina_file_get_string(remminafile, "server");
	if (ssh_server) {
		remmina_public_get_server_port(ssh_server, 22, &ssh->server, &ssh->port);
		if (ssh->server[0] == '\0') {
			g_free(ssh->server);
			remmina_public_get_server_port(server, 0, &ssh->server, NULL);
		}
	} else if (server == NULL) {
		ssh->server = g_strdup("localhost");
		ssh->port = 22;
	} else {
		remmina_public_get_server_port(server, 0, &ssh->server, NULL);
		ssh->port = 22;
	}

	ssh->user = g_strdup(ssh_username ? ssh_username : g_get_user_name());
	ssh->password = NULL;
	ssh->auth = remmina_file_get_int(remminafile, "ssh_auth", 0);
	ssh->charset = g_strdup(remmina_file_get_string(remminafile, "ssh_charset"));
	ssh->kex_algorithms = g_strdup(remmina_file_get_string(remminafile, "ssh_kex_algorithms"));
	ssh->ciphers = g_strdup(remmina_file_get_string(remminafile, "ssh_ciphers"));
	ssh->hostkeytypes = g_strdup(remmina_file_get_string(remminafile, "ssh_hostkeytypes"));
	ssh->proxycommand = g_strdup(remmina_file_get_string(remminafile, "ssh_proxycommand"));
	ssh->stricthostkeycheck = remmina_file_get_int(remminafile, "ssh_stricthostkeycheck", 0);
	gint c = remmina_file_get_int(remminafile, "ssh_compression", 0);
	ssh->compression = (c == 1) ? "yes" : "no";

	/* Public/Private keys */
	s = (ssh_privatekey ? g_strdup(ssh_privatekey) : remmina_ssh_find_identity());
	if (s) {
		ssh->privkeyfile = remmina_ssh_identity_path(s);
		g_free(s);
	} else {
		ssh->privkeyfile = NULL;
	}

	return TRUE;
}

static gboolean
remmina_ssh_init_from_ssh(RemminaSSH *ssh, const RemminaSSH *ssh_src)
{
	TRACE_CALL(__func__);
	ssh->session = NULL;
	ssh->authenticated = FALSE;
	ssh->error = NULL;
	pthread_mutex_init(&ssh->ssh_mutex, NULL);

	ssh->server = g_strdup(ssh_src->server);
	ssh->port = ssh_src->port;
	ssh->user = g_strdup(ssh_src->user);
	ssh->auth = ssh_src->auth;
	ssh->password = g_strdup(ssh_src->password);
	ssh->privkeyfile = g_strdup(ssh_src->privkeyfile);
	ssh->charset = g_strdup(ssh_src->charset);
	ssh->proxycommand = g_strdup(ssh_src->proxycommand);
	ssh->kex_algorithms = g_strdup(ssh_src->kex_algorithms);
	ssh->ciphers = g_strdup(ssh_src->ciphers);
	ssh->hostkeytypes = g_strdup(ssh_src->hostkeytypes);
	ssh->compression = ssh_src->compression;

	return TRUE;
}

gchar *
remmina_ssh_convert(RemminaSSH *ssh, const gchar *from)
{
	TRACE_CALL(__func__);
	gchar *to = NULL;

	if (ssh->charset && from)
		to = g_convert(from, -1, "UTF-8", ssh->charset, NULL, NULL, NULL);
	if (!to) to = g_strdup(from);
	return to;
}

gchar *
remmina_ssh_unconvert(RemminaSSH *ssh, const gchar *from)
{
	TRACE_CALL(__func__);
	gchar *to = NULL;

	if (ssh->charset && from)
		to = g_convert(from, -1, ssh->charset, "UTF-8", NULL, NULL, NULL);
	if (!to) to = g_strdup(from);
	return to;
}

void
remmina_ssh_free(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	if (ssh->session) {
		ssh_disconnect(ssh->session);
		ssh_free(ssh->session);
		ssh->session = NULL;
	}
	g_free(ssh->callback);
	g_free(ssh->server);
	g_free(ssh->user);
	g_free(ssh->password);
	g_free(ssh->privkeyfile);
	g_free(ssh->charset);
	g_free(ssh->error);
	pthread_mutex_destroy(&ssh->ssh_mutex);
	g_free(ssh);
}

/*-----------------------------------------------------------------------------*
*                           SSH Tunnel                                        *
*-----------------------------------------------------------------------------*/
struct _RemminaSSHTunnelBuffer {
	gchar * data;
	gchar * ptr;
	ssize_t len;
};

static RemminaSSHTunnelBuffer *
remmina_ssh_tunnel_buffer_new(ssize_t len)
{
	TRACE_CALL(__func__);
	RemminaSSHTunnelBuffer *buffer;

	buffer = g_new(RemminaSSHTunnelBuffer, 1);
	buffer->data = (gchar *)g_malloc(len);
	buffer->ptr = buffer->data;
	buffer->len = len;
	return buffer;
}

static void
remmina_ssh_tunnel_buffer_free(RemminaSSHTunnelBuffer *buffer)
{
	TRACE_CALL(__func__);
	if (buffer) {
		g_free(buffer->data);
		g_free(buffer);
	}
}

RemminaSSHTunnel *
remmina_ssh_tunnel_new_from_file(RemminaFile *remminafile)
{
	TRACE_CALL(__func__);
	RemminaSSHTunnel *tunnel;

	tunnel = g_new(RemminaSSHTunnel, 1);

	remmina_ssh_init_from_file(REMMINA_SSH(tunnel), remminafile);

	tunnel->tunnel_type = -1;
	tunnel->channels = NULL;
	tunnel->sockets = NULL;
	tunnel->socketbuffers = NULL;
	tunnel->num_channels = 0;
	tunnel->max_channels = 0;
	tunnel->x11_channel = NULL;
	tunnel->thread = 0;
	tunnel->running = FALSE;
	tunnel->server_sock = -1;
	tunnel->dest = NULL;
	tunnel->port = 0;
	tunnel->buffer = NULL;
	tunnel->buffer_len = 0;
	tunnel->channels_out = NULL;
	tunnel->remotedisplay = 0;
	tunnel->localdisplay = NULL;
	tunnel->init_func = NULL;
	tunnel->connect_func = NULL;
	tunnel->disconnect_func = NULL;
	tunnel->callback_data = NULL;

	return tunnel;
}

static void
remmina_ssh_tunnel_close_all_channels(RemminaSSHTunnel *tunnel)
{
	TRACE_CALL(__func__);
	int i;

	for (i = 0; i < tunnel->num_channels; i++) {
		close(tunnel->sockets[i]);
		remmina_ssh_tunnel_buffer_free(tunnel->socketbuffers[i]);
		ssh_channel_close(tunnel->channels[i]);
		ssh_channel_send_eof(tunnel->channels[i]);
		ssh_channel_free(tunnel->channels[i]);
	}

	g_free(tunnel->channels);
	tunnel->channels = NULL;
	g_free(tunnel->sockets);
	tunnel->sockets = NULL;
	g_free(tunnel->socketbuffers);
	tunnel->socketbuffers = NULL;

	tunnel->num_channels = 0;
	tunnel->max_channels = 0;

	if (tunnel->x11_channel) {
		ssh_channel_close(tunnel->x11_channel);
		ssh_channel_send_eof(tunnel->x11_channel);
		ssh_channel_free(tunnel->x11_channel);
		tunnel->x11_channel = NULL;
	}
}

static void
remmina_ssh_tunnel_remove_channel(RemminaSSHTunnel *tunnel, gint n)
{
	TRACE_CALL(__func__);
	ssh_channel_close(tunnel->channels[n]);
	ssh_channel_send_eof(tunnel->channels[n]);
	ssh_channel_free(tunnel->channels[n]);
	close(tunnel->sockets[n]);
	remmina_ssh_tunnel_buffer_free(tunnel->socketbuffers[n]);
	tunnel->num_channels--;
	tunnel->channels[n] = tunnel->channels[tunnel->num_channels];
	tunnel->channels[tunnel->num_channels] = NULL;
	tunnel->sockets[n] = tunnel->sockets[tunnel->num_channels];
	tunnel->socketbuffers[n] = tunnel->socketbuffers[tunnel->num_channels];
}

/* Register the new channel/socket pair */
static void
remmina_ssh_tunnel_add_channel(RemminaSSHTunnel *tunnel, ssh_channel channel, gint sock)
{
	TRACE_CALL(__func__);
	gint flags;
	gint i;

	i = tunnel->num_channels++;
	if (tunnel->num_channels > tunnel->max_channels) {
		/* Allocate an extra NULL pointer in channels for ssh_select */
		tunnel->channels = (ssh_channel *)g_realloc(tunnel->channels,
							    sizeof(ssh_channel) * (tunnel->num_channels + 1));
		tunnel->sockets = (gint *)g_realloc(tunnel->sockets,
						    sizeof(gint) * tunnel->num_channels);
		tunnel->socketbuffers = (RemminaSSHTunnelBuffer **)g_realloc(tunnel->socketbuffers,
									     sizeof(RemminaSSHTunnelBuffer *) * tunnel->num_channels);
		tunnel->max_channels = tunnel->num_channels;

		tunnel->channels_out = (ssh_channel *)g_realloc(tunnel->channels_out,
								sizeof(ssh_channel) * (tunnel->num_channels + 1));
	}
	tunnel->channels[i] = channel;
	tunnel->channels[i + 1] = NULL;
	tunnel->sockets[i] = sock;
	tunnel->socketbuffers[i] = NULL;

	flags = fcntl(sock, F_GETFL, 0);
	fcntl(sock, F_SETFL, flags | O_NONBLOCK);
}

static int
remmina_ssh_tunnel_accept_local_connection(RemminaSSHTunnel *tunnel, gboolean blocking)
{
	gint sock, sock_flags;

	sock_flags = fcntl(tunnel->server_sock, F_GETFL, 0);
	if (blocking)
		sock_flags &= ~O_NONBLOCK;
	else
		sock_flags |= O_NONBLOCK;
	fcntl(tunnel->server_sock, F_SETFL, sock_flags);

	/* Accept a local connection */
	sock = accept(tunnel->server_sock, NULL, NULL);
	if (sock < 0)
		REMMINA_SSH(tunnel)->error = g_strdup("Local socket not accepted");

	return sock;
}

static ssh_channel
remmina_ssh_tunnel_create_forward_channel(RemminaSSHTunnel *tunnel)
{
	ssh_channel channel = NULL;

	channel = ssh_channel_new(tunnel->ssh.session);
	if (!channel) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not create channel. %s"));
		return NULL;
	}

	/* Request the SSH server to connect to the destination */
	g_debug("SSH tunnel destination is %s", tunnel->dest);
	if (ssh_channel_open_forward(channel, tunnel->dest, tunnel->port, "127.0.0.1", 0) != SSH_OK) {
		ssh_channel_close(channel);
		ssh_channel_send_eof(channel);
		ssh_channel_free(channel);
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not connect to SSH tunnel. %s"));
		return NULL;
	}

	return channel;
}

static gpointer
remmina_ssh_tunnel_main_thread_proc(gpointer data)
{
	TRACE_CALL(__func__);
	RemminaSSHTunnel *tunnel = (RemminaSSHTunnel *)data;
	gchar *ptr;
	ssize_t len = 0, lenw = 0;
	fd_set set;
	struct timeval timeout;
	g_autoptr(GDateTime) t1 = NULL;
	g_autoptr(GDateTime) t2 = NULL;
	GTimeSpan diff; // microseconds
	ssh_channel channel = NULL;
	gboolean first = TRUE;
	gboolean disconnected;
	gint sock;
	gint maxfd;
	gint i;
	gint ret;
	struct sockaddr_in sin;

	t1 = t2 = g_date_time_new_now_local();

	switch (tunnel->tunnel_type) {
	case REMMINA_SSH_TUNNEL_OPEN:
		sock = remmina_ssh_tunnel_accept_local_connection(tunnel, TRUE);
		if (sock < 0) {
			tunnel->thread = 0;
			return NULL;
		}

		channel = remmina_ssh_tunnel_create_forward_channel(tunnel);
		if (!tunnel) {
			close(sock);
			tunnel->thread = 0;
			return NULL;
		}

		remmina_ssh_tunnel_add_channel(tunnel, channel, sock);
		break;

	case REMMINA_SSH_TUNNEL_X11:
		if ((tunnel->x11_channel = ssh_channel_new(tunnel->ssh.session)) == NULL) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not create channel. %s"));
			tunnel->thread = 0;
			return NULL;
		}
		if (!remmina_public_get_xauth_cookie(tunnel->localdisplay, &ptr)) {
			remmina_ssh_set_application_error(REMMINA_SSH(tunnel), "%s", ptr);
			g_free(ptr);
			tunnel->thread = 0;
			return NULL;
		}
		if (ssh_channel_open_session(tunnel->x11_channel) ||
		    ssh_channel_request_x11(tunnel->x11_channel, TRUE, NULL, ptr,
					    gdk_x11_screen_get_screen_number(gdk_screen_get_default()))) {
			g_free(ptr);
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not open channel. %s"));
			tunnel->thread = 0;
			return NULL;
		}
		g_free(ptr);
		if (ssh_channel_request_exec(tunnel->x11_channel, tunnel->dest)) {
			ptr = g_strdup_printf(_("Could not run %s on SSH server, %%s"), tunnel->dest);
			remmina_ssh_set_error(REMMINA_SSH(tunnel), ptr);
			g_free(ptr);
			tunnel->thread = 0;
			return NULL;
		}

		if (tunnel->init_func &&
		    !(*tunnel->init_func)(tunnel, tunnel->callback_data)) {
			if (tunnel->disconnect_func)
				(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
			tunnel->thread = 0;
			return NULL;
		}

		break;

	case REMMINA_SSH_TUNNEL_XPORT:
		/* Detect the next available port starting from 6010 on the server */
		for (i = 10; i <= MAX_X_DISPLAY_NUMBER; i++) {
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 7, 0)
			if (ssh_channel_listen_forward(REMMINA_SSH(tunnel)->session, (tunnel->bindlocalhost ? "localhost" : NULL), 6000 + i, NULL)) {
				continue;
			} else {
				tunnel->remotedisplay = i;
				break;
			}
#else
			if (ssh_forward_listen(REMMINA_SSH(tunnel)->session, (tunnel->bindlocalhost ? "localhost" : NULL), 6000 + i, NULL)) {
				continue;
			} else {
				tunnel->remotedisplay = i;
				break;
			}
#endif
		}
		if (tunnel->remotedisplay < 1) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not request port forwarding. %s"));
			if (tunnel->disconnect_func)
				(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
			tunnel->thread = 0;
			return NULL;
		}

		if (tunnel->init_func &&
		    !(*tunnel->init_func)(tunnel, tunnel->callback_data)) {
			if (tunnel->disconnect_func)
				(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
			tunnel->thread = 0;
			return NULL;
		}

		break;

	case REMMINA_SSH_TUNNEL_REVERSE:
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 7, 0)
		if (ssh_channel_listen_forward(REMMINA_SSH(tunnel)->session, NULL, tunnel->port, NULL)) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not request port forwarding. %s"));
			if (tunnel->disconnect_func)
				(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
			tunnel->thread = 0;
			return NULL;
		}
#else
		if (ssh_forward_listen(REMMINA_SSH(tunnel)->session, NULL, tunnel->port, NULL)) {
			// TRANSLATORS: The placeholder %s is an error message
			remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not request port forwarding. %s"));
			if (tunnel->disconnect_func)
				(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
			tunnel->thread = 0;
			return NULL;
		}
#endif

		if (tunnel->init_func &&
		    !(*tunnel->init_func)(tunnel, tunnel->callback_data)) {
			if (tunnel->disconnect_func)
				(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
			tunnel->thread = 0;
			return NULL;
		}

		break;
	}

	tunnel->buffer_len = 10240;
	tunnel->buffer = g_malloc(tunnel->buffer_len);

	/* Start the tunnel data transmission */
	while (tunnel->running) {
		if (tunnel->tunnel_type == REMMINA_SSH_TUNNEL_XPORT ||
		    tunnel->tunnel_type == REMMINA_SSH_TUNNEL_X11 ||
		    tunnel->tunnel_type == REMMINA_SSH_TUNNEL_REVERSE) {
			if (first) {
				first = FALSE;
				/* Wait for a period of time for the first incoming connection */
				if (tunnel->tunnel_type == REMMINA_SSH_TUNNEL_X11)
					channel = ssh_channel_accept_x11(tunnel->x11_channel, 15000);
				else
					channel = ssh_channel_accept_forward(REMMINA_SSH(tunnel)->session, 15000, &tunnel->port);
				if (!channel) {
					remmina_ssh_set_application_error(REMMINA_SSH(tunnel), _("The server did not respond."));
					if (tunnel->disconnect_func)
						(*tunnel->disconnect_func)(tunnel, tunnel->callback_data);
					tunnel->thread = 0;
					return NULL;
				}
				if (tunnel->connect_func)
					(*tunnel->connect_func)(tunnel, tunnel->callback_data);
				if (tunnel->tunnel_type == REMMINA_SSH_TUNNEL_REVERSE) {
					/* For reverse tunnel, we only need one connection. */
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 7, 0)
					ssh_channel_cancel_forward(REMMINA_SSH(tunnel)->session, NULL, tunnel->port);
#else
					ssh_forward_cancel(REMMINA_SSH(tunnel)->session, NULL, tunnel->port);
#endif
				}
			} else if (tunnel->tunnel_type != REMMINA_SSH_TUNNEL_REVERSE) {
				/* Poll once per some period of time if no incoming connections.
				 * Don’t try to poll continuously as it will significantly slow down the loop */
				t1 = g_date_time_new_now_local();
				diff = g_date_time_difference (t1, t2) * 10000000
					+ g_date_time_difference (t1, t2) / 100000;
				if (diff > 1) {
					g_debug ("[SSH] Polling tunnel channels");
					if (tunnel->tunnel_type == REMMINA_SSH_TUNNEL_X11)
						channel = ssh_channel_accept_x11(tunnel->x11_channel, 0);
					else
						channel = ssh_channel_accept_forward(REMMINA_SSH(tunnel)->session, 0, &tunnel->port);
					if (channel == NULL)
						t2 = t1;
				}
				 g_date_time_unref (t1);
				 g_date_time_unref (t2);
			}

			if (channel) {
				if (tunnel->tunnel_type == REMMINA_SSH_TUNNEL_REVERSE) {
					sin.sin_family = AF_INET;
					sin.sin_port = htons(tunnel->localport);
					sin.sin_addr.s_addr = inet_addr("127.0.0.1");
					sock = socket(AF_INET, SOCK_STREAM, 0);
					if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
						remmina_ssh_set_application_error(REMMINA_SSH(tunnel),
										  _("Cannot connect to local port %i."), tunnel->localport);
						close(sock);
						sock = -1;
					}
				} else {
					sock = remmina_public_open_xdisplay(tunnel->localdisplay);
				}
				if (sock >= 0) {
					remmina_ssh_tunnel_add_channel(tunnel, channel, sock);
				} else {
					/* Failed to create unix socket. Will this happen? */
					ssh_channel_close(channel);
					ssh_channel_send_eof(channel);
					ssh_channel_free(channel);
				}
				channel = NULL;
			}
		}

		if (tunnel->num_channels <= 0)
			/* No more connections. We should quit */
			break;

		timeout.tv_sec = 0;
		timeout.tv_usec = 200000;

		FD_ZERO(&set);
		maxfd = 0;
		for (i = 0; i < tunnel->num_channels; i++) {
			if (tunnel->sockets[i] > maxfd)
				maxfd = tunnel->sockets[i];
			FD_SET(tunnel->sockets[i], &set);
		}

		ret = ssh_select(tunnel->channels, tunnel->channels_out, maxfd + 1, &set, &timeout);
		if (!tunnel->running) break;
		if (ret == SSH_EINTR) continue;
		if (ret == -1) break;

		i = 0;
		while (tunnel->running && i < tunnel->num_channels) {
			disconnected = FALSE;
			if (FD_ISSET(tunnel->sockets[i], &set)) {
				while (!disconnected &&
				       (len = read(tunnel->sockets[i], tunnel->buffer, tunnel->buffer_len)) > 0) {
					for (ptr = tunnel->buffer, lenw = 0; len > 0; len -= lenw, ptr += lenw) {
						lenw = ssh_channel_write(tunnel->channels[i], (char *)ptr, len);
						if (lenw <= 0) {
							disconnected = TRUE;
							// TRANSLATORS: The placeholder %s is an error message
							remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not write to SSH channel. %s"));
							break;
						}
					}
				}
				if (len == 0) {
					// TRANSLATORS: The placeholder %s is an error message
					remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not read from tunnel listening socket. %s"));
					disconnected = TRUE;
				}
			}
			if (disconnected) {
				remmina_log_printf("[SSH] tunnel disconnected because %s\n", REMMINA_SSH(tunnel)->error);
				remmina_ssh_tunnel_remove_channel(tunnel, i);
				continue;
			}
			i++;
		}
		if (!tunnel->running) break;

		i = 0;
		while (tunnel->running && i < tunnel->num_channels) {
			disconnected = FALSE;
			if (!tunnel->socketbuffers[i]) {
				len = ssh_channel_poll(tunnel->channels[i], 0);
				if (len == SSH_ERROR || len == SSH_EOF) {
					// TRANSLATORS: The placeholder %s is an error message
					remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not poll SSH channel. %s"));
					disconnected = TRUE;
				} else if (len > 0) {
					tunnel->socketbuffers[i] = remmina_ssh_tunnel_buffer_new(len);
					len = ssh_channel_read_nonblocking(tunnel->channels[i], tunnel->socketbuffers[i]->data, len, 0);
					if (len <= 0) {
						// TRANSLATORS: The placeholder %s is an error message
						remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not read SSH channel in a non-blocking way. %s"));
						disconnected = TRUE;
					} else {
						tunnel->socketbuffers[i]->len = len;
					}
				}
			}

			if (!disconnected && tunnel->socketbuffers[i]) {
				for (lenw = 0; tunnel->socketbuffers[i]->len > 0;
				     tunnel->socketbuffers[i]->len -= lenw, tunnel->socketbuffers[i]->ptr += lenw) {
					lenw = write(tunnel->sockets[i], tunnel->socketbuffers[i]->ptr, tunnel->socketbuffers[i]->len);
					if (lenw == -1 && errno == EAGAIN && tunnel->running)
						/* Sometimes we cannot write to a socket (always EAGAIN), probably because it’s internal
						 * buffer is full. We need read the pending bytes from the socket first. so here we simply
						 * break, leave the buffer there, and continue with other data */
						break;
					if (lenw <= 0) {
						// TRANSLATORS: The placeholder %s is an error message
						remmina_ssh_set_error(REMMINA_SSH(tunnel), _("Could not send data to tunnel listening socket. %s"));
						disconnected = TRUE;
						break;
					}
				}
				if (tunnel->socketbuffers[i]->len <= 0) {
					remmina_ssh_tunnel_buffer_free(tunnel->socketbuffers[i]);
					tunnel->socketbuffers[i] = NULL;
				}
			}

			if (disconnected) {
				remmina_log_printf("Connection to SSH tunnel dropped. %s\n", REMMINA_SSH(tunnel)->error);
				remmina_ssh_tunnel_remove_channel(tunnel, i);
				continue;
			}
			i++;
		}
		/**
		 * Some protocols may open new connections during the session.
		 * e.g: SPICE opens a new connection for some channels.
		 */
		sock = remmina_ssh_tunnel_accept_local_connection(tunnel, FALSE);
		if (sock > 0) {
			channel = remmina_ssh_tunnel_create_forward_channel(tunnel);
			if (!channel) {
				remmina_log_printf("Could not open new SSH connection. %s\n", REMMINA_SSH(tunnel)->error);
				close(sock);
				/* Leave thread loop */
				tunnel->running = FALSE;
			} else {
				remmina_ssh_tunnel_add_channel(tunnel, channel, sock);
			}
		}
	}

	remmina_ssh_tunnel_close_all_channels(tunnel);

	return NULL;
}

static gpointer
remmina_ssh_tunnel_main_thread(gpointer data)
{
	TRACE_CALL(__func__);
	RemminaSSHTunnel *tunnel = (RemminaSSHTunnel *)data;

	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

	while (TRUE) {
		remmina_ssh_tunnel_main_thread_proc(data);
		if (tunnel->server_sock < 0 || tunnel->thread == 0 || !tunnel->running) break;
	}
	tunnel->thread = 0;
	return NULL;
}

void
remmina_ssh_tunnel_cancel_accept(RemminaSSHTunnel *tunnel)
{
	TRACE_CALL(__func__);
	if (tunnel->server_sock >= 0) {
		close(tunnel->server_sock);
		tunnel->server_sock = -1;
	}
}

gboolean
remmina_ssh_tunnel_open(RemminaSSHTunnel *tunnel, const gchar *host, gint port, gint local_port)
{
	TRACE_CALL(__func__);
	gint sock;
	gint sockopt = 1;
	struct sockaddr_in sin;

	tunnel->tunnel_type = REMMINA_SSH_TUNNEL_OPEN;
	tunnel->dest = g_strdup(host);
	tunnel->port = port;
	if (tunnel->port == 0) {
		REMMINA_SSH(tunnel)->error = g_strdup(_("Assign a destination port."));
		return FALSE;
	}

	/* Create the server socket that listens on the local port */
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
		REMMINA_SSH(tunnel)->error = g_strdup(_("Could not create socket."));
		return FALSE;
	}
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt));

	sin.sin_family = AF_INET;
	sin.sin_port = htons(local_port);
	sin.sin_addr.s_addr = inet_addr("127.0.0.1");

	if (bind(sock, (struct sockaddr *)&sin, sizeof(sin))) {
		REMMINA_SSH(tunnel)->error = g_strdup(_("Could not bind server socket to local port."));
		close(sock);
		return FALSE;
	}

	if (listen(sock, 1)) {
		REMMINA_SSH(tunnel)->error = g_strdup(_("Could not listen to local port."));
		close(sock);
		return FALSE;
	}

	tunnel->server_sock = sock;
	tunnel->running = TRUE;

	if (pthread_create(&tunnel->thread, NULL, remmina_ssh_tunnel_main_thread, tunnel)) {
		// TRANSLATORS: Do not translate pthread
		remmina_ssh_set_application_error(REMMINA_SSH(tunnel), _("Could not start pthread."));
		tunnel->thread = 0;
		return FALSE;
	}
	return TRUE;
}

gboolean
remmina_ssh_tunnel_x11(RemminaSSHTunnel *tunnel, const gchar *cmd)
{
	TRACE_CALL(__func__);
	tunnel->tunnel_type = REMMINA_SSH_TUNNEL_X11;
	tunnel->dest = g_strdup(cmd);
	tunnel->running = TRUE;

	if (pthread_create(&tunnel->thread, NULL, remmina_ssh_tunnel_main_thread, tunnel)) {
		// TRANSLATORS: Do not translate pthread
		remmina_ssh_set_application_error(REMMINA_SSH(tunnel), _("Could not start pthread."));
		tunnel->thread = 0;
		return FALSE;
	}
	return TRUE;
}

gboolean
remmina_ssh_tunnel_xport(RemminaSSHTunnel *tunnel, gboolean bindlocalhost)
{
	TRACE_CALL(__func__);
	tunnel->tunnel_type = REMMINA_SSH_TUNNEL_XPORT;
	tunnel->bindlocalhost = bindlocalhost;
	tunnel->running = TRUE;

	if (pthread_create(&tunnel->thread, NULL, remmina_ssh_tunnel_main_thread, tunnel)) {
		// TRANSLATORS: Do not translate pthread
		remmina_ssh_set_application_error(REMMINA_SSH(tunnel), _("Failed to initialize pthread."));
		tunnel->thread = 0;
		return FALSE;
	}
	return TRUE;
}

gboolean
remmina_ssh_tunnel_reverse(RemminaSSHTunnel *tunnel, gint port, gint local_port)
{
	TRACE_CALL(__func__);
	tunnel->tunnel_type = REMMINA_SSH_TUNNEL_REVERSE;
	tunnel->port = port;
	tunnel->localport = local_port;
	tunnel->running = TRUE;

	if (pthread_create(&tunnel->thread, NULL, remmina_ssh_tunnel_main_thread, tunnel)) {
		// TRANSLATORS: Do not translate pthread
		remmina_ssh_set_application_error(REMMINA_SSH(tunnel), _("Could not start pthread."));
		tunnel->thread = 0;
		return FALSE;
	}
	return TRUE;
}

gboolean
remmina_ssh_tunnel_terminated(RemminaSSHTunnel *tunnel)
{
	TRACE_CALL(__func__);
	return tunnel->thread == 0;
}

void
remmina_ssh_tunnel_free(RemminaSSHTunnel *tunnel)
{
	TRACE_CALL(__func__);
	pthread_t thread;

	thread = tunnel->thread;
	if (thread != 0) {
		tunnel->running = FALSE;
		pthread_cancel(thread);
		pthread_join(thread, NULL);
		tunnel->thread = 0;
	}

	if (tunnel->tunnel_type == REMMINA_SSH_TUNNEL_XPORT && tunnel->remotedisplay > 0) {
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 7, 0)
		ssh_channel_cancel_forward(REMMINA_SSH(tunnel)->session, NULL, 6000 + tunnel->remotedisplay);
#else
		ssh_forward_cancel(REMMINA_SSH(tunnel)->session, NULL, 6000 + tunnel->remotedisplay);
#endif
	}
	if (tunnel->server_sock >= 0) {
		close(tunnel->server_sock);
		tunnel->server_sock = -1;
	}
	remmina_ssh_tunnel_close_all_channels(tunnel);

	g_free(tunnel->buffer);
	g_free(tunnel->channels_out);
	g_free(tunnel->dest);
	g_free(tunnel->localdisplay);

	remmina_ssh_free(REMMINA_SSH(tunnel));
}

/*-----------------------------------------------------------------------------*
*                           SSH SFTP                                          *
*-----------------------------------------------------------------------------*/
RemminaSFTP *
remmina_sftp_new_from_file(RemminaFile *remminafile)
{
	TRACE_CALL(__func__);
	RemminaSFTP *sftp;

	sftp = g_new(RemminaSFTP, 1);

	remmina_ssh_init_from_file(REMMINA_SSH(sftp), remminafile);

	sftp->sftp_sess = NULL;

	return sftp;
}

RemminaSFTP *
remmina_sftp_new_from_ssh(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	RemminaSFTP *sftp;

	sftp = g_new(RemminaSFTP, 1);

	remmina_ssh_init_from_ssh(REMMINA_SSH(sftp), ssh);

	sftp->sftp_sess = NULL;

	return sftp;
}

gboolean
remmina_sftp_open(RemminaSFTP *sftp)
{
	TRACE_CALL(__func__);
	sftp->sftp_sess = sftp_new(sftp->ssh.session);
	if (!sftp->sftp_sess) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(REMMINA_SSH(sftp), _("Could not create SFTP session. %s"));
		return FALSE;
	}
	if (sftp_init(sftp->sftp_sess)) {
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(REMMINA_SSH(sftp), _("Could not start SFTP session. %s"));
		return FALSE;
	}
	return TRUE;
}

void
remmina_sftp_free(RemminaSFTP *sftp)
{
	TRACE_CALL(__func__);
	if (sftp->sftp_sess) {
		sftp_free(sftp->sftp_sess);
		sftp->sftp_sess = NULL;
	}
	remmina_ssh_free(REMMINA_SSH(sftp));
}

/*-----------------------------------------------------------------------------*
*                           SSH Shell                                         *
*-----------------------------------------------------------------------------*/
RemminaSSHShell *
remmina_ssh_shell_new_from_file(RemminaFile *remminafile)
{
	TRACE_CALL(__func__);
	RemminaSSHShell *shell;

	shell = g_new0(RemminaSSHShell, 1);

	remmina_ssh_init_from_file(REMMINA_SSH(shell), remminafile);

	shell->master = -1;
	shell->slave = -1;
	shell->exec = g_strdup(remmina_file_get_string(remminafile, "exec"));

	return shell;
}

RemminaSSHShell *
remmina_ssh_shell_new_from_ssh(RemminaSSH *ssh)
{
	TRACE_CALL(__func__);
	RemminaSSHShell *shell;

	shell = g_new0(RemminaSSHShell, 1);

	remmina_ssh_init_from_ssh(REMMINA_SSH(shell), ssh);

	shell->master = -1;
	shell->slave = -1;

	return shell;
}

static gboolean
remmina_ssh_call_exit_callback_on_main_thread(gpointer data)
{
	TRACE_CALL(__func__);

	RemminaSSHShell *shell = (RemminaSSHShell *)data;
	if (shell->exit_callback)
		shell->exit_callback(shell->user_data);
	return FALSE;
}

static gpointer
remmina_ssh_shell_thread(gpointer data)
{
	TRACE_CALL(__func__);
	RemminaSSHShell *shell = (RemminaSSHShell *)data;
	fd_set fds;
	struct timeval timeout;
	ssh_channel channel = NULL;
	ssh_channel ch[2], chout[2];
	gchar *buf = NULL;
	gint buf_len;
	gint len;
	gint i, ret;
	//gint screen;

	LOCK_SSH(shell)

	if ((channel = ssh_channel_new(REMMINA_SSH(shell)->session)) == NULL ||
	    ssh_channel_open_session(channel)) {
		UNLOCK_SSH(shell)
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(REMMINA_SSH(shell), _("Could not open channel. %s"));
		if (channel) ssh_channel_free(channel);
		shell->thread = 0;
		return NULL;
	}

	ssh_channel_request_pty(channel);

	/* ssh_channel_request_x11 works but I do not know yet how to use the
	 * channel. At the momonet I leave the code here, commented, for future
	 * investigations.
	 */
	//screen = gdk_x11_screen_get_screen_number(gdk_screen_get_default());
	//ret = ssh_channel_request_x11 (channel, FALSE, NULL, NULL, screen);
	/* TODO: We should have a callback that intercept an x11 request to use
	 * ssh_channel_accept_x11 */
	//if ( ret != SSH_OK ) {
	//g_print ("[SSH] X11 channel error: %d\n", ret);
	//}else {
	//ssh_channel_accept_x11 ( channel, 50);
	//}


	if (shell->exec && shell->exec[0])
		ret = ssh_channel_request_exec(channel, shell->exec);
	else
		ret = ssh_channel_request_shell(channel);
	if (ret) {
		UNLOCK_SSH(shell)
		// TRANSLATORS: The placeholder %s is an error message
		remmina_ssh_set_error(REMMINA_SSH(shell), _("Could not request shell. %s"));
		ssh_channel_close(channel);
		ssh_channel_send_eof(channel);
		ssh_channel_free(channel);
		shell->thread = 0;
		return NULL;
	}

	shell->channel = channel;

	UNLOCK_SSH(shell)

	buf_len = 1000;
	buf = g_malloc(buf_len + 1);

	ch[0] = channel;
	ch[1] = NULL;

	while (!shell->closed) {
		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		FD_ZERO(&fds);
		FD_SET(shell->slave, &fds);

		ret = ssh_select(ch, chout, shell->slave + 1, &fds, &timeout);
		if (ret == SSH_EINTR) continue;
		if (ret == -1) break;

		if (FD_ISSET(shell->slave, &fds)) {
			len = read(shell->slave, buf, buf_len);
			if (len <= 0) break;
			LOCK_SSH(shell)
			ssh_channel_write(channel, buf, len);
			UNLOCK_SSH(shell)
		}
		for (i = 0; i < 2; i++) {
			LOCK_SSH(shell)
			len = ssh_channel_poll(channel, i);
			UNLOCK_SSH(shell)
			if (len == SSH_ERROR || len == SSH_EOF) {
				shell->closed = TRUE;
				break;
			}
			if (len <= 0) continue;
			if (len > buf_len) {
				buf_len = len;
				buf = (gchar *)g_realloc(buf, buf_len + 1);
			}
			LOCK_SSH(shell)
			len = ssh_channel_read_nonblocking(channel, buf, len, i);
			UNLOCK_SSH(shell)
			if (len <= 0) {
				shell->closed = TRUE;
				break;
			}
			while (len > 0) {
				ret = write(shell->slave, buf, len);
				if (ret <= 0) break;
				len -= ret;
			}
		}
	}

	LOCK_SSH(shell)
	shell->channel = NULL;
	ssh_channel_close(channel);
	ssh_channel_send_eof(channel);
	ssh_channel_free(channel);
	UNLOCK_SSH(shell)

	g_free(buf);
	shell->thread = 0;

	if (shell->exit_callback)
		IDLE_ADD((GSourceFunc)remmina_ssh_call_exit_callback_on_main_thread, (gpointer)shell);
	return NULL;
}


gboolean
remmina_ssh_shell_open(RemminaSSHShell *shell, RemminaSSHExitFunc exit_callback, gpointer data)
{
	TRACE_CALL(__func__);
	gchar *slavedevice;
	struct termios stermios;

	shell->master = posix_openpt(O_RDWR | O_NOCTTY);
	if (shell->master == -1 ||
	    grantpt(shell->master) == -1 ||
	    unlockpt(shell->master) == -1 ||
	    (slavedevice = ptsname(shell->master)) == NULL ||
	    (shell->slave = open(slavedevice, O_RDWR | O_NOCTTY)) < 0) {
		REMMINA_SSH(shell)->error = g_strdup(_("Could not create PTY device."));
		return FALSE;
	}

	/* As per libssh documentation */
	tcgetattr(shell->slave, &stermios);
	stermios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
	stermios.c_oflag &= ~OPOST;
	stermios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
	stermios.c_cflag &= ~(CSIZE | PARENB);
	stermios.c_cflag |= CS8;
	tcsetattr(shell->slave, TCSANOW, &stermios);

	shell->exit_callback = exit_callback;
	shell->user_data = data;

	/* Once the process started, we should always TRUE and assume the pthread will be created always */
	pthread_create(&shell->thread, NULL, remmina_ssh_shell_thread, shell);

	return TRUE;
}

void
remmina_ssh_shell_set_size(RemminaSSHShell *shell, gint columns, gint rows)
{
	TRACE_CALL(__func__);
	LOCK_SSH(shell)
	if (shell->channel)
		ssh_channel_change_pty_size(shell->channel, columns, rows);
	UNLOCK_SSH(shell)
}

void
remmina_ssh_shell_free(RemminaSSHShell *shell)
{
	TRACE_CALL(__func__);
	pthread_t thread = shell->thread;

	shell->exit_callback = NULL;
	if (thread) {
		shell->closed = TRUE;
		pthread_join(thread, NULL);
	}
	close(shell->slave);
	if (shell->exec) {
		g_free(shell->exec);
		shell->exec = NULL;
	}
	/* It’s not necessary to close shell->slave since the other end (vte) will close it */;
	remmina_ssh_free(REMMINA_SSH(shell));
}

#endif /* HAVE_LIBSSH */