1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
12 #define WIN32_WINNT 0x400
13 #define _WIN32_WINNT 0x400
14 #define WIN32_LEAN_AND_MEAN
15 #if defined(_MSC_VER) && (_MSC_VER < 1300)
22 #ifdef HAVE_SYS_TYPES_H
23 #include <sys/types.h>
25 #ifdef HAVE_SYS_TIME_H
38 #ifdef HAVE_SYS_RESOURCE_H
39 #include <sys/resource.h>
41 #ifdef HAVE_SYS_SOCKET_H
42 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
47 #ifdef HAVE_NETINET_IN_H
48 #include <netinet/in.h>
50 #ifdef HAVE_NETINET6_IN6_H
51 #include <netinet6/in6.h>
54 #ifndef NULL_REP_IS_ZERO_BYTES
55 #error "It seems your platform does not represent NULL as zero. We can't cope."
58 #if 'a'!=97 || 'z'!=122 || 'A'!=65 || ' '!=32
59 #error "It seems that you encode characters in something other than ASCII."
62 /* ===== Compiler compatibility */
64 /* GCC can check printf types on arbitrary functions. */
66 #define CHECK_PRINTF(formatIdx, firstArg) \
67 __attribute__ ((format(printf, formatIdx, firstArg)))
69 #define CHECK_PRINTF(formatIdx, firstArg)
72 /* inline is __inline on windows. */
74 #define INLINE __inline
79 /* Try to get a reasonable __func__ substitute in place. */
81 /* MSVC compilers before VC7 don't have __func__ at all; later ones call it
84 #define __func__ "???"
86 #define __func__ __FUNCTION__
90 /* For platforms where autoconf works, make sure __func__ is defined
92 #ifndef HAVE_MACRO__func__
93 #ifdef HAVE_MACRO__FUNCTION__
94 #define __func__ __FUNCTION__
95 #elif HAVE_MACRO__FUNC__
96 #define __func__ __FUNC__
98 #define __func__ "???"
100 #endif /* ifndef MAVE_MACRO__func__ */
101 #endif /* if not windows */
103 #if defined(_MSC_VER) && (_MSC_VER < 1300)
104 /* MSVC versions before 7 apparently don't believe that you can cast uint64_t
105 * to double and really mean it. */
106 extern INLINE
double U64_TO_DBL(uint64_t x
) {
107 int64_t i
= (int64_t) x
;
108 return (i
< 0) ? ((double) INT64_MAX
) : (double) i
;
110 #define DBL_TO_U64(x) ((uint64_t)(int64_t) (x))
112 #define U64_TO_DBL(x) ((double) (x))
113 #define DBL_TO_U64(x) ((uint64_t) (x))
116 /* GCC has several useful attributes. */
117 #if defined(__GNUC__) && __GNUC__ >= 3
118 #define ATTR_NORETURN __attribute__((noreturn))
119 #define ATTR_PURE __attribute__((pure))
120 #define ATTR_CONST __attribute__((const))
121 #define ATTR_MALLOC __attribute__((malloc))
122 #define ATTR_NORETURN __attribute__((noreturn))
123 /* Alas, nonnull is not at present a good idea for us. We'd like to get
124 * warnings when we pass NULL where we shouldn't (which nonnull does, albeit
125 * spottily), but we don't want to tell the compiler to make optimizations
126 * with the assumption that the argument can't be NULL (since this would make
127 * many of our checks go away, and make our code less robust against
128 * programming errors). Unfortunately, nonnull currently does both of these
129 * things, and there's no good way to split them up.
131 * #define ATTR_NONNULL(x) __attribute__((nonnull x)) */
132 #define ATTR_NONNULL(x)
134 /** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
135 * of <b>exp</b> will probably be true.
137 * In other words, "if (PREDICT_LIKELY(foo))" is the same as "if (foo)",
138 * except that it tells the compiler that the branch will be taken most of the
139 * time. This can generate slightly better code with some CPUs.
141 #define PREDICT_LIKELY(exp) __builtin_expect(!!(exp), 1)
142 /** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
143 * of <b>exp</b> will probably be false.
145 * In other words, "if (PREDICT_UNLIKELY(foo))" is the same as "if (foo)",
146 * except that it tells the compiler that the branch will usually not be
147 * taken. This can generate slightly better code with some CPUs.
149 #define PREDICT_UNLIKELY(exp) __builtin_expect(!!(exp), 0)
151 #define ATTR_NORETURN
155 #define ATTR_NORETURN
156 #define ATTR_NONNULL(x)
157 #define PREDICT_LIKELY(exp) (exp)
158 #define PREDICT_UNLIKELY(exp) (exp)
161 /** Expands to a syntactically valid empty statement. */
162 #define STMT_NIL (void)0
165 /** STMT_BEGIN and STMT_END are used to wrap blocks inside macros so that
166 * the macro can be used as if it were a single C statement. */
167 #define STMT_BEGIN (void) ({
169 #elif defined(sun) || defined(__sun__)
170 #define STMT_BEGIN if (1) {
171 #define STMT_END } else STMT_NIL
173 #define STMT_BEGIN do {
174 #define STMT_END } while (0)
177 /* ===== String compatibility */
179 /* Windows names string functions differently from most other platforms. */
180 #define strncasecmp strnicmp
181 #define strcasecmp stricmp
184 size_t strlcat(char *dst
, const char *src
, size_t siz
) ATTR_NONNULL((1,2));
187 size_t strlcpy(char *dst
, const char *src
, size_t siz
) ATTR_NONNULL((1,2));
191 /** Casts the uint64_t value in <b>a</b> to the right type for an argument
193 #define U64_PRINTF_ARG(a) (a)
194 /** Casts the uint64_t* value in <b>a</b> to the right type for an argument
196 #define U64_SCANF_ARG(a) (a)
197 /** Expands to a literal uint64_t-typed constant for the value <b>n</b>. */
198 #define U64_LITERAL(n) (n ## ui64)
200 #define U64_PRINTF_ARG(a) ((long long unsigned int)(a))
201 #define U64_SCANF_ARG(a) ((long long unsigned int*)(a))
202 #define U64_LITERAL(n) (n ## llu)
205 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
206 /** The formatting string used to put a uint64_t value in a printf() or
207 * scanf() function. See also U64_PRINTF_ARG and U64_SCANF_ARG. */
208 #define U64_FORMAT "%I64u"
210 #define U64_FORMAT "%llu"
213 /** Represents an mmaped file. Allocated via tor_mmap_file; freed with
214 * tor_munmap_file. */
215 typedef struct tor_mmap_t
{
216 const char *data
; /**< Mapping of the file's contents. */
217 size_t size
; /**< Size of the file. */
219 /* None of the fields below should be accessed from outside compat.c */
220 #ifdef HAVE_SYS_MMAN_H
221 size_t mapping_size
; /**< Size of the actual mapping. (This is this file
222 * size, rounded up to the nearest page.) */
223 #elif defined MS_WINDOWS
230 tor_mmap_t
*tor_mmap_file(const char *filename
) ATTR_NONNULL((1));
231 void tor_munmap_file(tor_mmap_t
*handle
) ATTR_NONNULL((1));
233 int tor_snprintf(char *str
, size_t size
, const char *format
, ...)
234 CHECK_PRINTF(3,4) ATTR_NONNULL((1,3));
235 int tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
238 const void *tor_memmem(const void *haystack
, size_t hlen
, const void *needle
,
239 size_t nlen
) ATTR_PURE
ATTR_NONNULL((1,3));
240 static const void *tor_memstr(const void *haystack
, size_t hlen
,
241 const char *needle
) ATTR_PURE
ATTR_NONNULL((1,3));
242 static INLINE
const void *
243 tor_memstr(const void *haystack
, size_t hlen
, const char *needle
)
245 return tor_memmem(haystack
, hlen
, needle
, strlen(needle
));
248 /* Much of the time when we're checking ctypes, we're doing spec compliance,
249 * which all assumes we're doing ASCII. */
250 #define DECLARE_CTYPE_FN(name) \
251 static int TOR_##name(char c); \
252 extern const uint32_t TOR_##name##_TABLE[]; \
253 static INLINE int TOR_##name(char c) { \
255 return !!(TOR_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
257 DECLARE_CTYPE_FN(ISALPHA
)
258 DECLARE_CTYPE_FN(ISALNUM
)
259 DECLARE_CTYPE_FN(ISSPACE
)
260 DECLARE_CTYPE_FN(ISDIGIT
)
261 DECLARE_CTYPE_FN(ISXDIGIT
)
262 DECLARE_CTYPE_FN(ISPRINT
)
263 DECLARE_CTYPE_FN(ISLOWER
)
264 DECLARE_CTYPE_FN(ISUPPER
)
265 extern const char TOR_TOUPPER_TABLE
[];
266 extern const char TOR_TOLOWER_TABLE
[];
267 #define TOR_TOLOWER(c) (TOR_TOLOWER_TABLE[(uint8_t)c])
268 #define TOR_TOUPPER(c) (TOR_TOUPPER_TABLE[(uint8_t)c])
271 #define _SHORT_FILE_ (tor_fix_source_file(__FILE__))
272 const char *tor_fix_source_file(const char *fname
);
274 #define _SHORT_FILE_ (__FILE__)
275 #define tor_fix_source_file(s) (s)
278 /* ===== Time compatibility */
279 #if !defined(HAVE_GETTIMEOFDAY) && !defined(HAVE_STRUCT_TIMEVAL_TV_SEC)
282 unsigned int tv_usec
;
286 void tor_gettimeofday(struct timeval
*timeval
);
288 #ifdef HAVE_LOCALTIME_R
289 #define tor_localtime_r localtime_r
291 struct tm
*tor_localtime_r(const time_t *timep
, struct tm
*result
);
295 #define tor_gmtime_r gmtime_r
297 struct tm
*tor_gmtime_r(const time_t *timep
, struct tm
*result
);
300 /* ===== File compatibility */
301 int replace_file(const char *from
, const char *to
);
302 int touch_file(const char *fname
);
304 typedef struct tor_lockfile_t tor_lockfile_t
;
305 tor_lockfile_t
*tor_lockfile_lock(const char *filename
, int blocking
,
307 void tor_lockfile_unlock(tor_lockfile_t
*lockfile
);
309 off_t
tor_fd_getpos(int fd
);
310 int tor_fd_seekend(int fd
);
313 #define PATH_SEPARATOR "\\"
315 #define PATH_SEPARATOR "/"
318 /* ===== Net compatibility */
320 #if (SIZEOF_SOCKLEN_T == 0)
321 typedef int socklen_t
;
324 int tor_close_socket(int s
);
325 int tor_open_socket(int domain
, int type
, int protocol
);
326 int tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
);
327 int get_n_open_sockets(void);
329 #define tor_socket_send(s, buf, len, flags) send(s, buf, len, flags)
330 #define tor_socket_recv(s, buf, len, flags) recv(s, buf, len, flags)
332 /* Define struct in6_addr on platforms that do not have it. Generally,
333 * these platforms are ones without IPv6 support, but we want to have
334 * a working in6_addr there anyway, so we can use it to parse IPv6
336 #if !defined(HAVE_STRUCT_IN6_ADDR)
340 uint8_t u6_addr8
[16];
341 uint16_t u6_addr16
[8];
342 uint32_t u6_addr32
[4];
344 #define s6_addr in6_u.u6_addr8
345 #define s6_addr16 in6_u.u6_addr16
346 #define s6_addr32 in6_u.u6_addr32
350 #if defined(__APPLE__) || defined(__darwin__) || defined(__FreeBSD__) \
351 || defined(__NetBSD__) || defined(__OpenBSD__)
352 /* Many BSD variants seem not to define these. */
354 #define s6_addr16 __u6_addr.__u6_addr16
357 #define s6_addr32 __u6_addr.__u6_addr32
361 #ifndef HAVE_SA_FAMILY_T
362 typedef uint16_t sa_family_t
;
365 /* Apparently, MS and Solaris don't define s6_addr16 or s6_addr32. */
366 #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR32
367 #define S6_ADDR32(x) ((uint32_t*)(x).s6_addr32)
369 #define S6_ADDR32(x) ((uint32_t*)((char*)&(x).s6_addr))
371 #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR16
372 #define S6_ADDR16(x) ((uint16_t*)(x).s6_addr16)
374 #define S6_ADDR16(x) ((uint16_t*)((char*)&(x).s6_addr))
377 /* Define struct sockaddr_in6 on platforms that do not have it. See notes
378 * on struct in6_addr. */
379 #if !defined(HAVE_STRUCT_SOCKADDR_IN6)
380 struct sockaddr_in6
{
381 sa_family_t sin6_family
;
383 // uint32_t sin6_flowinfo;
384 struct in6_addr sin6_addr
;
385 // uint32_t sin6_scope_id;
389 int tor_inet_aton(const char *cp
, struct in_addr
*addr
) ATTR_NONNULL((1,2));
390 const char *tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
);
391 int tor_inet_pton(int af
, const char *src
, void *dst
);
392 int tor_lookup_hostname(const char *name
, uint32_t *addr
) ATTR_NONNULL((1,2));
393 void set_socket_nonblocking(int socket
);
394 int tor_socketpair(int family
, int type
, int protocol
, int fd
[2]);
395 int network_init(void);
397 /* For stupid historical reasons, windows sockets have an independent
398 * set of errnos, and an independent way to get them. Also, you can't
399 * always believe WSAEWOULDBLOCK. Use the macros below to compare
400 * errnos against expected values, and use tor_socket_errno to find
401 * the actual errno after a socket operation fails.
403 #if defined(MS_WINDOWS)
404 /** Return true if e is EAGAIN or the local equivalent. */
405 #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == WSAEWOULDBLOCK)
406 /** Return true if e is EINPROGRESS or the local equivalent. */
407 #define ERRNO_IS_EINPROGRESS(e) ((e) == WSAEINPROGRESS)
408 /** Return true if e is EINPROGRESS or the local equivalent as returned by
409 * a call to connect(). */
410 #define ERRNO_IS_CONN_EINPROGRESS(e) \
411 ((e) == WSAEINPROGRESS || (e)== WSAEINVAL || (e) == WSAEWOULDBLOCK)
412 /** Return true if e is EAGAIN or another error indicating that a call to
413 * accept() has no pending connections to return. */
414 #define ERRNO_IS_ACCEPT_EAGAIN(e) ERRNO_IS_EAGAIN(e)
415 /** Return true if e is EMFILE or another error indicating that a call to
416 * accept() has failed because we're out of fds or something. */
417 #define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
418 ((e) == WSAEMFILE || (e) == WSAENOBUFS)
419 /** Return true if e is EADDRINUSE or the local equivalent. */
420 #define ERRNO_IS_EADDRINUSE(e) ((e) == WSAEADDRINUSE)
421 int tor_socket_errno(int sock
);
422 const char *tor_socket_strerror(int e
);
424 #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN)
425 #define ERRNO_IS_EINPROGRESS(e) ((e) == EINPROGRESS)
426 #define ERRNO_IS_CONN_EINPROGRESS(e) ((e) == EINPROGRESS)
427 #define ERRNO_IS_ACCEPT_EAGAIN(e) ((e) == EAGAIN || (e) == ECONNABORTED)
428 #define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
429 ((e) == EMFILE || (e) == ENFILE || (e) == ENOBUFS || (e) == ENOMEM)
430 #define ERRNO_IS_EADDRINUSE(e) ((e) == EADDRINUSE)
431 #define tor_socket_errno(sock) (errno)
432 #define tor_socket_strerror(e) strerror(e)
435 /** Specified SOCKS5 status codes. */
437 SOCKS5_SUCCEEDED
= 0x00,
438 SOCKS5_GENERAL_ERROR
= 0x01,
439 SOCKS5_NOT_ALLOWED
= 0x02,
440 SOCKS5_NET_UNREACHABLE
= 0x03,
441 SOCKS5_HOST_UNREACHABLE
= 0x04,
442 SOCKS5_CONNECTION_REFUSED
= 0x05,
443 SOCKS5_TTL_EXPIRED
= 0x06,
444 SOCKS5_COMMAND_NOT_SUPPORTED
= 0x07,
445 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED
= 0x08,
446 } socks5_reply_status_t
;
448 /* ===== OS compatibility */
449 const char *get_uname(void);
451 uint16_t get_uint16(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
452 uint32_t get_uint32(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
453 uint64_t get_uint64(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
454 void set_uint16(char *cp
, uint16_t v
) ATTR_NONNULL((1));
455 void set_uint32(char *cp
, uint32_t v
) ATTR_NONNULL((1));
456 void set_uint64(char *cp
, uint64_t v
) ATTR_NONNULL((1));
458 /* These uint8 variants are defined to make the code more uniform. */
459 #define get_uint8(cp) (*(const uint8_t*)(cp))
460 static void set_uint8(char *cp
, uint8_t v
);
462 set_uint8(char *cp
, uint8_t v
)
467 #if !defined(HAVE_RLIM_T)
468 typedef unsigned long rlim_t
;
470 int set_max_file_descriptors(rlim_t limit
, int *max
);
471 int switch_id(const char *user
);
473 char *get_user_homedir(const char *username
);
476 int spawn_func(void (*func
)(void *), void *data
);
477 void spawn_exit(void) ATTR_NORETURN
;
479 #if defined(ENABLE_THREADS) && defined(MS_WINDOWS)
480 #define USE_WIN32_THREADS
481 #define TOR_IS_MULTITHREADED 1
482 #elif (defined(ENABLE_THREADS) && defined(HAVE_PTHREAD_H) && \
483 defined(HAVE_PTHREAD_CREATE))
485 #define TOR_IS_MULTITHREADED 1
487 #undef TOR_IS_MULTITHREADED
490 /* Because we use threads instead of processes on most platforms (Windows,
491 * Linux, etc), we need locking for them. On platforms with poor thread
492 * support or broken gethostbyname_r, these functions are no-ops. */
494 /** A generic lock structure for multithreaded builds. */
495 typedef struct tor_mutex_t
{
496 #if defined(USE_WIN32_THREADS)
497 CRITICAL_SECTION mutex
;
498 #elif defined(USE_PTHREADS)
499 pthread_mutex_t mutex
;
505 #ifdef TOR_IS_MULTITHREADED
506 tor_mutex_t
*tor_mutex_new(void);
507 void tor_mutex_init(tor_mutex_t
*m
);
508 void tor_mutex_acquire(tor_mutex_t
*m
);
509 void tor_mutex_release(tor_mutex_t
*m
);
510 void tor_mutex_free(tor_mutex_t
*m
);
511 void tor_mutex_uninit(tor_mutex_t
*m
);
512 unsigned long tor_get_thread_id(void);
513 void tor_threads_init(void);
515 #define tor_mutex_new() ((tor_mutex_t*)tor_malloc(sizeof(int)))
516 #define tor_mutex_init(m) STMT_NIL
517 #define tor_mutex_acquire(m) STMT_NIL
518 #define tor_mutex_release(m) STMT_NIL
519 #define tor_mutex_free(m) STMT_BEGIN tor_free(m); STMT_END
520 #define tor_mutex_uninit(m) STMT_NIL
521 #define tor_get_thread_id() (1UL)
522 #define tor_threads_init() STMT_NIL
525 void set_main_thread(void);
526 int in_main_thread(void);
528 #ifdef TOR_IS_MULTITHREADED
530 typedef struct tor_cond_t tor_cond_t
;
531 tor_cond_t
*tor_cond_new(void);
532 void tor_cond_free(tor_cond_t
*cond
);
533 int tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
);
534 void tor_cond_signal_one(tor_cond_t
*cond
);
535 void tor_cond_signal_all(tor_cond_t
*cond
);
539 /* Platform-specific helpers. */
541 char *format_win32_error(DWORD err
);
544 /*for some reason my compiler doesn't have these version flags defined
545 a nice homework assignment for someone one day is to define the rest*/
546 //these are the values as given on MSDN
549 #ifndef VER_SUITE_EMBEDDEDNT
550 #define VER_SUITE_EMBEDDEDNT 0x00000040
553 #ifndef VER_SUITE_SINGLEUSERTS
554 #define VER_SUITE_SINGLEUSERTS 0x00000100