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
|
/* Copyright (c) 2003-2004, Roger Dingledine
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
* Copyright (c) 2007-2018, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file compat.c
* \brief Wrappers to make calls more portable. This code defines
* functions such as tor_snprintf, get/set various data types,
* renaming, setting socket options, switching user IDs. It is basically
* where the non-portable items are conditionally included depending on
* the platform.
**/
#define COMPAT_PRIVATE
#include "common/compat.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <sys/locking.h>
#endif
#ifdef HAVE_UNAME
#include <sys/utsname.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_UTIME_H
#include <utime.h>
#endif
#ifdef HAVE_SYS_UTIME_H
#include <sys/utime.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_FCNTL_H
#include <sys/fcntl.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_CRT_EXTERNS_H
#include <crt_externs.h>
#endif
#ifdef HAVE_SYS_STATVFS_H
#include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_CAPABILITY_H
#include <sys/capability.h>
#endif
#ifdef _WIN32
#include <conio.h>
#include <wchar.h>
/* Some mingw headers lack these. :p */
#if defined(HAVE_DECL__GETWCH) && !HAVE_DECL__GETWCH
wint_t _getwch(void);
#endif
#ifndef WEOF
#define WEOF (wchar_t)(0xFFFF)
#endif
#if defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY
static inline void
SecureZeroMemory(PVOID ptr, SIZE_T cnt)
{
volatile char *vcptr = (volatile char*)ptr;
while (cnt--)
*vcptr++ = 0;
}
#endif /* defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY */
#elif defined(HAVE_READPASSPHRASE_H)
#include <readpassphrase.h>
#else
#include "tor_readpassphrase.h"
#endif /* defined(_WIN32) || ... */
/* Includes for the process attaching prevention */
#if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
/* Only use the linux prctl; the IRIX prctl is totally different */
#include <sys/prctl.h>
#elif defined(__APPLE__)
#include <sys/ptrace.h>
#endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) || ... */
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* FreeBSD needs this to know what version it is */
#endif
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif
#ifdef HAVE_SYS_SYSLIMITS_H
#include <sys/syslimits.h>
#endif
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#include "lib/log/torlog.h"
#include "common/util.h"
#include "lib/container/smartlist.h"
#include "lib/wallclock/tm_cvt.h"
#include "lib/net/address.h"
#include "common/sandbox.h"
/** As open(path, flags, mode), but return an fd with the close-on-exec mode
* set. */
int
tor_open_cloexec(const char *path, int flags, unsigned mode)
{
int fd;
const char *p = sandbox_intern_string(path);
#ifdef O_CLOEXEC
fd = open(p, flags|O_CLOEXEC, mode);
if (fd >= 0)
return fd;
/* If we got an error, see if it is EINVAL. EINVAL might indicate that,
* even though we were built on a system with O_CLOEXEC support, we
* are running on one without. */
if (errno != EINVAL)
return -1;
#endif /* defined(O_CLOEXEC) */
log_debug(LD_FS, "Opening %s with flags %x", p, flags);
fd = open(p, flags, mode);
#ifdef FD_CLOEXEC
if (fd >= 0) {
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
close(fd);
return -1;
}
}
#endif /* defined(FD_CLOEXEC) */
return fd;
}
/** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
* underlying file handle. */
FILE *
tor_fopen_cloexec(const char *path, const char *mode)
{
FILE *result = fopen(path, mode);
#ifdef FD_CLOEXEC
if (result != NULL) {
if (fcntl(fileno(result), F_SETFD, FD_CLOEXEC) == -1) {
log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
fclose(result);
return NULL;
}
}
#endif /* defined(FD_CLOEXEC) */
return result;
}
/** As rename(), but work correctly with the sandbox. */
int
tor_rename(const char *path_old, const char *path_new)
{
log_debug(LD_FS, "Renaming %s to %s", path_old, path_new);
return rename(sandbox_intern_string(path_old),
sandbox_intern_string(path_new));
}
#if defined(HAVE_MMAP) || defined(RUNNING_DOXYGEN)
/** Try to create a memory mapping for <b>filename</b> and return it. On
* failure, return NULL. Sets errno properly, using ERANGE to mean
* "empty file". Must only be called on trusted Tor-owned files, as changing
* the underlying file's size causes unspecified behavior. */
tor_mmap_t *
tor_mmap_file(const char *filename)
{
int fd; /* router file */
char *string;
int result;
tor_mmap_t *res;
size_t size, filesize;
struct stat st;
tor_assert(filename);
fd = tor_open_cloexec(filename, O_RDONLY, 0);
if (fd<0) {
int save_errno = errno;
int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
strerror(errno));
errno = save_errno;
return NULL;
}
/* Get the size of the file */
result = fstat(fd, &st);
if (result != 0) {
int save_errno = errno;
log_warn(LD_FS,
"Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
filename, strerror(errno));
close(fd);
errno = save_errno;
return NULL;
}
size = filesize = (size_t)(st.st_size);
if (st.st_size > SSIZE_T_CEILING || (off_t)size < st.st_size) {
log_warn(LD_FS, "File \"%s\" is too large. Ignoring.",filename);
errno = EFBIG;
close(fd);
return NULL;
}
if (!size) {
/* Zero-length file. If we call mmap on it, it will succeed but
* return NULL, and bad things will happen. So just fail. */
log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
errno = ERANGE;
close(fd);
return NULL;
}
string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (string == MAP_FAILED) {
int save_errno = errno;
log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
strerror(errno));
errno = save_errno;
return NULL;
}
res = tor_malloc_zero(sizeof(tor_mmap_t));
res->data = string;
res->size = filesize;
res->mapping_size = size;
return res;
}
/** Release storage held for a memory mapping; returns 0 on success,
* or -1 on failure (and logs a warning). */
int
tor_munmap_file(tor_mmap_t *handle)
{
int res;
if (handle == NULL)
return 0;
res = munmap((char*)handle->data, handle->mapping_size);
if (res == 0) {
/* munmap() succeeded */
tor_free(handle);
} else {
log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
strerror(errno));
res = -1;
}
return res;
}
#elif defined(_WIN32)
tor_mmap_t *
tor_mmap_file(const char *filename)
{
TCHAR tfilename[MAX_PATH]= {0};
tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
int empty = 0;
HANDLE file_handle = INVALID_HANDLE_VALUE;
DWORD size_low, size_high;
uint64_t real_size;
res->mmap_handle = NULL;
#ifdef UNICODE
mbstowcs(tfilename,filename,MAX_PATH);
#else
strlcpy(tfilename,filename,MAX_PATH);
#endif
file_handle = CreateFile(tfilename,
GENERIC_READ, FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (file_handle == INVALID_HANDLE_VALUE)
goto win_err;
size_low = GetFileSize(file_handle, &size_high);
if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
log_warn(LD_FS,"Error getting size of \"%s\".",filename);
goto win_err;
}
if (size_low == 0 && size_high == 0) {
log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
empty = 1;
goto err;
}
real_size = (((uint64_t)size_high)<<32) | size_low;
if (real_size > SIZE_MAX) {
log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
goto err;
}
res->size = real_size;
res->mmap_handle = CreateFileMapping(file_handle,
NULL,
PAGE_READONLY,
size_high,
size_low,
NULL);
if (res->mmap_handle == NULL)
goto win_err;
res->data = (char*) MapViewOfFile(res->mmap_handle,
FILE_MAP_READ,
0, 0, 0);
if (!res->data)
goto win_err;
CloseHandle(file_handle);
return res;
win_err: {
DWORD e = GetLastError();
int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
LOG_INFO : LOG_WARN;
char *msg = format_win32_error(e);
log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
tor_free(msg);
if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
errno = ENOENT;
else
errno = EINVAL;
}
err:
if (empty)
errno = ERANGE;
if (file_handle != INVALID_HANDLE_VALUE)
CloseHandle(file_handle);
tor_munmap_file(res);
return NULL;
}
/* Unmap the file, and return 0 for success or -1 for failure */
int
tor_munmap_file(tor_mmap_t *handle)
{
if (handle == NULL)
return 0;
if (handle->data) {
/* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
have to be redefined as non-const. */
BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
if (!ok) {
log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
(int)GetLastError());
}
}
if (handle->mmap_handle != NULL)
CloseHandle(handle->mmap_handle);
tor_free(handle);
return 0;
}
#else
#error "cannot implement tor_mmap_file"
#endif /* defined(HAVE_MMAP) || ... || ... */
/** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
* <b>needle</b>, return a pointer to the first occurrence of the needle
* within the haystack, or NULL if there is no such occurrence.
*
* This function is <em>not</em> timing-safe.
*
* Requires that <b>nlen</b> be greater than zero.
*/
const void *
tor_memmem(const void *_haystack, size_t hlen,
const void *_needle, size_t nlen)
{
#if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
tor_assert(nlen);
return memmem(_haystack, hlen, _needle, nlen);
#else
/* This isn't as fast as the GLIBC implementation, but it doesn't need to
* be. */
const char *p, *last_possible_start;
const char *haystack = (const char*)_haystack;
const char *needle = (const char*)_needle;
char first;
tor_assert(nlen);
if (nlen > hlen)
return NULL;
p = haystack;
/* Last position at which the needle could start. */
last_possible_start = haystack + hlen - nlen;
first = *(const char*)needle;
while ((p = memchr(p, first, last_possible_start + 1 - p))) {
if (fast_memeq(p, needle, nlen))
return p;
if (++p > last_possible_start) {
/* This comparison shouldn't be necessary, since if p was previously
* equal to last_possible_start, the next memchr call would be
* "memchr(p, first, 0)", which will return NULL. But it clarifies the
* logic. */
return NULL;
}
}
return NULL;
#endif /* defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2) */
}
/** Helper for tor_strtok_r_impl: Advances cp past all characters in
* <b>sep</b>, and returns its new value. */
static char *
strtok_helper(char *cp, const char *sep)
{
if (sep[1]) {
while (*cp && strchr(sep, *cp))
++cp;
} else {
while (*cp && *cp == *sep)
++cp;
}
return cp;
}
/** Implementation of strtok_r for platforms whose coders haven't figured out
* how to write one. Hey, retrograde libc developers! You can use this code
* here for free! */
char *
tor_strtok_r_impl(char *str, const char *sep, char **lasts)
{
char *cp, *start;
tor_assert(*sep);
if (str) {
str = strtok_helper(str, sep);
if (!*str)
return NULL;
start = cp = *lasts = str;
} else if (!*lasts || !**lasts) {
return NULL;
} else {
start = cp = *lasts;
}
if (sep[1]) {
while (*cp && !strchr(sep, *cp))
++cp;
} else {
cp = strchr(cp, *sep);
}
if (!cp || !*cp) {
*lasts = NULL;
} else {
*cp++ = '\0';
*lasts = strtok_helper(cp, sep);
}
return start;
}
/**
* Read a 16-bit value beginning at <b>cp</b>. Equivalent to
* *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
* unaligned memory access.
*/
uint16_t
get_uint16(const void *cp)
{
uint16_t v;
memcpy(&v,cp,2);
return v;
}
/**
* Read a 32-bit value beginning at <b>cp</b>. Equivalent to
* *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
* unaligned memory access.
*/
uint32_t
get_uint32(const void *cp)
{
uint32_t v;
memcpy(&v,cp,4);
return v;
}
/**
* Read a 64-bit value beginning at <b>cp</b>. Equivalent to
* *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
* unaligned memory access.
*/
uint64_t
get_uint64(const void *cp)
{
uint64_t v;
memcpy(&v,cp,8);
return v;
}
/**
* Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
* *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
* unaligned memory access. */
void
set_uint16(void *cp, uint16_t v)
{
memcpy(cp,&v,2);
}
/**
* Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
* *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
* unaligned memory access. */
void
set_uint32(void *cp, uint32_t v)
{
memcpy(cp,&v,4);
}
/**
* Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
* *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
* unaligned memory access. */
void
set_uint64(void *cp, uint64_t v)
{
memcpy(cp,&v,8);
}
/**
* Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
* the same as rename(2). On windows, this removes <b>to</b> first if
* it already exists.
* Returns 0 on success. Returns -1 and sets errno on failure.
*/
int
replace_file(const char *from, const char *to)
{
#ifndef _WIN32
return tor_rename(from, to);
#else
switch (file_status(to))
{
case FN_NOENT:
break;
case FN_FILE:
case FN_EMPTY:
if (unlink(to)) return -1;
break;
case FN_ERROR:
return -1;
case FN_DIR:
errno = EISDIR;
return -1;
}
return tor_rename(from,to);
#endif /* !defined(_WIN32) */
}
/** Change <b>fname</b>'s modification time to now. */
int
touch_file(const char *fname)
{
if (utime(fname, NULL)!=0)
return -1;
return 0;
}
/** Represents a lockfile on which we hold the lock. */
struct tor_lockfile_t {
/** Name of the file */
char *filename;
/** File descriptor used to hold the file open */
int fd;
};
/** Try to get a lock on the lockfile <b>filename</b>, creating it as
* necessary. If someone else has the lock and <b>blocking</b> is true,
* wait until the lock is available. Otherwise return immediately whether
* we succeeded or not.
*
* Set *<b>locked_out</b> to true if somebody else had the lock, and to false
* otherwise.
*
* Return a <b>tor_lockfile_t</b> on success, NULL on failure.
*
* (Implementation note: because we need to fall back to fcntl on some
* platforms, these locks are per-process, not per-thread. If you want
* to do in-process locking, use tor_mutex_t like a normal person.
* On Windows, when <b>blocking</b> is true, the maximum time that
* is actually waited is 10 seconds, after which NULL is returned
* and <b>locked_out</b> is set to 1.)
*/
tor_lockfile_t *
tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
{
tor_lockfile_t *result;
int fd;
*locked_out = 0;
log_info(LD_FS, "Locking \"%s\"", filename);
fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
if (fd < 0) {
log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
strerror(errno));
return NULL;
}
#ifdef _WIN32
_lseek(fd, 0, SEEK_SET);
if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
if (errno != EACCES && errno != EDEADLOCK)
log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
else
*locked_out = 1;
close(fd);
return NULL;
}
#elif defined(HAVE_FLOCK)
if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
if (errno != EWOULDBLOCK)
log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
else
*locked_out = 1;
close(fd);
return NULL;
}
#else
{
struct flock lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
if (errno != EACCES && errno != EAGAIN)
log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
else
*locked_out = 1;
close(fd);
return NULL;
}
}
#endif /* defined(_WIN32) || ... */
result = tor_malloc(sizeof(tor_lockfile_t));
result->filename = tor_strdup(filename);
result->fd = fd;
return result;
}
/** Release the lock held as <b>lockfile</b>. */
void
tor_lockfile_unlock(tor_lockfile_t *lockfile)
{
tor_assert(lockfile);
log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
#ifdef _WIN32
_lseek(lockfile->fd, 0, SEEK_SET);
if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
strerror(errno));
}
#elif defined(HAVE_FLOCK)
if (flock(lockfile->fd, LOCK_UN) < 0) {
log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
strerror(errno));
}
#else
/* Closing the lockfile is sufficient. */
#endif /* defined(_WIN32) || ... */
close(lockfile->fd);
lockfile->fd = -1;
tor_free(lockfile->filename);
tor_free(lockfile);
}
/** Number of extra file descriptors to keep in reserve beyond those that we
* tell Tor it's allowed to use. */
#define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
/** Learn the maximum allowed number of file descriptors, and tell the
* system we want to use up to that number. (Some systems have a low soft
* limit, and let us set it higher.) We compute this by finding the largest
* number that we can use.
*
* If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
* return -1 and <b>max_out</b> is untouched.
*
* If we can't find a number greater than or equal to <b>limit</b>, then we
* fail by returning -1 and <b>max_out</b> is untouched.
*
* If we are unable to set the limit value because of setrlimit() failing,
* return 0 and <b>max_out</b> is set to the current maximum value returned
* by getrlimit().
*
* Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
* and set <b>max_sockets</b> with that value as well.*/
int
set_max_file_descriptors(rlim_t limit, int *max_out)
{
if (limit < ULIMIT_BUFFER) {
log_warn(LD_CONFIG,
"ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
return -1;
}
/* Define some maximum connections values for systems where we cannot
* automatically determine a limit. Re Cygwin, see
* http://archives.seul.org/or/talk/Aug-2006/msg00210.html
* For an iPhone, 9999 should work. For Windows and all other unknown
* systems we use 15000 as the default. */
#ifndef HAVE_GETRLIMIT
#if defined(CYGWIN) || defined(__CYGWIN__)
const char *platform = "Cygwin";
const unsigned long MAX_CONNECTIONS = 3200;
#elif defined(_WIN32)
const char *platform = "Windows";
const unsigned long MAX_CONNECTIONS = 15000;
#else
const char *platform = "unknown platforms with no getrlimit()";
const unsigned long MAX_CONNECTIONS = 15000;
#endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */
log_fn(LOG_INFO, LD_NET,
"This platform is missing getrlimit(). Proceeding.");
if (limit > MAX_CONNECTIONS) {
log_warn(LD_CONFIG,
"We do not support more than %lu file descriptors "
"on %s. Tried to raise to %lu.",
(unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
return -1;
}
limit = MAX_CONNECTIONS;
#else /* !(!defined(HAVE_GETRLIMIT)) */
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
strerror(errno));
return -1;
}
if (rlim.rlim_max < limit) {
log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
"limited to %lu. Please change your ulimit -n.",
(unsigned long)limit, (unsigned long)rlim.rlim_max);
return -1;
}
if (rlim.rlim_max > rlim.rlim_cur) {
log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
(unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
}
/* Set the current limit value so if the attempt to set the limit to the
* max fails at least we'll have a valid value of maximum sockets. */
*max_out = (int)rlim.rlim_cur - ULIMIT_BUFFER;
set_max_sockets(*max_out);
rlim.rlim_cur = rlim.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
int couldnt_set = 1;
const int setrlimit_errno = errno;
#ifdef OPEN_MAX
uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
/* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
* full of nasty lies. I'm looking at you, OSX 10.5.... */
rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur);
if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
if (rlim.rlim_cur < (rlim_t)limit) {
log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
"OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
"ConnLimit; sorry.",
(unsigned long)try_limit, (unsigned long)OPEN_MAX,
(unsigned long)limit);
} else {
log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
"OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
"lied to us.",
(unsigned long)try_limit, (unsigned long)OPEN_MAX,
(unsigned long)rlim.rlim_max);
}
couldnt_set = 0;
}
}
#endif /* defined(OPEN_MAX) */
if (couldnt_set) {
log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
strerror(setrlimit_errno));
}
}
/* leave some overhead for logs, etc, */
limit = rlim.rlim_cur;
#endif /* !defined(HAVE_GETRLIMIT) */
if (limit > INT_MAX)
limit = INT_MAX;
tor_assert(max_out);
*max_out = (int)limit - ULIMIT_BUFFER;
set_max_sockets(*max_out);
return 0;
}
#ifndef _WIN32
/** Log details of current user and group credentials. Return 0 on
* success. Logs and return -1 on failure.
*/
static int
log_credential_status(void)
{
/** Log level to use when describing non-error UID/GID status. */
#define CREDENTIAL_LOG_LEVEL LOG_INFO
/* Real, effective and saved UIDs */
uid_t ruid, euid, suid;
/* Read, effective and saved GIDs */
gid_t rgid, egid, sgid;
/* Supplementary groups */
gid_t *sup_gids = NULL;
int sup_gids_size;
/* Number of supplementary groups */
int ngids;
/* log UIDs */
#ifdef HAVE_GETRESUID
if (getresuid(&ruid, &euid, &suid) != 0 ) {
log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
return -1;
} else {
log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
"UID is %u (real), %u (effective), %u (saved)",
(unsigned)ruid, (unsigned)euid, (unsigned)suid);
}
#else /* !(defined(HAVE_GETRESUID)) */
/* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
ruid = getuid();
euid = geteuid();
(void)suid;
log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
"UID is %u (real), %u (effective), unknown (saved)",
(unsigned)ruid, (unsigned)euid);
#endif /* defined(HAVE_GETRESUID) */
/* log GIDs */
#ifdef HAVE_GETRESGID
if (getresgid(&rgid, &egid, &sgid) != 0 ) {
log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
return -1;
} else {
log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
"GID is %u (real), %u (effective), %u (saved)",
(unsigned)rgid, (unsigned)egid, (unsigned)sgid);
}
#else /* !(defined(HAVE_GETRESGID)) */
/* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
rgid = getgid();
egid = getegid();
(void)sgid;
log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
"GID is %u (real), %u (effective), unknown (saved)",
(unsigned)rgid, (unsigned)egid);
#endif /* defined(HAVE_GETRESGID) */
/* log supplementary groups */
sup_gids_size = 64;
sup_gids = tor_calloc(64, sizeof(gid_t));
while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
errno == EINVAL &&
sup_gids_size < NGROUPS_MAX) {
sup_gids_size *= 2;
sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
}
if (ngids < 0) {
log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
strerror(errno));
tor_free(sup_gids);
return -1;
} else {
int i, retval = 0;
char *s = NULL;
smartlist_t *elts = smartlist_new();
for (i = 0; i<ngids; i++) {
smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
}
s = smartlist_join_strings(elts, " ", 0, NULL);
log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
tor_free(s);
SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
smartlist_free(elts);
tor_free(sup_gids);
return retval;
}
return 0;
}
#endif /* !defined(_WIN32) */
#ifndef _WIN32
/** Cached struct from the last getpwname() call we did successfully. */
static struct passwd *passwd_cached = NULL;
/** Helper: copy a struct passwd object.
*
* We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
* any others, and I don't want to run into incompatibilities.
*/
static struct passwd *
tor_passwd_dup(const struct passwd *pw)
{
struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
if (pw->pw_name)
new_pw->pw_name = tor_strdup(pw->pw_name);
if (pw->pw_dir)
new_pw->pw_dir = tor_strdup(pw->pw_dir);
new_pw->pw_uid = pw->pw_uid;
new_pw->pw_gid = pw->pw_gid;
return new_pw;
}
#define tor_passwd_free(pw) \
FREE_AND_NULL(struct passwd, tor_passwd_free_, (pw))
/** Helper: free one of our cached 'struct passwd' values. */
static void
tor_passwd_free_(struct passwd *pw)
{
if (!pw)
return;
tor_free(pw->pw_name);
tor_free(pw->pw_dir);
tor_free(pw);
}
/** Wrapper around getpwnam() that caches result. Used so that we don't need
* to give the sandbox access to /etc/passwd.
*
* The following fields alone will definitely be copied in the output: pw_uid,
* pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
*
* When called with a NULL argument, this function clears storage associated
* with static variables it uses.
**/
const struct passwd *
tor_getpwnam(const char *username)
{
struct passwd *pw;
if (username == NULL) {
tor_passwd_free(passwd_cached);
passwd_cached = NULL;
return NULL;
}
if ((pw = getpwnam(username))) {
tor_passwd_free(passwd_cached);
passwd_cached = tor_passwd_dup(pw);
log_info(LD_GENERAL, "Caching new entry %s for %s",
passwd_cached->pw_name, username);
return pw;
}
/* Lookup failed */
if (! passwd_cached || ! passwd_cached->pw_name)
return NULL;
if (! strcmp(username, passwd_cached->pw_name))
return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
return NULL;
}
/** Wrapper around getpwnam() that can use cached result from
* tor_getpwnam(). Used so that we don't need to give the sandbox access to
* /etc/passwd.
*
* The following fields alone will definitely be copied in the output: pw_uid,
* pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
*/
const struct passwd *
tor_getpwuid(uid_t uid)
{
struct passwd *pw;
if ((pw = getpwuid(uid))) {
return pw;
}
/* Lookup failed */
if (! passwd_cached)
return NULL;
if (uid == passwd_cached->pw_uid)
return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
return NULL;
}
#endif /* !defined(_WIN32) */
/** Return true iff we were compiled with capability support, and capabilities
* seem to work. **/
int
have_capability_support(void)
{
#ifdef HAVE_LINUX_CAPABILITIES
cap_t caps = cap_get_proc();
if (caps == NULL)
return 0;
cap_free(caps);
return 1;
#else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
return 0;
#endif /* defined(HAVE_LINUX_CAPABILITIES) */
}
#ifdef HAVE_LINUX_CAPABILITIES
/** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
* appropriate.
*
* If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
* CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
* setuid().
*
* If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
* PR_KEEPCAPS.
*
* Return 0 on success, and -1 on failure.
*/
static int
drop_capabilities(int pre_setuid)
{
/* We keep these three capabilities, and these only, as we setuid.
* After we setuid, we drop all but the first. */
const cap_value_t caplist[] = {
CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
};
const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
const int n_effective = pre_setuid ? 3 : 1;
const int n_permitted = pre_setuid ? 3 : 1;
const int n_inheritable = 1;
const int keepcaps = pre_setuid ? 1 : 0;
/* Sets whether we keep capabilities across a setuid. */
if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
where, strerror(errno));
return -1;
}
cap_t caps = cap_get_proc();
if (!caps) {
log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
where, strerror(errno));
return -1;
}
cap_clear(caps);
cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
int r = cap_set_proc(caps);
cap_free(caps);
if (r < 0) {
log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
where, strerror(errno));
return -1;
}
return 0;
}
#endif /* defined(HAVE_LINUX_CAPABILITIES) */
/** Call setuid and setgid to run as <b>user</b> and switch to their
* primary group. Return 0 on success. On failure, log and return -1.
*
* If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
* system to retain the abilitity to bind low ports.
*
* If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
* don't have capability support.
*/
int
switch_id(const char *user, const unsigned flags)
{
#ifndef _WIN32
const struct passwd *pw = NULL;
uid_t old_uid;
gid_t old_gid;
static int have_already_switched_id = 0;
const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
tor_assert(user);
if (have_already_switched_id)
return 0;
/* Log the initial credential state */
if (log_credential_status())
return -1;
log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
/* Get old UID/GID to check if we changed correctly */
old_uid = getuid();
old_gid = getgid();
/* Lookup the user and group information, if we have a problem, bail out. */
pw = tor_getpwnam(user);
if (pw == NULL) {
log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
return -1;
}
#ifdef HAVE_LINUX_CAPABILITIES
(void) warn_if_no_caps;
if (keep_bindlow) {
if (drop_capabilities(1))
return -1;
}
#else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
(void) keep_bindlow;
if (warn_if_no_caps) {
log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
"on this system.");
}
#endif /* defined(HAVE_LINUX_CAPABILITIES) */
/* Properly switch egid,gid,euid,uid here or bail out */
if (setgroups(1, &pw->pw_gid)) {
log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
(int)pw->pw_gid, strerror(errno));
if (old_uid == pw->pw_uid) {
log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
"the \"User\" option if you are already running as the user "
"you want to be. (If you did not set the User option in your "
"torrc, check whether it was specified on the command line "
"by a startup script.)", user);
} else {
log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
" as root.");
}
return -1;
}
if (setegid(pw->pw_gid)) {
log_warn(LD_GENERAL, "Error setting egid to %d: %s",
(int)pw->pw_gid, strerror(errno));
return -1;
}
if (setgid(pw->pw_gid)) {
log_warn(LD_GENERAL, "Error setting gid to %d: %s",
(int)pw->pw_gid, strerror(errno));
return -1;
}
if (setuid(pw->pw_uid)) {
log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
user, (int)pw->pw_uid, strerror(errno));
return -1;
}
if (seteuid(pw->pw_uid)) {
log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
user, (int)pw->pw_uid, strerror(errno));
return -1;
}
/* This is how OpenBSD rolls:
if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
strerror(errno));
return -1;
}
*/
/* We've properly switched egid, gid, euid, uid, and supplementary groups if
* we're here. */
#ifdef HAVE_LINUX_CAPABILITIES
if (keep_bindlow) {
if (drop_capabilities(0))
return -1;
}
#endif /* defined(HAVE_LINUX_CAPABILITIES) */
#if !defined(CYGWIN) && !defined(__CYGWIN__)
/* If we tried to drop privilege to a group/user other than root, attempt to
* restore root (E)(U|G)ID, and abort if the operation succeeds */
/* Only check for privilege dropping if we were asked to be non-root */
if (pw->pw_uid) {
/* Try changing GID/EGID */
if (pw->pw_gid != old_gid &&
(setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
log_warn(LD_GENERAL, "Was able to restore group credentials even after "
"switching GID: this means that the setgid code didn't work.");
return -1;
}
/* Try changing UID/EUID */
if (pw->pw_uid != old_uid &&
(setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
log_warn(LD_GENERAL, "Was able to restore user credentials even after "
"switching UID: this means that the setuid code didn't work.");
return -1;
}
}
#endif /* !defined(CYGWIN) && !defined(__CYGWIN__) */
/* Check what really happened */
if (log_credential_status()) {
return -1;
}
have_already_switched_id = 1; /* mark success so we never try again */
#if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && \
defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
if (pw->pw_uid) {
/* Re-enable core dumps if we're not running as root. */
log_info(LD_CONFIG, "Re-enabling coredumps");
if (prctl(PR_SET_DUMPABLE, 1)) {
log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
}
}
#endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && ... */
return 0;
#else /* !(!defined(_WIN32)) */
(void)user;
(void)flags;
log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
return -1;
#endif /* !defined(_WIN32) */
}
/* We only use the linux prctl for now. There is no Win32 support; this may
* also work on various BSD systems and Mac OS X - send testing feedback!
*
* On recent Gnu/Linux kernels it is possible to create a system-wide policy
* that will prevent non-root processes from attaching to other processes
* unless they are the parent process; thus gdb can attach to programs that
* they execute but they cannot attach to other processes running as the same
* user. The system wide policy may be set with the sysctl
* kernel.yama.ptrace_scope or by inspecting
* /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
*
* This ptrace scope will be ignored on Gnu/Linux for users with
* CAP_SYS_PTRACE and so it is very likely that root will still be able to
* attach to the Tor process.
*/
/** Attempt to disable debugger attachment: return 1 on success, -1 on
* failure, and 0 if we don't know how to try on this platform. */
int
tor_disable_debugger_attach(void)
{
int r = -1;
log_debug(LD_CONFIG,
"Attemping to disable debugger attachment to Tor for "
"unprivileged users.");
#if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \
&& defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
#define TRIED_TO_DISABLE
r = prctl(PR_SET_DUMPABLE, 0);
#elif defined(__APPLE__) && defined(PT_DENY_ATTACH)
#define TRIED_TO_ATTACH
r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
#endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */
// XXX: TODO - Mac OS X has dtrace and this may be disabled.
// XXX: TODO - Windows probably has something similar
#ifdef TRIED_TO_DISABLE
if (r == 0) {
log_debug(LD_CONFIG,"Debugger attachment disabled for "
"unprivileged users.");
return 1;
} else {
log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
strerror(errno));
}
#endif /* defined(TRIED_TO_DISABLE) */
#undef TRIED_TO_DISABLE
return r;
}
#ifdef HAVE_PWD_H
/** Allocate and return a string containing the home directory for the
* user <b>username</b>. Only works on posix-like systems. */
char *
get_user_homedir(const char *username)
{
const struct passwd *pw;
tor_assert(username);
if (!(pw = tor_getpwnam(username))) {
log_err(LD_CONFIG,"User \"%s\" not found.", username);
return NULL;
}
return tor_strdup(pw->pw_dir);
}
#endif /* defined(HAVE_PWD_H) */
/** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
* actually examine the filesystem; does a purely syntactic modification.
*
* The parent of the root director is considered to be iteself.
*
* Path separators are the forward slash (/) everywhere and additionally
* the backslash (\) on Win32.
*
* Cuts off any number of trailing path separators but otherwise ignores
* them for purposes of finding the parent directory.
*
* Returns 0 if a parent directory was successfully found, -1 otherwise (fname
* did not have any path separators or only had them at the end).
* */
int
get_parent_directory(char *fname)
{
char *cp;
int at_end = 1;
tor_assert(fname);
#ifdef _WIN32
/* If we start with, say, c:, then don't consider that the start of the path
*/
if (fname[0] && fname[1] == ':') {
fname += 2;
}
#endif /* defined(_WIN32) */
/* Now we want to remove all path-separators at the end of the string,
* and to remove the end of the string starting with the path separator
* before the last non-path-separator. In perl, this would be
* s#[/]*$##; s#/[^/]*$##;
* on a unixy platform.
*/
cp = fname + strlen(fname);
at_end = 1;
while (--cp >= fname) {
int is_sep = (*cp == '/'
#ifdef _WIN32
|| *cp == '\\'
#endif
);
if (is_sep) {
if (cp == fname) {
/* This is the first separator in the file name; don't remove it! */
cp[1] = '\0';
return 0;
}
*cp = '\0';
if (! at_end)
return 0;
} else {
at_end = 0;
}
}
return -1;
}
#ifndef _WIN32
/** Return a newly allocated string containing the output of getcwd(). Return
* NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
* Hurd hasn't got a PATH_MAX.)
*/
static char *
alloc_getcwd(void)
{
#ifdef HAVE_GET_CURRENT_DIR_NAME
/* Glibc makes this nice and simple for us. */
char *cwd = get_current_dir_name();
char *result = NULL;
if (cwd) {
/* We make a copy here, in case tor_malloc() is not malloc(). */
result = tor_strdup(cwd);
raw_free(cwd); // alias for free to avoid tripping check-spaces.
}
return result;
#else /* !(defined(HAVE_GET_CURRENT_DIR_NAME)) */
size_t size = 1024;
char *buf = NULL;
char *ptr = NULL;
while (ptr == NULL) {
buf = tor_realloc(buf, size);
ptr = getcwd(buf, size);
if (ptr == NULL && errno != ERANGE) {
tor_free(buf);
return NULL;
}
size *= 2;
}
return buf;
#endif /* defined(HAVE_GET_CURRENT_DIR_NAME) */
}
#endif /* !defined(_WIN32) */
/** Expand possibly relative path <b>fname</b> to an absolute path.
* Return a newly allocated string, possibly equal to <b>fname</b>. */
char *
make_path_absolute(char *fname)
{
#ifdef _WIN32
char *absfname_malloced = _fullpath(NULL, fname, 1);
/* We don't want to assume that tor_free can free a string allocated
* with malloc. On failure, return fname (it's better than nothing). */
char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
if (absfname_malloced) raw_free(absfname_malloced);
return absfname;
#else /* !(defined(_WIN32)) */
char *absfname = NULL, *path = NULL;
tor_assert(fname);
if (fname[0] == '/') {
absfname = tor_strdup(fname);
} else {
path = alloc_getcwd();
if (path) {
tor_asprintf(&absfname, "%s/%s", path, fname);
tor_free(path);
} else {
/* LCOV_EXCL_START Can't make getcwd fail. */
/* If getcwd failed, the best we can do here is keep using the
* relative path. (Perhaps / isn't readable by this UID/GID.) */
log_warn(LD_GENERAL, "Unable to find current working directory: %s",
strerror(errno));
absfname = tor_strdup(fname);
/* LCOV_EXCL_STOP */
}
}
return absfname;
#endif /* defined(_WIN32) */
}
#ifndef HAVE__NSGETENVIRON
#ifndef HAVE_EXTERN_ENVIRON_DECLARED
/* Some platforms declare environ under some circumstances, others don't. */
#ifndef RUNNING_DOXYGEN
extern char **environ;
#endif
#endif /* !defined(HAVE_EXTERN_ENVIRON_DECLARED) */
#endif /* !defined(HAVE__NSGETENVIRON) */
/** Return the current environment. This is a portable replacement for
* 'environ'. */
char **
get_environment(void)
{
#ifdef HAVE__NSGETENVIRON
/* This is for compatibility between OSX versions. Otherwise (for example)
* when we do a mostly-static build on OSX 10.7, the resulting binary won't
* work on OSX 10.6. */
return *_NSGetEnviron();
#else /* !(defined(HAVE__NSGETENVIRON)) */
return environ;
#endif /* defined(HAVE__NSGETENVIRON) */
}
/** Get name of current host and write it to <b>name</b> array, whose
* length is specified by <b>namelen</b> argument. Return 0 upon
* successful completion; otherwise return return -1. (Currently,
* this function is merely a mockable wrapper for POSIX gethostname().)
*/
MOCK_IMPL(int,
tor_gethostname,(char *name, size_t namelen))
{
return gethostname(name,namelen);
}
/** Hold the result of our call to <b>uname</b>. */
static char uname_result[256];
/** True iff uname_result is set. */
static int uname_result_is_set = 0;
/** Return a pointer to a description of our platform.
*/
MOCK_IMPL(const char *,
get_uname,(void))
{
#ifdef HAVE_UNAME
struct utsname u;
#endif
if (!uname_result_is_set) {
#ifdef HAVE_UNAME
if (uname(&u) != -1) {
/* (Linux says 0 is success, Solaris says 1 is success) */
strlcpy(uname_result, u.sysname, sizeof(uname_result));
} else
#endif /* defined(HAVE_UNAME) */
{
#ifdef _WIN32
OSVERSIONINFOEX info;
int i;
const char *plat = NULL;
static struct {
unsigned major; unsigned minor; const char *version;
} win_version_table[] = {
{ 6, 2, "Windows 8" },
{ 6, 1, "Windows 7" },
{ 6, 0, "Windows Vista" },
{ 5, 2, "Windows Server 2003" },
{ 5, 1, "Windows XP" },
{ 5, 0, "Windows 2000" },
/* { 4, 0, "Windows NT 4.0" }, */
{ 4, 90, "Windows Me" },
{ 4, 10, "Windows 98" },
/* { 4, 0, "Windows 95" } */
{ 3, 51, "Windows NT 3.51" },
{ 0, 0, NULL }
};
memset(&info, 0, sizeof(info));
info.dwOSVersionInfoSize = sizeof(info);
if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
" doesn't work.", sizeof(uname_result));
uname_result_is_set = 1;
return uname_result;
}
if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
plat = "Windows NT 4.0";
else
plat = "Windows 95";
} else {
for (i=0; win_version_table[i].major>0; ++i) {
if (win_version_table[i].major == info.dwMajorVersion &&
win_version_table[i].minor == info.dwMinorVersion) {
plat = win_version_table[i].version;
break;
}
}
}
if (plat) {
strlcpy(uname_result, plat, sizeof(uname_result));
} else {
if (info.dwMajorVersion > 6 ||
(info.dwMajorVersion==6 && info.dwMinorVersion>2))
tor_snprintf(uname_result, sizeof(uname_result),
"Very recent version of Windows [major=%d,minor=%d]",
(int)info.dwMajorVersion,(int)info.dwMinorVersion);
else
tor_snprintf(uname_result, sizeof(uname_result),
"Unrecognized version of Windows [major=%d,minor=%d]",
(int)info.dwMajorVersion,(int)info.dwMinorVersion);
}
#ifdef VER_NT_SERVER
if (info.wProductType == VER_NT_SERVER ||
info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
strlcat(uname_result, " [server]", sizeof(uname_result));
}
#endif /* defined(VER_NT_SERVER) */
#else /* !(defined(_WIN32)) */
/* LCOV_EXCL_START -- can't provoke uname failure */
strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
/* LCOV_EXCL_STOP */
#endif /* defined(_WIN32) */
}
uname_result_is_set = 1;
}
return uname_result;
}
/*
* Process control
*/
/** Implementation logic for compute_num_cpus(). */
static int
compute_num_cpus_impl(void)
{
#ifdef _WIN32
SYSTEM_INFO info;
memset(&info, 0, sizeof(info));
GetSystemInfo(&info);
if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
return (int)info.dwNumberOfProcessors;
else
return -1;
#elif defined(HAVE_SYSCONF)
#ifdef _SC_NPROCESSORS_CONF
long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
#else
long cpus_conf = -1;
#endif
#ifdef _SC_NPROCESSORS_ONLN
long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
#else
long cpus_onln = -1;
#endif
long cpus = -1;
if (cpus_conf > 0 && cpus_onln < 0) {
cpus = cpus_conf;
} else if (cpus_onln > 0 && cpus_conf < 0) {
cpus = cpus_onln;
} else if (cpus_onln > 0 && cpus_conf > 0) {
if (cpus_onln < cpus_conf) {
log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
"are available. Telling Tor to only use %ld. You can over"
"ride this with the NumCPUs option",
cpus_conf, cpus_onln, cpus_onln);
}
cpus = cpus_onln;
}
if (cpus >= 1 && cpus < INT_MAX)
return (int)cpus;
else
return -1;
#else
return -1;
#endif /* defined(_WIN32) || ... */
}
#define MAX_DETECTABLE_CPUS 16
/** Return how many CPUs we are running with. We assume that nobody is
* using hot-swappable CPUs, so we don't recompute this after the first
* time. Return -1 if we don't know how to tell the number of CPUs on this
* system.
*/
int
compute_num_cpus(void)
{
static int num_cpus = -2;
if (num_cpus == -2) {
num_cpus = compute_num_cpus_impl();
tor_assert(num_cpus != -2);
if (num_cpus > MAX_DETECTABLE_CPUS) {
/* LCOV_EXCL_START */
log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
"will not autodetect any more than %d, though. If you "
"want to configure more, set NumCPUs in your torrc",
num_cpus, MAX_DETECTABLE_CPUS);
num_cpus = MAX_DETECTABLE_CPUS;
/* LCOV_EXCL_STOP */
}
}
return num_cpus;
}
/** As localtime_r, but defined for platforms that don't have it:
*
* Convert *<b>timep</b> to a struct tm in local time, and store the value in
* *<b>result</b>. Return the result on success, or NULL on failure.
*/
struct tm *
tor_localtime_r(const time_t *timep, struct tm *result)
{
char *err = NULL;
struct tm *r = tor_localtime_r_msg(timep, result, &err);
if (err) {
log_warn(LD_BUG, "%s", err);
tor_free(err);
}
return r;
}
/** As gmtime_r, but defined for platforms that don't have it:
*
* Convert *<b>timep</b> to a struct tm in UTC, and store the value in
* *<b>result</b>. Return the result on success, or NULL on failure.
*/
struct tm *
tor_gmtime_r(const time_t *timep, struct tm *result)
{
char *err = NULL;
struct tm *r = tor_gmtime_r_msg(timep, result, &err);
if (err) {
log_warn(LD_BUG, "%s", err);
tor_free(err);
}
return r;
}
#if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
#define HAVE_UNIX_MLOCKALL
#endif
#ifdef HAVE_UNIX_MLOCKALL
/** Attempt to raise the current and max rlimit to infinity for our process.
* This only needs to be done once and can probably only be done when we have
* not already dropped privileges.
*/
static int
tor_set_max_memlock(void)
{
/* Future consideration for Windows is probably SetProcessWorkingSetSize
* This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
* http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
*/
struct rlimit limit;
/* RLIM_INFINITY is -1 on some platforms. */
limit.rlim_cur = RLIM_INFINITY;
limit.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
if (errno == EPERM) {
log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
"limits. Are you root?");
}
log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
strerror(errno));
return -1;
}
return 0;
}
#endif /* defined(HAVE_UNIX_MLOCKALL) */
/** Attempt to lock all current and all future memory pages.
* This should only be called once and while we're privileged.
* Like mlockall() we return 0 when we're successful and -1 when we're not.
* Unlike mlockall() we return 1 if we've already attempted to lock memory.
*/
int
tor_mlockall(void)
{
static int memory_lock_attempted = 0;
if (memory_lock_attempted) {
return 1;
}
memory_lock_attempted = 1;
/*
* Future consideration for Windows may be VirtualLock
* VirtualLock appears to implement mlock() but not mlockall()
*
* http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
*/
#ifdef HAVE_UNIX_MLOCKALL
if (tor_set_max_memlock() == 0) {
log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
}
if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
return 0;
} else {
if (errno == ENOSYS) {
/* Apple - it's 2009! I'm looking at you. Grrr. */
log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
"your platform.");
} else if (errno == EPERM) {
log_notice(LD_GENERAL, "It appears that you lack the permissions to "
"lock memory. Are you root?");
}
log_notice(LD_GENERAL, "Unable to lock all current and future memory "
"pages: %s", strerror(errno));
return -1;
}
#else /* !(defined(HAVE_UNIX_MLOCKALL)) */
log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
return -1;
#endif /* defined(HAVE_UNIX_MLOCKALL) */
}
/**
* On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
* you need to ask the socket for its actual errno. Also, you need to
* get your errors from WSAGetLastError, not errno. (If you supply a
* socket of -1, we check WSAGetLastError, but don't correct
* WSAEWOULDBLOCKs.)
*
* The upshot of all of this is that when a socket call fails, you
* should call tor_socket_errno <em>at most once</em> on the failing
* socket to get the error.
*/
#if defined(_WIN32)
int
tor_socket_errno(tor_socket_t sock)
{
int optval, optvallen=sizeof(optval);
int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
return err;
if (optval)
return optval;
}
return err;
}
#endif /* defined(_WIN32) */
#if defined(_WIN32)
#define E(code, s) { code, (s " [" #code " ]") }
struct { int code; const char *msg; } windows_socket_errors[] = {
E(WSAEINTR, "Interrupted function call"),
E(WSAEACCES, "Permission denied"),
E(WSAEFAULT, "Bad address"),
E(WSAEINVAL, "Invalid argument"),
E(WSAEMFILE, "Too many open files"),
E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
E(WSAEINPROGRESS, "Operation now in progress"),
E(WSAEALREADY, "Operation already in progress"),
E(WSAENOTSOCK, "Socket operation on nonsocket"),
E(WSAEDESTADDRREQ, "Destination address required"),
E(WSAEMSGSIZE, "Message too long"),
E(WSAEPROTOTYPE, "Protocol wrong for socket"),
E(WSAENOPROTOOPT, "Bad protocol option"),
E(WSAEPROTONOSUPPORT, "Protocol not supported"),
E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
/* What's the difference between NOTSUPP and NOSUPPORT? :) */
E(WSAEOPNOTSUPP, "Operation not supported"),
E(WSAEPFNOSUPPORT, "Protocol family not supported"),
E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
E(WSAEADDRINUSE, "Address already in use"),
E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
E(WSAENETDOWN, "Network is down"),
E(WSAENETUNREACH, "Network is unreachable"),
E(WSAENETRESET, "Network dropped connection on reset"),
E(WSAECONNABORTED, "Software caused connection abort"),
E(WSAECONNRESET, "Connection reset by peer"),
E(WSAENOBUFS, "No buffer space available"),
E(WSAEISCONN, "Socket is already connected"),
E(WSAENOTCONN, "Socket is not connected"),
E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
E(WSAETIMEDOUT, "Connection timed out"),
E(WSAECONNREFUSED, "Connection refused"),
E(WSAEHOSTDOWN, "Host is down"),
E(WSAEHOSTUNREACH, "No route to host"),
E(WSAEPROCLIM, "Too many processes"),
/* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
E(WSASYSNOTREADY, "Network subsystem is unavailable"),
E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
E(WSAEDISCON, "Graceful shutdown now in progress"),
#ifdef WSATYPE_NOT_FOUND
E(WSATYPE_NOT_FOUND, "Class type not found"),
#endif
E(WSAHOST_NOT_FOUND, "Host not found"),
E(WSATRY_AGAIN, "Nonauthoritative host not found"),
E(WSANO_RECOVERY, "This is a nonrecoverable error"),
E(WSANO_DATA, "Valid name, no data record of requested type)"),
/* There are some more error codes whose numeric values are marked
* <b>OS dependent</b>. They start with WSA_, apparently for the same
* reason that practitioners of some craft traditions deliberately
* introduce imperfections into their baskets and rugs "to allow the
* evil spirits to escape." If we catch them, then our binaries
* might not report consistent results across versions of Windows.
* Thus, I'm going to let them all fall through.
*/
{ -1, NULL },
};
/** There does not seem to be a strerror equivalent for Winsock errors.
* Naturally, we have to roll our own.
*/
const char *
tor_socket_strerror(int e)
{
int i;
for (i=0; windows_socket_errors[i].code >= 0; ++i) {
if (e == windows_socket_errors[i].code)
return windows_socket_errors[i].msg;
}
return strerror(e);
}
#endif /* defined(_WIN32) */
/** Called before we make any calls to network-related functions.
* (Some operating systems require their network libraries to be
* initialized.) */
int
network_init(void)
{
#ifdef _WIN32
/* This silly exercise is necessary before windows will allow
* gethostbyname to work. */
WSADATA WSAData;
int r;
r = WSAStartup(0x101,&WSAData);
if (r) {
log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
return -1;
}
if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
"might not work. (Sizes are %d and %d respectively.)",
(int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
}
/* WSAData.iMaxSockets might show the max sockets we're allowed to use.
* We might use it to complain if we're trying to be a server but have
* too few sockets available. */
#endif /* defined(_WIN32) */
return 0;
}
#ifdef _WIN32
/** Return a newly allocated string describing the windows system error code
* <b>err</b>. Note that error codes are different from errno. Error codes
* come from GetLastError() when a winapi call fails. errno is set only when
* ANSI functions fail. Whee. */
char *
format_win32_error(DWORD err)
{
TCHAR *str = NULL;
char *result;
DWORD n;
/* Somebody once decided that this interface was better than strerror(). */
n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, err,
MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
(LPVOID)&str,
0, NULL);
if (str && n) {
#ifdef UNICODE
size_t len;
if (n > 128*1024)
len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
* make sure. */
else
len = n * 2 + 1;
result = tor_malloc(len);
wcstombs(result,str,len);
result[len-1] = '\0';
#else /* !(defined(UNICODE)) */
result = tor_strdup(str);
#endif /* defined(UNICODE) */
} else {
result = tor_strdup("<unformattable error>");
}
if (str) {
LocalFree(str); /* LocalFree != free() */
}
return result;
}
#endif /* defined(_WIN32) */
#if defined(HW_PHYSMEM64)
/* This appears to be an OpenBSD thing */
#define INT64_HW_MEM HW_PHYSMEM64
#elif defined(HW_MEMSIZE)
/* OSX defines this one */
#define INT64_HW_MEM HW_MEMSIZE
#endif /* defined(HW_PHYSMEM64) || ... */
/**
* Helper: try to detect the total system memory, and return it. On failure,
* return 0.
*/
static uint64_t
get_total_system_memory_impl(void)
{
#if defined(__linux__)
/* On linux, sysctl is deprecated. Because proc is so awesome that you
* shouldn't _want_ to write portable code, I guess? */
unsigned long long result=0;
int fd = -1;
char *s = NULL;
const char *cp;
size_t file_size=0;
if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
return 0;
s = read_file_to_str_until_eof(fd, 65536, &file_size);
if (!s)
goto err;
cp = strstr(s, "MemTotal:");
if (!cp)
goto err;
/* Use the system sscanf so that space will match a wider number of space */
if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
goto err;
close(fd);
tor_free(s);
return result * 1024;
/* LCOV_EXCL_START Can't reach this unless proc is broken. */
err:
tor_free(s);
close(fd);
return 0;
/* LCOV_EXCL_STOP */
#elif defined (_WIN32)
/* Windows has MEMORYSTATUSEX; pretty straightforward. */
MEMORYSTATUSEX ms;
memset(&ms, 0, sizeof(ms));
ms.dwLength = sizeof(ms);
if (! GlobalMemoryStatusEx(&ms))
return 0;
return ms.ullTotalPhys;
#elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
/* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
* variant if we know about it. */
uint64_t memsize = 0;
size_t len = sizeof(memsize);
int mib[2] = {CTL_HW, INT64_HW_MEM};
if (sysctl(mib,2,&memsize,&len,NULL,0))
return 0;
return memsize;
#elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
/* On some systems (like FreeBSD I hope) you can use a size_t with
* HW_PHYSMEM. */
size_t memsize=0;
size_t len = sizeof(memsize);
int mib[2] = {CTL_HW, HW_USERMEM};
if (sysctl(mib,2,&memsize,&len,NULL,0))
return 0;
return memsize;
#else
/* I have no clue. */
return 0;
#endif /* defined(__linux__) || ... */
}
/**
* Try to find out how much physical memory the system has. On success,
* return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
*/
MOCK_IMPL(int,
get_total_system_memory, (size_t *mem_out))
{
static size_t mem_cached=0;
uint64_t m = get_total_system_memory_impl();
if (0 == m) {
/* LCOV_EXCL_START -- can't make this happen without mocking. */
/* We couldn't find our memory total */
if (0 == mem_cached) {
/* We have no cached value either */
*mem_out = 0;
return -1;
}
*mem_out = mem_cached;
return 0;
/* LCOV_EXCL_STOP */
}
#if SIZE_MAX != UINT64_MAX
if (m > SIZE_MAX) {
/* I think this could happen if we're a 32-bit Tor running on a 64-bit
* system: we could have more system memory than would fit in a
* size_t. */
m = SIZE_MAX;
}
#endif /* SIZE_MAX != UINT64_MAX */
*mem_out = mem_cached = (size_t) m;
return 0;
}
/** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
* bytes of passphrase into <b>output</b>. Return the number of bytes in
* the passphrase, excluding terminating NUL.
*/
ssize_t
tor_getpass(const char *prompt, char *output, size_t buflen)
{
tor_assert(buflen <= SSIZE_MAX);
tor_assert(buflen >= 1);
#if defined(HAVE_READPASSPHRASE)
char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
if (pwd == NULL)
return -1;
return strlen(pwd);
#elif defined(_WIN32)
int r = -1;
while (*prompt) {
_putch(*prompt++);
}
tor_assert(buflen <= INT_MAX);
wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
wchar_t *ptr = buf, *lastch = buf + buflen - 1;
while (ptr < lastch) {
wint_t ch = _getwch();
switch (ch) {
case '\r':
case '\n':
case WEOF:
goto done_reading;
case 3:
goto done; /* Can't actually read ctrl-c this way. */
case '\b':
if (ptr > buf)
--ptr;
continue;
case 0:
case 0xe0:
ch = _getwch(); /* Ignore; this is a function or arrow key */
break;
default:
*ptr++ = ch;
break;
}
}
done_reading:
;
#ifndef WC_ERR_INVALID_CHARS
#define WC_ERR_INVALID_CHARS 0x80
#endif
/* Now convert it to UTF-8 */
r = WideCharToMultiByte(CP_UTF8,
WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
buf, (int)(ptr-buf),
output, (int)(buflen-1),
NULL, NULL);
if (r <= 0) {
r = -1;
goto done;
}
tor_assert(r < (int)buflen);
output[r] = 0;
done:
SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
tor_free(buf);
return r;
#else
#error "No implementation for tor_getpass found!"
#endif /* defined(HAVE_READPASSPHRASE) || ... */
}
/** Return the amount of free disk space we have permission to use, in
* bytes. Return -1 if the amount of free space can't be determined. */
int64_t
tor_get_avail_disk_space(const char *path)
{
#ifdef HAVE_STATVFS
struct statvfs st;
int r;
memset(&st, 0, sizeof(st));
r = statvfs(path, &st);
if (r < 0)
return -1;
int64_t result = st.f_bavail;
if (st.f_frsize) {
result *= st.f_frsize;
} else if (st.f_bsize) {
result *= st.f_bsize;
} else {
return -1;
}
return result;
#elif defined(_WIN32)
ULARGE_INTEGER freeBytesAvail;
BOOL ok;
ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
if (!ok) {
return -1;
}
return (int64_t)freeBytesAvail.QuadPart;
#else
(void)path;
errno = ENOSYS;
return -1;
#endif /* defined(HAVE_STATVFS) || ... */
}
|