aboutsummaryrefslogtreecommitdiffstats
path: root/wsutil/filesystem.c
blob: 2b402f14cf7f82e8e1ce4a3723bdc3699378b3dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
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
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
/* filesystem.c
 * Filesystem utility routines
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <config.h>

/*
 * Required with GNU libc to get dladdr().
 * We define it here because <dlfcn.h> apparently gets included by
 * one of the headers we include below.
 */
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <glib.h>

#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <shlobj.h>
#include <wsutil/unicode-utils.h>
#else /* _WIN32 */
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#ifdef __linux__
#include <sys/utsname.h>
#endif
#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifdef HAVE_DLADDR
#include <dlfcn.h>
#endif
#include <pwd.h>
#endif /* _WIN32 */

#include "filesystem.h"
#include <wsutil/report_err.h>
#include <wsutil/privileges.h>
#include <wsutil/file_util.h>
#include <wsutil/utf8_entities.h>

#include <wiretap/wtap.h>   /* for WTAP_ERR_SHORT_WRITE */

#define PROFILES_DIR    "profiles"
#define PLUGINS_DIR_NAME    "plugins"

char *persconffile_dir = NULL;
char *persdatafile_dir = NULL;
char *persconfprofile = NULL;

static gboolean do_store_persconffiles = FALSE;
static GHashTable *profile_files = NULL;

/*
 * Given a pathname, return a pointer to the last pathname separator
 * character in the pathname, or NULL if the pathname contains no
 * separators.
 */
char *
find_last_pathname_separator(const char *path)
{
    char *separator;

#ifdef _WIN32
    char c;

    /*
     * We have to scan for '\' or '/'.
     * Get to the end of the string.
     */
    separator = strchr(path, '\0');     /* points to ending '\0' */
    while (separator > path) {
        c = *--separator;
        if (c == '\\' || c == '/')
            return separator;   /* found it */
    }

    /*
     * OK, we didn't find any, so no directories - but there might
     * be a drive letter....
     */
    return strchr(path, ':');
#else
    separator = strrchr(path, '/');
    return separator;
#endif
}

/*
 * Given a pathname, return the last component.
 */
const char *
get_basename(const char *path)
{
    const char *filename;

    g_assert(path != NULL);
    filename = find_last_pathname_separator(path);
    if (filename == NULL) {
        /*
         * There're no directories, drive letters, etc. in the
         * name; the pathname *is* the file name.
         */
        filename = path;
    } else {
        /*
         * Skip past the pathname or drive letter separator.
         */
        filename++;
    }
    return filename;
}

/*
 * Given a pathname, return a string containing everything but the
 * last component.  NOTE: this overwrites the pathname handed into
 * it....
 */
char *
get_dirname(char *path)
{
    char *separator;

    g_assert(path != NULL);
    separator = find_last_pathname_separator(path);
    if (separator == NULL) {
        /*
         * There're no directories, drive letters, etc. in the
         * name; there is no directory path to return.
         */
        return NULL;
    }

    /*
     * Get rid of the last pathname separator and the final file
     * name following it.
     */
    *separator = '\0';

    /*
     * "path" now contains the pathname of the directory containing
     * the file/directory to which it referred.
     */
    return path;
}

/*
 * Given a pathname, return:
 *
 *  the errno, if an attempt to "stat()" the file fails;
 *
 *  EISDIR, if the attempt succeeded and the file turned out
 *  to be a directory;
 *
 *  0, if the attempt succeeded and the file turned out not
 *  to be a directory.
 */

int
test_for_directory(const char *path)
{
    ws_statb64 statb;

    if (ws_stat64(path, &statb) < 0)
        return errno;

    if (S_ISDIR(statb.st_mode))
        return EISDIR;
    else
        return 0;
}

int
test_for_fifo(const char *path)
{
    ws_statb64 statb;

    if (ws_stat64(path, &statb) < 0)
        return errno;

    if (S_ISFIFO(statb.st_mode))
        return ESPIPE;
    else
        return 0;
}

/*
 * Directory from which the executable came.
 */
static char *progfile_dir;

#ifdef __APPLE__
/*
 * Directory of the application bundle in which we're contained,
 * if we're contained in an application bundle.  Otherwise, NULL.
 *
 * Note: Table 2-5 "Subdirectories of the Contents directory" of
 *
 *    https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW1
 *
 * says that the "Frameworks" directory
 *
 *    Contains any private shared libraries and frameworks used by the
 *    executable.  The frameworks in this directory are revision-locked
 *    to the application and cannot be superseded by any other, even
 *    newer, versions that may be available to the operating system.  In
 *    other words, the frameworks included in this directory take precedence
 *    over any other similarly named frameworks found in other parts of
 *    the operating system.  For information on how to add private
 *    frameworks to your application bundle, see Framework Programming Guide.
 *
 * so if we were to ship with any frameworks (e.g. Qt) we should
 * perhaps put them in a Frameworks directory rather than under
 * Resources.
 *
 * It also says that the "PlugIns" directory
 *
 *    Contains loadable bundles that extend the basic features of your
 *    application. You use this directory to include code modules that
 *    must be loaded into your applicationbs process space in order to
 *    be used. You would not use this directory to store standalone
 *    executables.
 *
 * Our plugins are just raw .so/.dylib files; I don't know whether by
 * "bundles" they mean application bundles (i.e., directory hierarchies)
 * or just "bundles" in the Mach-O sense (which are an image type that
 * can be loaded with dlopen() but not linked as libraries; our plugins
 * are, I think, built as dylibs and can be loaded either way).
 *
 * And it says that the "SharedSupport" directory
 *
 *    Contains additional non-critical resources that do not impact the
 *    ability of the application to run. You might use this directory to
 *    include things like document templates, clip art, and tutorials
 *    that your application expects to be present but that do not affect
 *    the ability of your application to run.
 *
 * I don't think I'd put the files that currently go under Resources/share
 * into that category; they're not, for example, sample Lua scripts that
 * don't actually get run by Wireshark, they're configuration/data files
 * for Wireshark whose absence might not prevent Wireshark from running
 * but that would affect how it behaves when run.
 */
static char *appbundle_dir;
#endif

/*
 * TRUE if we're running from the build directory and we aren't running
 * with special privileges.
 */
static gboolean running_in_build_directory_flag = FALSE;

#ifndef _WIN32
/*
 * Get the pathname of the executable using various platform-
 * dependent mechanisms for various UN*Xes.
 *
 * These calls all should return something independent of the argv[0]
 * passed to the program, so it shouldn't be fooled by an argv[0]
 * that doesn't match the executable path.
 *
 * Sadly, not all UN*Xes necessarily have dladdr(), and those that
 * do don't necessarily have dladdr(main) return information about
 * the executable image, and those that do aren't necessarily running
 * on a platform wherein the executable image can get its own path
 * from the kernel (either by a call or by it being handed to it along
 * with argv[] and the environment), and those that can don't
 * necessarily use that to supply the path you get from dladdr(main),
 * so we try this first and, if that fails, use dladdr(main) if
 * available.
 *
 * In particular, some dynamic linkers supply a dladdr() such that
 * dladdr(main) just returns something derived from argv[0], so
 * just using dladdr(main) is the wrong thing to do if there's
 * another mechanism that can get you a more reliable version of
 * the executable path.
 *
 * However, at least in newer versions of DragonFly BSD, the dynamic
 * linker *does* get it from the aux vector passed to the program
 * by the kernel,  readlink /proc/curproc/file - which came first?
 *
 * On OpenBSD, dladdr(main) returns a value derived from argv[0],
 * and there doesn't appear to be any way to get the executable path
 * from the kernel, so we're out of luck there.
 *
 * So, on platforms where some versions have a version of dladdr()
 * that gives an argv[0]-based path and that also have a mechanism
 * to get a more reliable version of the path, we try that.  On
 * other platforms, we return NULL.  If our caller gets back a NULL
 * from us, it falls back on dladdr(main) if dladdr() is available,
 * and if that fails or is unavailable, it falls back on processing
 * argv[0] itself.
 *
 * This is not guaranteed to return an absolute path; if it doesn't,
 * our caller must prepend the current directory if it's a path.
 *
 * This is not guaranteed to return the "real path"; it might return
 * something with symbolic links in the path.  Our caller must
 * use realpath() if they want the real thing, but that's also true of
 * something obtained by looking at argv[0].
 */
static const char *
get_executable_path(void)
{
#if defined(__APPLE__)
    char *executable_path;
    uint32_t path_buf_size;

    path_buf_size = PATH_MAX;
    executable_path = (char *)g_malloc(path_buf_size);
    if (_NSGetExecutablePath(executable_path, &path_buf_size) == -1) {
        executable_path = (char *)g_realloc(executable_path, path_buf_size);
        if (_NSGetExecutablePath(executable_path, &path_buf_size) == -1)
            return NULL;
    }
    return executable_path;
#elif defined(__linux__)
    /*
     * In older versions of GNU libc's dynamic linker, as used on Linux,
     * dladdr(main) supplies a path based on argv[0], so we use
     * /proc/self/exe instead; there are Linux distributions with
     * kernels that support /proc/self/exe and those older versions
     * of the dynamic linker, and this will get a better answer on
     * those versions.
     *
     * It only works on Linux 2.2 or later, so we just give up on
     * earlier versions.
     *
     * XXX - are there OS versions that support "exe" but not "self"?
     */
    struct utsname name;
    static char executable_path[PATH_MAX + 1];
    ssize_t r;

    if (uname(&name) == -1)
        return NULL;
    if (strncmp(name.release, "1.", 2) == 0)
        return NULL; /* Linux 1.x */
    if (strcmp(name.release, "2.0") == 0 ||
        strncmp(name.release, "2.0.", 4) == 0 ||
        strcmp(name.release, "2.1") == 0 ||
        strncmp(name.release, "2.1.", 4) == 0)
        return NULL; /* Linux 2.0.x or 2.1.x */
    if ((r = readlink("/proc/self/exe", executable_path, PATH_MAX)) == -1)
        return NULL;
    executable_path[r] = '\0';
    return executable_path;
#elif defined(__FreeBSD__) && defined(KERN_PROC_PATHNAME)
    /*
     * In older versions of FreeBSD's dynamic linker, dladdr(main)
     * supplies a path based on argv[0], so we use the KERN_PROC_PATHNAME
     * sysctl instead; there are, I think, versions of FreeBSD
     * that support the sysctl that have and those older versions
     * of the dynamic linker, and this will get a better answer on
     * those versions.
     */
    int mib[4];
    char *executable_path;
    size_t path_buf_size;

    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PATHNAME;
    mib[3] = -1;
    path_buf_size = PATH_MAX;
    executable_path = (char *)g_malloc(path_buf_size);
    if (sysctl(mib, 4, executable_path, &path_buf_size, NULL, 0) == -1) {
        if (errno != ENOMEM)
            return NULL;
        executable_path = (char *)g_realloc(executable_path, path_buf_size);
        if (sysctl(mib, 4, executable_path, &path_buf_size, NULL, 0) == -1)
            return NULL;
    }
    return executable_path;
#elif defined(__NetBSD__)
    /*
     * In all versions of NetBSD's dynamic linker as of 2013-08-12,
     * dladdr(main) supplies a path based on argv[0], so we use
     * /proc/curproc/exe instead.
     *
     * XXX - are there OS versions that support "exe" but not "curproc"
     * or "self"?  Are there any that support "self" but not "curproc"?
     */
    static char executable_path[PATH_MAX + 1];
    ssize_t r;

    if ((r = readlink("/proc/curproc/exe", executable_path, PATH_MAX)) == -1)
        return NULL;
    executable_path[r] = '\0';
    return executable_path;
#elif defined(__DragonFly__)
    /*
     * In older versions of DragonFly BSD's dynamic linker, dladdr(main)
     * supplies a path based on argv[0], so we use /proc/curproc/file
     * instead; it appears to be supported by all versions of DragonFly
     * BSD.
     */
    static char executable_path[PATH_MAX + 1];
    ssize_t r;

    if ((r = readlink("/proc/curproc/file", executable_path, PATH_MAX)) == -1)
        return NULL;
    executable_path[r] = '\0';
    return executable_path;
#elif (defined(sun) || defined(__sun)) && defined(HAVE_GETEXECNAME)
    /*
     * It appears that getexecname() dates back to at least Solaris 8,
     * but /proc/{pid}/path is first documented in the Solaris 10 documentation,
     * so we use getexecname() if available, rather than /proc/self/path/a.out
     * (which isn't documented, but appears to be a symlink to the
     * executable image file).
     */
    return getexecname();
#else
    /* Fill in your favorite UN*X's code here, if there is something */
    return NULL;
#endif
}
#endif /* _WIN32 */

/*
 * Get the pathname of the directory from which the executable came,
 * and save it for future use.  Returns NULL on success, and a
 * g_mallocated string containing an error on failure.
 */
char *
init_progfile_dir(const char *arg0
#ifdef _WIN32
    _U_
#endif
, int (*function_addr)(int, char **)
#if defined(_WIN32) || !defined(HAVE_DLADDR)
    _U_
#endif
)
{
#ifdef _WIN32
    TCHAR prog_pathname_w[_MAX_PATH+2];
    char *prog_pathname;
    DWORD error;
    TCHAR *msg_w;
    guchar *msg;
    size_t msglen;

    /*
     * Attempt to get the full pathname of the currently running
     * program.
     */
    if (GetModuleFileName(NULL, prog_pathname_w, G_N_ELEMENTS(prog_pathname_w)) != 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
        /*
         * XXX - Should we use g_utf16_to_utf8()?
         */
        prog_pathname = utf_16to8(prog_pathname_w);
        /*
         * We got it; strip off the last component, which would be
         * the file name of the executable, giving us the pathname
         * of the directory where the executable resides.
         */
        progfile_dir = g_path_get_dirname(prog_pathname);
        if (progfile_dir != NULL) {
            return NULL;    /* we succeeded */
        } else {
            /*
             * OK, no. What do we do now?
             */
            return g_strdup_printf("No \\ in executable pathname \"%s\"",
                prog_pathname);
        }
    } else {
        /*
         * Oh, well.  Return an indication of the error.
         */
        error = GetLastError();
        if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, error, 0, (LPTSTR) &msg_w, 0, NULL) == 0) {
            /*
             * Gak.  We can't format the message.
             */
            return g_strdup_printf("GetModuleFileName failed: %u (FormatMessage failed: %u)",
                error, GetLastError());
        }
        msg = utf_16to8(msg_w);
        LocalFree(msg_w);
        /*
         * "FormatMessage()" "helpfully" sticks CR/LF at the
         * end of the message.  Get rid of it.
         */
        msglen = strlen(msg);
        if (msglen >= 2) {
            msg[msglen - 1] = '\0';
            msg[msglen - 2] = '\0';
        }
        return g_strdup_printf("GetModuleFileName failed: %s (%u)",
            msg, error);
    }
#else
#ifdef HAVE_DLADDR
    Dl_info info;
#endif
    const char *execname;
    char *prog_pathname;
    char *curdir;
    long path_max;
    const char *pathstr;
    const char *path_start, *path_end;
    size_t path_component_len, path_len;
    char *retstr;
    char *path;
    char *dir_end;

    /*
     * Check whether WIRESHARK_RUN_FROM_BUILD_DIRECTORY is set in the
     * environment; if so, set running_in_build_directory_flag if we
     * weren't started with special privileges.  (If we were started
     * with special privileges, it's not safe to allow the user to point
     * us to some other directory; running_in_build_directory_flag, when
     * set, causes us to look for plugins and the like in the build
     * directory.)
     */
    if (g_getenv("WIRESHARK_RUN_FROM_BUILD_DIRECTORY") != NULL
        && !started_with_special_privs())
        running_in_build_directory_flag = TRUE;

    execname = get_executable_path();
#ifdef HAVE_DLADDR
    if (function_addr != NULL && execname == NULL) {
        /*
         * Try to use dladdr() to find the pathname of the executable.
         * dladdr() is not guaranteed to give you anything better than
         * argv[0] (i.e., it might not contain a / at all, much less
         * being an absolute path), and doesn't appear to do so on
         * Linux, but on other platforms it could give you an absolute
         * path and obviate the need for us to determine the absolute
         * path.
         */
DIAG_OFF(pedantic)
        if (dladdr((void *)function_addr, &info)) {
DIAG_ON(pedantic)
            execname = info.dli_fname;
        }
    }
#endif
    if (execname == NULL) {
        /*
         * OK, guess based on argv[0].
         */
        execname = arg0;
    }

    /*
     * Try to figure out the directory in which the currently running
     * program resides, given something purporting to be the executable
     * name (from dladdr() or from the argv[0] it was started with.
     * That might be the absolute path of the program, or a path relative
     * to the current directory of the process that started it, or
     * just a name for the program if it was started from the command
     * line and was searched for in $PATH.  It's not guaranteed to be
     * any of those, however, so there are no guarantees....
     */
    if (execname[0] == '/') {
        /*
         * It's an absolute path.
         */
        prog_pathname = g_strdup(execname);
    } else if (strchr(execname, '/') != NULL) {
        /*
         * It's a relative path, with a directory in it.
         * Get the current directory, and combine it
         * with that directory.
         */
        path_max = pathconf(".", _PC_PATH_MAX);
        if (path_max == -1) {
            /*
             * We have no idea how big a buffer to
             * allocate for the current directory.
             */
            return g_strdup_printf("pathconf failed: %s\n",
                g_strerror(errno));
        }
        curdir = (char *)g_malloc(path_max);
        if (getcwd(curdir, path_max) == NULL) {
            /*
             * It failed - give up, and just stick
             * with DATAFILE_DIR.
             */
            g_free(curdir);
            return g_strdup_printf("getcwd failed: %s\n",
                g_strerror(errno));
        }
        path = g_strdup_printf("%s/%s", curdir, execname);
        g_free(curdir);
        prog_pathname = path;
    } else {
        /*
         * It's just a file name.
         * Search the path for a file with that name
         * that's executable.
         */
        prog_pathname = NULL;   /* haven't found it yet */
        pathstr = g_getenv("PATH");
        path_start = pathstr;
        if (path_start != NULL) {
            while (*path_start != '\0') {
                path_end = strchr(path_start, ':');
                if (path_end == NULL)
                    path_end = path_start + strlen(path_start);
                path_component_len = path_end - path_start;
                path_len = path_component_len + 1
                    + strlen(execname) + 1;
                path = (char *)g_malloc(path_len);
                memcpy(path, path_start, path_component_len);
                path[path_component_len] = '\0';
                g_strlcat(path, "/", path_len);
                g_strlcat(path, execname, path_len);
                if (access(path, X_OK) == 0) {
                    /*
                     * Found it!
                     */
                    prog_pathname = path;
                    break;
                }

                /*
                 * That's not it.  If there are more
                 * path components to test, try them.
                 */
                if (*path_end == '\0') {
                    /*
                     * There's nothing more to try.
                     */
                    break;
                }
                if (*path_end == ':')
                    path_end++;
                path_start = path_end;
                g_free(path);
            }
            if (prog_pathname == NULL) {
                /*
                 * Program not found in path.
                 */
                return g_strdup_printf("\"%s\" not found in \"%s\"",
                    execname, pathstr);
            }
        } else {
            /*
             * PATH isn't set.
             * XXX - should we pick a default?
             */
            return g_strdup("PATH isn't set");
        }
    }

    /*
     * OK, we have what we think is the pathname
     * of the program.
     *
     * First, find the last "/" in the directory,
     * as that marks the end of the directory pathname.
     */
    dir_end = strrchr(prog_pathname, '/');
    if (dir_end != NULL) {
        /*
         * Found it.  Strip off the last component,
         * as that's the path of the program.
         */
        *dir_end = '\0';

        /*
         * Is there a "/.libs" at the end?
         */
        dir_end = strrchr(prog_pathname, '/');
        if (dir_end != NULL) {
            if (strcmp(dir_end, "/.libs") == 0) {
                /*
                 * Yup, it's ".libs".
                 * Strip that off; it's an
                 * artifact of libtool.
                 */
                *dir_end = '\0';

                /*
                 * This presumably means we're run from
                 * the libtool wrapper, which probably
                 * means we're being run from the build
                 * directory.  If we weren't started
                 * with special privileges, set
                 * running_in_build_directory_flag.
                 *
                 * XXX - should we check whether what
                 * follows ".libs/" begins with "lt-"?
                 */
                if (!started_with_special_privs())
                    running_in_build_directory_flag = TRUE;
            }
            else if (!started_with_special_privs()) {
                /*
                 * Check for the CMake output directory. As people may name
                 * their directories "run" (really?), also check for the
                 * CMakeCache.txt file before assuming a CMake output dir.
                 */
                if (strcmp(dir_end, "/run") == 0) {
                    gchar *cmake_file;
                    cmake_file = g_strdup_printf("%.*s/CMakeCache.txt",
                                                 (int)(dir_end - prog_pathname),
                                                 prog_pathname);
                    if (file_exists(cmake_file))
                        running_in_build_directory_flag = TRUE;
                    g_free(cmake_file);
                }
#ifdef __APPLE__
                if (!running_in_build_directory_flag) {
                    /*
                     * Scan up the path looking for a component
                     * named "Contents".  If we find it, we assume
                     * we're in a bundle, and that the top-level
                     * directory of the bundle is the one containing
                     * "Contents".
                     *
                     * Not all executables are in the Contents/MacOS
                     * directory, so we can't just check for those
                     * in the path and strip them off.
                     *
                     * XXX - should we assume that it's either
                     * Contents/MacOS or Resources/bin?
                     */
                    char *component_end, *p;

                    component_end = strchr(prog_pathname, '\0');
                    p = component_end;
                    for (;;) {
                        while (p >= prog_pathname && *p != '/')
                            p--;
                        if (p == prog_pathname) {
                            /*
                             * We're looking at the first component of
                             * the pathname now, so we're definitely
                             * not in a bundle, even if we're in
                             * "/Contents".
                             */
                            break;
                        }
                        if (strncmp(p, "/Contents", component_end - p) == 0) {
                            /* Found it. */
                            appbundle_dir = (char *)g_malloc(p - prog_pathname + 1);
                            memcpy(appbundle_dir, prog_pathname, p - prog_pathname);
                            appbundle_dir[p - prog_pathname] = '\0';
                            break;
                        }
                        component_end = p;
                        p--;
                    }
                }
#endif
            }
        }

        /*
         * OK, we have the path we want.
         */
        progfile_dir = prog_pathname;
        return NULL;
    } else {
        /*
         * This "shouldn't happen"; we apparently
         * have no "/" in the pathname.
         * Just free up prog_pathname.
         */
        retstr = g_strdup_printf("No / found in \"%s\"", prog_pathname);
        g_free(prog_pathname);
        return retstr;
    }
#endif
}

/*
 * Get the directory in which the program resides.
 */
const char *
get_progfile_dir(void)
{
    return progfile_dir;
}

/*
 * Get the directory in which the global configuration and data files are
 * stored.
 *
 * On Windows, we use the directory in which the executable for this
 * process resides.
 *
 * On UN*X, we use the DATAFILE_DIR value supplied by the configure
 * script, unless we think we're being run from the build directory,
 * in which case we use the directory in which the executable for this
 * process resides.
 *
 * XXX - if we ever make libwireshark a real library, used by multiple
 * applications (more than just TShark and versions of Wireshark with
 * various UIs), should the configuration files belong to the library
 * (and be shared by all those applications) or to the applications?
 *
 * If they belong to the library, that could be done on UNIX by the
 * configure script, but it's trickier on Windows, as you can't just
 * use the pathname of the executable.
 *
 * If they belong to the application, that could be done on Windows
 * by using the pathname of the executable, but we'd have to have it
 * passed in as an argument, in some call, on UNIX.
 *
 * Note that some of those configuration files might be used by code in
 * libwireshark, some of them might be used by dissectors (would they
 * belong to libwireshark, the application, or a separate library?),
 * and some of them might be used by other code (the Wireshark preferences
 * file includes resolver preferences that control the behavior of code
 * in libwireshark, dissector preferences, and UI preferences, for
 * example).
 */
const char *
get_datafile_dir(void)
{
    static const char *datafile_dir = NULL;

    if (datafile_dir != NULL)
        return datafile_dir;

#ifdef _WIN32
    /*
     * Do we have the pathname of the program?  If so, assume we're
     * running an installed version of the program.  If we fail,
     * we don't change "datafile_dir", and thus end up using the
     * default.
     *
     * XXX - does NSIS put the installation directory into
     * "\HKEY_LOCAL_MACHINE\SOFTWARE\Wireshark\InstallDir"?
     * If so, perhaps we should read that from the registry,
     * instead.
     */
    if (progfile_dir != NULL) {
        /*
         * Yes, we do; use that.
         */
        datafile_dir = progfile_dir;
    } else {
        /*
         * No, we don't.
         * Fall back on the default installation directory.
         */
        datafile_dir = "C:\\Program Files\\Wireshark\\";
    }
#else

    if (running_in_build_directory_flag) {
        /*
         * We're (probably) being run from the build directory and
         * weren't started with special privileges.
         *
         * (running_in_build_directory_flag is never set to TRUE
         * if we're started with special privileges, so we need
         * only check it; we don't need to call started_with_special_privs().)
         *
         * Use the top-level source directory as the datafile directory
         * because most of our data files (radius/, COPYING) are there.
         */
#ifdef TOP_SRCDIR
        /*
         * When TOP_SRCDIR is defined, assume autotools where files are not
         * copied to the build directory. This fallback location is relied on by
         * wslua_get_actual_filename().
         */
        datafile_dir = TOP_SRCDIR;
#else
        /*
         * Otherwise assume CMake. Here, data files (console.lua, radius/, etc.)
         * are copied to the build directory during the build.
         */
        datafile_dir = BUILD_TIME_DATAFILE_DIR;
#endif
        return datafile_dir;
    } else {
        if (g_getenv("WIRESHARK_DATA_DIR") && !started_with_special_privs()) {
            /*
             * The user specified a different directory for data files
             * and we aren't running with special privileges.
             * XXX - We might be able to dispense with the priv check
             */
            datafile_dir = g_strdup(g_getenv("WIRESHARK_DATA_DIR"));
        }
#ifdef __APPLE__
        /*
         * If we're running from an app bundle and weren't started
         * with special privileges, use the Contents/Resources/share/wireshark
         * subdirectory of the app bundle.
         *
         * (appbundle_dir is not set to a non-null value if we're
         * started with special privileges, so we need only check
         * it; we don't need to call started_with_special_privs().)
         */
        else if (appbundle_dir != NULL) {
            datafile_dir = g_strdup_printf("%s/Contents/Resources/share/wireshark",
                                           appbundle_dir);
        }
#endif
        else {
            datafile_dir = DATAFILE_DIR;
        }
    }

#endif
    return datafile_dir;
}

#if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
/*
 * Find the directory where the plugins are stored.
 *
 * On Windows, we use the plugin/{VERSION} subdirectory of the datafile
 * directory, where {VERSION} is the version number of this version of
 * Wireshark.
 *
 * On UN*X:
 *
 *    if we appear to be run from the build directory, we use the
 *    "plugin" subdirectory of the datafile directory;
 *
 *    otherwise, if the WIRESHARK_PLUGIN_DIR environment variable is
 *    set and we aren't running with special privileges, we use the
 *    value of that environment variable;
 *
 *    otherwise, if we're running from an app bundle in macOS, we
 *    use the Contents/PlugIns/wireshark subdirectory of the app bundle;
 *
 *    otherwise, we use the PLUGIN_INSTALL_DIR value supplied by the
 *    configure script.
 */
static char *plugin_dir = NULL;

static void
init_plugin_dir(void)
{
#ifdef _WIN32
    /*
     * On Windows, the data file directory is the installation
     * directory; the plugins are stored under it.
     *
     * Assume we're running the installed version of Wireshark;
     * on Windows, the data file directory is the directory
     * in which the Wireshark binary resides.
     */
    plugin_dir = g_build_filename(get_datafile_dir(), "plugins", VERSION, (gchar *)NULL);

    /*
     * Make sure that pathname refers to a directory.
     */
    if (test_for_directory(plugin_dir) != EISDIR) {
        /*
         * Either it doesn't refer to a directory or it
         * refers to something that doesn't exist.
         *
         * Assume that means we're running a version of
         * Wireshark we've built in a build directory,
         * in which case {datafile dir}\plugins is the
         * top-level plugins source directory, and use
         * that directory and set the "we're running in
         * a build directory" flag, so the plugin
         * scanner will check all subdirectories of that
         * directory for plugins.
         */
        g_free(plugin_dir);
        plugin_dir = g_build_filename(get_datafile_dir(), "plugins", (gchar *)NULL);
        running_in_build_directory_flag = TRUE;
    }
#else
    if (running_in_build_directory_flag) {
        /*
         * We're (probably) being run from the build directory and
         * weren't started with special privileges, so we'll use
         * the "plugins" subdirectory of the directory where the program
         * we're running is (that's the build directory).
         */
        plugin_dir = g_build_filename(get_progfile_dir(), "plugins", (gchar *)NULL);
    } else {
        if (g_getenv("WIRESHARK_PLUGIN_DIR") && !started_with_special_privs()) {
            /*
             * The user specified a different directory for plugins
             * and we aren't running with special privileges.
             */
            plugin_dir = g_strdup(g_getenv("WIRESHARK_PLUGIN_DIR"));
        }
#ifdef __APPLE__
        /*
         * If we're running from an app bundle and weren't started
         * with special privileges, use the Contents/PlugIns/wireshark
         * subdirectory of the app bundle.
         *
         * (appbundle_dir is not set to a non-null value if we're
         * started with special privileges, so we need only check
         * it; we don't need to call started_with_special_privs().)
         */
        else if (appbundle_dir != NULL) {
            plugin_dir = g_build_filename(appbundle_dir, "Contents/PlugIns/wireshark", (gchar *)NULL);
        }
#endif
        else {
            plugin_dir = g_strdup(PLUGIN_INSTALL_DIR);
        }
    }
#endif
}
#endif /* HAVE_PLUGINS || HAVE_LUA */

/*
 * Get the directory in which the plugins are stored.
 */
const char *
get_plugin_dir(void)
{
#if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
    if (!plugin_dir) init_plugin_dir();
    return plugin_dir;
#else
    return NULL;
#endif
}

#if defined(HAVE_EXTCAP)
/*
 * Find the directory where the extcap hooks are stored.
 *
 * On Windows, we use the "extcap" subdirectory of the datafile directory.
 *
 * On UN*X, we use the EXTCAP_DIR value supplied by the configure
 * script, unless we think we're being run from the build directory,
 * in which case we use the "extcap" subdirectory of the datafile directory.
 *
 * In both cases, we then use the subdirectory of that directory whose
 * name is the version number.
 *
 * XXX - if we think we're being run from the build directory, perhaps we
 * should have the extcap code not look in the version subdirectory
 * of the extcap directory, but look in all of the subdirectories
 * of the extcap directory, so it can just fetch the extcap hooks built
 * as part of the build process.
 */
static char *extcap_dir = NULL;

static void init_extcap_dir(void) {
#ifdef _WIN32
    const char *alt_extcap_path;

    /*
     * On Windows, the data file directory is the installation
     * directory; the extcap hooks are stored under it.
     *
     * Assume we're running the installed version of Wireshark;
     * on Windows, the data file directory is the directory
     * in which the Wireshark binary resides.
     */
    alt_extcap_path = g_getenv("WIRESHARK_EXTCAP_DIR");
    if (alt_extcap_path) {
        /*
         * The user specified a different directory for extcap hooks.
         */
        extcap_dir = g_strdup(alt_extcap_path);
    } else {
        extcap_dir = g_build_filename(get_datafile_dir(), "extcap", (gchar *)NULL);
    }
#else
    if (running_in_build_directory_flag) {
        /*
         * We're (probably) being run from the build directory and
         * weren't started with special privileges, so we'll use
         * the "extcap hooks" subdirectory of the directory where the program
         * we're running is (that's the build directory).
         */
        extcap_dir = g_build_filename(get_progfile_dir(), "extcap", (gchar *)NULL);
    } else {
        if (g_getenv("WIRESHARK_EXTCAP_DIR") && !started_with_special_privs()) {
            /*
             * The user specified a different directory for extcap hooks
             * and we aren't running with special privileges.
             */
            extcap_dir = g_strdup(g_getenv("WIRESHARK_EXTCAP_DIR"));
        }
#ifdef __APPLE__
        /*
         * If we're running from an app bundle and weren't started
         * with special privileges, use the Contents/MacOS/extcap
         * subdirectory of the app bundle.
         *
         * (appbundle_dir is not set to a non-null value if we're
         * started with special privileges, so we need only check
         * it; we don't need to call started_with_special_privs().)
         */
        else if (appbundle_dir != NULL) {
            extcap_dir = g_build_filename(appbundle_dir, "Contents/MacOS/extcap", (gchar *)NULL);
        }
#endif
        else {
            extcap_dir = g_strdup(EXTCAP_DIR);
        }
    }
#endif
}
#endif /* HAVE_EXTCAP */

/*
 * Get the directory in which the extcap hooks are stored.
 *
 * XXX - A fix instead of HAVE_EXTCAP must be found
 */
const char *
get_extcap_dir(void) {
#if defined(HAVE_EXTCAP)
    if (!extcap_dir)
        init_extcap_dir();
    return extcap_dir;
#else
    return NULL;
#endif
}

/*
 * Get the flag indicating whether we're running from a build
 * directory.
 */
gboolean
running_in_build_directory(void)
{
    return running_in_build_directory_flag;
}

/*
 * Get the directory in which files that, at least on UNIX, are
 * system files (such as "/etc/ethers") are stored; on Windows,
 * there's no "/etc" directory, so we get them from the global
 * configuration and data file directory.
 */
const char *
get_systemfile_dir(void)
{
#ifdef _WIN32
    return get_datafile_dir();
#else
    return "/etc";
#endif
}

void
set_profile_name(const gchar *profilename)
{
    g_free (persconfprofile);

    if (profilename && strlen(profilename) > 0 &&
        strcmp(profilename, DEFAULT_PROFILE) != 0) {
        persconfprofile = g_strdup (profilename);
    } else {
        /* Default Profile */
        persconfprofile = NULL;
    }
}

const char *
get_profile_name(void)
{
    if (persconfprofile) {
        return persconfprofile;
    } else {
        return DEFAULT_PROFILE;
    }
}

gboolean
is_default_profile(void)
{
    return (!persconfprofile || strcmp(persconfprofile, DEFAULT_PROFILE) == 0) ? TRUE : FALSE;
}

gboolean
has_global_profiles(void)
{
    WS_DIR *dir;
    WS_DIRENT *file;
    gchar *global_dir = get_global_profiles_dir();
    gchar *filename;
    gboolean has_global = FALSE;

    if ((test_for_directory(global_dir) == EISDIR) &&
        ((dir = ws_dir_open(global_dir, 0, NULL)) != NULL))
    {
        while ((file = ws_dir_read_name(dir)) != NULL) {
            filename = g_strdup_printf ("%s%s%s", global_dir, G_DIR_SEPARATOR_S,
                            ws_dir_get_name(file));
            if (test_for_directory(filename) == EISDIR) {
                has_global = TRUE;
                g_free (filename);
                break;
            }
            g_free (filename);
        }
        ws_dir_close(dir);
    }
    g_free(global_dir);
    return has_global;
}

void
profile_store_persconffiles(gboolean store)
{
    if (store) {
        profile_files = g_hash_table_new (g_str_hash, g_str_equal);
    }
    do_store_persconffiles = store;
}

/*
 * Get the directory in which personal configuration files reside.
 *
 * On Windows, it's "Wireshark", under %APPDATA% or, if %APPDATA% isn't set,
 * it's "%USERPROFILE%\Application Data" (which is what %APPDATA% normally
 * is on Windows 2000).
 *
 * On UNIX-compatible systems, we first look in XDG_CONFIG_HOME/wireshark
 * and, if that doesn't exist, ~/.wireshark, for backwards compatibility.
 * If neither exists, we use XDG_CONFIG_HOME/wireshark, so that the directory
 * is initially created as XDG_CONFIG_HOME/wireshark.  We use that regardless
 * of whether the user is running under an XDG desktop or not, so that
 * if the user's home directory is on a server and shared between
 * different desktop environments on different machines, they can all
 * share the same configuration file directory.
 *
 * XXX - what about stuff that shouldn't be shared between machines,
 * such as plugins in the form of shared loadable images?
 */
static const char *
get_persconffile_dir_no_profile(void)
{
#ifdef _WIN32
    const char *env;
#else
    char *xdg_path, *path;
    struct passwd *pwd;
    const char *homedir;
#endif

    /* Return the cached value, if available */
    if (persconffile_dir != NULL)
        return persconffile_dir;

#ifdef _WIN32
    /*
     * See if the user has selected an alternate environment.
     */
    env = g_getenv("WIRESHARK_APPDATA");
    if (env != NULL) {
        persconffile_dir = g_strdup(env);
        return persconffile_dir;
    }

    /*
     * Use %APPDATA% or %USERPROFILE%, so that configuration
     * files are stored in the user profile, rather than in
     * the home directory.  The Windows convention is to store
     * configuration information in the user profile, and doing
     * so means you can use Wireshark even if the home directory
     * is an inaccessible network drive.
     */
    env = g_getenv("APPDATA");
    if (env != NULL) {
        /*
         * Concatenate %APPDATA% with "\Wireshark".
         */
        persconffile_dir = g_build_filename(env, "Wireshark", NULL);
        return persconffile_dir;
    }

    /*
     * OK, %APPDATA% wasn't set, so use %USERPROFILE%\Application Data.
     */
    env = g_getenv("USERPROFILE");
    if (env != NULL) {
        persconffile_dir = g_build_filename(env, "Application Data", "Wireshark", NULL);
        return persconffile_dir;
    }

    /*
     * Give up and use "C:".
     */
    persconffile_dir = g_build_filename("C:", "Wireshark", NULL);
    return persconffile_dir;
#else
    /*
     * Check if XDG_CONFIG_HOME/wireshark exists and is a directory.
     */
    xdg_path = g_build_filename(g_get_user_config_dir(), "wireshark", NULL);
    if (g_file_test(xdg_path, G_FILE_TEST_IS_DIR)) {
        persconffile_dir = xdg_path;
        return persconffile_dir;
    }

    /*
     * It doesn't exist, or it does but isn't a directory, so try
     * ~/.wireshark.
     *
     * If $HOME is set, use that for ~.
     *
     * (Note: before GLib 2.36, g_get_home_dir() didn't look at $HOME,
     * but we always want to do so, so we don't use g_get_home_dir().)
     */
    homedir = g_getenv("HOME");
    if (homedir == NULL) {
        /*
         * It's not set.
         *
         * Get their home directory from the password file.
         * If we can't even find a password file entry for them,
         * use "/tmp".
         */
        pwd = getpwuid(getuid());
        if (pwd != NULL) {
            homedir = pwd->pw_dir;
        } else {
            homedir = "/tmp";
        }
    }
    path = g_build_filename(homedir, ".wireshark", NULL);
    if (g_file_test(path, G_FILE_TEST_IS_DIR)) {
        g_free(xdg_path);
        persconffile_dir = path;
        return persconffile_dir;
    }

    /*
     * Neither are directories that exist; use the XDG path, so we'll
     * create that as necessary.
     */
    g_free(path);
    persconffile_dir = xdg_path;
    return persconffile_dir;
#endif
}

void
set_persconffile_dir(const char *p)
{
    g_free(persconffile_dir);
    persconffile_dir = g_strdup(p);
}

char *
get_profiles_dir(void)
{
    return g_strdup_printf ("%s%s%s", get_persconffile_dir_no_profile (),
                    G_DIR_SEPARATOR_S, PROFILES_DIR);
}

char *
get_global_profiles_dir(void)
{
    return g_strdup_printf ("%s%s%s", get_datafile_dir(),
                               G_DIR_SEPARATOR_S, PROFILES_DIR);
}

static char *
get_persconffile_dir(const gchar *profilename)
{
    char *persconffile_profile_dir = NULL, *profile_dir;

    if (profilename && strlen(profilename) > 0 &&
        strcmp(profilename, DEFAULT_PROFILE) != 0) {
      profile_dir = get_profiles_dir();
      persconffile_profile_dir = g_strdup_printf ("%s%s%s", profile_dir,
                              G_DIR_SEPARATOR_S, profilename);
      g_free(profile_dir);
    } else {
      persconffile_profile_dir = g_strdup (get_persconffile_dir_no_profile ());
    }

    return persconffile_profile_dir;
}

gboolean
profile_exists(const gchar *profilename, gboolean global)
{
    gchar *path = NULL, *global_path;
    if (global) {
        global_path = get_global_profiles_dir();
        path = g_strdup_printf ("%s%s%s", global_path,
                           G_DIR_SEPARATOR_S, profilename);
        g_free(global_path);
        if (test_for_directory (path) == EISDIR) {
            g_free (path);
            return TRUE;
        }
    } else {
        path = get_persconffile_dir (profilename);
        if (test_for_directory (path) == EISDIR) {
            g_free (path);
            return TRUE;
        }
    }

    g_free (path);
    return FALSE;
}

static int
delete_directory (const char *directory, char **pf_dir_path_return)
{
    WS_DIR *dir;
    WS_DIRENT *file;
    gchar *filename;
    int ret = 0;

    if ((dir = ws_dir_open(directory, 0, NULL)) != NULL) {
        while ((file = ws_dir_read_name(dir)) != NULL) {
            filename = g_strdup_printf ("%s%s%s", directory, G_DIR_SEPARATOR_S,
                            ws_dir_get_name(file));
            if (test_for_directory(filename) != EISDIR) {
                ret = ws_remove(filename);
#if 0
            } else {
                /* The user has manually created a directory in the profile directory */
                /* I do not want to delete the directory recursively yet */
                ret = delete_directory (filename, pf_dir_path_return);
#endif
            }
            if (ret != 0) {
                *pf_dir_path_return = filename;
                break;
            }
            g_free (filename);
        }
        ws_dir_close(dir);
    }

    if (ret == 0 && (ret = ws_remove(directory)) != 0) {
        *pf_dir_path_return = g_strdup (directory);
    }

    return ret;
}

static int
reset_default_profile(char **pf_dir_path_return)
{
    char *profile_dir = get_persconffile_dir(NULL);
    gchar *filename, *del_file;
    GList *files, *file;
    int ret = 0;

    files = g_hash_table_get_keys(profile_files);
    file = g_list_first(files);
    while (file) {
        filename = (gchar *)file->data;
        del_file = g_strdup_printf("%s%s%s", profile_dir, G_DIR_SEPARATOR_S, filename);

        if (file_exists(del_file)) {
            ret = ws_remove(del_file);
            if (ret != 0) {
                *pf_dir_path_return = profile_dir;
                g_free(del_file);
                return ret;
            }
        }

        g_free(del_file);
        file = g_list_next(file);
    }

    g_free(profile_dir);
    return 0;
}

int
delete_persconffile_profile(const char *profilename, char **pf_dir_path_return)
{
    if (strcmp(profilename, DEFAULT_PROFILE) == 0) {
        return reset_default_profile(pf_dir_path_return);
    }

    char *profile_dir = get_persconffile_dir(profilename);
    int ret = 0;

    if (test_for_directory (profile_dir) == EISDIR) {
        ret = delete_directory (profile_dir, pf_dir_path_return);
    }

    g_free(profile_dir);
    return ret;
}

int
rename_persconffile_profile(const char *fromname, const char *toname,
                char **pf_from_dir_path_return, char **pf_to_dir_path_return)
{
    char *from_dir = get_persconffile_dir(fromname);
    char *to_dir = get_persconffile_dir(toname);
    int ret = 0;

    ret = ws_rename (from_dir, to_dir);
    if (ret != 0) {
        *pf_from_dir_path_return = from_dir;
        *pf_to_dir_path_return = to_dir;
        return ret;
    }

    g_free (from_dir);
    g_free (to_dir);

    return 0;
}

/*
 * Create the directory that holds personal configuration files, if
 * necessary.  If we attempted to create it, and failed, return -1 and
 * set "*pf_dir_path_return" to the pathname of the directory we failed
 * to create (it's g_mallocated, so our caller should free it); otherwise,
 * return 0.
 */
int
create_persconffile_profile(const char *profilename, char **pf_dir_path_return)
{
    char *pf_dir_path;
#ifdef _WIN32
    char *pf_dir_path_copy, *pf_dir_parent_path;
    size_t pf_dir_parent_path_len;
    int save_errno;
#endif
    ws_statb64 s_buf;
    int ret;

    if (profilename) {
        /*
         * Create the "Default" personal configuration files directory, if necessary.
         */
        if (create_persconffile_profile (NULL, pf_dir_path_return) == -1) {
            return -1;
        }

        /*
         * Check if profiles directory exists.
         * If not then create it.
         */
        pf_dir_path = get_profiles_dir ();
        if (ws_stat64(pf_dir_path, &s_buf) != 0) {
            if (errno != ENOENT) {
                /* Some other problem; give up now. */
                *pf_dir_path_return = pf_dir_path;
                return -1;
            }

            /*
             * It doesn't exist; try to create it.
             */
            ret = ws_mkdir(pf_dir_path, 0755);
            if (ret == -1) {
                *pf_dir_path_return = pf_dir_path;
                return ret;
            }
        }
        g_free(pf_dir_path);
    }

    pf_dir_path = get_persconffile_dir(profilename);
    if (ws_stat64(pf_dir_path, &s_buf) != 0) {
        if (errno != ENOENT) {
            /* Some other problem; give up now. */
            *pf_dir_path_return = pf_dir_path;
            return -1;
        }
#ifdef _WIN32
        /*
         * Does the parent directory of that directory
         * exist?  %APPDATA% may not exist even though
         * %USERPROFILE% does.
         *
         * We check for the existence of the directory
         * by first checking whether the parent directory
         * is just a drive letter and, if it's not, by
         * doing a "stat()" on it.  If it's a drive letter,
         * or if the "stat()" succeeds, we assume it exists.
         */
        pf_dir_path_copy = g_strdup(pf_dir_path);
        pf_dir_parent_path = get_dirname(pf_dir_path_copy);
        pf_dir_parent_path_len = strlen(pf_dir_parent_path);
        if (pf_dir_parent_path_len > 0
            && pf_dir_parent_path[pf_dir_parent_path_len - 1] != ':'
            && ws_stat64(pf_dir_parent_path, &s_buf) != 0) {
            /*
             * Not a drive letter and the stat() failed.
             */
            if (errno != ENOENT) {
                /* Some other problem; give up now. */
                *pf_dir_path_return = pf_dir_path;
                save_errno = errno;
                g_free(pf_dir_path_copy);
                errno = save_errno;
                return -1;
            }
            /*
             * No, it doesn't exist - make it first.
             */
            ret = ws_mkdir(pf_dir_parent_path, 0755);
            if (ret == -1) {
                *pf_dir_path_return = pf_dir_parent_path;
                save_errno = errno;
                g_free(pf_dir_path);
                errno = save_errno;
                return -1;
            }
        }
        g_free(pf_dir_path_copy);
        ret = ws_mkdir(pf_dir_path, 0755);
#else
        ret = g_mkdir_with_parents(pf_dir_path, 0755);
#endif
    } else {
        /*
         * Something with that pathname exists; if it's not
         * a directory, we'll get an error if we try to put
         * something in it, so we don't fail here, we wait
         * for that attempt fo fail.
         */
        ret = 0;
    }
    if (ret == -1)
        *pf_dir_path_return = pf_dir_path;
    return ret;
}

int
create_persconffile_dir(char **pf_dir_path_return)
{
    return create_persconffile_profile(persconfprofile, pf_dir_path_return);
}

int
copy_persconffile_profile(const char *toname, const char *fromname, gboolean from_global,
              char **pf_filename_return, char **pf_to_dir_path_return, char **pf_from_dir_path_return)
{
    gchar *from_dir;
    gchar *to_dir = get_persconffile_dir(toname);
    gchar *filename, *from_file, *to_file, *global_path;
    GList *files, *file;

    if (from_global) {
        if (strcmp(fromname, DEFAULT_PROFILE) == 0) {
            from_dir = get_global_profiles_dir();
        } else {
            global_path = get_global_profiles_dir();
            from_dir = g_strdup_printf ("%s%s%s", global_path, G_DIR_SEPARATOR_S, fromname);
            g_free(global_path);
        }
    } else {
        from_dir = get_persconffile_dir(fromname);
    }

    files = g_hash_table_get_keys(profile_files);
    file = g_list_first(files);
    while (file) {
        filename = (gchar *)file->data;
        from_file = g_strdup_printf ("%s%s%s", from_dir, G_DIR_SEPARATOR_S, filename);
        to_file =  g_strdup_printf ("%s%s%s", to_dir, G_DIR_SEPARATOR_S, filename);

        if (file_exists(from_file) && !copy_file_binary_mode(from_file, to_file)) {
            *pf_filename_return = g_strdup(filename);
            *pf_to_dir_path_return = to_dir;
            *pf_from_dir_path_return = from_dir;
            g_free (from_file);
            g_free (to_file);
            return -1;
        }

        g_free (from_file);
        g_free (to_file);

        file = g_list_next(file);
    }

    g_list_free (files);
    g_free (from_dir);
    g_free (to_dir);

    return 0;
}

/*
 * Get the (default) directory in which personal data is stored.
 *
 * On Win32, this is the "My Documents" folder in the personal profile.
 * On UNIX this is simply the current directory.
 */
/* XXX - should this and the get_home_dir() be merged? */
extern const char *
get_persdatafile_dir(void)
{
#ifdef _WIN32
    TCHAR tszPath[MAX_PATH];

    /* Return the cached value, if available */
    if (persdatafile_dir != NULL)
        return persdatafile_dir;

    /*
     * Hint: SHGetFolderPath is not available on MSVC 6 - without
     * Platform SDK
     */
    if (SHGetSpecialFolderPath(NULL, tszPath, CSIDL_PERSONAL, FALSE)) {
        persdatafile_dir = g_utf16_to_utf8(tszPath, -1, NULL, NULL, NULL);
        return persdatafile_dir;
    } else {
        return "";
    }
#else
    return "";
#endif
}

void
set_persdatafile_dir(const char *p)
{
    g_free(persdatafile_dir);
    persdatafile_dir = g_strdup(p);
}

#ifdef _WIN32
/*
 * Returns the user's home directory on Win32.
 */
static const char *
get_home_dir(void)
{
    static const char *home = NULL;
    const char *homedrive, *homepath;
    char *homestring;
    char *lastsep;

    /* Return the cached value, if available */
    if (home)
        return home;

    /*
     * XXX - should we use USERPROFILE anywhere in this process?
     * Is there a chance that it might be set but one or more of
     * HOMEDRIVE or HOMEPATH isn't set?
     */
    homedrive = g_getenv("HOMEDRIVE");
    if (homedrive != NULL) {
        homepath = g_getenv("HOMEPATH");
        if (homepath != NULL) {
            /*
             * This is cached, so we don't need to worry about
             * allocating multiple ones of them.
             */
            homestring = g_strdup_printf("%s%s", homedrive, homepath);

            /*
             * Trim off any trailing slash or backslash.
             */
            lastsep = find_last_pathname_separator(homestring);
            if (lastsep != NULL && *(lastsep + 1) == '\0') {
                /*
                 * Last separator is the last character
                 * in the string.  Nuke it.
                 */
                *lastsep = '\0';
            }
            home = homestring;
        } else
            home = homedrive;
    } else {
        /*
         * Give up and use C:.
         */
        home = "C:";
    }

    return home;
}
#endif

/*
 * Construct the path name of a personal configuration file, given the
 * file name.
 *
 * On Win32, if "for_writing" is FALSE, we check whether the file exists
 * and, if not, construct a path name relative to the ".wireshark"
 * subdirectory of the user's home directory, and check whether that
 * exists; if it does, we return that, so that configuration files
 * from earlier versions can be read.
 *
 * The returned file name was g_malloc()'d so it must be g_free()d when the
 * caller is done with it.
 */
char *
get_persconffile_path(const char *filename, gboolean from_profile)
{
    char *path, *dir = NULL;

    if (do_store_persconffiles && from_profile && !g_hash_table_lookup (profile_files, filename)) {
        /* Store filenames so we know which filenames belongs to a configuration profile */
        g_hash_table_insert (profile_files, g_strdup(filename), g_strdup(filename));
    }

    if (from_profile) {
      dir = get_persconffile_dir(persconfprofile);
      path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
                 dir, filename);
    } else {
      dir = get_persconffile_dir(NULL);
      path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
                 dir, filename);
    }

    g_free(dir);
    return path;
}

/*
 * Construct the path name of a global configuration file, given the
 * file name.
 *
 * The returned file name was g_malloc()'d so it must be g_free()d when the
 * caller is done with it.
 */
char *
get_datafile_path(const char *filename)
{
    if (running_in_build_directory_flag &&
        (!strcmp(filename, "AUTHORS-SHORT") ||
         !strcmp(filename, "hosts"))) {
        /* We're running in the build directory and the requested file is a
         * generated (or a test) file.  Return the file name in the build
         * directory (not in the source/data directory).
         * (Oh the things we do to keep the source directory pristine...)
         */
        return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_progfile_dir(), filename);
    } else {
        return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_datafile_dir(), filename);
    }
}

/* Get the personal plugin dir */
/* Return value is malloced so the caller should g_free() it. */
char *
get_plugins_pers_dir(void)
{
    return get_persconffile_path(PLUGINS_DIR_NAME, FALSE);
}

/*
 * Return an error message for UNIX-style errno indications on open or
 * create operations.
 */
const char *
file_open_error_message(int err, gboolean for_writing)
{
    const char *errmsg;
    static char errmsg_errno[1024+1];

    switch (err) {

    case ENOENT:
        if (for_writing)
            errmsg = "The path to the file \"%s\" doesn't exist.";
        else
            errmsg = "The file \"%s\" doesn't exist.";
        break;

    case EACCES:
        if (for_writing)
            errmsg = "You don't have permission to create or write to the file \"%s\".";
        else
            errmsg = "You don't have permission to read the file \"%s\".";
        break;

    case EISDIR:
        errmsg = "\"%s\" is a directory (folder), not a file.";
        break;

    case ENOSPC:
        errmsg = "The file \"%s\" could not be created because there is no space left on the file system.";
        break;

#ifdef EDQUOT
    case EDQUOT:
        errmsg = "The file \"%s\" could not be created because you are too close to, or over, your disk quota.";
        break;
#endif

    case EINVAL:
        errmsg = "The file \"%s\" could not be created because an invalid filename was specified.";
        break;

#ifdef ENAMETOOLONG
    case ENAMETOOLONG:
        /* XXX Make sure we truncate on a character boundary. */
        errmsg = "The file name \"%.80s" UTF8_HORIZONTAL_ELLIPSIS "\" is too long.";
        break;
#endif

    case ENOMEM:
        /*
         * The problem probably has nothing to do with how much RAM the
         * user has on their machine, so don't confuse them by saying
         * "memory".  The problem is probably either virtual address
         * space or swap space.
         */
#if GLIB_SIZEOF_VOID_P == 4
        /*
         * ILP32; we probably ran out of virtual address space.
         */
#define ENOMEM_REASON "it can't be handled by a 32-bit application"
#else
        /*
         * LP64 or LLP64; we probably ran out of swap space.
         */
#if defined(_WIN32)
        /*
         * You need to make the pagefile bigger.
         */
#define ENOMEM_REASON "the pagefile is too small"
#elif defined(__APPLE__)
        /*
         * dynamic_pager couldn't, or wouldn't, create more swap files.
         */
#define ENOMEM_REASON "your system ran out of swap file space"
#else
        /*
         * Either you have a fixed swap partition or a fixed swap file,
         * and it needs to be made bigger.
         *
         * This is UN*X, but it's not OS X, so we assume the user is
         * *somewhat* nerdy.
         */
#define ENOMEM_REASON "your system is out of swap space"
#endif
#endif /* GLIB_SIZEOF_VOID_P == 4 */
        if (for_writing)
            errmsg = "The file \"%s\" could not be created because " ENOMEM_REASON ".";
        else
            errmsg = "The file \"%s\" could not be opened because " ENOMEM_REASON ".";
        break;

    default:
        g_snprintf(errmsg_errno, sizeof(errmsg_errno),
               "The file \"%%s\" could not be %s: %s.",
               for_writing ? "created" : "opened",
               g_strerror(err));
        errmsg = errmsg_errno;
        break;
    }
    return errmsg;
}

/*
 * Return an error message for UNIX-style errno indications on write
 * operations.
 */
const char *
file_write_error_message(int err)
{
    const char *errmsg;
    static char errmsg_errno[1024+1];

    switch (err) {

    case ENOSPC:
        errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
        break;

#ifdef EDQUOT
    case EDQUOT:
        errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
        break;
#endif

    default:
        g_snprintf(errmsg_errno, sizeof(errmsg_errno),
               "An error occurred while writing to the file \"%%s\": %s.",
               g_strerror(err));
        errmsg = errmsg_errno;
        break;
    }
    return errmsg;
}


gboolean
file_exists(const char *fname)
{
    ws_statb64 file_stat;

    if (!fname) {
        return FALSE;
    }

#if defined(_MSC_VER) && _MSC_VER < 1900

    /*
     * This is a bit tricky on win32. The st_ino field is documented as:
     * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
     * but it *is* set to zero if stat() returns without an error,
     * so this is working, but maybe not quite the way expected. ULFL
     */
    file_stat.st_ino = 1;   /* this will make things work if an error occurred */
    ws_stat64(fname, &file_stat);
    if (file_stat.st_ino == 0) {
        return TRUE;
    } else {
        return FALSE;
    }
#else
    if (ws_stat64(fname, &file_stat) != 0 && errno == ENOENT) {
        return FALSE;
    } else {
        return TRUE;
    }
#endif
}

/*
 * Check that the from file is not the same as to file
 * We do it here so we catch all cases ...
 * Unfortunately, the file requester gives us an absolute file
 * name and the read file name may be relative (if supplied on
 * the command line), so we can't just compare paths. From Joerg Mayer.
 */
gboolean
files_identical(const char *fname1, const char *fname2)
{
    /* Two different implementations, because:
     *
     * - _fullpath is not available on UN*X, so we can't get full
     *   paths and compare them (which wouldn't work with hard links
     *   in any case);
     *
     * - st_ino isn't filled in with a meaningful value on Windows.
     */
#ifdef _WIN32
    char full1[MAX_PATH], full2[MAX_PATH];

    /*
     * Get the absolute full paths of the file and compare them.
     * That won't work if you have hard links, but those aren't
     * much used on Windows, even though NTFS supports them.
     *
     * XXX - will _fullpath work with UNC?
     */
    if( _fullpath( full1, fname1, MAX_PATH ) == NULL ) {
        return FALSE;
    }

    if( _fullpath( full2, fname2, MAX_PATH ) == NULL ) {
        return FALSE;
    }

    if(strcmp(full1, full2) == 0) {
        return TRUE;
    } else {
        return FALSE;
    }
#else
    ws_statb64 filestat1, filestat2;

    /*
     * Compare st_dev and st_ino.
     */
    if (ws_stat64(fname1, &filestat1) == -1)
        return FALSE;   /* can't get info about the first file */
    if (ws_stat64(fname2, &filestat2) == -1)
        return FALSE;   /* can't get info about the second file */
    return (filestat1.st_dev == filestat2.st_dev &&
        filestat1.st_ino == filestat2.st_ino);
#endif
}

/*
 * Copy a file in binary mode, for those operating systems that care about
 * such things.  This should be OK for all files, even text files, as
 * we'll copy the raw bytes, and we don't look at the bytes as we copy
 * them.
 *
 * Returns TRUE on success, FALSE on failure. If a failure, it also
 * displays a simple dialog window with the error message.
 */
gboolean
copy_file_binary_mode(const char *from_filename, const char *to_filename)
{
    int           from_fd, to_fd, err;
    ssize_t       nread, nwritten;
    guint8        *pd = NULL;

    /* Copy the raw bytes of the file. */
    from_fd = ws_open(from_filename, O_RDONLY | O_BINARY, 0000 /* no creation so don't matter */);
    if (from_fd < 0) {
        report_open_failure(from_filename, errno, FALSE);
        goto done;
    }

    /* Use open() instead of creat() so that we can pass the O_BINARY
       flag, which is relevant on Win32; it appears that "creat()"
       may open the file in text mode, not binary mode, but we want
       to copy the raw bytes of the file, so we need the output file
       to be open in binary mode. */
    to_fd = ws_open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
    if (to_fd < 0) {
        report_open_failure(to_filename, errno, TRUE);
        ws_close(from_fd);
        goto done;
    }

#define FS_READ_SIZE 65536
    pd = (guint8 *)g_malloc(FS_READ_SIZE);
    while ((nread = ws_read(from_fd, pd, FS_READ_SIZE)) > 0) {
        nwritten = ws_write(to_fd, pd, nread);
        if (nwritten < nread) {
            if (nwritten < 0)
                err = errno;
            else
                err = WTAP_ERR_SHORT_WRITE;
            report_write_failure(to_filename, err);
            ws_close(from_fd);
            ws_close(to_fd);
            goto done;
        }
    }
    if (nread < 0) {
        err = errno;
        report_read_failure(from_filename, err);
        ws_close(from_fd);
        ws_close(to_fd);
        goto done;
    }
    ws_close(from_fd);
    if (ws_close(to_fd) < 0) {
        report_write_failure(to_filename, errno);
        goto done;
    }

    g_free(pd);
    pd = NULL;
    return TRUE;

done:
    g_free(pd);
    return FALSE;
}

gchar *
data_file_url(const gchar *filename)
{
    gchar *file_path;
    gchar *uri;

    /* Absolute path? */
    if(g_path_is_absolute(filename)) {
        file_path = g_strdup(filename);
    } else if(running_in_build_directory()) {
        file_path = g_strdup_printf("%s/doc/%s", get_datafile_dir(), filename);
    } else {
        file_path = g_strdup_printf("%s/%s", get_datafile_dir(), filename);
    }

    /* XXX - check, if the file is really existing, otherwise display a simple_dialog about the problem */

    /* convert filename to uri */
    uri = g_filename_to_uri(file_path, NULL, NULL);
    g_free(file_path);
    return uri;
}

void
free_progdirs(void)
{
    g_free(persconffile_dir);
    persconffile_dir = NULL;
    g_free(persdatafile_dir);
    persdatafile_dir = NULL;
    g_free(persconfprofile);
    persconfprofile = NULL;
    g_free(progfile_dir);
    progfile_dir = NULL;
#if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
    g_free(plugin_dir);
    plugin_dir = NULL;
#endif
#ifdef HAVE_EXTCAP
    g_free(extcap_dir);
    extcap_dir = NULL;
#endif
}

/*
 * Editor modelines
 *
 * Local Variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * ex: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */