compat.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #ifndef TOR_COMPAT_H
  6. #define TOR_COMPAT_H
  7. #include "orconfig.h"
  8. #ifdef _WIN32
  9. #include <winsock2.h>
  10. #include <ws2tcpip.h>
  11. #endif
  12. #include "torint.h"
  13. #include "testsupport.h"
  14. #ifdef HAVE_SYS_PARAM_H
  15. #include <sys/param.h>
  16. #endif
  17. #ifdef HAVE_SYS_TYPES_H
  18. #include <sys/types.h>
  19. #endif
  20. #ifdef HAVE_SYS_TIME_H
  21. #include <sys/time.h>
  22. #endif
  23. #ifdef HAVE_TIME_H
  24. #include <time.h>
  25. #endif
  26. #ifdef HAVE_STRING_H
  27. #include <string.h>
  28. #endif
  29. #include <stdarg.h>
  30. #ifdef HAVE_SYS_RESOURCE_H
  31. #include <sys/resource.h>
  32. #endif
  33. #ifdef HAVE_SYS_SOCKET_H
  34. #include <sys/socket.h>
  35. #endif
  36. #ifdef HAVE_NETINET_IN_H
  37. #include <netinet/in.h>
  38. #endif
  39. #ifdef HAVE_NETINET6_IN6_H
  40. #include <netinet6/in6.h>
  41. #endif
  42. #if defined(__has_feature)
  43. # if __has_feature(address_sanitizer)
  44. /* Some of the fancy glibc strcmp() macros include references to memory that
  45. * clang rejects because it is off the end of a less-than-3. Clang hates this,
  46. * even though those references never actually happen. */
  47. # undef strcmp
  48. # endif
  49. #endif
  50. #include <stdio.h>
  51. #include <errno.h>
  52. #ifndef NULL_REP_IS_ZERO_BYTES
  53. #error "It seems your platform does not represent NULL as zero. We can't cope."
  54. #endif
  55. #ifndef DOUBLE_0_REP_IS_ZERO_BYTES
  56. #error "It seems your platform does not represent 0.0 as zeros. We can't cope."
  57. #endif
  58. #if 'a'!=97 || 'z'!=122 || 'A'!=65 || ' '!=32
  59. #error "It seems that you encode characters in something other than ASCII."
  60. #endif
  61. /* ===== Compiler compatibility */
  62. /* GCC can check printf and scanf types on arbitrary functions. */
  63. #ifdef __GNUC__
  64. #define CHECK_PRINTF(formatIdx, firstArg) \
  65. __attribute__ ((format(printf, formatIdx, firstArg)))
  66. #else
  67. #define CHECK_PRINTF(formatIdx, firstArg)
  68. #endif
  69. #ifdef __GNUC__
  70. #define CHECK_SCANF(formatIdx, firstArg) \
  71. __attribute__ ((format(scanf, formatIdx, firstArg)))
  72. #else
  73. #define CHECK_SCANF(formatIdx, firstArg)
  74. #endif
  75. /* inline is __inline on windows. */
  76. #ifdef _WIN32
  77. #define inline __inline
  78. #endif
  79. /* Try to get a reasonable __func__ substitute in place. */
  80. #if defined(_MSC_VER)
  81. #define __func__ __FUNCTION__
  82. #else
  83. /* For platforms where autoconf works, make sure __func__ is defined
  84. * sanely. */
  85. #ifndef HAVE_MACRO__func__
  86. #ifdef HAVE_MACRO__FUNCTION__
  87. #define __func__ __FUNCTION__
  88. #elif HAVE_MACRO__FUNC__
  89. #define __func__ __FUNC__
  90. #else
  91. #define __func__ "???"
  92. #endif
  93. #endif /* ifndef MAVE_MACRO__func__ */
  94. #endif /* if not windows */
  95. #define U64_TO_DBL(x) ((double) (x))
  96. #define DBL_TO_U64(x) ((uint64_t) (x))
  97. #ifdef ENUM_VALS_ARE_SIGNED
  98. #define ENUM_BF(t) unsigned
  99. #else
  100. /** Wrapper for having a bitfield of an enumerated type. Where possible, we
  101. * just use the enumerated type (so the compiler can help us and notice
  102. * problems), but if enumerated types are unsigned, we must use unsigned,
  103. * so that the loss of precision doesn't make large values negative. */
  104. #define ENUM_BF(t) t
  105. #endif
  106. /* GCC has several useful attributes. */
  107. #if defined(__GNUC__) && __GNUC__ >= 3
  108. #define ATTR_NORETURN __attribute__((noreturn))
  109. #define ATTR_CONST __attribute__((const))
  110. #define ATTR_MALLOC __attribute__((malloc))
  111. #define ATTR_NORETURN __attribute__((noreturn))
  112. #define ATTR_WUR __attribute__((warn_unused_result))
  113. /* Alas, nonnull is not at present a good idea for us. We'd like to get
  114. * warnings when we pass NULL where we shouldn't (which nonnull does, albeit
  115. * spottily), but we don't want to tell the compiler to make optimizations
  116. * with the assumption that the argument can't be NULL (since this would make
  117. * many of our checks go away, and make our code less robust against
  118. * programming errors). Unfortunately, nonnull currently does both of these
  119. * things, and there's no good way to split them up.
  120. *
  121. * #define ATTR_NONNULL(x) __attribute__((nonnull x)) */
  122. #define ATTR_NONNULL(x)
  123. #define ATTR_UNUSED __attribute__ ((unused))
  124. /** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
  125. * of <b>exp</b> will probably be true.
  126. *
  127. * In other words, "if (PREDICT_LIKELY(foo))" is the same as "if (foo)",
  128. * except that it tells the compiler that the branch will be taken most of the
  129. * time. This can generate slightly better code with some CPUs.
  130. */
  131. #define PREDICT_LIKELY(exp) __builtin_expect(!!(exp), 1)
  132. /** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
  133. * of <b>exp</b> will probably be false.
  134. *
  135. * In other words, "if (PREDICT_UNLIKELY(foo))" is the same as "if (foo)",
  136. * except that it tells the compiler that the branch will usually not be
  137. * taken. This can generate slightly better code with some CPUs.
  138. */
  139. #define PREDICT_UNLIKELY(exp) __builtin_expect(!!(exp), 0)
  140. #else
  141. #define ATTR_NORETURN
  142. #define ATTR_CONST
  143. #define ATTR_MALLOC
  144. #define ATTR_NORETURN
  145. #define ATTR_NONNULL(x)
  146. #define ATTR_UNUSED
  147. #define ATTR_WUR
  148. #define PREDICT_LIKELY(exp) (exp)
  149. #define PREDICT_UNLIKELY(exp) (exp)
  150. #endif
  151. /** Expands to a syntactically valid empty statement. */
  152. #define STMT_NIL (void)0
  153. /** Expands to a syntactically valid empty statement, explicitly (void)ing its
  154. * argument. */
  155. #define STMT_VOID(a) while (0) { (void)(a); }
  156. #ifdef __GNUC__
  157. /** STMT_BEGIN and STMT_END are used to wrap blocks inside macros so that
  158. * the macro can be used as if it were a single C statement. */
  159. #define STMT_BEGIN (void) ({
  160. #define STMT_END })
  161. #elif defined(sun) || defined(__sun__)
  162. #define STMT_BEGIN if (1) {
  163. #define STMT_END } else STMT_NIL
  164. #else
  165. #define STMT_BEGIN do {
  166. #define STMT_END } while (0)
  167. #endif
  168. /* Some tools (like coccinelle) don't like to see operators as macro
  169. * arguments. */
  170. #define OP_LT <
  171. #define OP_GT >
  172. #define OP_GE >=
  173. #define OP_LE <=
  174. #define OP_EQ ==
  175. #define OP_NE !=
  176. /* ===== String compatibility */
  177. #ifdef _WIN32
  178. /* Windows names string functions differently from most other platforms. */
  179. #define strncasecmp _strnicmp
  180. #define strcasecmp _stricmp
  181. #endif
  182. #if defined __APPLE__
  183. /* On OSX 10.9 and later, the overlap-checking code for strlcat would
  184. * appear to have a severe bug that can sometimes cause aborts in Tor.
  185. * Instead, use the non-checking variants. This is sad.
  186. *
  187. * See https://trac.torproject.org/projects/tor/ticket/15205
  188. */
  189. #undef strlcat
  190. #undef strlcpy
  191. #endif
  192. #ifndef HAVE_STRLCAT
  193. size_t strlcat(char *dst, const char *src, size_t siz) ATTR_NONNULL((1,2));
  194. #endif
  195. #ifndef HAVE_STRLCPY
  196. size_t strlcpy(char *dst, const char *src, size_t siz) ATTR_NONNULL((1,2));
  197. #endif
  198. #ifdef _MSC_VER
  199. /** Casts the uint64_t value in <b>a</b> to the right type for an argument
  200. * to printf. */
  201. #define U64_PRINTF_ARG(a) (a)
  202. /** Casts the uint64_t* value in <b>a</b> to the right type for an argument
  203. * to scanf. */
  204. #define U64_SCANF_ARG(a) (a)
  205. /** Expands to a literal uint64_t-typed constant for the value <b>n</b>. */
  206. #define U64_LITERAL(n) (n ## ui64)
  207. #define I64_PRINTF_ARG(a) (a)
  208. #define I64_SCANF_ARG(a) (a)
  209. #define I64_LITERAL(n) (n ## i64)
  210. #else
  211. #define U64_PRINTF_ARG(a) ((long long unsigned int)(a))
  212. #define U64_SCANF_ARG(a) ((long long unsigned int*)(a))
  213. #define U64_LITERAL(n) (n ## llu)
  214. #define I64_PRINTF_ARG(a) ((long long signed int)(a))
  215. #define I64_SCANF_ARG(a) ((long long signed int*)(a))
  216. #define I64_LITERAL(n) (n ## ll)
  217. #endif
  218. #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
  219. /** The formatting string used to put a uint64_t value in a printf() or
  220. * scanf() function. See also U64_PRINTF_ARG and U64_SCANF_ARG. */
  221. #define U64_FORMAT "%I64u"
  222. #define I64_FORMAT "%I64d"
  223. #else
  224. #define U64_FORMAT "%llu"
  225. #define I64_FORMAT "%lld"
  226. #endif
  227. #if (SIZEOF_INTPTR_T == SIZEOF_INT)
  228. #define INTPTR_T_FORMAT "%d"
  229. #define INTPTR_PRINTF_ARG(x) ((int)(x))
  230. #elif (SIZEOF_INTPTR_T == SIZEOF_LONG)
  231. #define INTPTR_T_FORMAT "%ld"
  232. #define INTPTR_PRINTF_ARG(x) ((long)(x))
  233. #elif (SIZEOF_INTPTR_T == 8)
  234. #define INTPTR_T_FORMAT I64_FORMAT
  235. #define INTPTR_PRINTF_ARG(x) I64_PRINTF_ARG(x)
  236. #else
  237. #error Unknown: SIZEOF_INTPTR_T
  238. #endif
  239. /** Represents an mmaped file. Allocated via tor_mmap_file; freed with
  240. * tor_munmap_file. */
  241. typedef struct tor_mmap_t {
  242. const char *data; /**< Mapping of the file's contents. */
  243. size_t size; /**< Size of the file. */
  244. /* None of the fields below should be accessed from outside compat.c */
  245. #ifdef HAVE_SYS_MMAN_H
  246. size_t mapping_size; /**< Size of the actual mapping. (This is this file
  247. * size, rounded up to the nearest page.) */
  248. #elif defined _WIN32
  249. HANDLE mmap_handle;
  250. #endif
  251. } tor_mmap_t;
  252. tor_mmap_t *tor_mmap_file(const char *filename) ATTR_NONNULL((1));
  253. int tor_munmap_file(tor_mmap_t *handle) ATTR_NONNULL((1));
  254. int tor_snprintf(char *str, size_t size, const char *format, ...)
  255. CHECK_PRINTF(3,4) ATTR_NONNULL((1,3));
  256. int tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  257. CHECK_PRINTF(3,0) ATTR_NONNULL((1,3));
  258. int tor_asprintf(char **strp, const char *fmt, ...)
  259. CHECK_PRINTF(2,3);
  260. int tor_vasprintf(char **strp, const char *fmt, va_list args)
  261. CHECK_PRINTF(2,0);
  262. const void *tor_memmem(const void *haystack, size_t hlen, const void *needle,
  263. size_t nlen) ATTR_NONNULL((1,3));
  264. static const void *tor_memstr(const void *haystack, size_t hlen,
  265. const char *needle) ATTR_NONNULL((1,3));
  266. static inline const void *
  267. tor_memstr(const void *haystack, size_t hlen, const char *needle)
  268. {
  269. return tor_memmem(haystack, hlen, needle, strlen(needle));
  270. }
  271. /* Much of the time when we're checking ctypes, we're doing spec compliance,
  272. * which all assumes we're doing ASCII. */
  273. #define DECLARE_CTYPE_FN(name) \
  274. static int TOR_##name(char c); \
  275. extern const uint32_t TOR_##name##_TABLE[]; \
  276. static inline int TOR_##name(char c) { \
  277. uint8_t u = c; \
  278. return !!(TOR_##name##_TABLE[(u >> 5) & 7] & (1u << (u & 31))); \
  279. }
  280. DECLARE_CTYPE_FN(ISALPHA)
  281. DECLARE_CTYPE_FN(ISALNUM)
  282. DECLARE_CTYPE_FN(ISSPACE)
  283. DECLARE_CTYPE_FN(ISDIGIT)
  284. DECLARE_CTYPE_FN(ISXDIGIT)
  285. DECLARE_CTYPE_FN(ISPRINT)
  286. DECLARE_CTYPE_FN(ISLOWER)
  287. DECLARE_CTYPE_FN(ISUPPER)
  288. extern const char TOR_TOUPPER_TABLE[];
  289. extern const char TOR_TOLOWER_TABLE[];
  290. #define TOR_TOLOWER(c) (TOR_TOLOWER_TABLE[(uint8_t)c])
  291. #define TOR_TOUPPER(c) (TOR_TOUPPER_TABLE[(uint8_t)c])
  292. char *tor_strtok_r_impl(char *str, const char *sep, char **lasts);
  293. #ifdef HAVE_STRTOK_R
  294. #define tor_strtok_r(str, sep, lasts) strtok_r(str, sep, lasts)
  295. #else
  296. #define tor_strtok_r(str, sep, lasts) tor_strtok_r_impl(str, sep, lasts)
  297. #endif
  298. #ifdef _WIN32
  299. #define SHORT_FILE__ (tor_fix_source_file(__FILE__))
  300. const char *tor_fix_source_file(const char *fname);
  301. #else
  302. #define SHORT_FILE__ (__FILE__)
  303. #define tor_fix_source_file(s) (s)
  304. #endif
  305. /* ===== Time compatibility */
  306. #if !defined(HAVE_GETTIMEOFDAY) && !defined(HAVE_STRUCT_TIMEVAL_TV_SEC)
  307. /** Implementation of timeval for platforms that don't have it. */
  308. struct timeval {
  309. time_t tv_sec;
  310. unsigned int tv_usec;
  311. };
  312. #endif
  313. void tor_gettimeofday(struct timeval *timeval);
  314. struct tm *tor_localtime_r(const time_t *timep, struct tm *result);
  315. struct tm *tor_gmtime_r(const time_t *timep, struct tm *result);
  316. #ifndef timeradd
  317. /** Replacement for timeradd on platforms that do not have it: sets tvout to
  318. * the sum of tv1 and tv2. */
  319. #define timeradd(tv1,tv2,tvout) \
  320. do { \
  321. (tvout)->tv_sec = (tv1)->tv_sec + (tv2)->tv_sec; \
  322. (tvout)->tv_usec = (tv1)->tv_usec + (tv2)->tv_usec; \
  323. if ((tvout)->tv_usec >= 1000000) { \
  324. (tvout)->tv_usec -= 1000000; \
  325. (tvout)->tv_sec++; \
  326. } \
  327. } while (0)
  328. #endif
  329. #ifndef timersub
  330. /** Replacement for timersub on platforms that do not have it: sets tvout to
  331. * tv1 minus tv2. */
  332. #define timersub(tv1,tv2,tvout) \
  333. do { \
  334. (tvout)->tv_sec = (tv1)->tv_sec - (tv2)->tv_sec; \
  335. (tvout)->tv_usec = (tv1)->tv_usec - (tv2)->tv_usec; \
  336. if ((tvout)->tv_usec < 0) { \
  337. (tvout)->tv_usec += 1000000; \
  338. (tvout)->tv_sec--; \
  339. } \
  340. } while (0)
  341. #endif
  342. #ifndef timercmp
  343. /** Replacement for timersub on platforms that do not have it: returns true
  344. * iff the relational operator "op" makes the expression tv1 op tv2 true.
  345. *
  346. * Note that while this definition should work for all boolean opeators, some
  347. * platforms' native timercmp definitions do not support >=, <=, or ==. So
  348. * don't use those.
  349. */
  350. #define timercmp(tv1,tv2,op) \
  351. (((tv1)->tv_sec == (tv2)->tv_sec) ? \
  352. ((tv1)->tv_usec op (tv2)->tv_usec) : \
  353. ((tv1)->tv_sec op (tv2)->tv_sec))
  354. #endif
  355. /* ===== File compatibility */
  356. int tor_open_cloexec(const char *path, int flags, unsigned mode);
  357. FILE *tor_fopen_cloexec(const char *path, const char *mode);
  358. int tor_rename(const char *path_old, const char *path_new);
  359. int replace_file(const char *from, const char *to);
  360. int touch_file(const char *fname);
  361. typedef struct tor_lockfile_t tor_lockfile_t;
  362. tor_lockfile_t *tor_lockfile_lock(const char *filename, int blocking,
  363. int *locked_out);
  364. void tor_lockfile_unlock(tor_lockfile_t *lockfile);
  365. off_t tor_fd_getpos(int fd);
  366. int tor_fd_setpos(int fd, off_t pos);
  367. int tor_fd_seekend(int fd);
  368. int tor_ftruncate(int fd);
  369. int64_t tor_get_avail_disk_space(const char *path);
  370. #ifdef _WIN32
  371. #define PATH_SEPARATOR "\\"
  372. #else
  373. #define PATH_SEPARATOR "/"
  374. #endif
  375. /* ===== Net compatibility */
  376. #if (SIZEOF_SOCKLEN_T == 0)
  377. typedef int socklen_t;
  378. #endif
  379. #ifdef _WIN32
  380. /* XXX Actually, this should arguably be SOCKET; we use intptr_t here so that
  381. * any inadvertant checks for the socket being <= 0 or > 0 will probably
  382. * still work. */
  383. #define tor_socket_t intptr_t
  384. #define TOR_SOCKET_T_FORMAT INTPTR_T_FORMAT
  385. #define SOCKET_OK(s) ((SOCKET)(s) != INVALID_SOCKET)
  386. #define TOR_INVALID_SOCKET INVALID_SOCKET
  387. #else
  388. /** Type used for a network socket. */
  389. #define tor_socket_t int
  390. #define TOR_SOCKET_T_FORMAT "%d"
  391. /** Macro: true iff 's' is a possible value for a valid initialized socket. */
  392. #define SOCKET_OK(s) ((s) >= 0)
  393. /** Error/uninitialized value for a tor_socket_t. */
  394. #define TOR_INVALID_SOCKET (-1)
  395. #endif
  396. int tor_close_socket_simple(tor_socket_t s);
  397. int tor_close_socket(tor_socket_t s);
  398. tor_socket_t tor_open_socket_with_extensions(
  399. int domain, int type, int protocol,
  400. int cloexec, int nonblock);
  401. MOCK_DECL(tor_socket_t,
  402. tor_open_socket,(int domain, int type, int protocol));
  403. tor_socket_t tor_open_socket_nonblocking(int domain, int type, int protocol);
  404. tor_socket_t tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr,
  405. socklen_t *len);
  406. tor_socket_t tor_accept_socket_nonblocking(tor_socket_t sockfd,
  407. struct sockaddr *addr,
  408. socklen_t *len);
  409. tor_socket_t tor_accept_socket_with_extensions(tor_socket_t sockfd,
  410. struct sockaddr *addr,
  411. socklen_t *len,
  412. int cloexec, int nonblock);
  413. MOCK_DECL(tor_socket_t,
  414. tor_connect_socket,(tor_socket_t socket,const struct sockaddr *address,
  415. socklen_t address_len));
  416. int get_n_open_sockets(void);
  417. MOCK_DECL(int,
  418. tor_getsockname,(tor_socket_t socket, struct sockaddr *address,
  419. socklen_t *address_len));
  420. #define tor_socket_send(s, buf, len, flags) send(s, buf, len, flags)
  421. #define tor_socket_recv(s, buf, len, flags) recv(s, buf, len, flags)
  422. /** Implementation of struct in6_addr for platforms that do not have it.
  423. * Generally, these platforms are ones without IPv6 support, but we want to
  424. * have a working in6_addr there anyway, so we can use it to parse IPv6
  425. * addresses. */
  426. #if !defined(HAVE_STRUCT_IN6_ADDR)
  427. struct in6_addr
  428. {
  429. union {
  430. uint8_t u6_addr8[16];
  431. uint16_t u6_addr16[8];
  432. uint32_t u6_addr32[4];
  433. } in6_u;
  434. #define s6_addr in6_u.u6_addr8
  435. #define s6_addr16 in6_u.u6_addr16
  436. #define s6_addr32 in6_u.u6_addr32
  437. };
  438. #endif
  439. /** @{ */
  440. /** Many BSD variants seem not to define these. */
  441. #if defined(__APPLE__) || defined(__darwin__) || defined(__FreeBSD__) \
  442. || defined(__NetBSD__) || defined(__OpenBSD__)
  443. #ifndef s6_addr16
  444. #define s6_addr16 __u6_addr.__u6_addr16
  445. #endif
  446. #ifndef s6_addr32
  447. #define s6_addr32 __u6_addr.__u6_addr32
  448. #endif
  449. #endif
  450. /** @} */
  451. #ifndef HAVE_SA_FAMILY_T
  452. typedef uint16_t sa_family_t;
  453. #endif
  454. /** @{ */
  455. /** Apparently, MS and Solaris don't define s6_addr16 or s6_addr32; these
  456. * macros get you a pointer to s6_addr32 or local equivalent. */
  457. #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR32
  458. #define S6_ADDR32(x) ((uint32_t*)(x).s6_addr32)
  459. #else
  460. #define S6_ADDR32(x) ((uint32_t*)((char*)&(x).s6_addr))
  461. #endif
  462. #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR16
  463. #define S6_ADDR16(x) ((uint16_t*)(x).s6_addr16)
  464. #else
  465. #define S6_ADDR16(x) ((uint16_t*)((char*)&(x).s6_addr))
  466. #endif
  467. /** @} */
  468. /** Implementation of struct sockaddr_in6 on platforms that do not have
  469. * it. See notes on struct in6_addr. */
  470. #if !defined(HAVE_STRUCT_SOCKADDR_IN6)
  471. struct sockaddr_in6 {
  472. sa_family_t sin6_family;
  473. uint16_t sin6_port;
  474. // uint32_t sin6_flowinfo;
  475. struct in6_addr sin6_addr;
  476. // uint32_t sin6_scope_id;
  477. };
  478. #endif
  479. MOCK_DECL(int,tor_gethostname,(char *name, size_t namelen));
  480. int tor_inet_aton(const char *cp, struct in_addr *addr) ATTR_NONNULL((1,2));
  481. const char *tor_inet_ntop(int af, const void *src, char *dst, size_t len);
  482. int tor_inet_pton(int af, const char *src, void *dst);
  483. MOCK_DECL(int,tor_lookup_hostname,(const char *name, uint32_t *addr));
  484. int set_socket_nonblocking(tor_socket_t socket);
  485. int tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2]);
  486. int network_init(void);
  487. /* For stupid historical reasons, windows sockets have an independent
  488. * set of errnos, and an independent way to get them. Also, you can't
  489. * always believe WSAEWOULDBLOCK. Use the macros below to compare
  490. * errnos against expected values, and use tor_socket_errno to find
  491. * the actual errno after a socket operation fails.
  492. */
  493. #if defined(_WIN32)
  494. /** Expands to WSA<b>e</b> on Windows, and to <b>e</b> elsewhere. */
  495. #define SOCK_ERRNO(e) WSA##e
  496. /** Return true if e is EAGAIN or the local equivalent. */
  497. #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == WSAEWOULDBLOCK)
  498. /** Return true if e is EINPROGRESS or the local equivalent. */
  499. #define ERRNO_IS_EINPROGRESS(e) ((e) == WSAEINPROGRESS)
  500. /** Return true if e is EINPROGRESS or the local equivalent as returned by
  501. * a call to connect(). */
  502. #define ERRNO_IS_CONN_EINPROGRESS(e) \
  503. ((e) == WSAEINPROGRESS || (e)== WSAEINVAL || (e) == WSAEWOULDBLOCK)
  504. /** Return true if e is EAGAIN or another error indicating that a call to
  505. * accept() has no pending connections to return. */
  506. #define ERRNO_IS_ACCEPT_EAGAIN(e) ERRNO_IS_EAGAIN(e)
  507. /** Return true if e is EMFILE or another error indicating that a call to
  508. * accept() has failed because we're out of fds or something. */
  509. #define ERRNO_IS_RESOURCE_LIMIT(e) \
  510. ((e) == WSAEMFILE || (e) == WSAENOBUFS)
  511. /** Return true if e is EADDRINUSE or the local equivalent. */
  512. #define ERRNO_IS_EADDRINUSE(e) ((e) == WSAEADDRINUSE)
  513. /** Return true if e is EINTR or the local equivalent */
  514. #define ERRNO_IS_EINTR(e) ((e) == WSAEINTR || 0)
  515. int tor_socket_errno(tor_socket_t sock);
  516. const char *tor_socket_strerror(int e);
  517. #else
  518. #define SOCK_ERRNO(e) e
  519. #if EAGAIN == EWOULDBLOCK
  520. /* || 0 is for -Wparentheses-equality (-Wall?) appeasement under clang */
  521. #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || 0)
  522. #else
  523. #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == EWOULDBLOCK)
  524. #endif
  525. #define ERRNO_IS_EINTR(e) ((e) == EINTR || 0)
  526. #define ERRNO_IS_EINPROGRESS(e) ((e) == EINPROGRESS || 0)
  527. #define ERRNO_IS_CONN_EINPROGRESS(e) ((e) == EINPROGRESS || 0)
  528. #define ERRNO_IS_ACCEPT_EAGAIN(e) \
  529. (ERRNO_IS_EAGAIN(e) || (e) == ECONNABORTED)
  530. #define ERRNO_IS_RESOURCE_LIMIT(e) \
  531. ((e) == EMFILE || (e) == ENFILE || (e) == ENOBUFS || (e) == ENOMEM)
  532. #define ERRNO_IS_EADDRINUSE(e) (((e) == EADDRINUSE) || 0)
  533. #define tor_socket_errno(sock) (errno)
  534. #define tor_socket_strerror(e) strerror(e)
  535. #endif
  536. /** Specified SOCKS5 status codes. */
  537. typedef enum {
  538. SOCKS5_SUCCEEDED = 0x00,
  539. SOCKS5_GENERAL_ERROR = 0x01,
  540. SOCKS5_NOT_ALLOWED = 0x02,
  541. SOCKS5_NET_UNREACHABLE = 0x03,
  542. SOCKS5_HOST_UNREACHABLE = 0x04,
  543. SOCKS5_CONNECTION_REFUSED = 0x05,
  544. SOCKS5_TTL_EXPIRED = 0x06,
  545. SOCKS5_COMMAND_NOT_SUPPORTED = 0x07,
  546. SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
  547. } socks5_reply_status_t;
  548. /* ===== OS compatibility */
  549. MOCK_DECL(const char *, get_uname, (void));
  550. uint16_t get_uint16(const void *cp) ATTR_NONNULL((1));
  551. uint32_t get_uint32(const void *cp) ATTR_NONNULL((1));
  552. uint64_t get_uint64(const void *cp) ATTR_NONNULL((1));
  553. void set_uint16(void *cp, uint16_t v) ATTR_NONNULL((1));
  554. void set_uint32(void *cp, uint32_t v) ATTR_NONNULL((1));
  555. void set_uint64(void *cp, uint64_t v) ATTR_NONNULL((1));
  556. /* These uint8 variants are defined to make the code more uniform. */
  557. #define get_uint8(cp) (*(const uint8_t*)(cp))
  558. static void set_uint8(void *cp, uint8_t v);
  559. static inline void
  560. set_uint8(void *cp, uint8_t v)
  561. {
  562. *(uint8_t*)cp = v;
  563. }
  564. #if !defined(HAVE_RLIM_T)
  565. typedef unsigned long rlim_t;
  566. #endif
  567. int get_max_sockets(void);
  568. int set_max_file_descriptors(rlim_t limit, int *max);
  569. int tor_disable_debugger_attach(void);
  570. #if defined(HAVE_SYS_CAPABILITY_H) && defined(HAVE_CAP_SET_PROC)
  571. #define HAVE_LINUX_CAPABILITIES
  572. #endif
  573. int have_capability_support(void);
  574. /** Flag for switch_id; see switch_id() for documentation */
  575. #define SWITCH_ID_KEEP_BINDLOW (1<<0)
  576. /** Flag for switch_id; see switch_id() for documentation */
  577. #define SWITCH_ID_WARN_IF_NO_CAPS (1<<1)
  578. int switch_id(const char *user, unsigned flags);
  579. #ifdef HAVE_PWD_H
  580. char *get_user_homedir(const char *username);
  581. #endif
  582. #ifndef _WIN32
  583. const struct passwd *tor_getpwnam(const char *username);
  584. const struct passwd *tor_getpwuid(uid_t uid);
  585. #endif
  586. int get_parent_directory(char *fname);
  587. char *make_path_absolute(char *fname);
  588. char **get_environment(void);
  589. int get_total_system_memory(size_t *mem_out);
  590. int compute_num_cpus(void);
  591. int tor_mlockall(void);
  592. /** Macros for MIN/MAX. Never use these when the arguments could have
  593. * side-effects.
  594. * {With GCC extensions we could probably define a safer MIN/MAX. But
  595. * depending on that safety would be dangerous, since not every platform
  596. * has it.}
  597. **/
  598. #ifndef MAX
  599. #define MAX(a,b) ( ((a)<(b)) ? (b) : (a) )
  600. #endif
  601. #ifndef MIN
  602. #define MIN(a,b) ( ((a)>(b)) ? (b) : (a) )
  603. #endif
  604. /* Platform-specific helpers. */
  605. #ifdef _WIN32
  606. char *format_win32_error(DWORD err);
  607. #endif
  608. /*for some reason my compiler doesn't have these version flags defined
  609. a nice homework assignment for someone one day is to define the rest*/
  610. //these are the values as given on MSDN
  611. #ifdef _WIN32
  612. #ifndef VER_SUITE_EMBEDDEDNT
  613. #define VER_SUITE_EMBEDDEDNT 0x00000040
  614. #endif
  615. #ifndef VER_SUITE_SINGLEUSERTS
  616. #define VER_SUITE_SINGLEUSERTS 0x00000100
  617. #endif
  618. #endif
  619. #ifdef TOR_UNIT_TESTS
  620. void tor_sleep_msec(int msec);
  621. #endif
  622. #ifdef COMPAT_PRIVATE
  623. #if !defined(HAVE_SOCKETPAIR) || defined(_WIN32) || defined(TOR_UNIT_TESTS)
  624. #define NEED_ERSATZ_SOCKETPAIR
  625. STATIC int tor_ersatz_socketpair(int family, int type, int protocol,
  626. tor_socket_t fd[2]);
  627. #endif
  628. #endif
  629. ssize_t tor_getpass(const char *prompt, char *output, size_t buflen);
  630. /* This needs some of the declarations above so we include it here. */
  631. #include "compat_threads.h"
  632. #endif