compat.h 26 KB

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