compat.h 26 KB

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