summaryrefslogtreecommitdiffstats
path: root/tdeioslave/sftp/tdeio_sftp.cpp
blob: 3fb611f58cc05af44a4a6ec0421f1e0ac43bee58 (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
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
/*
 * Copyright (c) 2001  Lucas Fisher       <[email protected]>
 * Copyright (c) 2009  Andreas Schneider  <[email protected]>
 * Copyright (c) 2020  Martin Sandsmark   <[email protected]>
 *                     KDE2 port
 * Copyright (c) 2022  Mavridis Philippe  <[email protected]>
 *                     Trinity port
 *
 * Portions Copyright (c) 2020-2021 Harald Sitter <[email protected]>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License (LGPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later
 * version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "tdeio_sftp.h"

#include <fcntl.h>

#include <tqapplication.h>
#include <tqfile.h>
#include <tqdir.h>

#include <numeric>
#include <functional>

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <string.h>

#include <arpa/inet.h>
#include <netinet/in.h>

#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <tdeapplication.h>
#include <kdebug.h>
#include <tdemessagebox.h>
#include <tdeglobal.h>
#include <kstandarddirs.h>
#include <tdelocale.h>
#include <kurl.h>
#include <tdeio/ioslave_defaults.h>
#include <kmimetype.h>
#include <kmimemagic.h>
#include <signal.h>

#include <libssh/libssh.h>
#include <libssh/sftp.h>
#include <libssh/callbacks.h>

#define TDEIO_SFTP_SPECIAL_TIMEOUT 30
#define ZERO_STRUCTP(x) do { if ((x) != NULL) memset((char *)(x), 0, sizeof(*(x))); } while(0)

using namespace TDEIO;
extern "C"
{
  int KDE_EXPORT kdemain( int argc, char **argv )
  {
    TDEInstance instance( "tdeio_sftp" );

    kdDebug(TDEIO_SFTP_DB) << "*** Starting tdeio_sftp " << endl;

    if (argc != 4) {
      kdDebug(TDEIO_SFTP_DB) << "Usage: tdeio_sftp  protocol domain-socket1 domain-socket2" << endl;
      exit(-1);
    }
    sftpProtocol slave(argv[2], argv[3]);

    if (getenv("DEBUG_TDEIO_SFTP")) {
        // Give us a coredump in the journal
        signal(6, SIG_DFL);
    }

    slave.dispatchLoop();

    kdDebug(TDEIO_SFTP_DB) << "*** tdeio_sftp Done" << endl;
    return 0;
  }
}

// Some helper functions/classes
namespace {

// A quick and dirty scope guard implementation
class ExitGuard {
public:
  template<class Callable>
  ExitGuard(Callable && undo_func) : f(std::forward<Callable>(undo_func)) {}
  ExitGuard(ExitGuard && other) : f(std::move(other.f)) {
      other.f = nullptr;
  }

  ~ExitGuard() {
    run();
  }

  void run() noexcept {
    if(f) { f(); f = nullptr; }
  }

  void abort() {
    f = nullptr;
  }

  ExitGuard(const ExitGuard&) = delete;
  void operator= (const ExitGuard&) = delete;

private:
    std::function<void()> f;
};

// A small helper to purge passwords. Paranoiac's note: this is not enough to guarantee the
// complete purge of the password and all its copy from memory (ioslaves are sending the passwords
// via dcop, so it's far beyond calling it "secure" in any way), but it's still better than nothing.
void purgeString(TQString &s) {
  s.fill('\0');
  s.setLength(0);
  s = TQString::null;
}

// A helper class to cleanup password when it goes out of the scope
class PasswordPurger: public ExitGuard {
public:
  PasswordPurger(TQString &pw) : ExitGuard( [&pw](){purgeString(pw);} ) {}
};

} /* namespace */

// The callback function for libssh
int auth_callback(const char *prompt, char *buf, size_t len,
                  int echo, int verify, void *userdata)
{
  if (userdata == NULL) {
    return -1;
  }

  sftpProtocol *slave = (sftpProtocol *) userdata;

  if (slave->auth_callback(prompt, buf, len, echo, verify, userdata) < 0) {
    return -1;
  }

  return 0;
}

void log_callback(ssh_session session, int priority, const char *message,
    void *userdata) {
  if (userdata == NULL) {
    return;
  }

  sftpProtocol *slave = (sftpProtocol *) userdata;

  slave->log_callback(session, priority, message, userdata);
}

class PublicKeyAuth: public SSHAuthMethod {
public:
  int flag() override {return SSH_AUTH_METHOD_PUBLICKEY;};
  TQString name() override { return i18n("public key"); };
  int authenticate(sftpProtocol *ioslave) const override {
    return ioslave->authenticatePublicKey();
  }
  SSHAuthMethod* clone() override {return new PublicKeyAuth; }
};

class KeyboardInteractiveAuth: public SSHAuthMethod {
public:
  KeyboardInteractiveAuth(bool noPaswordQuery = false): mNoPaswordQuery(noPaswordQuery) {}

  int flag() override {return SSH_AUTH_METHOD_INTERACTIVE;};
  TQString name() override { return i18n("keyboard interactive"); };
  int authenticate(sftpProtocol *ioslave) const override {
    return ioslave->authenticateKeyboardInteractive(mNoPaswordQuery);
  }
  SSHAuthMethod* clone() override {return new KeyboardInteractiveAuth(mNoPaswordQuery); }

private:
  const bool mNoPaswordQuery;
};

class PasswordAuth: public SSHAuthMethod {
public:
  PasswordAuth(bool noPaswordQuery = false): mNoPaswordQuery(noPaswordQuery) {}

  int flag() override {return SSH_AUTH_METHOD_PASSWORD;};
  TQString name() override { return i18n("password"); };
  int authenticate(sftpProtocol *ioslave) const override {
    return ioslave->authenticatePassword(mNoPaswordQuery);
  }
  SSHAuthMethod* clone() override {return new PasswordAuth(mNoPaswordQuery); }

private:
  const bool mNoPaswordQuery;
};

// Public key authentication
int sftpProtocol::auth_callback(const char *prompt, char *buf, size_t len,
                                int echo, int verify, void *userdata)
{
  // unused variables
  (void) echo;
  (void) verify;
  (void) userdata;
  (void) prompt;

  Q_ASSERT(len>0);

  kdDebug(TDEIO_SFTP_DB) << "Entering public key authentication callback" << endl;

  int rc=0;
  mPubKeyAuthData.wasCalled = true;

  AuthInfo pubKeyInfo = authInfo();

  pubKeyInfo.keepPassword = false; // don't save passwords for public key,
                                   // that's the task of ssh-agent.
  pubKeyInfo.readOnly     = true;  // We don't want to handle user name change when authing with a key

  TQString errMsg;
  TQString keyFile;
#if LIBSSH_VERSION_INT < SSH_VERSION_INT(0, 10, 0)
  // no way to determine keyfile name on older libssh
#else
  char *ssh_key_file = 0;
  rc = ssh_userauth_publickey_auto_get_current_identity(mSession, &ssh_key_file);

  if (rc == 0 && ssh_key_file && ssh_key_file[0]) {
    keyFile = ssh_key_file;
  }
  ssh_string_free_char(ssh_key_file);
#endif

  bool firstTry = !mPubKeyAuthData.attemptedKeys.contains(keyFile);

  if (!firstTry) {
    errMsg = i18n("Incorrect or invalid passphrase.").append('\n');
  }

  // libssh prompt is trash and we know we use this function only for publickey auth, so we'll give
  // the user a descent prompt
  if (!keyFile.isEmpty()) {
      pubKeyInfo.prompt = i18n("Please enter the passphrase for next public key:\n%1").arg(keyFile);
  } else { // Generally shouldn't happend but on older libssh
      pubKeyInfo.prompt = i18n("Please enter the passphrase for your public key.");
  }

  // We don't want to clobber with normal passwords in kpasswdserver's cache
  pubKeyInfo.realmValue = "keyfile passphrase:" + keyFile;

  if (openPassDlg(pubKeyInfo, errMsg)) {
    if (len < pubKeyInfo.password.utf8().length()+1) {
      kdDebug(TDEIO_SFTP_DB) << "Insufficient buffer size for password: " << len
        << " (" << pubKeyInfo.password.utf8().length()+1 << "needed)" << endl;
    }

    strncpy(buf, pubKeyInfo.password.utf8().data(), len-1);
    buf[len-1]=0; // Just to be on the safe side

    purgeString(pubKeyInfo.password);
  } else {
    kdDebug(TDEIO_SFTP_DB) << "User canceled entry of public key passphrase" << endl;
    rc = -1;
    mPubKeyAuthData.wasCanceled = true;
  }

  // take a note that we already tried unlocking this keyfile
  if(firstTry) {
    mPubKeyAuthData.attemptedKeys.append(keyFile);
  }

  return rc;
}

void sftpProtocol::log_callback(ssh_session session, int priority,
    const char *message, void *userdata) {
  (void) session;
  (void) userdata;

  kdDebug(TDEIO_SFTP_DB) << "[" << priority << "] " << message << endl;
}

int sftpProtocol::authenticatePublicKey(){
  // First let's do some cleanup
  mPubKeyAuthData.wasCalled = 0;
  mPubKeyAuthData.wasCanceled = 0;
  mPubKeyAuthData.attemptedKeys.clear();

  kdDebug(TDEIO_SFTP_DB) << "Trying to authenticate with public key" << endl;
  int rc;

  while (1) {
    mPubKeyAuthData.wasCalled = 0;
    rc = ssh_userauth_publickey_auto(mSession, nullptr, nullptr);

    kdDebug(TDEIO_SFTP_DB) << "ssh_userauth_publickey_auto returned rc=" << rc
      << " ssh_err=" << ssh_get_error_code(mSession)
      << " (" <<  ssh_get_error(mSession) << ")" << endl;
    if (rc == SSH_AUTH_DENIED) {
      if (!mPubKeyAuthData.wasCalled) {
        kdDebug(TDEIO_SFTP_DB) << "Passkey auth denied because it has no matching key" << endl;
        break; /* rc == SSH_AUTH_DENIED */
      } else if (mPubKeyAuthData.wasCanceled) {
        kdDebug(TDEIO_SFTP_DB) << "Passkey auth denied because user canceled" << endl;
        rc = sftpProtocol::SSH_AUTH_CANCELED;
        break;
      } else {
        kdDebug(TDEIO_SFTP_DB) << "User entered wrong passphrase for the key" << endl;
        // Try it again
      }
    } else {
      // every other rc is either error or success
      break;
    }
  }

  return rc;
}

int sftpProtocol::authenticateKeyboardInteractive(bool noPaswordQuery) {
  int rc = SSH_AUTH_ERROR;

  kdDebug(TDEIO_SFTP_DB) << "Entering keyboard interactive function" << endl;

  while (1) {
    int n = 0;
    int i = 0;

    rc = ssh_userauth_kbdint(mSession, NULL, NULL);

    if (rc == SSH_AUTH_DENIED) { // do nothing
      kdDebug(TDEIO_SFTP_DB) << "kb-interactive auth was denied; retrying again" << endl;
    } else if (rc != SSH_AUTH_INFO) {
      kdDebug(TDEIO_SFTP_DB) << "Finishing kb-interactive auth rc=" << rc
        << " ssh_err=" << ssh_get_error_code(mSession)
        << " (" <<  ssh_get_error(mSession) << ")" << endl;
      break;
    }

    // See "RFC4256 Section 3.3 User Interface" for meaning of the values
    TQString name, instruction, prompt;
    name = TQString::fromUtf8(ssh_userauth_kbdint_getname(mSession));
    instruction = TQString::fromUtf8(ssh_userauth_kbdint_getinstruction(mSession));
    n = ssh_userauth_kbdint_getnprompts(mSession);

    kdDebug(TDEIO_SFTP_DB) << "name=" << name << " instruction=" << instruction
      << " prompts:" << n << endl;

    for (i = 0; i < n; ++i) {
      char echo;
      bool isPassword=false;
      TQString answer;
      TQString errMsg;

      prompt = TQString::fromUtf8(ssh_userauth_kbdint_getprompt(mSession, i, &echo));
      kdDebug(TDEIO_SFTP_DB) << "prompt=" << prompt << " echo=" << TQString::number(echo) << endl;

      TDEIO::AuthInfo infoKbdInt = authInfo();
      infoKbdInt.realmValue = prompt; // each prompt will be treated on its own by kpasswdserver
      infoKbdInt.keepPassword = false;

      if (!name.isEmpty()) {
        infoKbdInt.caption = TQString(i18n("SFTP Login") + " - " + name);
      }

      // Those strings might or might not contain some sensitive information
      PasswordPurger answerPurger{answer};
      PasswordPurger infoPurger{infoKbdInt.password};

      if (!echo) {
        // ssh server requests us to ask user a question without displaying an answer. In normal
        // circumstances this is probably a password, but it might be something else depending
        // on the server configuration.
        if (prompt.lower().startsWith("password")) {
          // We can assume that the ssh server asks for a password and we will handle that case
          // with more care since it's what most users will see
          isPassword = true;
          if (noPaswordQuery) { // if we have a cached password we might use it
            kdDebug(TDEIO_SFTP_DB) << "Using cached password" << endl;
            answer = mPassword;
            purgeString(mPassword); // if we used up password purge it
          } else {
            infoKbdInt.prompt = i18n("Please enter your password.");
            infoKbdInt.realmValue = TQString(); // passwords use generic realm
            infoKbdInt.keepPassword = true;

            if (mPasswordWasPrompted) {
              errMsg = i18n("Login failed: incorrect password or username.").append('\n');
            }
            mPasswordWasPrompted = true;
          }
        } else {
          // If the server's request doesn't look like a password, keep the servers prompt but
          // don't prompt for saving the answer
          infoKbdInt.prompt = i18n("Please enter answer for the next request:");
          if (!instruction.isEmpty()) {
            infoKbdInt.prompt.append("\n\n").append(instruction);
          }
          infoKbdInt.prompt.append("\n\n").append(prompt);
          infoKbdInt.readOnly = true; // set username readonly (enable changing it only with password)
        }

        if (answer.isNull()) {
          if (openPassDlg(infoKbdInt, errMsg)) {
            answer = infoKbdInt.password;
            kdDebug(TDEIO_SFTP_DB) << "Got the answer from the password dialog" << endl;

            if (isPassword) {
              TQString sshUser=sshUsername();
              if (infoKbdInt.username != sshUser) {
                kdDebug(TDEIO_SFTP_DB) << "Username changed from " << sshUser
                                       << " to " << infoKbdInt.username << endl;
                mCachedUsername = infoKbdInt.username;
                mPassword = infoKbdInt.password;

                return sftpProtocol::SSH_AUTH_NEED_RECONNECT;
              }
            }
          } else {
            return sftpProtocol::SSH_AUTH_CANCELED;
          }
        }
      } else {
        // ssh server asks for some clear-text information from a user (e.g. a one-time
        // identification code) which should be echoed while user enters it. As for now tdeio has
        // no means to handle that correctly, so we will have to be creative with the password
        // dialog.
        TQString newPrompt;

        if (!instruction.isEmpty()) {
          newPrompt = instruction + "\n\n";
        }
        newPrompt.append(prompt).append("\n\n");
        newPrompt.append(i18n("Use the username input field to answer this question."));
        infoKbdInt.prompt = newPrompt;

        infoKbdInt.url.setUser(infoKbdInt.username);
        infoKbdInt.username = TQString::null;

        infoKbdInt.readOnly = false;

        if (openPassDlg(infoKbdInt)) {
          answer = infoKbdInt.username;
          kdDebug(TDEIO_SFTP_DB) << "Got the answer from the password dialog: " << answer << endl;
        } else {
          return sftpProtocol::SSH_AUTH_CANCELED;
        }
      }

      if (ssh_userauth_kbdint_setanswer(mSession, i, answer.utf8().data()) < 0) {
        kdDebug(TDEIO_SFTP_DB) << "An error occurred setting the answer: "
          << ssh_get_error(mSession) << endl;
        /* FIXME: display the error to the user <2024-01-10 Fat-Zer> */
        return SSH_AUTH_ERROR;
      }
    } // for each ssh_userauth_kbdint_getprompt()
  } // while (1)

  return rc;
}

int sftpProtocol::authenticatePassword(bool noPaswordQuery) {
  kdDebug(TDEIO_SFTP_DB) << "Trying to authenticate with password" << endl;

  AuthInfo info = authInfo();
  info.keepPassword = true;
  info.prompt = i18n("Please enter your username and password.");

  int rc;
  do {
    TQString errMsg;
    TQString password;

    PasswordPurger pPurger(password);

    if(noPaswordQuery) { // on the first try use cached password
      password = mPassword;
      purgeString(mPassword);
    } else {
      if (mPasswordWasPrompted) {
        errMsg = i18n("Login failed: incorrect password or username.").append('\n');
      }

      mPasswordWasPrompted = true;

      // Handle user canceled or dialog failed to open...
      if (!openPassDlg(info, errMsg)) {
        kdDebug(TDEIO_SFTP_DB) << "User canceled password dialog" << endl;
        return sftpProtocol::SSH_AUTH_CANCELED;
      }

      password = info.password;

      TQString sshUser=sshUsername();
      if (info.username != sshUser) {
        kdDebug(TDEIO_SFTP_DB) << "Username changed from " << sshUser
                               << " to " << info.username << endl;
        mCachedUsername = info.username;
        mPassword = info.password;
        // libssh doc says that most servers don't permit changing the username during
        // authentication, so we should reinitialize the session here
        return sftpProtocol::SSH_AUTH_NEED_RECONNECT;
      }
    }

    rc = ssh_userauth_password(mSession, NULL, password.utf8().data());

  } while (rc == SSH_AUTH_DENIED && !noPaswordQuery);
  return rc;
}


TQString sftpProtocol::sshUsername() {
  int rc;
  TQString rv;

  char *ssh_username = NULL;
  rc = ssh_options_get(mSession, SSH_OPTIONS_USER, &ssh_username);
  if (rc == 0 && ssh_username && ssh_username[0]) {
    rv = TQString::fromUtf8(ssh_username);
  }
  ssh_string_free_char(ssh_username);

  return rv;
}


TDEIO::AuthInfo sftpProtocol::authInfo() {
  TDEIO::AuthInfo rv;

  rv.url.setProtocol("sftp");
  rv.url.setHost(mHost);
  rv.url.setPort(mPort);
  rv.url.setUser(mUsername);

  rv.caption = i18n("SFTP Login");
  rv.comment = "sftp://" + mHost + ':' + TQString::number(mPort);
  rv.commentLabel = i18n("site:");

  if(!mUsername.isEmpty()) {
    rv.username = mUsername;
  } if(!mCachedUsername.isEmpty()) {
    rv.username = mCachedUsername;
  } else if (mSession) {
    rv.username = sshUsername();
  }

  // if username was specified in the address string it shouldn't be changed
  if (!mUsername.isEmpty()) {
    rv.readOnly = true;
  }

  return rv;
}

void sftpProtocol::reportError(const KURL &url, const int err) {
  kdDebug(TDEIO_SFTP_DB) << "url = " << url.url() << " - err=" << err << endl;

  switch (err) {
    case SSH_FX_OK:
      break;
    case SSH_FX_NO_SUCH_FILE:
    case SSH_FX_NO_SUCH_PATH:
      error(TDEIO::ERR_DOES_NOT_EXIST, url.prettyURL());
      break;
    case SSH_FX_PERMISSION_DENIED:
      error(TDEIO::ERR_ACCESS_DENIED, url.prettyURL());
      break;
    case SSH_FX_FILE_ALREADY_EXISTS:
      error(TDEIO::ERR_FILE_ALREADY_EXIST, url.prettyURL());
      break;
    case SSH_FX_INVALID_HANDLE:
      error(TDEIO::ERR_MALFORMED_URL, url.prettyURL());
      break;
    case SSH_FX_OP_UNSUPPORTED:
      error(TDEIO::ERR_UNSUPPORTED_ACTION, url.prettyURL());
      break;
    case SSH_FX_BAD_MESSAGE:
      error(TDEIO::ERR_UNKNOWN, url.prettyURL());
      break;
    default:
      error(TDEIO::ERR_INTERNAL, url.prettyURL());
      break;
  }
}

bool sftpProtocol::createUDSEntry(const TQString &filename, const TQByteArray &path,
      UDSEntry &entry, short int details) {
  mode_t type;
  mode_t access;
  char *link;

  Q_ASSERT(entry.count() == 0);

  sftp_attributes sb = sftp_lstat(mSftp, path.data());
  if (sb == NULL) {
    return false;
  }

  UDSAtom atom;
  atom.m_uds = UDS_NAME;
  atom.m_str = filename;
  entry.append(atom);

  if (sb->type == SSH_FILEXFER_TYPE_SYMLINK) {
    atom.m_uds = UDS_FILE_TYPE;
    atom.m_long = S_IFREG;
    entry.append(atom);
    link = sftp_readlink(mSftp, path.data());
    if (link == NULL) {
      sftp_attributes_free(sb);
      return false;
    }
    atom.m_uds = UDS_LINK_DEST;
    atom.m_str = TQFile::decodeName(link);
    entry.append(atom);
    delete link;
    // A symlink -> follow it only if details > 1
    if (details > 1) {
      sftp_attributes sb2 = sftp_stat(mSftp, path.data());
      if (sb2 == NULL) {
        // It is a link pointing to nowhere
        type = S_IFMT - 1;
        access = S_IRWXU | S_IRWXG | S_IRWXO;
        atom.m_uds = UDS_FILE_TYPE;
        atom.m_long = type;
        entry.append(atom);

        atom.m_uds = UDS_ACCESS;
        atom.m_long = access;
        entry.append(atom);

        atom.m_uds = UDS_SIZE;
        atom.m_long = 0LL;
        entry.append(atom);

        goto notype;
      }
      sftp_attributes_free(sb);
      sb = sb2;
    }
  }

  switch (sb->type) {
    case SSH_FILEXFER_TYPE_REGULAR:
      atom.m_uds = UDS_FILE_TYPE;
      atom.m_long = S_IFREG;
      entry.append(atom);
      break;
    case SSH_FILEXFER_TYPE_DIRECTORY:
      atom.m_uds = UDS_FILE_TYPE;
      atom.m_long = S_IFDIR;
      entry.append(atom);
      break;
    case SSH_FILEXFER_TYPE_SYMLINK:
      atom.m_uds = UDS_FILE_TYPE;
      atom.m_long = S_IFLNK;
      entry.append(atom);
      break;
    case SSH_FILEXFER_TYPE_SPECIAL:
    case SSH_FILEXFER_TYPE_UNKNOWN:
      atom.m_uds = UDS_FILE_TYPE;
      atom.m_long = S_IFMT - 1;
      entry.append(atom);
      break;
  }

  access = sb->permissions & 07777;
  atom.m_uds = UDS_ACCESS;
  atom.m_long = access;
  entry.append(atom);

  atom.m_uds = UDS_SIZE;
  atom.m_long = sb->size;
  entry.append(atom);

notype:
  if (details > 0) {
    if (sb->owner) {
      atom.m_uds = UDS_USER;
      atom.m_str = TQString::fromUtf8(sb->owner);
      entry.append(atom);
    } else {
      atom.m_uds = UDS_USER;
      atom.m_str = TQString::number(sb->uid);
      entry.append(atom);
    }

    if (sb->group) {
      atom.m_uds = UDS_GROUP;
      atom.m_str = TQString::fromUtf8(sb->group);
      entry.append(atom);
    } else {
      atom.m_uds = UDS_GROUP;
      atom.m_str = TQString::number(sb->gid);
      entry.append(atom);
    }
    atom.m_uds = UDS_ACCESS_TIME;
    atom.m_long = sb->atime;
    entry.append(atom);

    atom.m_uds = UDS_MODIFICATION_TIME;
    atom.m_long = sb->mtime;
    entry.append(atom);

    atom.m_uds = UDS_MODIFICATION_TIME;
    atom.m_long = sb->createtime;
    entry.append(atom);
  }

  sftp_attributes_free(sb);

  return true;
}

TQString sftpProtocol::canonicalizePath(const TQString &path) {
  kdDebug(TDEIO_SFTP_DB) << "Path to canonicalize: " << path << endl;
  TQString cPath;
  char *sPath = NULL;

  if (path.isEmpty()) {
    return cPath;
  }

  sPath = sftp_canonicalize_path(mSftp, path.utf8().data());
  if (sPath == NULL) {
    kdDebug(TDEIO_SFTP_DB) << "Could not canonicalize path: " << path << endl;
    return cPath;
  }

  cPath = TQFile::decodeName(sPath);
  delete sPath;

  kdDebug(TDEIO_SFTP_DB) << "Canonicalized path: " << cPath << endl;

  return cPath;
}

sftpProtocol::sftpProtocol(const TQCString &pool_socket, const TQCString &app_socket)
             : SlaveBase("tdeio_sftp", pool_socket, app_socket),
                  mConnected(false), mPort(-1), mSession(NULL), mSftp(NULL) {
#ifndef TQ_WS_WIN
  kdDebug(TDEIO_SFTP_DB) << "pid = " << getpid() << endl;

  kdDebug(TDEIO_SFTP_DB) << "debug = " << getenv("TDEIO_SFTP_LOG_VERBOSITY") << endl;
#endif

  mCallbacks = (ssh_callbacks) malloc(sizeof(struct ssh_callbacks_struct));
  if (mCallbacks == NULL) {
    error(TDEIO::ERR_OUT_OF_MEMORY, i18n("Could not allocate callbacks"));
    return;
  }
  ZERO_STRUCTP(mCallbacks);

  mCallbacks->userdata = this;
  mCallbacks->auth_function = ::auth_callback;
  if (getenv("TDEIO_SFTP_LOG_VERBOSITY")) {
    mCallbacks->log_function = ::log_callback;
  }

  ssh_callbacks_init(mCallbacks);
}

sftpProtocol::~sftpProtocol() {
#ifndef TQ_WS_WIN
  kdDebug(TDEIO_SFTP_DB) << "pid = " << getpid() << endl;
#endif
  closeConnection();

  free(mCallbacks);

  /* cleanup and shut down cryto stuff */
  ssh_finalize();

  purgeString(mPassword);
}

void sftpProtocol::setHost(const TQString& h, int port, const TQString& user, const TQString& pass) {
  kdDebug(TDEIO_SFTP_DB) << "setHost(): " << user << "@" << h << ":" << port << endl;

  if (mConnected) {
    closeConnection();
  }

  mHost = h;

  if (port > 0) {
    mPort = port;
  } else {
    struct servent *pse;
    if ((pse = getservbyname("ssh", "tcp") ) == NULL) {
      mPort = 22;
    } else {
      mPort = ntohs(pse->s_port);
    }
  }

  kdDebug(TDEIO_SFTP_DB) << "setHost(): mPort=" << mPort << endl;

  mUsername = user;
  mPassword = pass;
  mCachedUsername = TQString::null;
}


int sftpProtocol::initializeConnection() {
  unsigned char *hash = NULL; // the server hash
  char *hexa;
  char *verbosity;
  int rc, state;
  int timeout_sec = 30, timeout_usec = 0;

  mSession = ssh_new();
  if (mSession == NULL) {
    error(TDEIO::ERR_INTERNAL, i18n("Could not create a new SSH session."));
    return SSH_ERROR;
  }

  kdDebug(TDEIO_SFTP_DB) << "Creating the SSH session and setting options" << endl;

  // Set timeout
  rc = ssh_options_set(mSession, SSH_OPTIONS_TIMEOUT, &timeout_sec);
  if (rc < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Could not set a timeout.";
  }
  rc = ssh_options_set(mSession, SSH_OPTIONS_TIMEOUT_USEC, &timeout_usec);
  if (rc < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Could not set a timeout in usec.";
  }

  // Don't use any compression
  rc = ssh_options_set(mSession, SSH_OPTIONS_COMPRESSION_C_S, "none");
  if (rc < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Could not set compression client <- server.";
  }

  rc = ssh_options_set(mSession, SSH_OPTIONS_COMPRESSION_S_C, "none");
  if (rc < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Could not set compression server -> client.";
  }

  // Set host and port
  rc = ssh_options_set(mSession, SSH_OPTIONS_HOST, mHost.utf8().data());
  if (rc < 0) {
    error(TDEIO::ERR_OUT_OF_MEMORY, i18n("Could not set host."));
    return SSH_ERROR;
  }

  if (mPort > 0) {
    rc = ssh_options_set(mSession, SSH_OPTIONS_PORT, &mPort);
    if (rc < 0) {
      error(TDEIO::ERR_OUT_OF_MEMORY, i18n("Could not set port."));
      return SSH_ERROR;
    }
  }

  // Set the username
  if (!mCachedUsername.isEmpty() || !mUsername.isEmpty()) {
    TQString username = !mCachedUsername.isEmpty() ? mCachedUsername : mUsername;
    rc = ssh_options_set(mSession, SSH_OPTIONS_USER, username.utf8().data());
    if (rc < 0) {
      error(TDEIO::ERR_OUT_OF_MEMORY, i18n("Could not set username."));
      return rc;
    }
  }

  verbosity = getenv("TDEIO_SFTP_LOG_VERBOSITY");
  if (verbosity) {
    rc = ssh_options_set(mSession, SSH_OPTIONS_LOG_VERBOSITY_STR, verbosity);
    if (rc < 0) {
      error(TDEIO::ERR_OUT_OF_MEMORY, i18n("Could not set log verbosity."));
      return rc;
    }
  }

  // Read ~/.ssh/config
  rc = ssh_options_parse_config(mSession, NULL);
  if (rc < 0) {
    error(TDEIO::ERR_INTERNAL, i18n("Could not parse the config file."));
    return rc;
  }

  ssh_set_callbacks(mSession, mCallbacks);

  kdDebug(TDEIO_SFTP_DB) << "Trying to connect to the SSH server" << endl;

  /* try to connect */
  rc = ssh_connect(mSession);
  if (rc < 0) {
    error(TDEIO::ERR_COULD_NOT_CONNECT, TQString::fromUtf8(ssh_get_error(mSession)));
    return rc;
  }

  ExitGuard connectionCloser([this](){ closeConnection(); });

  kdDebug(TDEIO_SFTP_DB) << "Getting the SSH server hash" << endl;

  /* get the hash */
  ssh_key serverKey;
#if LIBSSH_VERSION_INT < SSH_VERSION_INT(0, 7, 90)
  rc = ssh_get_publickey(mSession, &serverKey);
#else
  rc = ssh_get_server_publickey(mSession, &serverKey);
#endif
  if (rc<0) {
    error(TDEIO::ERR_COULD_NOT_CONNECT, TQString::fromUtf8(ssh_get_error(mSession)));
    return rc;
  }

  size_t hlen;
#if LIBSSH_VERSION_INT < SSH_VERSION_INT(0, 8, 90)
  rc = ssh_get_publickey_hash(serverKey, SSH_PUBLICKEY_HASH_MD5, &hash, &hlen);
#else
  rc = ssh_get_publickey_hash(serverKey, SSH_PUBLICKEY_HASH_SHA256, &hash, &hlen);
#endif
  if (rc<0) {
    error(TDEIO::ERR_COULD_NOT_CONNECT, TQString::fromUtf8(ssh_get_error(mSession)));
    return rc;
  }

  kdDebug(TDEIO_SFTP_DB) << "Checking if the SSH server is known" << endl;

  /* check the server public key hash */
#if LIBSSH_VERSION_INT < SSH_VERSION_INT(0, 7, 90)
  state = ssh_is_server_known(mSession);
#else
  state = ssh_session_is_known_server(mSession);
#endif
  switch (state) {
    case TDEIO_SSH_KNOWN_HOSTS_OK:
      break;
    case TDEIO_SSH_KNOWN_HOSTS_OTHER:
      delete hash;
      error(TDEIO::ERR_CONNECTION_BROKEN, i18n("The host key for this server was "
            "not found, but another type of key exists.\n"
            "An attacker might change the default server key to confuse your "
            "client into thinking the key does not exist.\n"
            "Please contact your system administrator.\n%1").arg(TQString::fromUtf8(ssh_get_error(mSession))));
      return SSH_ERROR;
    case TDEIO_SSH_KNOWN_HOSTS_CHANGED:
      hexa = ssh_get_hexa(hash, hlen);
      delete hash;
      /* TODO print known_hosts file, port? */
      error(TDEIO::ERR_CONNECTION_BROKEN, i18n("The host key for the server %1 has changed.\n"
          "This could either mean that DNS SPOOFING is happening or the IP "
          "address for the host and its host key have changed at the same time.\n"
          "The fingerprint for the key sent by the remote host is:\n %2\n"
          "Please contact your system administrator.\n%3").arg(
          mHost).arg(TQString::fromUtf8(hexa)).arg(TQString::fromUtf8(ssh_get_error(mSession))));
      delete hexa;
      return SSH_ERROR;
    case TDEIO_SSH_KNOWN_HOSTS_NOT_FOUND:
    case TDEIO_SSH_KNOWN_HOSTS_UNKNOWN: {
      TQString msg;     // msg for dialog box
      TQString caption; // dialog box caption
      hexa = ssh_get_hexa(hash, hlen);
      delete hash;
      caption = i18n("Warning: Cannot verify host's identity.");
      msg = i18n("The authenticity of host %1 cannot be established.\n"
        "The key fingerprint is: %2\n"
        "Are you sure you want to continue connecting?").arg(mHost).arg(hexa);
      delete hexa;

      if (KMessageBox::Yes != messageBox(WarningYesNo, msg, caption)) {
        error(TDEIO::ERR_USER_CANCELED, TQString());
        return SSH_ERROR;
      }

      /* write the known_hosts file */
      kdDebug(TDEIO_SFTP_DB) << "Adding server to known_hosts file." << endl;
#if LIBSSH_VERSION_INT < SSH_VERSION_INT(0, 7, 90)
      if (ssh_write_knownhost(mSession) != SSH_OK) {
#else
      if (ssh_session_update_known_hosts(mSession) != SSH_OK) {
#endif
        error(TDEIO::ERR_USER_CANCELED, TQString::fromUtf8(ssh_get_error(mSession)));
        return SSH_ERROR;
      }
      break;
    }
    case TDEIO_SSH_KNOWN_HOSTS_ERROR:
      delete hash;
      error(TDEIO::ERR_COULD_NOT_CONNECT, TQString::fromUtf8(ssh_get_error(mSession)));
      return SSH_ERROR;
  }

  kdDebug(TDEIO_SFTP_DB) << "Trying to authenticate with the server" << endl;

  connectionCloser.abort();

  return SSH_OK;
}


void sftpProtocol::openConnection() {

  if (mConnected) {
    return;
  }

  kdDebug(TDEIO_SFTP_DB) << "username=" << mUsername << ", host=" << mHost << ", port=" << mPort << endl;

  infoMessage(i18n("Opening SFTP connection to host %1:%2").arg(mHost).arg(mPort));

  if (mHost.isEmpty()) {
    kdDebug(TDEIO_SFTP_DB) << "openConnection(): Need hostname..." << endl;
    error(TDEIO::ERR_UNKNOWN_HOST, i18n("No hostname specified."));
    return;
  }

  // Check for cached authentication info if no password is specified...
  if (mPassword.isEmpty()) {
    AuthInfo info = authInfo();

    kdDebug(TDEIO_SFTP_DB) << "checking cache: info.username = " << info.username
      << ", info.url = " << info.url.prettyURL() << endl;

    if (checkCachedAuthentication(info)) {
      kdDebug() << "using cached" << endl;
      mCachedUsername = info.username;
      mPassword = info.password;

      purgeString(info.password); //< not really necessary because of Qt's implicit data sharing
    }
  }

  mPasswordWasPrompted = false;
  PasswordPurger pwPurger{mPassword};

  int rc;

connection_restart:
  // Start the ssh connection.
  if (initializeConnection() < 0) {
    return;
  }
  ExitGuard connectionCloser([this](){ closeConnection(); });

  // Try to authenticate (this required before calling ssh_auth_list())
  rc = ssh_userauth_none(mSession, NULL);
  if (rc == SSH_AUTH_ERROR) {
    error(TDEIO::ERR_COULD_NOT_LOGIN, i18n("Authentication failed (method: %1).")
                                      .arg(i18n("none")));
    return;
  }


  // Preinit the list of supported auth methods
  static const auto authMethodsNormal= [](){
    std::vector<std::unique_ptr<SSHAuthMethod>> rv;
    rv.emplace_back(std::make_unique<PublicKeyAuth>());
    rv.emplace_back(std::make_unique<KeyboardInteractiveAuth>());
    rv.emplace_back(std::make_unique<PasswordAuth>());
    return rv;
  }();

  const static int supportedMethods = std::accumulate(
      authMethodsNormal.begin(), authMethodsNormal.end(),
      SSH_AUTH_METHOD_NONE | SSH_AUTH_METHOD_HOSTBASED, //< methods supported automagically
      [](int acc, const auto &m){ return acc |= m->flag(); });

  int attemptedMethods = 0;

  while (rc != SSH_AUTH_SUCCESS) {
    // Note this loop can rerun in case of multistage ssh authentication e.g. "password,publickey"
    // which will require user to provide a valid password at first and then a valid public key.
    // see AuthenticationMethods in man 5 sshd_config for more info
    bool wasCanceled = false;
    int availableMethodes = ssh_auth_list(mSession);

    if (!availableMethodes) {
      // Technically libssh docs suggest that the server merely MAY send auth methods, but it's
      // highly unclear what we should do in such case and it looks like openssh doesn't have an
      // option for that, so let's just consider this server a jerk and don't talk to him anymore.
      error(TDEIO::ERR_COULD_NOT_LOGIN, i18n("Authentication failed."
            " The server did not send any authentication methods!"));
      return;
    } else if (!(availableMethodes & supportedMethods)) {
      error(TDEIO::ERR_COULD_NOT_LOGIN, i18n("Authentication failed."
            " The server sent only unsupported authentication methods!"));
      return;
    }

    const auto *authMethods = &authMethodsNormal;

    // If we have cached password we want try to use it before public key
    if(!mPassword.isEmpty()) {
      static const auto authMethodsWithPassword = []() {
        std::vector<std::unique_ptr<SSHAuthMethod>> rv;
        rv.emplace_back(std::make_unique<KeyboardInteractiveAuth>(/* noPasswordQuery = */true));
        rv.emplace_back(std::make_unique<PasswordAuth>(/* noPasswordQuery = */true));
        for (const auto &m: authMethodsNormal) { rv.emplace_back(m->clone()); }
        return rv;
      }();

      authMethods = &authMethodsWithPassword;
    }

    // Actually iterate over the list of methods and try them out
    for (const auto &method: *authMethods) {
      if (!(availableMethodes & method->flag())) { continue; }

      rc = method->authenticate( this );
      attemptedMethods |= method->flag();
      if (rc == SSH_AUTH_SUCCESS || rc == SSH_AUTH_PARTIAL) {
        kdDebug(TDEIO_SFTP_DB) << "method=" << method->name() << ": auth "
          << (rc == SSH_AUTH_SUCCESS ? "success" : "partial") << endl;
        break; // either next auth method or continue on with the connect
      } else if (rc == SSH_AUTH_AGAIN || rc == SSH_AUTH_ERROR ) {
        // SSH_AUTH_AGAIN returned in case of some errors like if server hangs up or there were too many auth attempts
        error(TDEIO::ERR_COULD_NOT_LOGIN, i18n("Authentication failed (method: %1).")
            .arg(method->name()));
        /* FIXME: add some additional info from ssh_get_error() if available <2024-01-20 Fat-Zer> */
        return;
      } else if (rc == SSH_AUTH_CANCELED) {
        kdDebug(TDEIO_SFTP_DB) << "method=" << method->name() << " was canceled by user"  << endl;
        // don't quit immediately due to that the user might have canceled one method to use another
        wasCanceled = true;
      } else if (rc == SSH_AUTH_NEED_RECONNECT) {
        kdDebug(TDEIO_SFTP_DB) << "method=" << method->name() << " requested reconnection"  << endl;
        goto connection_restart;
      } else if (rc == SSH_AUTH_DENIED) {
        kdDebug(TDEIO_SFTP_DB) << "Auth for method=" << method->name() << " was denied"  << endl;
        // do nothing, just proceed with next auth method
      } else {
        // Shouldn't happen, but to be on the safe side better handle it
        error(TDEIO::ERR_UNKNOWN, i18n("Authentication failed unexpectedly"));
        return;
      }
    }

    // At this point rc values should be one of:
    //   SSH_AUTH_SUCCESS, SSH_AUTH_PARTIAL, SSH_AUTH_DENIED or SSH_AUTH_CANCELED
    if (wasCanceled && (rc == SSH_AUTH_CANCELED || rc == SSH_AUTH_DENIED)) {
      error(TDEIO::ERR_USER_CANCELED, TQString::null);
      return;
    } else if (rc != SSH_AUTH_SUCCESS && rc != SSH_AUTH_PARTIAL) {
      TQStringList attemptedMethodsLst;
      for (auto &method: authMethodsNormal) {
        if (attemptedMethods & method->flag()) { attemptedMethodsLst  << method->name(); }
      }

      TQString errMsg = i18n("Authentication denied (attempted method was: %1).",
                             "Authentication denied (attempted methods were: %1).",
                              attemptedMethodsLst.size())
                        .arg(attemptedMethodsLst.join(", "));
      if (availableMethodes & ~supportedMethods) {
        errMsg.append("\n")
              .append(i18n("Note: server also declares some other unsupported authentication methods"));
      }
      error(TDEIO::ERR_COULD_NOT_LOGIN, errMsg);
      return;
    }
  }

  // start sftp session
  kdDebug(TDEIO_SFTP_DB) << "Trying to request the sftp session" << endl;
  mSftp = sftp_new(mSession);
  if (mSftp == NULL) {
    error(TDEIO::ERR_COULD_NOT_LOGIN, i18n("Unable to request the SFTP subsystem. "
          "Make sure SFTP is enabled on the server."));
    return;
  }

  kdDebug(TDEIO_SFTP_DB) << "Trying to initialize the sftp session" << endl;
  if (sftp_init(mSftp) < 0) {
    error(TDEIO::ERR_COULD_NOT_LOGIN, i18n("Could not initialize the SFTP session."));
    return;
  }

  // Login succeeded!
  infoMessage(i18n("Successfully connected to %1").arg(mHost));

  //setTimeoutSpecialCommand(TDEIO_SFTP_SPECIAL_TIMEOUT);

  mConnected = true;
  connectionCloser.abort();

  connected();

  return;
}

void sftpProtocol::closeConnection() {
  kdDebug(TDEIO_SFTP_DB) << "closeConnection()" << endl;

  sftp_free(mSftp);
  mSftp = NULL;

  ssh_disconnect(mSession);
  mSession = NULL;

  mConnected = false;
}

#if 0
void sftpProtocol::special(const TQByteArray &data) {
    int rc;
    kdDebug(TDEIO_SFTP_DB) << "special(): polling";

    /*
     * channel_poll() returns the number of bytes that may be read on the
     * channel. It does so by checking the input buffer and eventually the
     * network socket for data to read. If the input buffer is not empty, it
     * will not probe the network (and such not read packets nor reply to
     * keepalives).
     *
     * As channel_poll can act on two specific buffers (a channel has two
     * different stream: stdio and stderr), polling for data on the stderr
     * stream has more chance of not being in the problematic case (data left
     * in the buffer). Checking the return value (for >0) would be a good idea
     * to debug the problem.
     */
    rc = channel_poll(mSftp->channel, 0);
    if (rc > 0) {
        rc = channel_poll(mSftp->channel, 1);
    }

    if (rc < 0) {
        kdDebug(TDEIO_SFTP_DB) << "channel_poll failed: " << ssh_get_error(mSession);
    }

    setTimeoutSpecialCommand(TDEIO_SFTP_SPECIAL_TIMEOUT);
}
#endif

void sftpProtocol::statMime(const KURL &url) {
  kdDebug(TDEIO_SFTP_DB) << "stat: " << url.url() << endl;

  openConnection();
  if (!mConnected) {
    error(TDEIO::ERR_CONNECTION_BROKEN, url.prettyURL());
    return;
  }

  const TQString path = url.path();
  const TQByteArray path_c = path.utf8();

  sftp_attributes sb = sftp_lstat(mSftp, path_c.data());
  if (sb == NULL) {
    reportError(url, sftp_get_error(mSftp));
    return;
  }

  switch (sb->type) {
    case SSH_FILEXFER_TYPE_DIRECTORY:
      sftp_attributes_free(sb);
      emit mimeType("inode/directory");
      return;
    case SSH_FILEXFER_TYPE_SPECIAL:
    case SSH_FILEXFER_TYPE_UNKNOWN:
      error(TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL());
      sftp_attributes_free(sb);
      return;
    case SSH_FILEXFER_TYPE_SYMLINK:
    case SSH_FILEXFER_TYPE_REGULAR:
      break;
  }

  size_t fileSize = sb->size;
  sftp_attributes_free(sb);

  int flags = 0;

  flags = O_RDONLY;

  mOpenFile = sftp_open(mSftp, path_c.data(), flags, 0);

  if (mOpenFile == NULL) {
    error(TDEIO::ERR_CANNOT_OPEN_FOR_READING, path);
    return;
  }

  // Determine the mimetype of the file to be retrieved, and emit it.
  // This is mandatory in all slaves (for KRun/BrowserRun to work).
  // If we're not opening the file ReadOnly or ReadWrite, don't attempt to
  // read the file and send the mimetype.
  size_t bytesRequested = 1024;
  ssize_t bytesRead = 0;
  TQByteArray buffer(bytesRequested);

  bytesRead = sftp_read(mOpenFile, buffer.data(), bytesRequested);
  if (bytesRead < 0) {
      error(TDEIO::ERR_COULD_NOT_READ, mOpenUrl.prettyURL());
      closeFile();
      return;
  } else {
      TQByteArray fileData;
      fileData.setRawData(buffer.data(), bytesRead);
      KMimeMagicResult *p_mimeType = KMimeMagic::self()->findBufferFileType(fileData, mOpenUrl.fileName());
      emit mimeType(p_mimeType->mimeType());
  }

  sftp_close(mOpenFile);

  mOpenFile = NULL;
}

#if 0
void sftpProtocol::read(TDEIO::filesize_t bytes) {
  kdDebug(TDEIO_SFTP_DB) << "read, offset = " << openOffset << ", bytes = " << bytes;

  Q_ASSERT(mOpenFile != NULL);

  TQVarLengthArray<char> buffer(bytes);

  ssize_t bytesRead = sftp_read(mOpenFile, buffer.data(), bytes);
  Q_ASSERT(bytesRead <= static_cast<ssize_t>(bytes));

  if (bytesRead < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Could not read " << mOpenUrl;
    error(TDEIO::ERR_COULD_NOT_READ, mOpenUrl.prettyURL());
    close();
    return;
  }

  TQByteArray fileData = TQByteArray::fromRawData(buffer.data(), bytesRead);
  data(fileData);
}

void sftpProtocol::write(const TQByteArray &data) {
  kdDebug(TDEIO_SFTP_DB) << "write, offset = " << openOffset << ", bytes = " << data.size();

  Q_ASSERT(mOpenFile != NULL);

  ssize_t bytesWritten = sftp_write(mOpenFile, data.data(), data.size());
  if (bytesWritten < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Could not write to " << mOpenUrl;
    error(TDEIO::ERR_COULD_NOT_WRITE, mOpenUrl.prettyURL());
    close();
    return;
  }

  written(bytesWritten);
}

void sftpProtocol::seek(TDEIO::filesize_t offset) {
  kdDebug(TDEIO_SFTP_DB) << "seek, offset = " << offset;

  Q_ASSERT(mOpenFile != NULL);

  if (sftp_seek64(mOpenFile, static_cast<uint64_t>(offset)) < 0) {
    error(TDEIO::ERR_COULD_NOT_SEEK, mOpenUrl.path());
    close();
  }

  position(sftp_tell64(mOpenFile));
}
#endif

void sftpProtocol::closeFile() {
  if (mOpenFile) {
    sftp_close(mOpenFile);

    mOpenFile = NULL;
    finished();
  }
}

void sftpProtocol::get(const KURL& url) {
  kdDebug(TDEIO_SFTP_DB) << "get(): " << url.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  TQByteArray path = url.path().utf8();

  char buf[MAX_XFER_BUF_SIZE] = {0};
  sftp_file file = NULL;
  ssize_t bytesread = 0;
  // time_t curtime = 0;
  time_t lasttime = 0;
  time_t starttime = 0;
  ssize_t totalbytesread  = 0;

  sftp_attributes sb = sftp_lstat(mSftp, path.data());
  if (sb == NULL) {
    reportError(url, sftp_get_error(mSftp));
    return;
  }

  switch (sb->type) {
    case SSH_FILEXFER_TYPE_DIRECTORY:
      error(TDEIO::ERR_IS_DIRECTORY, url.prettyURL());
      sftp_attributes_free(sb);
      return;
    case SSH_FILEXFER_TYPE_SPECIAL:
    case SSH_FILEXFER_TYPE_UNKNOWN:
    error(TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL());
      sftp_attributes_free(sb);
      return;
    case SSH_FILEXFER_TYPE_SYMLINK:
    case SSH_FILEXFER_TYPE_REGULAR:
      break;
  }

  // Open file
  file = sftp_open(mSftp, path.data(), O_RDONLY, 0);
  if (file == NULL) {
    error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL());
    sftp_attributes_free(sb);
    return;
  }

  // Determine the mimetype of the file to be retrieved, and emit it.
  // This is mandatory in all slaves (for KRun/BrowserRun to work)
  // In real "remote" slaves, this is usually done using findByNameAndContent
  // after receiving some data. But we don't know how much data the mimemagic rules
  // need, so for local files, better use findByUrl with localUrl=true.
  KMimeType::Ptr mt = KMimeType::findByURL( url, sb->permissions, false /* remote URL */ );
  emit mimeType( mt->name() ); // FIXME test me

  kdDebug(TDEIO_SFTP_DB) << "Total size: " << TQString::number(sb->size) << endl;
  // Set the total size
  totalSize(sb->size);

  const TQString resumeOffset = metaData(TQString("resume"));
  if (!resumeOffset.isEmpty()) {
    bool ok;
    ssize_t offset = resumeOffset.toLong(&ok);
    if (ok && (offset > 0) && ((unsigned long long) offset < sb->size))
    {
      if (sftp_seek64(file, offset) == 0) {
        canResume();
        totalbytesread = offset;
        kdDebug(TDEIO_SFTP_DB) << "Resume offset: " << TQString::number(offset) << endl;
      }
    }
  }

  if (file != NULL) {
    bool isFirstPacket = true;
    lasttime = starttime = time(NULL);

    for (;;) {
      bytesread = sftp_read(file, buf, MAX_XFER_BUF_SIZE);
      kdDebug(TDEIO_SFTP_DB) << "bytesread=" << TQString::number(bytesread) << endl;
      if (bytesread == 0) {
        // All done reading
        break;
      } else if (bytesread < 0) {
        kdDebug(TDEIO_SFTP_DB) << "Failed to read";
        error(TDEIO::ERR_COULD_NOT_READ, url.prettyURL());
        sftp_attributes_free(sb);
        return;
      }

      TQByteArray  filedata;
      filedata.setRawData(buf, bytesread);
      if (isFirstPacket) {
        KMimeMagicResult *p_mimeType = KMimeMagic::self()->findBufferFileType(filedata, mOpenUrl.fileName());
        mimeType(p_mimeType->mimeType());
        kdDebug(TDEIO_SFTP_DB) << "mimetype=" << p_mimeType->mimeType() << endl;
        isFirstPacket = false;
      }
      data(filedata);
      filedata.resetRawData(buf, bytesread);

      // increment total bytes read
      totalbytesread += bytesread;

      processedSize(totalbytesread);
    }

    kdDebug(TDEIO_SFTP_DB) << "size processed=" << totalbytesread << endl;
    sftp_close(file);
    //data(TQByteArray());
    processedSize((sb->size));
  }

  sftp_attributes_free(sb);
  finished();
}

void sftpProtocol::put(const KURL& url, int permissions, bool overwrite, bool resume) {
  kdDebug(TDEIO_SFTP_DB) << "put(): " << url.url()
                      << " , permissions = " << TQString::number(permissions)
                      << ", overwrite = " << overwrite
                      << ", resume = " << resume << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  const TQString dest_orig = url.path();
  const TQByteArray dest_orig_c = dest_orig.utf8();
  const TQString dest_part = dest_orig + ".part";
  const TQByteArray dest_part_c = dest_part.utf8();
  uid_t owner = 0;
  gid_t group = 0;

  sftp_attributes sb = sftp_lstat(mSftp, dest_orig_c.data());
  const bool bOrigExists = (sb != NULL);
  bool bPartExists = false;
  const bool bMarkPartial = config()->readEntry("MarkPartial", "true") == "true";

  // Don't change permissions of the original file
  if (bOrigExists) {
      permissions = sb->permissions;
      owner = sb->uid;
      group = sb->gid;
  }

  if (bMarkPartial) {
    sftp_attributes sbPart = sftp_lstat(mSftp, dest_part_c.data());
    bPartExists = (sbPart != NULL);

    if (bPartExists && !resume && !overwrite &&
        sbPart->size > 0 && sbPart->type == SSH_FILEXFER_TYPE_REGULAR) {
      kdDebug(TDEIO_SFTP_DB) << "put : calling canResume with "
        << TQString::number(sbPart->size) << endl;

      // Maybe we can use this partial file for resuming
      // Tell about the size we have, and the app will tell us
      // if it's ok to resume or not.
      if (canResume(sbPart->size)) {
          resume = true;
      }

      kdDebug(TDEIO_SFTP_DB) << "put got answer " << resume << endl;

      delete sbPart;
    }
  }

  if (bOrigExists && !(overwrite) && !(resume)) {
    if (sb->type == SSH_FILEXFER_TYPE_DIRECTORY) {
      error(TDEIO::ERR_DIR_ALREADY_EXIST, dest_orig);
    } else {
      error(TDEIO::ERR_FILE_ALREADY_EXIST, dest_orig);
    }
    sftp_attributes_free(sb);
    return;
  }

  int result;
  TQByteArray dest;
  sftp_file file = NULL;

  // Loop until we got 0 (end of data)
  do {
    TQByteArray buffer;
    dataReq(); // Request for data
    result = readData(buffer);

    if (result >= 0 && buffer.size()) {
      kdDebug(TDEIO_SFTP_DB) << TQString("Got %1 bytes of data").arg(buffer.size()) << endl;
      if (dest.isEmpty()) {
        if (bMarkPartial) {
          kdDebug(TDEIO_SFTP_DB) << "Appending .part extension to " << dest_orig << endl;
          dest = dest_part_c;
          if (bPartExists && !(resume)) {
            kdDebug(TDEIO_SFTP_DB) << "Deleting partial file " << dest_part << endl;
            sftp_unlink(mSftp, dest_part_c.data());
            // Catch errors when we try to open the file.
          }
        } else {
          dest = dest_orig_c;
          if (bOrigExists && !(resume)) {
            kdDebug(TDEIO_SFTP_DB) << "Deleting destination file " << dest_orig << endl;
            sftp_unlink(mSftp, dest_orig_c.data());
            // Catch errors when we try to open the file.
          }
        } // bMarkPartial

        if ((resume)) {
          sftp_attributes fstat;

          kdDebug(TDEIO_SFTP_DB) << "Trying to append: " << dest.data() << endl;
          file = sftp_open(mSftp, dest.data(), O_RDWR, 0);  // append if resuming
          if (file) {
             fstat = sftp_fstat(file);
             if (fstat) {
                sftp_seek64(file, fstat->size); // Seek to end TODO
                sftp_attributes_free(fstat);
             }
          }
        } else {
          mode_t initialMode;

          if (permissions != -1) {
            initialMode = permissions | S_IWUSR | S_IRUSR;
          } else {
            initialMode = 0644;
          }

          kdDebug(TDEIO_SFTP_DB) << "Trying to open: " << dest.data() << ", mode=" << TQString::number(initialMode) << endl;
          file = sftp_open(mSftp, dest.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
        } // resume

        if (file == NULL) {
          kdDebug(TDEIO_SFTP_DB) << "COULD NOT WRITE " << dest.data()
                              << " permissions=" << permissions
                              << " error=" << ssh_get_error(mSession) << endl;
          if (sftp_get_error(mSftp) == SSH_FX_PERMISSION_DENIED) {
            error(TDEIO::ERR_WRITE_ACCESS_DENIED, TQString::fromUtf8(dest));
          } else {
            error(TDEIO::ERR_CANNOT_OPEN_FOR_WRITING, TQString::fromUtf8(dest));
          }
          sftp_attributes_free(sb);
          finished();
          return;
        } // file
      } // dest.isEmpty

      ssize_t bytesWritten = sftp_write(file, buffer.data(), buffer.size());
      kdDebug(TDEIO_SFTP_DB) << TQString("Written %1 bytes").arg(bytesWritten) << endl;
      if (bytesWritten < 0) {
        error(TDEIO::ERR_COULD_NOT_WRITE, dest_orig);
        result = -1;
      }
    } // result
  } while (result > 0);
  sftp_attributes_free(sb);

  // An error occurred deal with it.
  if (result < 0) {
    kdDebug(TDEIO_SFTP_DB) << "Error during 'put'. Aborting." << endl;

    if (file != NULL) {
      sftp_close(file);

      sftp_attributes attr = sftp_stat(mSftp, dest.data());
      if (bMarkPartial && attr != NULL) {
        size_t size = config()->readLongNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE);
        if (attr->size < size) {
          sftp_unlink(mSftp, dest.data());
        }
      }
      delete attr;
      sftp_attributes_free(attr);
    }

    //::exit(255);
    finished();
    return;
  }

  if (file == NULL) { // we got nothing to write out, so we never opened the file
    finished();
    return;
  }

  if (sftp_close(file) < 0) {
    kdWarning(TDEIO_SFTP_DB) << "Error when closing file descriptor" << endl;
    error(TDEIO::ERR_COULD_NOT_WRITE, dest_orig);
    return;
  }

  // after full download rename the file back to original name
  if (bMarkPartial) {
    // If the original URL is a symlink and we were asked to overwrite it,
    // remove the symlink first. This ensures that we do not overwrite the
    // current source if the symlink points to it.
    if ((overwrite)) {
      sftp_unlink(mSftp, dest_orig_c.data());
    }

    if (sftp_rename(mSftp, dest.data(), dest_orig_c.data()) < 0) {
      kdWarning(TDEIO_SFTP_DB) << " Couldn't rename " << dest.data() << " to " << dest_orig << endl;
      error(TDEIO::ERR_CANNOT_RENAME_PARTIAL, dest_orig);
      return;
    }
  }

  // set final permissions
  if (permissions != -1 && !(resume)) {
    kdDebug(TDEIO_SFTP_DB) << "Trying to set final permissions of " << dest_orig << " to " << TQString::number(permissions) << endl;
    if (sftp_chmod(mSftp, dest_orig_c.data(), permissions) < 0) {
      warning(i18n( "Could not change permissions for\n%1").arg(dest_orig));
    }
  }

  // set original owner and group
  if (bOrigExists) {
      kdDebug(TDEIO_SFTP_DB) << "Trying to restore original owner and group of " << dest_orig << endl;
      if (sftp_chown(mSftp, dest_orig_c.data(), owner, group) < 0) {
          // warning(i18n( "Could not change owner and group for\n%1", dest_orig));
      }
  }

  // set modification time
#if 0
  const TQString mtimeStr = metaData("modified");
  if (!mtimeStr.isEmpty()) {
    TQDateTime dt = TQDateTime::fromString(mtimeStr, TQt::ISODate);
    if (dt.isValid()) {
      struct timeval times[2];

      sftp_attributes attr = sftp_lstat(mSftp, dest_orig_c.data());
      if (attr != NULL) {
        times[0].tv_sec = attr->atime; //// access time, unchanged
        times[1].tv_sec =  dt.toTime_t(); // modification time
        times[0].tv_usec = times[1].tv_usec = 0;

        sftp_utimes(mSftp, dest_orig_c.data(), times);
        sftp_attributes_free(attr);
      }
    }
  }
#endif
  // We have done our job => finish
  finished();
}

void sftpProtocol::copy(const KURL &src, const KURL &dest, int permissions, bool overwrite)
{
  kdDebug(TDEIO_SFTP_DB) << src.url() << " -> " << dest.url() << " , permissions = " << TQString::number(permissions)
                                      << ", overwrite = " << overwrite << endl;

  error(TDEIO::ERR_UNSUPPORTED_ACTION, TQString());
}

void sftpProtocol::stat(const KURL& url) {
  kdDebug(TDEIO_SFTP_DB) << url.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  if (! url.hasPath() || TQDir::isRelativePath(url.path()) ||
      url.path().contains("/./") || url.path().contains("/../")) {
    TQString cPath;

    if (url.hasPath()) {
      cPath = canonicalizePath(url.path());
    } else {
      cPath = canonicalizePath(TQString("."));
    }

    if (cPath.isEmpty()) {
      error(TDEIO::ERR_MALFORMED_URL, url.prettyURL());
      return;
    }
    KURL redir(url);
    redir.setPath(cPath);
    redirection(redir);

    kdDebug(TDEIO_SFTP_DB) << "redirecting to " << redir.url() << endl;

    finished();
    return;
  }

  TQByteArray path = url.path().utf8();

  const TQString sDetails = metaData(TQString("details"));
  const int details = sDetails.isEmpty() ? 2 : sDetails.toInt();

  UDSEntry entry;
  entry.clear();
  if (!createUDSEntry(url.fileName(), path, entry, details)) {
    error(TDEIO::ERR_DOES_NOT_EXIST, url.prettyURL());
    return;
  }

  statEntry(entry);

  finished();
}

void sftpProtocol::mimetype(const KURL& url){
  kdDebug(TDEIO_SFTP_DB) << url.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  // stat() feeds the mimetype
  statMime(url);
  closeFile();

  finished();
}

void sftpProtocol::listDir(const KURL& url) {
  kdDebug(TDEIO_SFTP_DB) << "list directory: " << url.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  if (! url.hasPath() || TQDir::isRelativePath(url.path()) ||
      url.path().contains("/./") || url.path().contains("/../")) {
    TQString cPath;

    if (url.hasPath()) {
      cPath = canonicalizePath(url.path());
    } else {
      cPath = canonicalizePath(TQString("."));
    }

    if (cPath.isEmpty()) {
      error(TDEIO::ERR_MALFORMED_URL, url.prettyURL());
      return;
    }
    KURL redir(url);
    redir.setPath(cPath);
    redirection(redir);

    kdDebug(TDEIO_SFTP_DB) << "redirecting to " << redir.url() << endl;

    finished();
    return;
  }

  TQByteArray path = url.path().utf8();

  sftp_dir dp = sftp_opendir(mSftp, path.data());
  if (dp == NULL) {
    reportError(url, sftp_get_error(mSftp));
    return;
  }

  sftp_attributes dirent = NULL;
  const TQString sDetails = metaData(TQString("details"));
  const int details = sDetails.isEmpty() ? 2 : sDetails.toInt();
  TQValueList<TQByteArray> entryNames;
  UDSEntry entry;

  kdDebug(TDEIO_SFTP_DB) << "readdir: " << path.data() << ", details: " << TQString::number(details) << endl;

  UDSAtom atom;

  for (;;) {
    mode_t access;
    mode_t type;
    char *link;

    dirent = sftp_readdir(mSftp, dp);
    if (dirent == NULL) {
      break;
    }

    entry.clear();
    atom.m_uds = UDS_NAME;
    atom.m_str = TQFile::decodeName(dirent->name);
    entry.append(atom);

    if (dirent->type == SSH_FILEXFER_TYPE_SYMLINK) {
      TQCString file = (TQString::fromUtf8(path) + "/" + TQFile::decodeName(dirent->name)).utf8().data();

      atom.m_uds = UDS_FILE_TYPE;
      atom.m_long = S_IFREG;
      entry.append(atom);

      link = sftp_readlink(mSftp, file.data());
      if (link == NULL) {
        sftp_attributes_free(dirent);
        error(TDEIO::ERR_INTERNAL, i18n("Could not read link: %1").arg(TQString::fromUtf8(file)));
        return;
      }
      atom.m_uds = UDS_LINK_DEST;
      atom.m_str = TQFile::decodeName(link);
      entry.append(atom);
      delete link;
      // A symlink -> follow it only if details > 1
      if (details > 1) {
        sftp_attributes sb = sftp_stat(mSftp, file.data());
        if (sb == NULL) {
          // It is a link pointing to nowhere
          type = S_IFMT - 1;
          access = S_IRWXU | S_IRWXG | S_IRWXO;
          atom.m_uds = UDS_FILE_TYPE;
          atom.m_long = type;
          entry.append(atom);
          atom.m_uds = UDS_ACCESS;
          atom.m_long = access;
          entry.append(atom);
          atom.m_uds = UDS_SIZE;
          atom.m_long = 0;
          entry.append(atom);

          goto notype;
        }
        sftp_attributes_free(dirent);
        dirent = sb;
      }
    }

    switch (dirent->type) {
      case SSH_FILEXFER_TYPE_REGULAR:
        atom.m_uds = UDS_FILE_TYPE;
        atom.m_long = S_IFREG;
        entry.append(atom);
        break;
      case SSH_FILEXFER_TYPE_DIRECTORY:
        atom.m_uds = UDS_FILE_TYPE;
        atom.m_long = S_IFDIR;
        entry.append(atom);
        break;
      case SSH_FILEXFER_TYPE_SYMLINK:
        atom.m_uds = UDS_FILE_TYPE;
        atom.m_long = S_IFLNK;
        entry.append(atom);
        break;
      case SSH_FILEXFER_TYPE_SPECIAL:
      case SSH_FILEXFER_TYPE_UNKNOWN:
        break;
    }

    access = dirent->permissions & 07777;
    atom.m_uds = UDS_ACCESS;
    atom.m_long = access;
    entry.append(atom);

    atom.m_uds = UDS_SIZE;
    atom.m_long = dirent->size;
    entry.append(atom);

notype:
    if (details > 0) {
      atom.m_uds = UDS_USER;
      if (dirent->owner) {
          atom.m_str = TQString::fromUtf8(dirent->owner);
      } else {
          atom.m_str = TQString::number(dirent->uid);
      }
      entry.append(atom);

      atom.m_uds = UDS_GROUP;
      if (dirent->group) {
          atom.m_str = TQString::fromUtf8(dirent->group);
      } else {
          atom.m_str = TQString::number(dirent->gid);
      }
      entry.append(atom);

      atom.m_uds = UDS_ACCESS_TIME;
      atom.m_long = dirent->atime;
      entry.append(atom);

      atom.m_uds = UDS_MODIFICATION_TIME;
      atom.m_long = dirent->mtime;
      entry.append(atom);

      atom.m_uds = UDS_MODIFICATION_TIME;
      atom.m_long = dirent->createtime;
      entry.append(atom);
    }

    sftp_attributes_free(dirent);
    listEntry(entry, false);
  } // for ever
  sftp_closedir(dp);
  listEntry(entry, true); // ready

  finished();
}

void sftpProtocol::mkdir(const KURL &url, int permissions) {
  kdDebug(TDEIO_SFTP_DB) << "create directory: " << url.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  if (url.path().isEmpty()) {
    error(TDEIO::ERR_MALFORMED_URL, url.prettyURL());
    return;
  }
  const TQString path = url.path();
  const TQByteArray path_c = path.utf8();

  // Remove existing file or symlink, if requested.
  if (metaData(TQString("overwrite")) == TQString("true")) {
    kdDebug(TDEIO_SFTP_DB) << "overwrite set, remove existing file or symlink: " << url.url() << endl;
    sftp_unlink(mSftp, path_c.data());
  }

  kdDebug(TDEIO_SFTP_DB) << "Trying to create directory: " << path << endl;
  sftp_attributes sb = sftp_lstat(mSftp, path_c.data());
  if (sb == NULL) {
    if (sftp_mkdir(mSftp, path_c.data(), 0777) < 0) {
      reportError(url, sftp_get_error(mSftp));
      sftp_attributes_free(sb);
      return;
    } else {
      kdDebug(TDEIO_SFTP_DB) << "Successfully created directory: " << url.url() << endl;
      if (permissions != -1) {
        chmod(url, permissions);
      } else {
        finished();
      }
      sftp_attributes_free(sb);
      return;
    }
  }

  if (sb->type == SSH_FILEXFER_TYPE_DIRECTORY) {
    error(TDEIO::ERR_DIR_ALREADY_EXIST, path);
  } else {
    error(TDEIO::ERR_FILE_ALREADY_EXIST, path);
  }

  sftp_attributes_free(sb);
  return;
}

void sftpProtocol::rename(const KURL& src, const KURL& dest, bool overwrite) {
  kdDebug(TDEIO_SFTP_DB) << "rename " << src.url() << " to " << dest.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  TQByteArray qsrc = src.path().utf8();
  TQByteArray qdest = dest.path().utf8();

  sftp_attributes sb = sftp_lstat(mSftp, qdest.data());
  if (sb != NULL) {
    if (!overwrite) {
      if (sb->type == SSH_FILEXFER_TYPE_DIRECTORY) {
        error(TDEIO::ERR_DIR_ALREADY_EXIST, dest.url());
      } else {
        error(TDEIO::ERR_FILE_ALREADY_EXIST, dest.url());
      }
      sftp_attributes_free(sb);
      return;
    }

    del(dest, sb->type == SSH_FILEXFER_TYPE_DIRECTORY ? true : false);
  }
  sftp_attributes_free(sb);

  if (sftp_rename(mSftp, qsrc.data(), qdest.data()) < 0) {
    reportError(dest, sftp_get_error(mSftp));
    return;
  }

  finished();
}

void sftpProtocol::symlink(const TQString& target, const KURL& dest, bool overwrite) {
  kdDebug(TDEIO_SFTP_DB) << "link " << target << "->" << dest.url()
                      << ", overwrite = " << overwrite << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  TQByteArray t = target.utf8();
  TQByteArray d = dest.path().utf8();

  bool failed = false;
  if (sftp_symlink(mSftp, t.data(), d.data()) < 0) {
    if (overwrite) {
      sftp_attributes sb = sftp_lstat(mSftp, d.data());
      if (sb == NULL) {
        failed = true;
      } else {
        if (sftp_unlink(mSftp, d.data()) < 0) {
          failed = true;
        } else {
          if (sftp_symlink(mSftp, t.data(), d.data()) < 0) {
            failed = true;
          }
        }
      }
      sftp_attributes_free(sb);
    }
  }

  if (failed) {
    reportError(dest, sftp_get_error(mSftp));
    return;
  }

  finished();
}

void sftpProtocol::chmod(const KURL& url, int permissions) {
  kdDebug(TDEIO_SFTP_DB) << "change permission of " << url.url() << " to " << TQString::number(permissions) << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  TQByteArray path = url.path().utf8();

  if (sftp_chmod(mSftp, path.data(), permissions) < 0) {
    reportError(url, sftp_get_error(mSftp));
    return;
  }

  finished();
}

void sftpProtocol::del(const KURL &url, bool isfile){
  kdDebug(TDEIO_SFTP_DB) << "deleting " << (isfile ? "file: " : "directory: ") << url.url() << endl;

  openConnection();
  if (!mConnected) {
    return;
  }

  TQByteArray path = url.path().utf8();

  if (isfile) {
    if (sftp_unlink(mSftp, path.data()) < 0) {
      reportError(url, sftp_get_error(mSftp));
      return;
    }
  } else {
    if (sftp_rmdir(mSftp, path.data()) < 0) {
      reportError(url, sftp_get_error(mSftp));
      return;
    }
  }

  finished();
}

void sftpProtocol::slave_status() {
  kdDebug(TDEIO_SFTP_DB) << "connected to " << mHost << "?: " << mConnected << endl;
  slaveStatus((mConnected ? mHost : TQString()), mConnected);
}