File: gnome-vfs-utils.c

package info (click to toggle)
gnome-vfs 1%3A2.24.4-6
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 17,120 kB
  • ctags: 10,397
  • sloc: ansic: 78,516; sh: 10,341; makefile: 902; perl: 99
file content (2196 lines) | stat: -rw-r--r-- 57,729 bytes parent folder | download | duplicates (5)
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
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */

/* gnome-vfs-utils.c - Private utility functions for the GNOME Virtual
   File System.

   Copyright (C) 1999 Free Software Foundation
   Copyright (C) 2000, 2001 Eazel, Inc.

   The Gnome Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   The Gnome 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 the Gnome Library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.

   Authors: Ettore Perazzoli <ettore@comm2000.it>
   	    John Sullivan <sullivan@eazel.com> 
            Darin Adler <darin@eazel.com>
*/

#include <config.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include "gnome-vfs-utils.h"

#include "gnome-vfs-private-utils.h"
#include "gnome-vfs-ops.h"
#include "gnome-vfs-mime-handlers.h"
#include "gnome-vfs-mime-private.h"
#include "gnome-vfs-method.h"
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <gconf/gconf-client.h>
#ifndef G_OS_WIN32
#include <pwd.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define KILOBYTE_FACTOR 1024.0
#define MEGABYTE_FACTOR (1024.0 * 1024.0)
#define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)

#define READ_CHUNK_SIZE 8192

#define MAX_SYMLINKS_FOLLOWED 32


/**
 * gnome_vfs_format_file_size_for_display:
 * @size: a #GnomeVFSFileSize (a #guint64 value).
 * 
 * Formats the file @size passed so that it is easy for
 * the user to read. Gives the size in bytes, kilobytes, megabytes or
 * gigabytes, choosing whatever is appropriate.
 * 
 * Returns: a newly allocated string with the size ready to be shown.
 */

gchar*
gnome_vfs_format_file_size_for_display (GnomeVFSFileSize size)
{
	if (size < (GnomeVFSFileSize) KILOBYTE_FACTOR) {
		return g_strdup_printf (dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
	} else {
		gdouble displayed_size;

		if (size < (GnomeVFSFileSize) MEGABYTE_FACTOR) {
			displayed_size = (gdouble) size / KILOBYTE_FACTOR;
			return g_strdup_printf (_("%.1f KB"),
						       displayed_size);
		} else if (size < (GnomeVFSFileSize) GIGABYTE_FACTOR) {
			displayed_size = (gdouble) size / MEGABYTE_FACTOR;
			return g_strdup_printf (_("%.1f MB"),
						       displayed_size);
		} else {
			displayed_size = (gdouble) size / GIGABYTE_FACTOR;
			return g_strdup_printf (_("%.1f GB"),
						       displayed_size);
		}
	}
}

typedef enum {
	UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
	UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
	UNSAFE_PATH       = 0x4,  /* Allows '/' and '&' and '='  */
	UNSAFE_DOS_PATH   = 0x8,  /* Allows '/' and '&' and '=' and ':' */
	UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
	UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
} UnsafeCharacterSet;

static const guchar acceptable[96] =
{ /*  X0   X1   X2   X3   X4   X5   X6   X7   X8   X9   XA   XB   XC   XD   XE   XF */
  /* spc    !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */
    0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C, 
  /*   0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
    0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20, 
  /*   @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
    0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 
  /*   P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
    0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F, 
  /*   `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
    0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 
  /*   p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
    0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20  
};

enum {
	RESERVED = 1,
	UNRESERVED,
	DELIMITERS,
	UNWISE,
	CONTROL,
	SPACE	
};

static const guchar uri_character_kind[128] =
{
    CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   , 
    CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,
    CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,
    CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,CONTROL   ,
    /* ' '        !          "          #          $          %          &          '      */
    SPACE     ,UNRESERVED,DELIMITERS,DELIMITERS,RESERVED  ,DELIMITERS,RESERVED  ,UNRESERVED,
    /*  (         )          *          +          ,          -          .          /      */
    UNRESERVED,UNRESERVED,UNRESERVED,RESERVED  ,RESERVED  ,UNRESERVED,UNRESERVED,RESERVED  , 
    /*  0         1          2          3          4          5          6          7      */
    UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  8         9          :          ;          <          =          >          ?      */
    UNRESERVED,UNRESERVED,RESERVED  ,RESERVED  ,DELIMITERS,RESERVED  ,DELIMITERS,RESERVED  ,
    /*  @         A          B          C          D          E          F          G      */
    RESERVED  ,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  H         I          J          K          L          M          N          O      */
    UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  P         Q          R          S          T          U          V          W      */
    UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  X         Y          Z          [          \          ]          ^          _      */
    UNRESERVED,UNRESERVED,UNRESERVED,UNWISE    ,UNWISE    ,UNWISE    ,UNWISE    ,UNRESERVED,
    /*  `         a          b          c          d          e          f          g      */
    UNWISE    ,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  h         i          j          k          l          m          n          o      */
    UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  p         q          r          s          t          u          v          w      */
    UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,UNRESERVED,
    /*  x         y          z         {           |          }          ~         DEL     */
    UNRESERVED,UNRESERVED,UNRESERVED,UNWISE    ,UNWISE    ,UNWISE    ,UNRESERVED,CONTROL
};


/*  Below modified from libwww HTEscape.c */

#define HEX_ESCAPE '%'

/*  Escape undesirable characters using %
 *  -------------------------------------
 *
 * This function takes a pointer to a string in which
 * some characters may be unacceptable unescaped.
 * It returns a string which has these characters
 * represented by a '%' character followed by two hex digits.
 *
 * This routine returns a g_malloced string.
 */

static const gchar hex[16] = "0123456789ABCDEF";

static gchar *
gnome_vfs_escape_string_internal (const gchar *string, 
				  UnsafeCharacterSet mask)
{
#define ACCEPTABLE_CHAR(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))

	const gchar *p;
	gchar *q;
	gchar *result;
	guchar c;
	gint unacceptable;
	UnsafeCharacterSet use_mask;

	g_return_val_if_fail (mask == UNSAFE_ALL
			      || mask == UNSAFE_ALLOW_PLUS
			      || mask == UNSAFE_PATH
			      || mask == UNSAFE_DOS_PATH
			      || mask == UNSAFE_HOST
			      || mask == UNSAFE_SLASHES, NULL);

	if (string == NULL) {
		return NULL;
	}
	
	unacceptable = 0;
	use_mask = mask;
	for (p = string; *p != '\0'; p++) {
		c = *p;
		if (!ACCEPTABLE_CHAR (c)) {
			unacceptable++;
		}
		if ((use_mask == UNSAFE_HOST) && 
		    (unacceptable || (c == '/'))) {
			/* when escaping a host, if we hit something that needs to be escaped, or we finally
			 * hit a path separator, revert to path mode (the host segment of the url is over).
			 */
			use_mask = UNSAFE_PATH;
		}
	}
	
	result = g_malloc (p - string + unacceptable * 2 + 1);

	use_mask = mask;
	for (q = result, p = string; *p != '\0'; p++){
		c = *p;
		
		if (!ACCEPTABLE_CHAR (c)) {
			*q++ = HEX_ESCAPE; /* means hex coming */
			*q++ = hex[c >> 4];
			*q++ = hex[c & 15];
		} else {
			*q++ = c;
		}
		if ((use_mask == UNSAFE_HOST) &&
		    (!ACCEPTABLE_CHAR (c) || (c == '/'))) {
			use_mask = UNSAFE_PATH;
		}
	}
	
	*q = '\0';
	
	return result;
}

/**
 * gnome_vfs_escape_string:
 * @string: string to be escaped.
 *
 * Escapes @string, replacing any and all special characters 
 * with equivalent escape sequences.
 *
 * Return value: a newly allocated string equivalent to @string
 * but with all special characters escaped.
 */
gchar *
gnome_vfs_escape_string (const gchar *string)
{
	return gnome_vfs_escape_string_internal (string, UNSAFE_ALL);
}

/**
 * gnome_vfs_escape_path_string:
 * @path: string to be escaped.
 *
 * Escapes @path, replacing only special characters that would not
 * be found in paths (so '/', '&', and '=' will not be escaped by
 * this function).
 *
 * Return value: a newly allocated string equivalent to @path but
 * with non-path characters escaped.
 */
gchar *
gnome_vfs_escape_path_string (const gchar *path)
{
#ifdef G_OS_WIN32
	gchar *path_copy = g_strdup (path);
	gchar *p = path_copy;
	gchar *retval;

	/* Replace backslashes with slashes, that is what is used in
	 * Explorer's "Internet Shortcuts" (.url files), so presumably
	 * it's the standard.
	 */
	while (*p) {
		if (*p == '\\')
			*p = '/';
		p++;
	}
	/* Paths starting with a drive letter get an extra leading slash */
	if (g_ascii_isalpha (path_copy[0]) && path_copy[1] == ':') {
		gchar *escaped_rest = gnome_vfs_escape_string_internal (path_copy+2, UNSAFE_PATH);
		path_copy[2] = '\0';
		retval = g_strconcat ("/", path_copy, escaped_rest, NULL);
		g_free (escaped_rest);
	} else
		retval = gnome_vfs_escape_string_internal (path_copy, UNSAFE_PATH);
	g_free (path_copy);

	return retval;
#else
	return gnome_vfs_escape_string_internal (path, UNSAFE_PATH);
#endif
}

/**
 * gnome_vfs_escape_host_and_path_string:
 * @path: string to be escaped.
 *
 * Escapes @path, replacing only special characters that would not
 * be found in paths or host name (so '/', '&', '=', ':' and '@'
 * will not be escaped by this function).
 *
 * Return value: a newly allocated string equivalent to @path but
 * with non-path/host characters escaped.
 */
gchar *
gnome_vfs_escape_host_and_path_string (const gchar *path)
{
	return gnome_vfs_escape_string_internal (path, UNSAFE_HOST);
}

/**
 * gnome_vfs_escape_slashes:
 * @string: string to be escaped.
 *
 * Escapes only '/' and '%' characters in @string, replacing
 * them with their escape sequence equivalents.
 *
 * Return value: a newly allocated string equivalent to @string,
 * but with no unescaped '/' or '%' characters.
 */
gchar *
gnome_vfs_escape_slashes (const gchar *string)
{
	return gnome_vfs_escape_string_internal (string, UNSAFE_SLASHES);
}

/**
 * gnome_vfs_escape_set:
 * @string: string to be escaped.
 * @match_set: a string containing all characters to be escaped in @string. 
 *  
 * Escapes all characters in @string which are listed in @match_set.  
 * 
 * Return value: a newly allocated string equivalent to @string but 
 * with characters in @match_string escaped.
 */
char *
gnome_vfs_escape_set (const char *string,
	              const char *match_set)
{
	char *result;
	const char *scanner;
	char *result_scanner;
	int escape_count;

	escape_count = 0;

	if (string == NULL) {
		return NULL;
	}

	if (match_set == NULL) {
		return g_strdup (string);
	}
	
	for (scanner = string; *scanner != '\0'; scanner++) {
		if (strchr(match_set, *scanner) != NULL) {
			/* this character is in the set of characters 
			 * we want escaped.
			 */
			escape_count++;
		}
	}
	
	if (escape_count == 0) {
		return g_strdup (string);
	}

	/* allocate two extra characters for every character that
	 * needs escaping and space for a trailing zero
	 */
	result = g_malloc (scanner - string + escape_count * 2 + 1);
	for (scanner = string, result_scanner = result; *scanner != '\0'; scanner++) {
		if (strchr(match_set, *scanner) != NULL) {
			/* this character is in the set of characters 
			 * we want escaped.
			 */
			*result_scanner++ = HEX_ESCAPE;
			*result_scanner++ = hex[*scanner >> 4];
			*result_scanner++ = hex[*scanner & 15];
			
		} else {
			*result_scanner++ = *scanner;
		}
	}

	*result_scanner = '\0';

	return result;
}

/**
 * gnome_vfs_expand_initial_tilde:
 * @path: a local file path which may start with a '~'.
 *
 * If @path starts with a ~, representing the user's home
 * directory, expand it to the actual path location.
 *
 * Return value: a newly allocated string with the initial
 * tilde (if there was one) converted to an actual path.
 */
char *
gnome_vfs_expand_initial_tilde (const char *path)
{
#ifndef G_OS_WIN32
	char *slash_after_user_name, *user_name;
	struct passwd *passwd_file_entry;

	g_return_val_if_fail (path != NULL, NULL);

	if (path[0] != '~') {
		return g_strdup (path);
	}
	
	if (path[1] == '/' || path[1] == '\0') {
		return g_strconcat (g_get_home_dir (), &path[1], NULL);
	}

	slash_after_user_name = strchr (&path[1], '/');
	if (slash_after_user_name == NULL) {
		user_name = g_strdup (&path[1]);
	} else {
		user_name = g_strndup (&path[1],
				       slash_after_user_name - &path[1]);
	}
	passwd_file_entry = getpwnam (user_name);
	g_free (user_name);

	if (passwd_file_entry == NULL || passwd_file_entry->pw_dir == NULL) {
		return g_strdup (path);
	}

	return g_strconcat (passwd_file_entry->pw_dir,
			    slash_after_user_name,
			    NULL);
#else
	return g_strdup (path);
#endif
}

static int
hex_to_int (gchar c)
{
	return  c >= '0' && c <= '9' ? c - '0'
		: c >= 'A' && c <= 'F' ? c - 'A' + 10
		: c >= 'a' && c <= 'f' ? c - 'a' + 10
		: -1;
}

static int
unescape_character (const char *scanner)
{
	int first_digit;
	int second_digit;

	first_digit = hex_to_int (*scanner++);
	if (first_digit < 0) {
		return -1;
	}

	second_digit = hex_to_int (*scanner++);
	if (second_digit < 0) {
		return -1;
	}

	return (first_digit << 4) | second_digit;
}

/**
 * gnome_vfs_unescape_string:
 * @escaped_string: an escaped uri, path, or other string.
 * @illegal_characters: a string containing a sequence of characters
 * considered "illegal" to be escaped, '\0' is automatically in this list.
 *
 * Decodes escaped characters (i.e. PERCENTxx sequences) in @escaped_string.
 * Characters are encoded in PERCENTxy form, where xy is the ASCII hex code 
 * for character 16x+y.
 * 
 * Return value: a newly allocated string with the unescaped
 * equivalents, or %NULL if @escaped_string contained an escaped
 * encoding of one of the characters in @illegal_characters.
 */
char *
gnome_vfs_unescape_string (const gchar *escaped_string, 
			   const gchar *illegal_characters)
{
	const gchar *in;
	gchar *out, *result;
	gint character;
	
	if (escaped_string == NULL) {
		return NULL;
	}

	result = g_malloc (strlen (escaped_string) + 1);
	
	out = result;
	for (in = escaped_string; *in != '\0'; in++) {
		character = *in;
		if (*in == HEX_ESCAPE) {
			character = unescape_character (in + 1);

			/* Check for an illegal character. We consider '\0' illegal here. */
			if (character <= 0
			    || (illegal_characters != NULL
				&& strchr (illegal_characters, (char)character) != NULL)) {
				g_free (result);
				return NULL;
			}
			in += 2;
		}
		*out++ = (char)character;
	}
	
	*out = '\0';
	g_assert (out - result <= strlen (escaped_string));
	return result;
	
}

/**
 * gnome_vfs_unescape_string_for_display:
 * @escaped: a string encoded with escaped sequences.
 * 
 * Similar to gnome_vfs_unescape_string, but it returns something
 * semi-intelligable to a user even upon receiving traumatic input
 * such as %00 or URIs in bad form.
 * 
 * See also: gnome_vfs_unescape_string().
 * 
 * WARNING: You should never use this function on a whole URI!  It
 * unescapes reserved characters, and can result in a mangled URI
 * that can not be re-entered.  For example, it unescapes "#" "&" and "?",
 * which have special meanings in URI strings.

 * Return value: a pointer to a g_malloc'd string with all characters
 * replacing their escaped hex values.
 */
gchar *
gnome_vfs_unescape_string_for_display (const gchar *escaped)
{
	const gchar *in, *start_escape;
	gchar *out, *result;
	gint i,j;
	gchar c;
	gint invalid_escape;

	if (escaped == NULL) {
		return NULL;
	}

	result = g_malloc (strlen (escaped) + 1);
	
	out = result;
	for (in = escaped; *in != '\0'; ) {
		start_escape = in;
		c = *in++;
		invalid_escape = 0;
		
		if (c == HEX_ESCAPE) {
			/* Get the first hex digit. */
			i = hex_to_int (*in++);
			if (i < 0) {
				invalid_escape = 1;
				in--;
			}
			c = i << 4;
			
			if (invalid_escape == 0) {
				/* Get the second hex digit. */
				i = hex_to_int (*in++);
				if (i < 0) {
					invalid_escape = 2;
					in--;
				}
				c |= i;
			}
			if (invalid_escape == 0) {
				/* Check for an illegal character. */
				if (c == '\0') {
					invalid_escape = 3;
				}
			}
		}
		if (invalid_escape != 0) {
			for (j = 0; j < invalid_escape; j++) {
				*out++ = *start_escape++;
			}
		} else {
			*out++ = c;
		}
	}
	
	*out = '\0';
	g_assert (out - result <= strlen (escaped));
	return result;
}

/**
 * gnome_vfs_remove_optional_escapes:
 * @uri: an escaped uri.
 * 
 * Scans the @uri and converts characters that do not have to be 
 * escaped into an un-escaped form. The characters that get treated this
 * way are defined as unreserved by the RFC.
 * 
 * Return value: an error value if the @uri is found to be malformed.
 */
GnomeVFSResult
gnome_vfs_remove_optional_escapes (char *uri)
{
	guchar *scanner;
	int character;
	int length;

	if (uri == NULL) {
		return GNOME_VFS_OK;
	}
	
	length = strlen (uri);

	for (scanner = (guchar *)uri; *scanner != '\0'; scanner++, length--) {
		if (*scanner == HEX_ESCAPE) {
			character = unescape_character ((char *)scanner + 1);
			if (character < 0) {
				/* invalid hexadecimal character */
				return GNOME_VFS_ERROR_INVALID_URI;
			}

			if (uri_character_kind [character] == UNRESERVED) {
				/* This character does not need to be escaped, convert it
				 * to a non-escaped form.
				 */
				*scanner = (guchar)character;
				g_assert (length >= 3);

				/* Shrink the string covering up the two extra digits of the
				 * escaped character. Include the trailing '\0' in the copy
				 * to keep the string terminated.
				 */
				memmove (scanner + 1, scanner + 3, length - 2);
			} else {
				/* This character must stay escaped, skip the entire
				 * escaped sequence
				 */
				scanner += 2;
			}
			length -= 2;

		} else if (*scanner > 127
			|| uri_character_kind [*scanner] == DELIMITERS
			|| uri_character_kind [*scanner] == UNWISE
			|| uri_character_kind [*scanner] == CONTROL) {
			/* It is illegal for this character to be in an un-escaped form
			 * in the uri.
			 */
			return GNOME_VFS_ERROR_INVALID_URI;
		}
	}
	return GNOME_VFS_OK;
}

static char *
gnome_vfs_make_uri_canonical_old (const char *original_uri_text)
{
	GnomeVFSURI *uri;
	char *result;

	uri = gnome_vfs_uri_new_private (original_uri_text, TRUE, TRUE, FALSE);
	if (uri == NULL) {
		return NULL;
	} 

	result = gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_NONE);
	gnome_vfs_uri_unref (uri);

	return result;
}

/**
 * gnome_vfs_make_path_name_canonical:
 * @path: a file path, relative or absolute.
 * 
 * Calls _gnome_vfs_canonicalize_pathname(), allocating storage for the 
 * result and providing for a cleaner memory management.
 * 
 * Return value: a canonical version of @path.
 */
gchar *
gnome_vfs_make_path_name_canonical (const gchar *path)
{
	char *path_clone;
	char *result;

	path_clone = g_strdup (path);
	result = _gnome_vfs_canonicalize_pathname (path_clone);
	if (result != path_clone) {
		g_free (path_clone);
		return g_strdup (result);
	}

	return path_clone;
}

/**
 * gnome_vfs_list_deep_free:
 * @list: list to be freed.
 *
 * Free @list and call g_free() on all data members.
 */
void
gnome_vfs_list_deep_free (GList *list)
{
	GList *p;

	if (list == NULL)
		return;

	for (p = list; p != NULL; p = p->next) {
		g_free (p->data);
	}
	g_list_free (list);
}

/**
 * gnome_vfs_get_local_path_from_uri:
 * @uri: uri to convert to a local path.
 * 
 * Create a local path for a file:/// uri. Do not use with uris
 * of other methods.
 *
 * Return value: a newly allocated string containing the local path.
 * %NULL is returned on error or if the uri isn't a file: uri
 * without a fragment identifier (or chained uri).
 */
char *
gnome_vfs_get_local_path_from_uri (const char *uri)
{
	const char *path_part;

	if (!_gnome_vfs_istr_has_prefix (uri, "file:/")) {
		return NULL;
	}
	
	path_part = uri + strlen ("file:");
	if (strchr (path_part, '#') != NULL) {
		return NULL;
	}
	
	if (_gnome_vfs_istr_has_prefix (path_part, "///")) {
		path_part += 2;
	} else if (_gnome_vfs_istr_has_prefix (path_part, "//")) {
		return NULL;
	}

	return gnome_vfs_unescape_string (path_part, "/");
}

/**
 * gnome_vfs_get_uri_from_local_path:
 * @local_full_path: a full local filesystem path (i.e. not relative).
 * 
 * Returns a file:/// URI for the local path @local_full_path, 
 * such as a path provided by gtk_file_chooser_get_filename().
 * The resulting URI may be provided, for instance, to gnome_vfs_uri_new().
 *
 * On Windows @local_full_path should be in the UTF-8 encoding, and can start with a drive
 * letter, but doesn't have to.
 *
 * Return value: a newly allocated string containing the uri corresponding 
 * to @local_full_path (%NULL for some bad errors).
 */
char *
gnome_vfs_get_uri_from_local_path (const char *local_full_path)
{
	char *escaped_path, *result;
	
	if (local_full_path == NULL) {
		return NULL;
	}

	g_return_val_if_fail (g_path_is_absolute (local_full_path), NULL);

	escaped_path = gnome_vfs_escape_path_string (local_full_path);

	result = g_strconcat ("file://", escaped_path, NULL);
	g_free (escaped_path);
	return result;
}

/**
 * gnome_vfs_get_volume_free_space:
 * @vfs_uri: a #GnomeVFSURI.
 * @size: a #GnomeVFSFileSize.
 * 
 * Stores the amount of free space in bytes on @vfs-uri's
 * volume in @size.
 *
 * Returns: %GNOME_VFS_OK on success, otherwise an
 * %GNOME_VFS_ERROR_* code.
 */
GnomeVFSResult
gnome_vfs_get_volume_free_space (const GnomeVFSURI *vfs_uri, 
				 GnomeVFSFileSize  *size)
{	
	if (!VFS_METHOD_HAS_FUNC(vfs_uri->method, get_volume_free_space))
		return GNOME_VFS_ERROR_NOT_SUPPORTED;

	return vfs_uri->method->get_volume_free_space (vfs_uri->method, vfs_uri, size);
}

/**
 * gnome_vfs_icon_path_from_filename:
 * @filename: path to a file. Could be relative or absolute path.
 *
 * Return value: Returns the icon path for the @filename. Example:
 * gnome_vfs_icon_path_from_filename ("nautilus/nautilus-desktop.png") will return a string 
 * forming the full path of the file nautilus-desktop.png ie $PREFIX/share/pixmaps/nautilus/nautilus-desktop.png.
 */
char *
gnome_vfs_icon_path_from_filename (const char *filename)
{
	const char *gnome_var;
	char *full_filename;
	char **paths, **temp_paths;

	if (g_path_is_absolute (filename) &&
	    g_file_test (filename, G_FILE_TEST_EXISTS))
		return g_strdup (filename);

	gnome_var = g_getenv ("GNOME_PATH");

	if (gnome_var == NULL) {
		gnome_var = GNOME_VFS_PREFIX;
	}

	paths = g_strsplit (gnome_var, G_SEARCHPATH_SEPARATOR_S, 0); 

	for (temp_paths = paths; *temp_paths != NULL; temp_paths++) {
		full_filename = g_build_filename (*temp_paths,
						  "share",
						  "pixmaps",
						  filename,
						  NULL);
		if (g_file_test (full_filename, G_FILE_TEST_EXISTS)) {
			g_strfreev (paths);
			return full_filename;
		}
		g_free (full_filename);
		full_filename = NULL;
	}

	g_strfreev (paths);
	return NULL;
}

static char *
strdup_to (const char *string, const char *end)
{
	if (end == NULL) {
		return g_strdup (string);
	}
	return g_strndup (string, end - string);
}

static gboolean
is_executable_file (const char *path)
{
	/* Check that it exists and is regular. */
	if (!g_file_test (path, G_FILE_TEST_IS_REGULAR)) {
		return FALSE;
	}

	/* Check that it's executable. */
	if (!g_file_test (path, G_FILE_TEST_IS_EXECUTABLE)) {
		return FALSE;
	}

	return TRUE;
}

static gboolean
executable_in_path (const char *executable_name)
{
	const char *path_list, *piece_start, *piece_end;
	char *piece, *raw_path, *expanded_path;
	gboolean is_good;

	path_list = g_getenv ("PATH");

	for (piece_start = path_list; ; piece_start = piece_end + 1) {
		/* Find the next piece of PATH. */
		piece_end = strchr (piece_start, G_SEARCHPATH_SEPARATOR);
		piece = strdup_to (piece_start, piece_end);
		g_strstrip (piece);
		
		if (piece[0] == '\0') {
			is_good = FALSE;
		} else {
			/* Try out this path with the executable. */
			raw_path = g_build_filename (piece, executable_name, NULL);
			/* XXX Can this be necessary? Surely PATH
			 * isn't supposed to contain actual tildes,
			 * but the shell expands any tilde one tries
			 * to add to PATH?
			 */ 
			expanded_path = gnome_vfs_expand_initial_tilde (raw_path);
			g_free (raw_path);
			
			is_good = is_executable_file (expanded_path);
			g_free (expanded_path);
		}
		
		g_free (piece);
		
		if (is_good) {
			return TRUE;
		}

		if (piece_end == NULL) {
			return FALSE;
		}
	}
}

static char *
get_executable_name_from_command_string (const char *command_string)
{
	/* FIXME bugzilla.eazel.com 2757: 
	 * We need to handle quoting here for the full-path case */
	return g_strstrip (strdup_to (command_string, strchr (command_string, ' ')));
}

/**
 * gnome_vfs_is_executable_command_string:
 * @command_string: a string representing a command ie "xterm -bg white".
 * 
 * Checks if @command_string starts with the full path of an executable file
 * or an executable in $PATH.
 *
 * Returns: %TRUE if @command_string started with an executable file, and is in $PATH,
 * %FALSE otherwise.
 */
gboolean
gnome_vfs_is_executable_command_string (const char *command_string)
{
	char *executable_name;
	char *executable_path;
	gboolean found;

	/* Check whether command_string is a full path for an executable. */
	if (g_path_is_absolute (command_string)) {

		/* FIXME bugzilla.eazel.com 2757:
		 * Because we don't handle quoting, we can check for full
		 * path including spaces, but no parameters, and full path
		 * with no spaces with or without parameters. But this will
		 * fail for quoted full path with spaces, and parameters.
		 */

		/* This works if command_string contains a space, but not
		 * if command_string has parameters.
		 */
		if (is_executable_file (command_string)) {
			return TRUE;
		}

		/* This works if full path has no spaces, with or without parameters */
		executable_path = get_executable_name_from_command_string (command_string);
		found = is_executable_file (executable_path);
		g_free (executable_path);

		return found;
	}
	
	executable_name = get_executable_name_from_command_string (command_string);
	found = executable_in_path (executable_name);
	g_free (executable_name);

	return found;
}

/**
 * gnome_vfs_read_entire_file:
 * @uri: uri of the file to read.
 * @file_size: after reading the file, contains the size of the file read.
 * @file_contents: contains the file_size bytes, the contents of the file at @uri.
 * 
 * Reads an entire file into memory for convenience. Beware accidentally
 * loading large files into memory with this function.
 *
 * Since version 2.10 the string stored in @file_contents will be null-terminated,
 * so for text files you can use result as a normal string.
 *
 * Return value: an integer representing the result of the operation.
 *
 * Since: 2.2
 */
GnomeVFSResult
gnome_vfs_read_entire_file (const char *uri,
			    int *file_size,
			    char **file_contents)
{
	GnomeVFSResult result;
	GnomeVFSHandle *handle;
	char *buffer;
	GnomeVFSFileSize total_bytes_read;
	GnomeVFSFileSize bytes_read;

	g_assert (file_contents != NULL);

	if (file_size != NULL)
		*file_size = 0;
	*file_contents = NULL;

	/* Open the file. */
	result = gnome_vfs_open (&handle, uri, GNOME_VFS_OPEN_READ);
	if (result != GNOME_VFS_OK) {
		return result;
	}

	/* Read the whole thing. */
	buffer = NULL;
	total_bytes_read = 0;
	do {
		buffer = g_realloc (buffer, total_bytes_read + READ_CHUNK_SIZE);
		result = gnome_vfs_read (handle,
					 buffer + total_bytes_read,
					 READ_CHUNK_SIZE,
					 &bytes_read);
		if (result != GNOME_VFS_OK && result != GNOME_VFS_ERROR_EOF) {
			g_free (buffer);
			gnome_vfs_close (handle);
			return result;
		}

		/* Check for overflow. */
		if (total_bytes_read + bytes_read < total_bytes_read) {
			g_free (buffer);
			gnome_vfs_close (handle);
			return GNOME_VFS_ERROR_TOO_BIG;
		}

		total_bytes_read += bytes_read;
	} while (result == GNOME_VFS_OK);

	buffer = g_realloc (buffer, total_bytes_read + 1);
	buffer[total_bytes_read] = '\0';

	/* Close the file. */
	result = gnome_vfs_close (handle);
	if (result != GNOME_VFS_OK) {
		g_free (buffer);
		return result;
	}

	/* Return the file. */
	if (file_size != NULL)
		*file_size = total_bytes_read;
	*file_contents = g_realloc (buffer, total_bytes_read + 1);
	return GNOME_VFS_OK;
}

static char *
gnome_vfs_make_valid_utf8 (const char *name)
{
	GString *string;
	const char *remainder, *invalid;
	int remaining_bytes, valid_bytes;

	string = NULL;
	remainder = name;
	remaining_bytes = strlen (name);

	while (remaining_bytes != 0) {
		if (g_utf8_validate (remainder, remaining_bytes, &invalid)) {
			break;
		}
		valid_bytes = invalid - remainder;

		if (string == NULL) {
			string = g_string_sized_new (remaining_bytes);
		}
		g_string_append_len (string, remainder, valid_bytes);
		g_string_append_c (string, '?');

		remaining_bytes -= valid_bytes + 1;
		remainder = invalid + 1;
	}

	if (string == NULL) {
		return g_strdup (name);
	}

	g_string_append (string, remainder);
	g_string_append (string, _(" (invalid Unicode)"));
	g_assert (g_utf8_validate (string->str, -1, NULL));

	return g_string_free (string, FALSE);
}

static char *
gnome_vfs_format_uri_for_display_internal (const char *uri,
					   gboolean filenames_are_utf8)
{
	char *canonical_uri, *path, *utf8_path;

	g_return_val_if_fail (uri != NULL, g_strdup (""));

	canonical_uri = gnome_vfs_make_uri_canonical_old (uri);

	/* If there's no fragment and it's a local path. */
	path = gnome_vfs_get_local_path_from_uri (canonical_uri);
	
	if (path != NULL) {
		if (!filenames_are_utf8) {
			utf8_path = g_filename_to_utf8(path, -1, NULL, NULL, NULL);
			if (utf8_path) {
				g_free (canonical_uri);
				g_free (path);
				return utf8_path;
			} 
		} else if (g_utf8_validate (path, -1, NULL)) {
			g_free (canonical_uri);
			return path;
		}
	}

	if (canonical_uri && !g_utf8_validate (canonical_uri, -1, NULL)) {
		utf8_path = gnome_vfs_make_valid_utf8 (canonical_uri);
		g_free (canonical_uri);
		canonical_uri = utf8_path;
	}

	g_free (path);
	return canonical_uri;
}


/**
 * gnome_vfs_format_uri_for_display:
 * @uri: uri to be displayed.
 *
 * Filter, modify, unescape and change @uri to make it appropriate
 * for display to users. The conversion is done such that the roundtrip
 * to UTF-8 is reversible.
 * 
 * Rules:
 * 	file: uri without fragments should appear as local paths.
 * 	file: uri with fragments should appear as file:uri.
 * 	All other uri appear as expected.
 *
 * Return value: a newly allocated string which represents @uri and can be displayed.
 *
 * Since: 2.2
 */

char *
gnome_vfs_format_uri_for_display (const char *uri) 
{
	gboolean utf8;
	const char **charsets;

	utf8 = g_get_filename_charsets (&charsets);

	return gnome_vfs_format_uri_for_display_internal (uri, utf8);
}

static gboolean
is_valid_scheme_character (char c)
{
	return g_ascii_isalnum (c) || c == '+' || c == '-' || c == '.';
}

static gboolean
has_valid_scheme (const char *uri)
{
	const char *p;

	p = uri;

	if (!is_valid_scheme_character (*p)) {
		return FALSE;
	}

	do {
		p++;
	} while (is_valid_scheme_character (*p));

	return *p == ':';
}

static char *
gnome_vfs_escape_high_chars (const guchar *string)
{
	char *result;
	const guchar *scanner;
	guchar *result_scanner;
	int escape_count;
	static const gchar hex[16] = "0123456789ABCDEF";

#define ACCEPTABLE(a) ((a)>=32 && (a)<128)
	
	escape_count = 0;

	if (string == NULL) {
		return NULL;
	}

	for (scanner = string; *scanner != '\0'; scanner++) {
		if (!ACCEPTABLE(*scanner)) {
			escape_count++;
		}
	}
	
	if (escape_count == 0) {
		return g_strdup ((char *)string);
	}

	/* allocate two extra characters for every character that
	 * needs escaping and space for a trailing zero
	 */
	result = g_malloc (scanner - string + escape_count * 2 + 1);
	for (scanner = string, result_scanner = (guchar *)result; *scanner != '\0'; scanner++) {
		if (!ACCEPTABLE(*scanner)) {
			*result_scanner++ = '%';
			*result_scanner++ = hex[*scanner >> 4];
			*result_scanner++ = hex[*scanner & 15];
			
		} else {
			*result_scanner++ = *scanner;
		}
	}

	*result_scanner = '\0';

	return result;
}

/* http uris look like <something>.<2-4 letters>, possibly followed by a slash and some text. */
static gboolean
looks_like_http_uri (const char *str)
{
	int len;
	int i;
	char c;
	const char *first_slash;

	first_slash = strchr(str, '/');
	if (first_slash == NULL) {
		len = strlen (str);
	} else {
		len = first_slash - str;
	}
	for (i = 0; i < 5 && i < len; i++) {
		c = str[len - 1 - i];
		if (i >= 2 && c == '.') {
			return TRUE;
		}
		if (!g_ascii_isalpha (c)) {
			return FALSE;
		}
	}
	return FALSE;
}

/* The strip_trailing_whitespace option is intended to make copy/paste of
 * URIs less error-prone when it is known that trailing whitespace isn't
 * part of the uri.
 */
static char *
gnome_vfs_make_uri_from_input_internal (const char *text,
					gboolean filenames_are_utf8,
					gboolean strip_trailing_whitespace)
{
	char *stripped, *uri, *locale_path, *escaped;

	g_return_val_if_fail (text != NULL, g_strdup (""));

	/* Strip off leading whitespaces (since they can't be part of a valid
	   uri).   Only strip off trailing whitespaces when requested since
	   they might be part of a valid uri.
	 */
	if (strip_trailing_whitespace) {
		stripped = g_strstrip (g_strdup (text));
	} else {
		stripped = g_strchug (g_strdup (text));
	}

	if (g_path_is_absolute (stripped)) {
		if (!filenames_are_utf8) {
			locale_path = g_filename_to_utf8 (stripped, -1, NULL, NULL, NULL);
			if (locale_path != NULL) {
				uri = gnome_vfs_get_uri_from_local_path (locale_path);
				g_free (locale_path);
			} else {
				/* We couldn't convert to the locale. */
				/* FIXME: We should probably give a user-visible error here. */
				uri = g_strdup("");
			}
		} else {
			uri = gnome_vfs_get_uri_from_local_path (stripped);
		}
	} else switch (stripped[0]) {
	case '\0':
		uri = g_strdup ("");
		break;
#ifndef G_OS_WIN32
	case '~': {
		char *path, *filesystem_path;
		if (!filenames_are_utf8) {
			filesystem_path = g_filename_to_utf8(stripped, -1, NULL, NULL, NULL);
		} else {
			filesystem_path = g_strdup (stripped);
		}
                /* deliberately falling into default case on fail */
		if (filesystem_path != NULL) {
			path = gnome_vfs_expand_initial_tilde (filesystem_path);
			g_free (filesystem_path);
			if (*path == '/') {
				uri = gnome_vfs_get_uri_from_local_path (path);
				g_free (path);
				break;
			}
			g_free (path);
		}
                /* don't insert break here, read above comment */
	}
#endif
	default:
		if (has_valid_scheme (stripped)) {
			uri = gnome_vfs_escape_high_chars ((guchar *)stripped);
		} else if (looks_like_http_uri (stripped)) {
			escaped = gnome_vfs_escape_high_chars ((guchar *)stripped);
			uri = g_strconcat ("http://", escaped, NULL);
			g_free (escaped);
		} else {
			escaped = gnome_vfs_escape_high_chars ((guchar *)stripped);
			uri = g_strconcat ("file:///", escaped, NULL);
			g_free (escaped);
		}
	}

	g_free (stripped);

	return uri;
	
}

/**
 * gnome_vfs_make_uri_from_input:
 * @location: a possibly mangled "uri", in UTF-8.
 *
 * Takes a user input path/uri and makes a valid uri out of it.
 *
 * This function is the reverse of gnome_vfs_format_uri_for_display()
 * but it also handles the fact that the user could have typed
 * arbitrary UTF-8 in the entry showing the string.
 *
 * Returns: a newly allocated uri.
 *
 * Since: 2.2
 */
char *
gnome_vfs_make_uri_from_input (const char *location)
{
	gboolean utf8;
	const char **charsets;

	utf8 = g_get_filename_charsets (&charsets);

	return gnome_vfs_make_uri_from_input_internal (location, utf8, TRUE);
}

/**
 * gnome_vfs_make_uri_from_input_with_trailing_ws:
 * @location: a possibly mangled uri, in UTF-8.
 *
 * Takes a user input path/uri and makes a valid uri out of it.
 *
 * This function is indentical to gnome_vfs_make_uri_from_input() except
 * that this version won't strip any trailing slashes.
 *
 * Returns: a newly allocated uri.
 *
 * Since: 2.12
 */
char *
gnome_vfs_make_uri_from_input_with_trailing_ws (const char *location)
{
	gboolean utf8;
	const char **charsets;

	utf8 = g_get_filename_charsets (&charsets);

	return gnome_vfs_make_uri_from_input_internal (location, utf8, FALSE);	
}

/**
 * gnome_vfs_make_uri_from_input_with_dirs:
 * @location: a relative or absolute path.
 * @dirs: directory to use as a base directory if @location is a relative path.
 *
 * Determines a fully qualified uri from a relative or absolute input path.
 * Basically calls gnome_vfs_make_uri_from_input() except it specifically
 * tries to support paths relative to the specified directories (can be homedir
 * and/or current directory). See #GnomeVFSMakeURIDirs for more information.
 *
 * Return value: a newly allocated string containing the fully qualified uri.
 *
 * Since: 2.4
 */
char *
gnome_vfs_make_uri_from_input_with_dirs (const char *location,
					 GnomeVFSMakeURIDirs dirs)
{
	char *uri, *path, *dir;

	if (g_path_is_absolute (location))
		uri = gnome_vfs_make_uri_from_input (location);
	else switch (location[0]) {
	case '\0':
		uri = g_strdup ("");
		break;
#ifndef G_OS_WIN32		
	case '~':
		uri = gnome_vfs_make_uri_from_input (location);
		break;
#endif
	default:
		/* this might be a relative path, check if it exists relative
		 * to current dir and home dir.
		 */
		uri = NULL;
		if (dirs & GNOME_VFS_MAKE_URI_DIR_CURRENT) {
			dir = g_get_current_dir ();
			path = g_build_filename (dir, location, NULL);
			g_free (dir);
			
			if (g_file_test (path, G_FILE_TEST_EXISTS)) {
				uri = gnome_vfs_make_uri_from_input (path);
			}
			g_free (path);
		}

		if (uri == NULL &&
		    dirs & GNOME_VFS_MAKE_URI_DIR_HOMEDIR) {
			path = g_build_filename (g_get_home_dir (), location, NULL);
		
			if (g_file_test (path, G_FILE_TEST_EXISTS)) {
				uri = gnome_vfs_make_uri_from_input (path);
			}
			g_free (path);
		}

		if (uri == NULL) {
			uri = gnome_vfs_make_uri_from_input (location);
		}
	}
	
	return uri;
}


/**
 * gnome_vfs_make_uri_canonical_strip_fragment:
 * @uri: a #GnomeVFSURI.
 *
 * Returns a canonicalized uri. If @uri contains a fragment (anything after a '#') strips off that and
 * then makes the @uri canonical.
 *
 * Returns: a newly allocated string containing a canonical @uri.
 *
 * Since: 2.2
 */

char *
gnome_vfs_make_uri_canonical_strip_fragment (const char *uri)
{
	const char *fragment;
	char *without_fragment, *canonical;

	fragment = strchr (uri, '#');
	if (fragment == NULL) {
		return gnome_vfs_make_uri_canonical (uri);
	}

	without_fragment = g_strndup (uri, fragment - uri);
	canonical = gnome_vfs_make_uri_canonical (without_fragment);
	g_free (without_fragment);
	return canonical;
}

static gboolean
uris_match (const char *uri_1, const char *uri_2, gboolean ignore_fragments)
{
	char *canonical_1, *canonical_2;
	gboolean result;

	if (ignore_fragments) {
		canonical_1 = gnome_vfs_make_uri_canonical_strip_fragment (uri_1);
		canonical_2 = gnome_vfs_make_uri_canonical_strip_fragment (uri_2);
	} else {
		canonical_1 = gnome_vfs_make_uri_canonical (uri_1);
		canonical_2 = gnome_vfs_make_uri_canonical (uri_2);
	}

	result = strcmp (canonical_1, canonical_2) ? FALSE : TRUE;

	g_free (canonical_1);
	g_free (canonical_2);
	
	return result;
}

/**
 * gnome_vfs_uris_match:
 * @uri_1: stringified uri to compare with @uri_2.
 * @uri_2: stringified uri to compare with @uri_1.
 * 
 * Compare two uris.
 *
 * Return value: %TRUE if they are the same, %FALSE otherwise.
 *
 * Since: 2.2
 */

gboolean
gnome_vfs_uris_match (const char *uri_1, const char *uri_2)
{
	return uris_match (uri_1, uri_2, FALSE);
}

static gboolean
gnome_vfs_uri_is_local_scheme (const char *uri)
{
	gboolean is_local_scheme;
	char *temp_scheme;
	int i;
	char *local_schemes[] = {"file:", "help:", "ghelp:", "gnome-help:",
				 "trash:", "man:", "info:", 
				 "hardware:", "search:", "pipe:",
				 "gnome-trash:", NULL};

	is_local_scheme = FALSE;
	for (temp_scheme = *local_schemes, i = 0; temp_scheme != NULL; i++, temp_scheme = local_schemes[i]) {
		is_local_scheme = _gnome_vfs_istr_has_prefix (uri, temp_scheme);
		if (is_local_scheme) {
			break;
		}
	}
	

	return is_local_scheme;
}

static char *
gnome_vfs_handle_trailing_slashes (const char *uri)
{
	char *temp, *uri_copy;
	gboolean previous_char_is_column, previous_chars_are_slashes_without_column;
	gboolean previous_chars_are_slashes_with_column;
	gboolean is_local_scheme;

	g_assert (uri != NULL);

	uri_copy = g_strdup (uri);
	if (strlen (uri_copy) <= 2) {
		return uri_copy;
	}

	is_local_scheme = gnome_vfs_uri_is_local_scheme (uri);

	previous_char_is_column = FALSE;
	previous_chars_are_slashes_without_column = FALSE;
	previous_chars_are_slashes_with_column = FALSE;

	/* remove multiple trailing slashes */
	for (temp = uri_copy; *temp != '\0'; temp++) {
		if (*temp == '/' && !previous_char_is_column) {
			previous_chars_are_slashes_without_column = TRUE;
		} else if (*temp == '/' && previous_char_is_column) {
			previous_chars_are_slashes_without_column = FALSE;
			previous_char_is_column = TRUE;
			previous_chars_are_slashes_with_column = TRUE;
		} else {
			previous_chars_are_slashes_without_column = FALSE;
			previous_char_is_column = FALSE;
			previous_chars_are_slashes_with_column = FALSE;
		}

		if (*temp == ':') {
			previous_char_is_column = TRUE;
		}
	}

	if (*temp == '\0' && previous_chars_are_slashes_without_column) {
		if (is_local_scheme) {
			/* go back till you remove them all. */
			for (temp--; *(temp) == '/'; temp--) {
				*temp = '\0';
			}
		} else {
			/* go back till you remove them all but one. */
			for (temp--; *(temp - 1) == '/'; temp--) {
				*temp = '\0';
			}			
		}
	}

	if (*temp == '\0' && previous_chars_are_slashes_with_column) {
		/* go back till you remove them all but three. */
		for (temp--; *(temp - 3) != ':' && *(temp - 2) != ':' && *(temp - 1) != ':'; temp--) {
			*temp = '\0';
		}
	}


	return uri_copy;
}

/**
 * gnome_vfs_make_uri_canonical:
 * @uri: an absolute or relative stringified uri. It might have scheme.
 *
 * Standardizes the format of the @uri, so that it can be used
 * later in other functions that expect a canonical uri.
 *
 * Returns: a newly allocated string that contains the canonical 
 * representation of @uri.
 *
 * Since: 2.2
 */

char *
gnome_vfs_make_uri_canonical (const char *uri)
{
	char *canonical_uri, *old_uri, *p;
	gboolean relative_uri;

	relative_uri = FALSE;

	if (uri == NULL) {
		return NULL;
	}

	/* FIXME bugzilla.eazel.com 648: 
	 * This currently ignores the issue of two uris that are not identical but point
	 * to the same data except for the specific cases of trailing '/' characters,
	 * file:/ and file:///, and "lack of file:".
	 */

	canonical_uri = gnome_vfs_handle_trailing_slashes (uri);

	/* Note: In some cases, a trailing slash means nothing, and can
	 * be considered equivalent to no trailing slash. But this is
	 * not true in every case; specifically not for web addresses passed
	 * to a web-browser. So we don't have the trailing-slash-equivalence
	 * logic here, but we do use that logic in EelDirectory where
	 * the rules are more strict.
	 */

#ifndef G_OS_WIN32
#define URI_CONTAINS_NO_SCHEME(uri) (strchr (uri, ':') == NULL)
#else
#define URI_CONTAINS_NO_SCHEME(uri) \
  (strlen (uri) > 2 && strchr (uri + 2, ':') == NULL)
#endif


	/* Add file: if there is no scheme. */
	if (URI_CONTAINS_NO_SCHEME (canonical_uri)) {
		old_uri = canonical_uri;

		if (!g_path_is_absolute (old_uri)) {
			/* FIXME bugzilla.eazel.com 5069: 
			 *  bandaid alert. Is this really the right thing to do?
			 * 
			 * We got what really is a relative path. We do a little bit of
			 * a stretch here and assume it was meant to be a cryptic absolute path,
			 * and convert it to one. Since we can't call gnome_vfs_uri_new and
			 * gnome_vfs_uri_to_string to do the right make-canonical conversion,
			 * we have to do it ourselves.
			 */
			relative_uri = TRUE;
			canonical_uri = gnome_vfs_make_path_name_canonical (old_uri);
			g_free (old_uri);
			old_uri = canonical_uri;
			canonical_uri = g_strconcat ("file:///", old_uri, NULL);
		} else {
			canonical_uri = g_strconcat ("file:", old_uri, NULL);
		}
		g_free (old_uri);
	}

	/* Lower-case the scheme. */
	for (p = canonical_uri; *p != ':'; p++) {
		g_assert (*p != '\0');
		*p = g_ascii_tolower (*p);
	}

	if (!relative_uri) {
		old_uri = canonical_uri;
		canonical_uri = gnome_vfs_make_uri_canonical_old (canonical_uri);
		if (canonical_uri != NULL) {
			g_free (old_uri);
		} else {
			canonical_uri = old_uri;
		}
	}
	
	/* FIXME bugzilla.eazel.com 2802:
	 * Work around gnome-vfs's desire to convert file:foo into file://foo
	 * by converting to file:///foo here. When you remove this, check that
	 * typing "foo" into location bar does not crash and returns an error
	 * rather than displaying the contents of /
	 */
	if (canonical_uri != NULL
	    && g_str_has_prefix (canonical_uri, "file://")
	    && !g_str_has_prefix (canonical_uri, "file:///")) {
		old_uri = canonical_uri;
		canonical_uri = g_strconcat ("file:/", old_uri + 5, NULL);
		g_free (old_uri);
	}

	return canonical_uri;
}

/**
 * gnome_vfs_get_uri_scheme:
 * @uri: a stringified uri.
 *
 * Retrieve the scheme used in @uri.
 *
 * Return value: a newly allocated string containing the scheme, %NULL
 * if @uri doesn't contain a scheme.
 *
 * Since: 2.2
 */

char *
gnome_vfs_get_uri_scheme (const char *uri)
{
	char *colon;

	g_return_val_if_fail (uri != NULL, NULL);

	colon = strchr (uri, ':');
	
	if (colon == NULL) {
		return NULL;
	}

	return g_ascii_strdown (uri, colon - uri);
}

/* Note that NULL's and full paths are also handled by this function.
 * A NULL location will return the current working directory
 */
static char *
file_uri_from_local_relative_path (const char *location)
{
	char *current_dir;
	char *base_uri, *base_uri_slash;
	char *location_escaped;
	char *uri;

	current_dir = g_get_current_dir ();
	base_uri = gnome_vfs_get_uri_from_local_path (current_dir);
	/* g_get_current_dir returns w/o trailing / */
	base_uri_slash = g_strconcat (base_uri, "/", NULL);

	location_escaped = gnome_vfs_escape_path_string (location);

	uri = gnome_vfs_uri_make_full_from_relative (base_uri_slash, location_escaped);

	g_free (location_escaped);
	g_free (base_uri_slash);
	g_free (base_uri);
	g_free (current_dir);

	return uri;
}

/**
 * gnome_vfs_make_uri_from_shell_arg:
 * @uri: path to make the uri from.
 *
 * Similar to gnome_vfs_make_uri_from_input(), except that:
 * 
 * 1) guesses relative paths instead of http domains.
 * 2) doesn't bother stripping leading/trailing white space.
 * 3) doesn't bother with ~ expansion--that's done by the shell.
 *
 * Returns: a newly allocated string representing @uri.
 *
 * Since: 2.2
 */

char *
gnome_vfs_make_uri_from_shell_arg (const char *location)
{
	char *uri;

	g_return_val_if_fail (location != NULL, g_strdup (""));

	if (g_path_is_absolute (location))
		uri = gnome_vfs_get_uri_from_local_path (location);
	else switch (location[0]) {
	case '\0':
		uri = g_strdup ("");
		break;
	default:
		if (has_valid_scheme (location)) {
			uri = g_strdup (location);
		} else {
			uri = file_uri_from_local_relative_path (location);
		}
	}

	return uri;
}

/**
 * gnome_vfs_make_uri_full_from_relative:
 * @base_uri: path to use as the base for the full uri.
 * @relative_uri: full or relative path to be appended to the @base_uri.
 *
 * Returns a string representing the full uri given a full @base_uri and a 
 * secondary uri which may be relative.
 *
 * Deprecated: This function is deprecated, please use 
 * gnome_vfs_uri_make_full_from_relative() from gnome-vfs-uri.h .
 *
 * Return value: a newly allocated string containing the uri.
 * (%NULL for some bad errors).
 *
 * Since: 2.2
 */

char *
gnome_vfs_make_uri_full_from_relative (const char *base_uri, 
				       const char *relative_uri)
{
	return gnome_vfs_uri_make_full_from_relative (base_uri, relative_uri);
}

GnomeVFSResult
_gnome_vfs_uri_resolve_all_symlinks_uri (GnomeVFSURI *uri,
					 GnomeVFSURI **result_uri)
{
	GnomeVFSURI *new_uri, *resolved_uri;
	GnomeVFSFileInfo *info;
	GnomeVFSResult res;
	char *escaped_symlink;
	char *p;
	int n_followed_symlinks;

	/* Ref the original uri so we don't lose it */
	uri = gnome_vfs_uri_ref (uri);

	*result_uri = NULL;

	info = gnome_vfs_file_info_new ();

	p = uri->text;
	n_followed_symlinks = 0;
	while (*p != 0) {
		while (*p == GNOME_VFS_URI_PATH_CHR)
			p++;
		while (*p != 0 && *p != GNOME_VFS_URI_PATH_CHR)
			p++;

		new_uri = gnome_vfs_uri_dup (uri);
		g_free (new_uri->text);
		new_uri->text = g_strndup (uri->text, p - uri->text);
		
		gnome_vfs_file_info_clear (info);
		res = gnome_vfs_get_file_info_uri (new_uri, info, GNOME_VFS_FILE_INFO_DEFAULT);
		if (res != GNOME_VFS_OK) {
			gnome_vfs_uri_unref (new_uri);
			goto out;
		}
		if (info->type == GNOME_VFS_FILE_TYPE_SYMBOLIC_LINK &&
		    info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_SYMLINK_NAME) {
			n_followed_symlinks++;
			if (n_followed_symlinks > MAX_SYMLINKS_FOLLOWED) {
				res = GNOME_VFS_ERROR_TOO_MANY_LINKS;
				gnome_vfs_uri_unref (new_uri);
				goto out;
			}
			escaped_symlink = gnome_vfs_escape_path_string (info->symlink_name);
			resolved_uri = gnome_vfs_uri_resolve_symbolic_link (new_uri, escaped_symlink);
			g_assert (resolved_uri != NULL);

			if (*p != 0) {
				gnome_vfs_uri_unref (new_uri);

				new_uri = gnome_vfs_uri_append_string (resolved_uri, p);

				gnome_vfs_uri_unref (uri);
				gnome_vfs_uri_unref (resolved_uri);

				uri = gnome_vfs_uri_ref (new_uri);
			} else {
				gnome_vfs_uri_unref (uri);
				uri = resolved_uri;
			}

			p = uri->text;
		} 
		gnome_vfs_uri_unref (new_uri);
	}

	res = GNOME_VFS_OK;
	*result_uri = gnome_vfs_uri_dup (uri);
 out:
	gnome_vfs_file_info_unref (info);
	gnome_vfs_uri_unref (uri);
	return res;
}

GnomeVFSResult
_gnome_vfs_uri_resolve_all_symlinks (const char *text_uri,
				     char **resolved_text_uri)
{
	GnomeVFSURI *uri, *resolved_uri;
	GnomeVFSResult res;

	*resolved_text_uri = NULL;

	uri = gnome_vfs_uri_new (text_uri);

	if (uri == NULL) {
		return GNOME_VFS_ERROR_NOT_SUPPORTED;
	}
	if (uri->text == NULL) {
		gnome_vfs_uri_unref (uri);
		return GNOME_VFS_ERROR_NOT_SUPPORTED;
	}

	res = _gnome_vfs_uri_resolve_all_symlinks_uri (uri, &resolved_uri);

	if (res == GNOME_VFS_OK) {
		*resolved_text_uri = gnome_vfs_uri_to_string (resolved_uri, GNOME_VFS_URI_HIDE_NONE);
		gnome_vfs_uri_unref (resolved_uri);
	}
	gnome_vfs_uri_unref (uri);
	return res;
}

char *
gnome_vfs_resolve_symlink (const char *path,
			   const char *symlink)
{
	char *p, *filename;
	char **strs;
	int i, j, n;
	GString *res_path;

	g_assert (path != NULL);
	g_assert (symlink != NULL);

	p = strrchr (path, '/');
	
	if (symlink[0] == '/' || p == NULL) {
		return g_strdup (symlink);
	}

	/* either use whole path as base (if it ends in '/'),
	 * or chop its filename part */
	p = g_strndup (path, p - path);
		
	filename = g_build_filename (p, symlink, NULL);
	g_free (p);

	strs = g_strsplit (filename, "/", -1);

	g_free (filename);

	n = g_strv_length (strs);

	for (i = 0; i < n; i++) {
		if (!strcmp (strs[i], "") ||
		    !strcmp (strs[i], ".")) {
			g_free (strs[i]);
			strs[i] = NULL;
		} else if (!strcmp (strs[i], "..")) {
			g_free (strs[i]);
			strs[i] = NULL;

			for (j = i; strs[j] == NULL && j > 0; j--)
				;

			g_free (strs[j]);
			strs[j] = NULL;
		}
	}

	res_path = g_string_new (NULL);

	for (i = 0; i < n; i++)
		if (strs[i] != NULL) {
			g_string_append_c (res_path, '/');
			g_string_append (res_path, strs[i]);
			g_free (strs[i]);
		}

	/* TODO also re-append '/' if the symlink ends in '/'? */ 
	if (res_path->len == 0)
		g_string_append_c (res_path, '/');

	g_free (strs);

	return g_string_free (res_path, FALSE);
}

gboolean 
_gnome_vfs_uri_is_in_subdir (GnomeVFSURI *uri, GnomeVFSURI *dir)
{
	GnomeVFSFileInfo *dirinfo, *info;
	GnomeVFSURI *resolved_dir, *parent, *tmp;
	GnomeVFSResult res;
	gboolean is_in_dir;

	resolved_dir = NULL;
	parent = NULL;

	is_in_dir = FALSE;
	
	dirinfo = gnome_vfs_file_info_new ();
	info = gnome_vfs_file_info_new ();

	res = gnome_vfs_get_file_info_uri (dir, dirinfo, GNOME_VFS_FILE_INFO_DEFAULT);
	if (res != GNOME_VFS_OK || dirinfo->type != GNOME_VFS_FILE_TYPE_DIRECTORY) {
		goto out;
	}

	res = _gnome_vfs_uri_resolve_all_symlinks_uri (dir, &resolved_dir);
	if (res != GNOME_VFS_OK) {
		goto out;
	}
	
	res = _gnome_vfs_uri_resolve_all_symlinks_uri (uri, &tmp);
	if (res != GNOME_VFS_OK) {
		goto out;
	}
	
	parent = gnome_vfs_uri_get_parent (tmp);
	gnome_vfs_uri_unref (tmp);

	while (parent != NULL) {
		res = gnome_vfs_get_file_info_uri (parent, info, GNOME_VFS_FILE_INFO_DEFAULT);
		if (res != GNOME_VFS_OK) {
			break;
		}

		if (dirinfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_DEVICE &&
		    dirinfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_INODE &&
		    info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_DEVICE &&
		    info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_INODE) {
			if (dirinfo->device == info->device &&
			    dirinfo->inode == info->inode) {
				is_in_dir = TRUE;
				break;
			}
		} else {
			if (gnome_vfs_uri_equal (dir, parent)) {
				is_in_dir = TRUE;
				break;
			}
		}
		
		tmp = gnome_vfs_uri_get_parent (parent);
		gnome_vfs_uri_unref (parent);
		parent = tmp;
	}

 out:
	if (resolved_dir != NULL) {
		gnome_vfs_uri_unref (resolved_dir);
	}
	if (parent != NULL) {
		gnome_vfs_uri_unref (parent);
	}
	gnome_vfs_file_info_unref (info);
	gnome_vfs_file_info_unref (dirinfo);
	return is_in_dir;
}

/**
 * gnome_vfs_url_show:
 * @url: url to be shown.
 * 
 * Launches the default application or component associated with the given @url.
 *
 * Return value: %GNOME_VFS_OK if the default action was launched,
 * %GNOME_VFS_ERROR_BAD_PARAMETERS for an invalid or non-existant @url,
 * %GNOME_VFS_ERROR_NO_DEFAULT if no default action is associated with the @url.
 * Also error codes from gnome_vfs_mime_action_launch()
 * or gnome_vfs_mime_action_launch_with_env().
 *
 * Since: 2.4
 */
GnomeVFSResult
gnome_vfs_url_show (const char *url)
{
	return gnome_vfs_url_show_with_env (url, NULL);
}

/**
 * gnome_vfs_url_show_with_env:
 * @url: url to be shown.
 * @envp: environment data.
 * 
 * Like gnome_vfs_url_show() except that the default action will be launched
 * with the given environment.
 *
 * Return value: %GNOME_VFS_OK if the default action was launched.
 * %GNOME_VFS_ERROR_BAD_PARAMETERS for an invalid or non-existant @url,
 * %GNOME_VFS_ERROR_NO_DEFAULT if no default action is associated with the @url.
 * Also error codes from gnome_vfs_mime_application_launch_with_env()
 * or gnome_vfs_mime_action_launch_with_env().
 *
 * Since: 2.4
 */
GnomeVFSResult
gnome_vfs_url_show_with_env (const char  *url,
                             char       **envp)
{
	GnomeVFSMimeApplication *app;
	GnomeVFSMimeAction *action;
	GnomeVFSResult result;
	GList params;
	char *type;
	char *scheme;

	g_return_val_if_fail (url != NULL, GNOME_VFS_ERROR_BAD_PARAMETERS);

	scheme = gnome_vfs_get_uri_scheme (url);
	if (scheme == NULL) {
		return GNOME_VFS_ERROR_BAD_PARAMETERS;
	}
	
	/* check if this scheme requires special handling */
	if (_gnome_vfs_use_handler_for_scheme (scheme)) {
		result = _gnome_vfs_url_show_using_handler_with_env (url, envp);
		g_free (scheme);
		return result;
	}
	
	g_free (scheme);

	result = _gnome_vfs_get_slow_mime_type_internal (url, &type);
	if (result != GNOME_VFS_OK) {
		return result;
	}
	
	params.data = (char *) url;
	params.prev = NULL;
	params.next = NULL;

	app = gnome_vfs_mime_get_default_application_for_uri (url, type);
	
	if (app != NULL) {
		result = gnome_vfs_mime_application_launch_with_env (app, &params, envp);
		gnome_vfs_mime_application_free (app);
		g_free (type);
		return result;
	}
	
	action = gnome_vfs_mime_get_default_action (type);
	
	if (action != NULL) {
		result = gnome_vfs_mime_action_launch_with_env (action, &params, envp);
		gnome_vfs_mime_action_free (action);
		g_free (type);
		return result;
	}
	
	g_free (type);
	return GNOME_VFS_ERROR_NO_DEFAULT;	
}