compat.h 25 KB

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