File: gvfsbackendftp.c

package info (click to toggle)
gvfs 1.30.4-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 22,580 kB
  • ctags: 12,211
  • sloc: ansic: 113,948; sh: 4,957; xml: 2,353; makefile: 1,601; python: 1,448; sed: 16
file content (1846 lines) | stat: -rw-r--r-- 57,726 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
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
/* GIO - GLib Input, Output and Streaming Library
 *
 * Copyright (C) 2008,2009 Benjamin Otte <otte@gnome.org>
 *               2008,2009 Andreas Henriksson <andreas@fatal.se>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * Author: Benjamin Otte <otte@gnome.org>
 *         Andreas Henriksson <andreas@fatal.se>
 */


#include <config.h>

#include <errno.h> /* for strerror (EAGAIN) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <glib/gi18n.h>
#include <gio/gio.h>

#include "gvfsbackendftp.h"
#include "gvfsjobopenforread.h"
#include "gvfsjobread.h"
#include "gvfsjobseekread.h"
#include "gvfsjobopenforwrite.h"
#include "gvfsjobwrite.h"
#include "gvfsjobseekwrite.h"
#include "gvfsjobsetdisplayname.h"
#include "gvfsjobqueryinfo.h"
#include "gvfsjobqueryfsinfo.h"
#include "gvfsjobqueryattributes.h"
#include "gvfsjobenumerate.h"
#include "gvfsdaemonprotocol.h"
#include "gvfsdaemonutils.h"
#include "gvfskeyring.h"

#include "ParseFTPList.h"
#include "gvfsftpconnection.h"
#include "gvfsftpdircache.h"
#include "gvfsftpfile.h"
#include "gvfsftptask.h"

/*** GTK DOC ***/

/**
 * GVfsFtpMethod:
 * @G_VFS_FTP_METHOD_UNKNOWN: method has not yet been determined
 * @G_VFS_FTP_METHOD_EPSV: use EPSV command
 * @G_VFS_FTP_METHOD_PASV: use PASV command
 * @G_VFS_FTP_METHOD_PASV_ADDR: use PASV command, but ignore the returned 
 *                              address and only use it's port
 * @G_VFS_FTP_METHOD_EPRT: use the EPRT command
 * @G_VFS_FTP_METHOD_PORT: use the PORT command
 *
 * Possible methods for creating data connections to the ftp server. If the 
 * method is @G_VFS_FTP_METHOD_UNKNOWN, all possibilities are tried.
 */


/*
 * about filename interpretation in the ftp backend
 *
 * As GVfs composes paths using a slash character, we cannot allow a slash as
 * part of a basename. Other critical characters are \r \n and sometimes the
 * space. We therefore g_uri_escape_string() filenames by default and concatenate
 * paths using slashes. This should make GVfs happy.
 *
 * Luckily, TVFS (see RFC 3xxx for details) is a specification that does exactly
 * what we want. It disallows slashes, \r and \n in filenames, so we can happily
 * use it without the need to escape. We also can operate on full paths as our
 * paths exactly match those of a TVFS-using FTP server.
 */

/** CODE ***/

G_DEFINE_TYPE (GVfsBackendFtp, g_vfs_backend_ftp, G_VFS_TYPE_BACKEND)

static gboolean
gvfs_backend_ftp_determine_features (GVfsFtpTask *task)
{
  const struct {
    const char *        name;        	/* name of feature */
    GVfsFtpFeature      enable;                /* flags to enable with this feature */
  } features[] = {
    { "MDTM", G_VFS_FTP_FEATURE_MDTM },
    { "SIZE", G_VFS_FTP_FEATURE_SIZE },
    { "TVFS", G_VFS_FTP_FEATURE_TVFS },
    { "EPRT", G_VFS_FTP_FEATURE_EPRT },
    { "EPSV", G_VFS_FTP_FEATURE_EPSV },
    { "UTF8", G_VFS_FTP_FEATURE_UTF8 },
    { "AUTH TLS", G_VFS_FTP_FEATURE_AUTH_TLS },
    { "AUTH SSL", G_VFS_FTP_FEATURE_AUTH_SSL },
  };
  guint i, j;
  char **reply;

  if (!g_vfs_ftp_task_send_and_check (task, 0, NULL, NULL, &reply, "FEAT"))
    return FALSE;

  task->backend->features = 0;
  for (i = 1; reply[i]; i++)
    {
      char *feature = reply[i];

      if (feature[0] != ' ')
        continue;
      feature++;

      /* There should just be one space according to RFC2389, but some
       * servers have more so we deal with any number of leading spaces.
       */
      while (g_ascii_isspace (feature[0]))
        feature++;

      for (j = 0; j < G_N_ELEMENTS (features); j++)
        {
          if (g_ascii_strcasecmp (feature, features[j].name) == 0)
            {
              g_debug ("# feature %s supported\n", features[j].name);
              task->backend->features |= 1 << features[j].enable;
            }
        }
    }

  g_strfreev (reply);

  return TRUE;
}

static void
gvfs_backend_ftp_determine_site_features (GVfsFtpTask *task)
{
  const struct {
    const char *        name;        	/* name of feature */
    GVfsFtpFeature      enable;         /* flags to enable with this feature */
  } features[] = {
    { "CHMOD", G_VFS_FTP_FEATURE_CHMOD },
    { "CHGRP", G_VFS_FTP_FEATURE_CHGRP },
  };
  guint i, j;
  char **reply;

  if (g_vfs_ftp_task_is_in_error (task))
    return;

  if (!g_vfs_ftp_task_send_and_check (task, 0, NULL, NULL, &reply, "SITE HELP"))
    {
      g_vfs_ftp_task_clear_error (task);
      return;
    }

  if (g_strv_length (reply) == 1)
    {
      /* vsftpd returns just a single string, so we split it into multiple
       * and then treat it like a regular reply */
      char **split;

      split = g_strsplit (reply[0], " ", -1);
      g_strfreev (reply);
      reply = split;
    }

  for (i = 1; reply[i]; i++)
    {
      char *feature = reply[i];

      while (g_ascii_isspace (feature[0]))
        feature++;

      for (j = 0; j < G_N_ELEMENTS (features); j++)
        {
          if (g_ascii_strcasecmp (feature, features[j].name) == 0)
            {
              g_debug ("# site feature %s supported\n", features[j].name);
              task->backend->features |= 1 << features[j].enable;
            }
        }
    }

  g_strfreev (reply);

  return;
}

static void
gvfs_backend_ftp_determine_system (GVfsFtpTask *task)
{
  static const struct {
    const char *  id;
    GVfsFtpSystem system;
    const char *  debug_name;
  } known_systems[] = {
    /* NB: the first entry that matches is taken, so order matters */
    { "UNIX ", G_VFS_FTP_SYSTEM_UNIX, "Unix"},
    { "WINDOWS_NT ", G_VFS_FTP_SYSTEM_WINDOWS, "Windows NT" }
  };
  guint i;
  char *system_name;
  char **reply;

  if (g_vfs_ftp_task_is_in_error (task))
    return;

  if (!g_vfs_ftp_task_send_and_check (task, 0, NULL, NULL, &reply, "SYST"))
    {
      g_vfs_ftp_task_clear_error (task);
      return;
    }

  system_name = reply[0] + 4;
  for (i = 0; i < G_N_ELEMENTS (known_systems); i++)
    {
      if (g_ascii_strncasecmp (system_name,
                               known_systems[i].id,
                	       strlen (known_systems[i].id)) == 0)
        {
          task->backend->system = known_systems[i].system;
          g_debug ("# system is %s\n", known_systems[i].debug_name);
          break;
        }
    }

  g_strfreev (reply);
}

static void
gvfs_backend_ftp_setup_directory_cache (GVfsBackendFtp *ftp)
{
  if (ftp->system == G_VFS_FTP_SYSTEM_UNIX)
    ftp->dir_funcs = &g_vfs_ftp_dir_cache_funcs_unix;
  else
    ftp->dir_funcs = &g_vfs_ftp_dir_cache_funcs_default;

  ftp->dir_cache = g_vfs_ftp_dir_cache_new (ftp->dir_funcs);
}

/* This parses a file according to RFC 959 Appendix II:
 *
 * the server should return a line of the form:
 *   257<space>"<directory-name>"<space><commentary>
 * That is, the server will tell the user what string to use when
 * referring to the created  directory.  The directory name can
 * contain any character; embedded double-quotes should be escaped by
 * double-quotes (the "quote-doubling" convention).
 *
 * Note that we actually accept (as regexp):
 * ....\s*"<directory-name>".*
 * so we're quite a bit more lax.
 *
 * If parsing this name fails, this function returns NULL.
 */
static GVfsFtpFile *
g_vfs_backend_create_file_from_reply (GVfsBackendFtp *ftp, const char *name)
{
  GVfsFtpFile *file;
  const char *quote;
  GString *unescaped;

  /* strip leading spaces */
  while (g_ascii_isspace (*name))
    name++;

  if (*name++ != '"')
    {
      g_debug ("# filename didn't start with a quote\n");
      return NULL;
    }

  unescaped = g_string_new (NULL);
  while ((quote = strchr (name, '"')))
    {
      g_string_append_len (unescaped, name, quote-name);
      name = quote + 2;
      if (quote[1] == '"')
        g_string_append_c (unescaped, '"');
      else
        break;
    }

  /* NB: The name variable may point into bad space here */
  if (quote == NULL)
    {
      g_debug ("# filename didn't end with a quote\n");
      g_string_free (unescaped, TRUE);
      return NULL;
    }
  else if (!g_ascii_isspace (quote[1]))
    {
      /* issue a warning here, just so we can guess right from debug logs */
      g_debug ("# warning: filename didn't contain space after final quote\n");
    }

  file = g_vfs_ftp_file_new_from_ftp (ftp, unescaped->str);

  g_string_free (unescaped, TRUE);
  return file;
}

static void
gvfs_backend_ftp_determine_default_location (GVfsFtpTask *task)
{
  char **reply;
  GVfsFtpFile *home;

  if (g_vfs_ftp_task_is_in_error (task))
    return;

  if (!g_vfs_ftp_task_send_and_check (task, 0, NULL, NULL, &reply, "PWD"))
    {
      g_vfs_ftp_task_clear_error (task);
      return;
    }

  home = g_vfs_backend_create_file_from_reply (task->backend, reply[0] + 4);
  if (home != NULL)
    {
      g_vfs_backend_set_default_location (G_VFS_BACKEND (task->backend),
                                          g_vfs_ftp_file_get_gvfs_path (home));
      g_vfs_ftp_file_free (home);
    }

  g_strfreev (reply);
}

/*** COMMON FUNCTIONS WITH SPECIAL HANDLING ***/

static gboolean
g_vfs_ftp_task_cd (GVfsFtpTask *task, const GVfsFtpFile *file)
{
  guint response = g_vfs_ftp_task_send (task,
                			G_VFS_FTP_PASS_550,
                			"CWD %s", g_vfs_ftp_file_get_ftp_path (file));
  if (response == 550)
    {
      g_set_error_literal (&task->error,
                           G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY,
                	   _("The file is not a directory"));
      response = 0;
    }

  return response != 0;
}

static gboolean
g_vfs_ftp_task_try_cd (GVfsFtpTask *task, const GVfsFtpFile *file)
{
  if (g_vfs_ftp_task_is_in_error (task))
    return FALSE;

  if (!g_vfs_ftp_task_cd (task, file))
    {
      g_vfs_ftp_task_clear_error (task);
      return FALSE;
    }
 
  return TRUE;
}

/*** default directory reading ***/

static void
g_vfs_backend_ftp_finalize (GObject *object)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (object);

  if (ftp->addr)
    g_object_unref (ftp->addr);

  /* has been cleared on unmount, however it has to be cleared when mount fails */
  if (ftp->queue)
    g_queue_free (ftp->queue);

  g_cond_clear (&ftp->cond);
  g_mutex_clear (&ftp->mutex);

  g_free (ftp->user);
  g_free (ftp->password);

  g_clear_object (&ftp->server_identity);
  g_clear_object (&ftp->certificate);

  if (G_OBJECT_CLASS (g_vfs_backend_ftp_parent_class)->finalize)
    (*G_OBJECT_CLASS (g_vfs_backend_ftp_parent_class)->finalize) (object);
}

static void
g_vfs_backend_ftp_init (GVfsBackendFtp *ftp)
{
  g_mutex_init (&ftp->mutex);
  g_cond_init (&ftp->cond);
}

/* If the initial connection has a verification error, display the certificate
 * to the user and ask whether to proceed. */
static gboolean
initial_certificate_cb (GTlsConnection *conn,
                        GTlsCertificate *certificate,
                        GTlsCertificateFlags errors,
                        gpointer user_data)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (user_data);

  /* Save the certificate and result for reconnections. */
  ftp->certificate = g_object_ref (certificate);
  ftp->certificate_errors = errors;

  return gvfs_accept_certificate (ftp->mount_source, certificate, errors);
}

static void
do_mount (GVfsBackend *backend,
          GVfsJobMount *job,
          GMountSpec *mount_spec,
          GMountSource *mount_source,
          gboolean is_automount)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  char *prompt = NULL;
  char *username;
  char *password;
  char *display_name;
  gboolean aborted, anonymous, break_on_fail;
  GPasswordSave password_save = G_PASSWORD_SAVE_NEVER;
  GNetworkAddress *addr;
  guint port;

restart:
  task.conn = g_vfs_ftp_connection_new (ftp->addr, task.cancellable, &task.error);
  /* fail fast here. No need to ask for a password if we know the hostname
   * doesn't exist or the given host/port doesn't have an ftp server running.
   */
  if (task.conn == NULL)
    {
      g_vfs_ftp_task_done (&task);
      return;
    }

  /* send pre-login commands */
  g_vfs_ftp_task_receive (&task, 0, NULL);

  /* Secure the initial connection if necessary. This may result in a prompt
   * for the user. */
  ftp->mount_source = mount_source;
  if (ftp->use_tls &&
      !g_vfs_ftp_task_enable_tls (&task, initial_certificate_cb, ftp))
    {
      ftp->mount_source = NULL;
      g_vfs_ftp_task_done (&task);
      return;
    }
  ftp->mount_source = NULL;

  if (!g_vfs_backend_ftp_uses_workaround (ftp, G_VFS_FTP_WORKAROUND_FEAT_AFTER_LOGIN) &&
      !gvfs_backend_ftp_determine_features (&task))
    {
      g_vfs_backend_ftp_use_workaround (ftp, G_VFS_FTP_WORKAROUND_FEAT_AFTER_LOGIN);
      ftp->features = 0;
      g_vfs_ftp_task_clear_error (&task);
      if (!g_vfs_ftp_connection_is_usable (task.conn))
        {
          g_vfs_ftp_connection_free (task.conn);
          goto restart;
        }
    }

  addr = G_NETWORK_ADDRESS (ftp->addr);
  g_object_ref (addr);
  port = g_network_address_get_port (addr);
  username = NULL;
  password = NULL;
  break_on_fail = FALSE;
 
  if (ftp->user != NULL && strcmp (ftp->user, "anonymous") == 0)
    {
      anonymous = TRUE;
      break_on_fail = TRUE;
      goto try_login;
    }
 
  if (g_vfs_keyring_lookup_password (ftp->user,
                		     g_network_address_get_hostname (addr),
                		     NULL,
                		     "ftp",
                		     NULL,
                		     NULL,
                		     port == 21 ? 0 : port,
                		     &username,
                		     NULL,
                		     &password) &&
      username != NULL &&
      password != NULL)
    {
      anonymous = FALSE;
      goto try_login;
    }
  g_free (username);
  g_free (password);
  username = NULL;
  password = NULL;

  while (TRUE)
    {
      GAskPasswordFlags flags;
      if (prompt == NULL)
        {
          if (ftp->has_initial_user)
            /* Translators: the first %s is the username, the second the host name */
            prompt = g_strdup_printf (_("Enter password for %s on %s"), ftp->user, ftp->host_display_name);
          else
            /* translators: %s here is the hostname */
            prompt = g_strdup_printf (_("Enter password for %s"), ftp->host_display_name);
        }
         
      flags = G_ASK_PASSWORD_NEED_PASSWORD;
       
      if (!ftp->has_initial_user)
        flags |= G_ASK_PASSWORD_NEED_USERNAME | G_ASK_PASSWORD_ANONYMOUS_SUPPORTED;
     
      if (g_vfs_keyring_is_available ())
        flags |= G_ASK_PASSWORD_SAVING_SUPPORTED;
     
      if (!g_mount_source_ask_password (
                	mount_source,
                        prompt,
                	ftp->user,
                        NULL,
                        flags,
                        &aborted,
                        &password,
                        &username,
                        NULL,
                	&anonymous,
                        &password_save) ||
          aborted)
        {
          g_set_error_literal (&task.error, G_IO_ERROR,
                               aborted ? G_IO_ERROR_FAILED_HANDLED : G_IO_ERROR_PERMISSION_DENIED,
                	       _("Password dialog cancelled"));
          break;
        }

      /* NEED_USERNAME wasn't set */
      if (ftp->has_initial_user)
        {
          g_free (username);
          username = g_strdup (ftp->user);
        }
     
try_login:
      g_free (ftp->user);
      g_free (ftp->password);
      if (anonymous)
        {
          g_free (username);
          g_free (password);
          ftp->user = g_strdup ("anonymous");
          ftp->password = g_strdup ("");
          if (g_vfs_ftp_task_login (&task, "anonymous", "") != 0)
            break;
          g_free (ftp->user);
          g_free (ftp->password);
          ftp->user = NULL;
          ftp->password = NULL;
        }
      else
        {
          ftp->user = username ? username : g_strdup ("");
          ftp->password = password;
          if (g_vfs_ftp_task_login (&task, ftp->user, ftp->password) != 0)
            break;
        }
     
      if (break_on_fail ||
          !g_error_matches (task.error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED))
        break;

      g_vfs_ftp_task_clear_error (&task);
    }
 
  /* send post-login commands */
  if (g_vfs_backend_ftp_uses_workaround (ftp, G_VFS_FTP_WORKAROUND_FEAT_AFTER_LOGIN) &&
      !g_vfs_ftp_task_is_in_error (&task))
    {
      if (!gvfs_backend_ftp_determine_features (&task))
        {
          g_vfs_ftp_task_clear_error (&task);
          ftp->features = G_VFS_FTP_FEATURES_DEFAULT;
        }
    }
  g_vfs_ftp_task_setup_connection (&task);
  gvfs_backend_ftp_determine_system (&task);
  gvfs_backend_ftp_determine_site_features (&task);
  gvfs_backend_ftp_setup_directory_cache (ftp);
  gvfs_backend_ftp_determine_default_location (&task);

  /* Save the address of the current connection, so that for future connections,
   * we are sure to connect to the same machine.
   * The idea here is to avoid using mirrors that have a different state, which
   * might cause Heisenbugs.
   */
  if (!g_vfs_ftp_task_is_in_error (&task))
    {
      g_object_unref (ftp->addr);
      ftp->addr = G_SOCKET_CONNECTABLE (g_vfs_ftp_connection_get_address (task.conn, &task.error));
      if (ftp->addr == NULL)
        {
          g_debug ("# error querying remote address: %s\nUsing original address instead.\n", task.error->message);
          g_vfs_ftp_task_clear_error (&task);
          ftp->addr = g_object_ref (addr);
        }
    }

  if (g_vfs_ftp_task_is_in_error (&task))
    {
      g_vfs_ftp_connection_free (task.conn);
      task.conn = NULL;
      g_vfs_ftp_task_done (&task);
      g_object_unref (addr);
      return;
    }

  if (prompt && !anonymous)
    {
      /* a prompt was created, so we have to save the password */
      g_vfs_keyring_save_password (ftp->user,
                                   g_network_address_get_hostname (addr),
                                   NULL,
                                   "ftp",
                                   NULL,
                                   NULL,
                                   port == 21 ? 0 : port,
                                   ftp->password,
                                   password_save);
      g_free (prompt);
    }

  mount_spec = g_mount_spec_new (ftp->use_tls ? "ftps" : "ftp");
  g_mount_spec_set (mount_spec, "host", g_network_address_get_hostname (addr));
  if (port != 21)
    {
      char *port_str = g_strdup_printf ("%u", port);
      g_mount_spec_set (mount_spec, "port", port_str);
      g_free (port_str);
    }

  if (ftp->has_initial_user)
    g_mount_spec_set (mount_spec, "user", ftp->user);
     
  if (g_str_equal (ftp->user, "anonymous"))
    display_name = g_strdup (ftp->host_display_name);
  else
    {
      /* Translators: the first %s is the username, the second the host name */
      display_name = g_strdup_printf (_("%s on %s"), ftp->user, ftp->host_display_name);
    }
  g_vfs_backend_set_mount_spec (backend, mount_spec);
  g_mount_spec_unref (mount_spec);

  g_vfs_backend_set_display_name (backend, display_name);
  g_free (display_name);
  g_vfs_backend_set_icon_name (backend, "folder-remote");
  g_vfs_backend_set_symbolic_icon_name (backend, "folder-remote-symbolic");

  ftp->connections = 1;
  ftp->max_connections = G_MAXUINT;
  ftp->queue = g_queue_new ();
 
  g_object_unref (addr);
  g_vfs_ftp_task_done (&task);
}

static gboolean
try_mount (GVfsBackend *backend,
          GVfsJobMount *job,
          GMountSpec *mount_spec,
          GMountSource *mount_source,
          gboolean is_automount)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  const char *host, *port_str;
  guint port;

  host = g_mount_spec_get (mount_spec, "host");
  if (host == NULL)
    {
      g_vfs_job_failed (G_VFS_JOB (job),
                       G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                       _("No hostname specified"));
      return TRUE;
    }
  port_str = g_mount_spec_get (mount_spec, "port");
  if (port_str == NULL)
    {
      port = 21;
    }
  else
    {
      /* FIXME: error handling? */
      port = strtoul (port_str, NULL, 10);
    }

  ftp->addr = g_network_address_new (host, port);
  ftp->user = g_strdup (g_mount_spec_get (mount_spec, "user"));
  ftp->has_initial_user = ftp->user != NULL;
  if (port == 21)
    ftp->host_display_name = g_strdup (host);
  else
    ftp->host_display_name = g_strdup_printf ("%s:%u", host, port);
  ftp->use_tls = strcmp (g_mount_spec_get_type (mount_spec), "ftps") == 0;
  if (ftp->use_tls)
    ftp->server_identity = g_object_ref (ftp->addr);

  return FALSE;
}

static void
do_unmount (GVfsBackend *   backend,
            GVfsJobUnmount *job,
            GMountUnmountFlags flags,
            GMountSource *mount_source)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpConnection *conn;

  g_mutex_lock (&ftp->mutex);
  while ((conn = g_queue_pop_head (ftp->queue)))
    {
      /* FIXME: properly quit */
      g_vfs_ftp_connection_free (conn);
    }
  g_queue_free (ftp->queue);
  ftp->queue = NULL;
  g_cond_broadcast (&ftp->cond);
  g_mutex_unlock (&ftp->mutex);
  g_vfs_job_succeeded (G_VFS_JOB (job));
}

/* NB: sets EPERM if file exists, ENOENT if not - an error will _always_ be set */
static void
error_550_permission_or_not_found (GVfsFtpTask *task, gpointer file)
{
  GFileInfo *info;
  
  info = g_vfs_ftp_dir_cache_lookup_file (task->backend->dir_cache, task, file, FALSE);
  if (info)
    {
      g_object_unref (info);
      g_set_error_literal (&task->error,
                           G_IO_ERROR,
                           G_IO_ERROR_PERMISSION_DENIED,
                           _("Insufficient permissions"));
    }
  else
    {
      /* clear potential error from file lookup above */
      g_vfs_ftp_task_clear_error (task);
      g_set_error_literal (&task->error,
                           G_IO_ERROR,
                           G_IO_ERROR_NOT_FOUND,
                           _("File doesn't exist"));
    }
}

static void
error_550_exists (GVfsFtpTask *task, gpointer file)
{
  GFileInfo *info;
  
  info = g_vfs_ftp_dir_cache_lookup_file (task->backend->dir_cache, task, file, FALSE);
  if (info)
    {
      g_object_unref (info);
      g_set_error_literal (&task->error,
                           G_IO_ERROR,
                           G_IO_ERROR_EXISTS,
                           _("Target file already exists"));
    }
  else
    {
      /* clear potential error from file lookup above */
      g_vfs_ftp_task_clear_error (task);
    }
}

static void
error_550_is_directory (GVfsFtpTask *task, gpointer file)
{
  GFileInfo *info;
  
  /* need to resolve symlinks here to know if a link is a dir or not */
  info = g_vfs_ftp_dir_cache_lookup_file (task->backend->dir_cache, task, file, TRUE);
  if (info && g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
    {
      g_object_unref (info);
      g_set_error_literal (&task->error, G_IO_ERROR,
                           G_IO_ERROR_IS_DIRECTORY,
                           _("File is directory"));
      return;
    }
  else if (info)
    g_object_unref (info);
  
  /* clear potential error from file lookup above */
  g_vfs_ftp_task_clear_error (task);
}

static void
error_550_parent_not_found (GVfsFtpTask *task, gpointer file)
{
  GVfsFtpFile *dir = g_vfs_ftp_file_new_parent (file);

  if (!g_vfs_ftp_file_equal (file, dir) && !g_vfs_ftp_task_try_cd (task, dir))
    {
      /* Yes, this is a weird error for a missing parent directory */
      g_set_error_literal (&task->error, G_IO_ERROR,
                           G_IO_ERROR_NOT_FOUND,
                           _("No such file or directory"));
    }

  g_vfs_ftp_file_free (dir);
}

static void
do_open_for_read (GVfsBackend *backend,
                  GVfsJobOpenForRead *job,
                  const char *filename)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file;
  static const GVfsFtpErrorFunc open_read_handlers[] = { error_550_is_directory, 
                                                         error_550_permission_or_not_found, 
                                                         NULL };

  g_vfs_ftp_task_setup_data_connection (&task);
  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);

  g_vfs_ftp_task_send_and_check (&task,
                                 G_VFS_FTP_PASS_100 | G_VFS_FTP_FAIL_200,
                                 open_read_handlers,
                                 file,
                                 NULL,
                                 "RETR %s", g_vfs_ftp_file_get_ftp_path (file));
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_open_data_connection (&task);

  if (!g_vfs_ftp_task_is_in_error (&task))
    {
      /* don't push the connection back, it's our handle now */
      GVfsFtpConnection *conn = g_vfs_ftp_task_take_connection (&task);

      g_vfs_job_open_for_read_set_handle (job, conn);
      g_vfs_job_open_for_read_set_can_seek (job, FALSE);
    }

  g_vfs_ftp_task_done (&task);
}

static void
do_close_read (GVfsBackend *     backend,
               GVfsJobCloseRead *job,
               GVfsBackendHandle handle)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpConnection *conn = handle;

  g_vfs_ftp_task_give_connection (&task, conn);
  g_vfs_ftp_task_close_data_connection (&task);
  g_vfs_ftp_task_receive (&task, 0, NULL);

  g_vfs_ftp_task_done (&task);
}

static void
do_read (GVfsBackend *     backend,
         GVfsJobRead *     job,
         GVfsBackendHandle handle,
         char *            buffer,
         gsize             bytes_requested)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpConnection *conn = handle;
  GInputStream *input;
  gssize n_bytes;

  input = g_io_stream_get_input_stream (g_vfs_ftp_connection_get_data_stream (conn));
  n_bytes = g_input_stream_read (input,
                                 buffer,
                                 bytes_requested,
                                 task.cancellable,
                                 &task.error);

  if (n_bytes >= 0)
    g_vfs_job_read_set_size (job, n_bytes);

  g_vfs_ftp_task_done (&task);
}

static void
do_start_write (GVfsFtpTask *task,
                GFileCreateFlags flags,
                const char *format,
                ...) G_GNUC_PRINTF (3, 4);
static void
do_start_write (GVfsFtpTask *task,
                GFileCreateFlags flags,
                const char *format,
                ...)
{
  GVfsJobOpenForWrite *job = G_VFS_JOB_OPEN_FOR_WRITE (task->job);
  va_list varargs;

  /* FIXME: can we honour the flags? */

  g_vfs_ftp_task_setup_data_connection (task);

  va_start (varargs, format);
  g_vfs_ftp_task_sendv (task,
                        G_VFS_FTP_PASS_100 | G_VFS_FTP_FAIL_200,
                        NULL,
                        format,
                        varargs);
  va_end (varargs);

  g_vfs_ftp_task_open_data_connection (task);

  if (!g_vfs_ftp_task_is_in_error (task))
    {
      GIOStream *stream;

      /* don't push the connection back, it's our handle now */
      GVfsFtpConnection *conn = g_vfs_ftp_task_take_connection (task);
      g_vfs_job_open_for_write_set_handle (G_VFS_JOB_OPEN_FOR_WRITE (task->job), conn);
      g_vfs_job_open_for_write_set_can_seek (G_VFS_JOB_OPEN_FOR_WRITE (task->job), FALSE);

      stream = g_vfs_ftp_connection_get_data_stream (conn);
      g_object_set_data_full (G_OBJECT (stream), "g-vfs-backend-ftp-filename",
                              g_strdup (job->filename), g_free);
    }
}

static void
do_create (GVfsBackend *backend,
           GVfsJobOpenForWrite *job,
           const char *filename,
           GFileCreateFlags flags)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GFileInfo *info;
  GVfsFtpFile *file;

  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);
  info = g_vfs_ftp_dir_cache_lookup_file (ftp->dir_cache, &task, file, FALSE);
  if (info)
    {
      g_object_unref (info);
      g_set_error_literal (&task.error,
                           G_IO_ERROR,
                	   G_IO_ERROR_EXISTS,
                	   _("Target file already exists"));
      g_vfs_ftp_file_free (file);
      g_vfs_ftp_task_done (&task);
      return;
    }
  do_start_write (&task, flags, "STOR %s", g_vfs_ftp_file_get_ftp_path (file));
  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_done (&task);
}

static void
do_append (GVfsBackend *backend,
           GVfsJobOpenForWrite *job,
           const char *filename,
           GFileCreateFlags flags)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file;

  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);
  do_start_write (&task, flags, "APPE %s", g_vfs_ftp_file_get_ftp_path (file));
  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_done (&task);
}

static void
do_replace (GVfsBackend *backend,
            GVfsJobOpenForWrite *job,
            const char *filename,
            const char *etag,
            gboolean make_backup,
            GFileCreateFlags flags)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file, *backupfile = NULL;
  static const GVfsFtpErrorFunc rnfr_handlers[] = { error_550_permission_or_not_found,
                                                    NULL };

  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);

  if (make_backup)
    {
      GFileInfo *info;
      char *backup_path = g_strconcat (filename, "~", NULL);
      backupfile = g_vfs_ftp_file_new_from_gvfs (ftp, backup_path);
      g_free (backup_path);

      info = g_vfs_ftp_dir_cache_lookup_file (ftp->dir_cache, &task, file, FALSE);

      if (info)
        {
          guint ret;

          g_object_unref (info);

          ret = g_vfs_ftp_task_send (&task,
                                     G_VFS_FTP_PASS_550,
                                     "DELE %s", g_vfs_ftp_file_get_ftp_path (backupfile));
          if (!ret)
            goto err_backup;
          g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, backupfile);

          ret = g_vfs_ftp_task_send_and_check (&task,
                                               G_VFS_FTP_PASS_300 | G_VFS_FTP_FAIL_200,
                                               rnfr_handlers,
                                               file,
                                               NULL,
                                               "RNFR %s", g_vfs_ftp_file_get_ftp_path (file));
          if (!ret)
            goto err_backup;

          ret = g_vfs_ftp_task_send (&task,
                                     0,
                                     "RNTO %s", g_vfs_ftp_file_get_ftp_path (backupfile));
          if (!ret)
            goto err_backup;

          g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
        }
      g_vfs_ftp_file_free (backupfile);
    }

  do_start_write (&task, flags, "STOR %s", g_vfs_ftp_file_get_ftp_path (file));
  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_done (&task);

  return;

err_backup:
  g_vfs_ftp_file_free (file);
  g_vfs_ftp_file_free (backupfile);
  g_vfs_ftp_task_clear_error (&task);
  g_set_error_literal (&task.error,
                       G_IO_ERROR,
                       G_IO_ERROR_CANT_CREATE_BACKUP,
                       _("Backup file creation failed"));
  g_vfs_ftp_task_done (&task);
}

static void
do_close_write (GVfsBackend *backend,
                GVfsJobCloseWrite *job,
                GVfsBackendHandle handle)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpConnection *conn = handle;
  GIOStream *stream;
  const gchar *filename;
  GVfsFtpFile *file;

  stream = g_vfs_ftp_connection_get_data_stream (conn);
  filename = g_object_get_data (G_OBJECT (stream), "g-vfs-backend-ftp-filename");
  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);

  g_vfs_ftp_task_give_connection (&task, handle);
  g_vfs_ftp_task_close_data_connection (&task);
  g_vfs_ftp_task_receive (&task, 0, NULL);

  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_done (&task);
}

static void
do_write (GVfsBackend *backend,
          GVfsJobWrite *job,
          GVfsBackendHandle handle,
          char *buffer,
          gsize buffer_size)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpConnection *conn = handle;
  GOutputStream *output;
  gssize n_bytes;

  output = g_io_stream_get_output_stream (g_vfs_ftp_connection_get_data_stream (conn));

  /* FIXME: use write_all here? */
  n_bytes = g_output_stream_write (output,
                                   buffer,
                                   buffer_size,
                                   task.cancellable,
                                   &task.error);
           
  if (n_bytes >= 0)
    g_vfs_job_write_set_written_size (job, n_bytes);

  g_vfs_ftp_task_done (&task);
}

static void
do_query_info (GVfsBackend *backend,
               GVfsJobQueryInfo *job,
               const char *filename,
               GFileQueryInfoFlags query_flags,
               GFileInfo *info,
               GFileAttributeMatcher *matcher)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file;
  GFileInfo *real;
 
  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);
  real = g_vfs_ftp_dir_cache_lookup_file (ftp->dir_cache,
                                          &task,
                                          file,
                                          query_flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS ? FALSE : TRUE);

  if (real)
    {
      g_file_info_copy_into (real, info);
      g_object_unref (real);
    }
  else if (!g_vfs_ftp_task_is_in_error (&task))
    {
      g_set_error_literal (&task.error,
                           G_IO_ERROR,
                           G_IO_ERROR_NOT_FOUND,
                           _("File doesn't exist"));
    }

  g_vfs_ftp_task_done (&task);
  g_vfs_ftp_file_free (file);
}

static gboolean
try_query_settable_attributes (GVfsBackend *backend,
			       GVfsJobQueryAttributes *job,
			       const char *filename)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GFileAttributeInfoList *list;

  if (!g_vfs_backend_ftp_has_feature (ftp, G_VFS_FTP_FEATURE_CHMOD))
    {    
      g_vfs_job_failed (G_VFS_JOB (job),
                        G_IO_ERROR,
                        G_IO_ERROR_NOT_SUPPORTED,
                        _("Operation unsupported"));
      return TRUE;
    }    

  list = g_file_attribute_info_list_new ();

  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_UNIX_MODE,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
  
  g_vfs_job_query_attributes_set_list (job, list);
  g_vfs_job_succeeded (G_VFS_JOB (job));
  g_file_attribute_info_list_unref (list);
  
  return TRUE;
}

static void
do_set_attribute (GVfsBackend *backend,
                  GVfsJobSetAttribute *job,
                  const char *filename,
                  const char *attribute,
                  GFileAttributeType type,
                  gpointer value_p,
                  GFileQueryInfoFlags flags)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file;

  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);

  if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
    {
      if (type != G_FILE_ATTRIBUTE_TYPE_UINT32) 
        {
          g_set_error_literal (&task.error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("Invalid attribute type (uint32 expected)"));
        }
      else if (!g_vfs_backend_ftp_has_feature (ftp, G_VFS_FTP_FEATURE_CHMOD))
        {
          g_set_error_literal (&task.error,
                               G_IO_ERROR,
                               G_IO_ERROR_NOT_SUPPORTED,
                               _("Operation unsupported"));
        }
      else
        {
          guint mode = *(guint32 *)value_p;

          if (g_vfs_ftp_task_send (&task,
                                   0,
                                   "SITE CHMOD %04o %s",
                                   mode & (S_IRWXU | S_IRWXG | S_IRWXO),
                                   g_vfs_ftp_file_get_ftp_path (file)))
            {
              g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
            }
        }
    }
  else
    {
      g_set_error_literal (&task.error,
                           G_IO_ERROR,
                           G_IO_ERROR_NOT_SUPPORTED,
                           _("Operation unsupported"));
    }

  g_vfs_ftp_task_done (&task);
  g_vfs_ftp_file_free (file);
}

static void
do_enumerate (GVfsBackend *backend,
              GVfsJobEnumerate *job,
              const char *dirname,
              GFileAttributeMatcher *matcher,
              GFileQueryInfoFlags query_flags)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *dir;
  GList *list, *walk;

  dir = g_vfs_ftp_file_new_from_gvfs (ftp, dirname);
  list = g_vfs_ftp_dir_cache_lookup_dir (ftp->dir_cache,
                                         &task,
                                         dir,
                                         TRUE,
                                         query_flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS ? FALSE : TRUE);
  g_vfs_ftp_file_free (dir);
  if (g_vfs_ftp_task_is_in_error (&task))
    {
      g_assert (list == NULL);
      g_vfs_ftp_task_done (&task);
      return;
    }

  g_vfs_ftp_task_done (&task);

  for (walk = list; walk; walk = walk->next)
    {
      GFileInfo *matched_info = g_file_info_new ();

      /* copy into a new GFileInfo as g_vfs_job_enumerate_add_info()
       * modifies the given GFileInfo */
      g_file_info_copy_into (walk->data, matched_info);
      g_vfs_job_enumerate_add_info (job, matched_info);
      g_object_unref (matched_info);
      g_object_unref (walk->data);
    }
  g_vfs_job_enumerate_done (job);

  g_list_free (list);
}

static void
do_set_display_name (GVfsBackend *backend,
                     GVfsJobSetDisplayName *job,
                     const char *filename,
                     const char *display_name)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *original, *dir, *now;

  original = g_vfs_ftp_file_new_from_gvfs (ftp, filename);
  dir = g_vfs_ftp_file_new_parent (original);
  now = g_vfs_ftp_file_new_child (dir, display_name, &task.error);
  g_vfs_ftp_task_send (&task,
                       G_VFS_FTP_PASS_300 | G_VFS_FTP_FAIL_200,
                       "RNFR %s", g_vfs_ftp_file_get_ftp_path (original));
  g_vfs_ftp_task_send (&task,
                       0,
                       "RNTO %s", g_vfs_ftp_file_get_ftp_path (now));

  /* FIXME: parse result of RNTO here? */
  g_vfs_job_set_display_name_set_new_path (job, g_vfs_ftp_file_get_gvfs_path (now));
  g_vfs_ftp_dir_cache_purge_dir (ftp->dir_cache, dir);
  g_vfs_ftp_file_free (now);
  g_vfs_ftp_file_free (dir);
  g_vfs_ftp_file_free (original);

  g_vfs_ftp_task_done (&task);
}

static void
do_delete (GVfsBackend *backend,
           GVfsJobDelete *job,
           const char *filename)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file;
  guint response;

  /* We try file deletion first. If that fails, we try directory deletion.
   * The file-first-then-directory order has been decided by coin-toss. */
  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);
  response = g_vfs_ftp_task_send (&task,
                		  G_VFS_FTP_PASS_500,
                		  "DELE %s", g_vfs_ftp_file_get_ftp_path (file));
  if (G_VFS_FTP_RESPONSE_GROUP (response) == 5)
    {
      response = g_vfs_ftp_task_send (&task,
                		      G_VFS_FTP_PASS_550,
                		      "RMD %s", g_vfs_ftp_file_get_ftp_path (file));
      if (response == 550)
        {
          GList *list = g_vfs_ftp_dir_cache_lookup_dir (ftp->dir_cache,
                                                        &task,
                                                        file,
                                                        FALSE,
                                                        FALSE);
          if (list)
            {
              g_set_error_literal (&task.error,
                		   G_IO_ERROR,
                		   G_IO_ERROR_NOT_EMPTY,
                		   g_strerror (ENOTEMPTY));
              g_list_free_full (list, g_object_unref);
            }
          else
            {
              g_vfs_ftp_task_clear_error (&task);
              g_vfs_ftp_task_set_error_from_response (&task, response);
            }
        }
    }

  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_done (&task);
}

static void
do_make_directory (GVfsBackend *backend,
                   GVfsJobMakeDirectory *job,
                   const char *filename)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *file;
  static const GVfsFtpErrorFunc make_directory_handlers[] = { error_550_exists, error_550_parent_not_found, NULL };

  file = g_vfs_ftp_file_new_from_gvfs (ftp, filename);
  g_vfs_ftp_task_send_and_check (&task,
                                 0,
                                 make_directory_handlers,
                                 file,
                                 NULL,
                                 "MKD %s", g_vfs_ftp_file_get_ftp_path (file));

  /* FIXME: Compare created file with name from server result to be sure
   * it's correct and otherwise fail. */
  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, file);
  g_vfs_ftp_file_free (file);

  g_vfs_ftp_task_done (&task);
}

static void
do_move (GVfsBackend *backend,
         GVfsJobMove *job,
         const char *source,
         const char *destination,
         GFileCopyFlags flags,
         GFileProgressCallback progress_callback,
         gpointer progress_callback_data)
{
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *srcfile, *destfile;
  static const GVfsFtpErrorFunc rnfr_handlers[] = { error_550_permission_or_not_found,
                                                    NULL };

  /* FIXME: what about G_FILE_COPY_NOFOLLOW_SYMLINKS and G_FILE_COPY_ALL_METADATA? */

  if (flags & G_FILE_COPY_BACKUP)
    {
      /* FIXME: implement? */

      if (flags & G_FILE_COPY_NO_FALLBACK_FOR_MOVE)
        {
          g_set_error_literal (&task.error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backups not supported"));
        }
      else
        {
          /* Return G_IO_ERROR_NOT_SUPPORTED instead of G_IO_ERROR_CANT_CREATE_BACKUP
           * to be proceeded with copy and delete fallback (see g_file_move). */
          g_set_error_literal (&task.error,
                               G_IO_ERROR,
                               G_IO_ERROR_NOT_SUPPORTED,
                               "Operation not supported");
        }

      g_vfs_ftp_task_done (&task);
      return;
    }

  srcfile = g_vfs_ftp_file_new_from_gvfs (ftp, source);
  destfile = g_vfs_ftp_file_new_from_gvfs (ftp, destination);
  if (g_vfs_ftp_task_try_cd (&task, destfile))
    {
      char *basename = g_path_get_basename (source);
      GVfsFtpFile *real = g_vfs_ftp_file_new_child (destfile, basename, &task.error);

      g_free (basename);
      if (real == NULL)
        {
          goto out;
        }
      else
        {
          g_vfs_ftp_file_free (destfile);
          destfile = real;
        }
    }

  if (!(flags & G_FILE_COPY_OVERWRITE))
    {
      GFileInfo *info = g_vfs_ftp_dir_cache_lookup_file (ftp->dir_cache,
                                                         &task,
                                                         destfile,
                                                         FALSE);

      if (info)
        {
          g_object_unref (info);
          g_set_error_literal (&task.error,
                	       G_IO_ERROR,
                               G_IO_ERROR_EXISTS,
                	       _("Target file already exists"));
          goto out;
        }
    }


  if (!g_vfs_ftp_task_send_and_check (&task,
                                 G_VFS_FTP_PASS_300 | G_VFS_FTP_FAIL_200,
                                 rnfr_handlers,
                                 srcfile,
                                 NULL,
                                 "RNFR %s", g_vfs_ftp_file_get_ftp_path (srcfile)))
    goto out;

  g_vfs_ftp_task_send (&task,
                       0,
                       "RNTO %s", g_vfs_ftp_file_get_ftp_path (destfile));

  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, srcfile);
  g_vfs_ftp_dir_cache_purge_file (ftp->dir_cache, destfile);
out:
  g_vfs_ftp_file_free (srcfile);
  g_vfs_ftp_file_free (destfile);

  g_vfs_ftp_task_done (&task);
}

static gssize
ftp_output_stream_splice (GOutputStream *output,
                          GInputStream *input,
                          goffset total_size,
                          GFileProgressCallback progress_callback,
                          gpointer progress_callback_data,
                          GCancellable *cancellable,
                          GError **error)
{
  gssize n_read, n_written;
  gssize bytes_copied;
  char buffer[8192], *p;

  bytes_copied = 0;
  for (;;) 
    {
      n_read = g_input_stream_read (input, buffer, sizeof (buffer), cancellable, error);
      if (n_read == -1)
        return -1;
      if (n_read == 0)
        break;

      p = buffer;
      while (n_read > 0)
        {
          n_written = g_output_stream_write (output, p, n_read, cancellable, error);
          if (n_written == -1)
            return -1;

          p += n_written;
          n_read -= n_written;
          bytes_copied += n_written;

          if (progress_callback)
            progress_callback (bytes_copied, total_size, progress_callback_data);
        }
    }

  return bytes_copied;
}

static void
do_pull_improve_error_message (GVfsFtpTask *task,
		               GFile       *dest,
                               gboolean     overwrite)
{
  GFileInfo *info;
  GFileType file_type;
  
  /* There was an error opening the source, try to set a good error for it.
   * Code taken from glib's gio/gfile.c:open_source_for_copy() function */

  if (g_vfs_ftp_task_error_matches (task, G_IO_ERROR, G_IO_ERROR_IS_DIRECTORY))
    {
      /* The source is a directory, don't fail with WOULD_RECURSE immediately, 
       * as that is less useful to the app. Better check for errors on the 
       * target instead. 
       */
      g_vfs_ftp_task_clear_error (task);
      
      info = g_file_query_info (dest, G_FILE_ATTRIBUTE_STANDARD_TYPE,
				G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
				task->cancellable, &task->error);
      if (info != NULL)
	{
	  file_type = g_file_info_get_file_type (info);
	  g_object_unref (info);
	  
	  if (overwrite)
	    {
	      if (file_type == G_FILE_TYPE_DIRECTORY)
		{
		  g_set_error_literal (&task->error, G_IO_ERROR, G_IO_ERROR_WOULD_MERGE,
                                       _("Can't copy directory over directory"));
		  return;
		}
	      /* continue to would_recurse error */
	    }
	  else
	    {
	      g_set_error_literal (&task->error, G_IO_ERROR, G_IO_ERROR_EXISTS,
                                   _("Target file already exists"));
	      return;
	    }
	}
      else
	{
	  /* Error getting info from target, return that error 
           * (except for NOT_FOUND, which is no error here) 
           */
	  if (!g_vfs_ftp_task_error_matches (task, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
            return;
          g_vfs_ftp_task_clear_error (task);
	}
      
      g_set_error_literal (&task->error, G_IO_ERROR, G_IO_ERROR_WOULD_RECURSE,
                           _("Can't recursively copy directory"));
    }
}

static void
do_pull (GVfsBackend *         backend,
         GVfsJobPull *         job,
         const char *          source,
         const char *          local_path,
         GFileCopyFlags        flags,
         gboolean              remove_source,
         GFileProgressCallback progress_callback,
         gpointer              progress_callback_data)
{
  static const GVfsFtpErrorFunc open_read_handlers[] = { error_550_is_directory,
                                                         error_550_permission_or_not_found, 
                                                         NULL };
  GVfsBackendFtp *ftp = G_VFS_BACKEND_FTP (backend);
  GVfsFtpTask task = G_VFS_FTP_TASK_INIT (ftp, G_VFS_JOB (job));
  GVfsFtpFile *src;
  GFile *dest;
  GInputStream *input;
  GOutputStream *output;
  goffset total_size = 0;
  
  src = g_vfs_ftp_file_new_from_gvfs (ftp, source);
  dest = g_file_new_for_path (local_path);

  /* If the source is a symlink, then it needs to be handled specially. */
  if (flags & G_FILE_COPY_NOFOLLOW_SYMLINKS)
    {
      GFileInfo *info = g_vfs_ftp_dir_cache_lookup_file (ftp->dir_cache,
                                                         &task,
                                                         src,
                                                         FALSE);
      if (!info)
        goto out;

      if (g_file_info_get_is_symlink (info))
        {
          /* Fall back to the default implementation to copy the symlink.
           * Because of the cache, this doesn't require any extra I/O
           * operations. */
          g_set_error_literal (&task.error,
                               G_IO_ERROR,
                               G_IO_ERROR_NOT_SUPPORTED,
                               "Operation not supported");
          g_object_unref (info);
          goto out;
        }
      g_object_unref (info);
    }

  if (progress_callback)
    {
      GFileInfo *info = g_vfs_ftp_dir_cache_lookup_file (ftp->dir_cache, &task, src, TRUE);
      if (info)
        {
          total_size = g_file_info_get_size (info);
          g_object_unref (info);
        }
    }

  g_vfs_ftp_task_setup_data_connection (&task);
  g_vfs_ftp_task_send_and_check (&task,
                                 G_VFS_FTP_PASS_100 | G_VFS_FTP_FAIL_200,
                                 open_read_handlers,
                                 src,
                                 NULL,
                                 "RETR %s", g_vfs_ftp_file_get_ftp_path (src));
  g_vfs_ftp_task_open_data_connection (&task);
  if (g_vfs_ftp_task_is_in_error (&task))
    {
      do_pull_improve_error_message (&task, dest, flags & G_FILE_COPY_OVERWRITE);
      goto out;
    }

  if (flags & G_FILE_COPY_OVERWRITE)
    output = G_OUTPUT_STREAM (g_file_replace (dest,
                                              NULL,
                                              flags & G_FILE_COPY_BACKUP ? TRUE : FALSE,
                                              G_FILE_CREATE_REPLACE_DESTINATION,
                                              task.cancellable,
                                              &task.error));
  else
    output = G_OUTPUT_STREAM (g_file_create (dest,
                                             0,
                                             task.cancellable,
                                             &task.error));
  if (output == NULL)
    {
      g_vfs_ftp_task_close_data_connection (&task);
      g_vfs_ftp_task_receive (&task, 0, NULL);
      goto out;
    }

  input = g_io_stream_get_input_stream (g_vfs_ftp_connection_get_data_stream (task.conn));
  ftp_output_stream_splice (output,
                            input,
                            total_size,
                            progress_callback,
                            progress_callback_data,
                            task.cancellable,
                            &task.error);
  g_vfs_ftp_task_close_data_connection (&task);
  g_vfs_ftp_task_receive (&task, 0, NULL);
  g_object_unref (output);

  if (remove_source)
    {
      g_vfs_ftp_task_send (&task,
                	   G_VFS_FTP_PASS_500,
                           "DELE %s", g_vfs_ftp_file_get_ftp_path (src));
    }

out:
  g_object_unref (dest);
  g_vfs_ftp_file_free (src);
  g_vfs_ftp_task_done (&task);
}

static gboolean
try_query_fs_info (GVfsBackend *backend,
                   GVfsJobQueryFsInfo *job,
                   const char *filename,
                   GFileInfo *info,
                   GFileAttributeMatcher *matcher)
{
  g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, "ftp");
  g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE, TRUE);
  g_vfs_job_succeeded (G_VFS_JOB (job));
  return TRUE;
}

static void
g_vfs_backend_ftp_class_init (GVfsBackendFtpClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GVfsBackendClass *backend_class = G_VFS_BACKEND_CLASS (klass);
 
  gobject_class->finalize = g_vfs_backend_ftp_finalize;

  backend_class->mount = do_mount;
  backend_class->try_mount = try_mount;
  backend_class->unmount = do_unmount;
  backend_class->open_for_read = do_open_for_read;
  backend_class->close_read = do_close_read;
  backend_class->read = do_read;
  backend_class->create = do_create;
  backend_class->append_to = do_append;
  backend_class->replace = do_replace;
  backend_class->close_write = do_close_write;
  backend_class->write = do_write;
  backend_class->query_info = do_query_info;
  backend_class->enumerate = do_enumerate;
  backend_class->set_display_name = do_set_display_name;
  backend_class->delete = do_delete;
  backend_class->make_directory = do_make_directory;
  backend_class->move = do_move;
  backend_class->try_query_settable_attributes = try_query_settable_attributes;
  backend_class->try_query_fs_info = try_query_fs_info;
  backend_class->set_attribute = do_set_attribute;
  backend_class->pull = do_pull;
}

/*** PUBLIC API ***/

/**
 * g_vfs_backend_ftp_has_feature:
 * @ftp: the backend
 * @feature: feature to check
 *
 * Checks if the FTP server supports a given @feature. Features are determined
 * once during the mount phase and are not queried again.
 *
 * Returns: %TRUE if @feature is supported.
 **/
gboolean
g_vfs_backend_ftp_has_feature (GVfsBackendFtp *ftp,
                               GVfsFtpFeature  feature)
{
  g_return_val_if_fail (G_VFS_IS_BACKEND_FTP (ftp), FALSE);
  g_return_val_if_fail (feature < 32, FALSE);

  return (ftp->features & (1 << feature)) != 0;
}

/**
 * g_vfs_backend_ftp_uses_workaround:
 * @ftp: the backend
 * @workaround: workaround to check
 *
 * Checks if the given @workaround was enabled previously using
 * g_vfs_backend_ftp_use_workaround(). See that function for a discussion
 * of the purpose of workarounds.
 *
 * Returns: %TRUE if the workaround is enabled
 **/
gboolean
g_vfs_backend_ftp_uses_workaround (GVfsBackendFtp *  ftp,
                                  GVfsFtpWorkaround workaround)
{
  g_return_val_if_fail (G_VFS_IS_BACKEND_FTP (ftp), FALSE);
  g_return_val_if_fail (workaround < 32, FALSE);

  return (g_atomic_int_get (&ftp->workarounds) & (1 << workaround)) != 0;
}

/**
 * g_vfs_backend_ftp_use_workaround:
 * @ftp: the backend
 * @workaround: workaround to set
 *
 * Sets the given @workaround to be used on the backend. Workarounds are flags
 * set on the backend to ensure a special behavior in the client to work
 * around problems with servers. See the existing workarounds for examples.
 **/
void
g_vfs_backend_ftp_use_workaround (GVfsBackendFtp *  ftp,
                                  GVfsFtpWorkaround workaround)
{
  int cur, set;

  g_return_if_fail (G_VFS_IS_BACKEND_FTP (ftp));
  g_return_if_fail (workaround < 32);

  set = 1 << workaround;
  while (((cur = g_atomic_int_get (&ftp->workarounds)) & set) == 0 &&
         !g_atomic_int_compare_and_exchange (&ftp->workarounds, cur, cur | set));
   
}