1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, 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])
270 char *tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
);
272 #define tor_strtok_r(str, sep, lasts) strtok_r(str, sep, lasts)
274 #define tor_strtok_r(str, sep, lasts) tor_strtok_r_impl(str, sep, lasts)
278 #define _SHORT_FILE_ (tor_fix_source_file(__FILE__))
279 const char *tor_fix_source_file(const char *fname
);
281 #define _SHORT_FILE_ (__FILE__)
282 #define tor_fix_source_file(s) (s)
285 /* ===== Time compatibility */
286 #if !defined(HAVE_GETTIMEOFDAY) && !defined(HAVE_STRUCT_TIMEVAL_TV_SEC)
289 unsigned int tv_usec
;
293 void tor_gettimeofday(struct timeval
*timeval
);
295 #ifdef HAVE_LOCALTIME_R
296 #define tor_localtime_r localtime_r
298 struct tm
*tor_localtime_r(const time_t *timep
, struct tm
*result
);
302 #define tor_gmtime_r gmtime_r
304 struct tm
*tor_gmtime_r(const time_t *timep
, struct tm
*result
);
307 /* ===== File compatibility */
308 int replace_file(const char *from
, const char *to
);
309 int touch_file(const char *fname
);
311 typedef struct tor_lockfile_t tor_lockfile_t
;
312 tor_lockfile_t
*tor_lockfile_lock(const char *filename
, int blocking
,
314 void tor_lockfile_unlock(tor_lockfile_t
*lockfile
);
316 off_t
tor_fd_getpos(int fd
);
317 int tor_fd_seekend(int fd
);
320 #define PATH_SEPARATOR "\\"
322 #define PATH_SEPARATOR "/"
325 /* ===== Net compatibility */
327 #if (SIZEOF_SOCKLEN_T == 0)
328 typedef int socklen_t
;
331 int tor_close_socket(int s
);
332 int tor_open_socket(int domain
, int type
, int protocol
);
333 int tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
);
334 int get_n_open_sockets(void);
336 #define tor_socket_send(s, buf, len, flags) send(s, buf, len, flags)
337 #define tor_socket_recv(s, buf, len, flags) recv(s, buf, len, flags)
339 /* Define struct in6_addr on platforms that do not have it. Generally,
340 * these platforms are ones without IPv6 support, but we want to have
341 * a working in6_addr there anyway, so we can use it to parse IPv6
343 #if !defined(HAVE_STRUCT_IN6_ADDR)
347 uint8_t u6_addr8
[16];
348 uint16_t u6_addr16
[8];
349 uint32_t u6_addr32
[4];
351 #define s6_addr in6_u.u6_addr8
352 #define s6_addr16 in6_u.u6_addr16
353 #define s6_addr32 in6_u.u6_addr32
357 #if defined(__APPLE__) || defined(__darwin__) || defined(__FreeBSD__) \
358 || defined(__NetBSD__) || defined(__OpenBSD__)
359 /* Many BSD variants seem not to define these. */
361 #define s6_addr16 __u6_addr.__u6_addr16
364 #define s6_addr32 __u6_addr.__u6_addr32
368 #ifndef HAVE_SA_FAMILY_T
369 typedef uint16_t sa_family_t
;
372 /* Apparently, MS and Solaris don't define s6_addr16 or s6_addr32. */
373 #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR32
374 #define S6_ADDR32(x) ((uint32_t*)(x).s6_addr32)
376 #define S6_ADDR32(x) ((uint32_t*)((char*)&(x).s6_addr))
378 #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR16
379 #define S6_ADDR16(x) ((uint16_t*)(x).s6_addr16)
381 #define S6_ADDR16(x) ((uint16_t*)((char*)&(x).s6_addr))
384 /* Define struct sockaddr_in6 on platforms that do not have it. See notes
385 * on struct in6_addr. */
386 #if !defined(HAVE_STRUCT_SOCKADDR_IN6)
387 struct sockaddr_in6
{
388 sa_family_t sin6_family
;
390 // uint32_t sin6_flowinfo;
391 struct in6_addr sin6_addr
;
392 // uint32_t sin6_scope_id;
396 int tor_inet_aton(const char *cp
, struct in_addr
*addr
) ATTR_NONNULL((1,2));
397 const char *tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
);
398 int tor_inet_pton(int af
, const char *src
, void *dst
);
399 int tor_lookup_hostname(const char *name
, uint32_t *addr
) ATTR_NONNULL((1,2));
400 void set_socket_nonblocking(int socket
);
401 int tor_socketpair(int family
, int type
, int protocol
, int fd
[2]);
402 int network_init(void);
404 /* For stupid historical reasons, windows sockets have an independent
405 * set of errnos, and an independent way to get them. Also, you can't
406 * always believe WSAEWOULDBLOCK. Use the macros below to compare
407 * errnos against expected values, and use tor_socket_errno to find
408 * the actual errno after a socket operation fails.
410 #if defined(MS_WINDOWS)
411 /** Return true if e is EAGAIN or the local equivalent. */
412 #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == WSAEWOULDBLOCK)
413 /** Return true if e is EINPROGRESS or the local equivalent. */
414 #define ERRNO_IS_EINPROGRESS(e) ((e) == WSAEINPROGRESS)
415 /** Return true if e is EINPROGRESS or the local equivalent as returned by
416 * a call to connect(). */
417 #define ERRNO_IS_CONN_EINPROGRESS(e) \
418 ((e) == WSAEINPROGRESS || (e)== WSAEINVAL || (e) == WSAEWOULDBLOCK)
419 /** Return true if e is EAGAIN or another error indicating that a call to
420 * accept() has no pending connections to return. */
421 #define ERRNO_IS_ACCEPT_EAGAIN(e) ERRNO_IS_EAGAIN(e)
422 /** Return true if e is EMFILE or another error indicating that a call to
423 * accept() has failed because we're out of fds or something. */
424 #define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
425 ((e) == WSAEMFILE || (e) == WSAENOBUFS)
426 /** Return true if e is EADDRINUSE or the local equivalent. */
427 #define ERRNO_IS_EADDRINUSE(e) ((e) == WSAEADDRINUSE)
428 int tor_socket_errno(int sock
);
429 const char *tor_socket_strerror(int e
);
431 #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN)
432 #define ERRNO_IS_EINPROGRESS(e) ((e) == EINPROGRESS)
433 #define ERRNO_IS_CONN_EINPROGRESS(e) ((e) == EINPROGRESS)
434 #define ERRNO_IS_ACCEPT_EAGAIN(e) ((e) == EAGAIN || (e) == ECONNABORTED)
435 #define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
436 ((e) == EMFILE || (e) == ENFILE || (e) == ENOBUFS || (e) == ENOMEM)
437 #define ERRNO_IS_EADDRINUSE(e) ((e) == EADDRINUSE)
438 #define tor_socket_errno(sock) (errno)
439 #define tor_socket_strerror(e) strerror(e)
442 /** Specified SOCKS5 status codes. */
444 SOCKS5_SUCCEEDED
= 0x00,
445 SOCKS5_GENERAL_ERROR
= 0x01,
446 SOCKS5_NOT_ALLOWED
= 0x02,
447 SOCKS5_NET_UNREACHABLE
= 0x03,
448 SOCKS5_HOST_UNREACHABLE
= 0x04,
449 SOCKS5_CONNECTION_REFUSED
= 0x05,
450 SOCKS5_TTL_EXPIRED
= 0x06,
451 SOCKS5_COMMAND_NOT_SUPPORTED
= 0x07,
452 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED
= 0x08,
453 } socks5_reply_status_t
;
455 /* ===== OS compatibility */
456 const char *get_uname(void);
458 uint16_t get_uint16(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
459 uint32_t get_uint32(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
460 uint64_t get_uint64(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
461 void set_uint16(char *cp
, uint16_t v
) ATTR_NONNULL((1));
462 void set_uint32(char *cp
, uint32_t v
) ATTR_NONNULL((1));
463 void set_uint64(char *cp
, uint64_t v
) ATTR_NONNULL((1));
465 /* These uint8 variants are defined to make the code more uniform. */
466 #define get_uint8(cp) (*(const uint8_t*)(cp))
467 static void set_uint8(char *cp
, uint8_t v
);
469 set_uint8(char *cp
, uint8_t v
)
474 #if !defined(HAVE_RLIM_T)
475 typedef unsigned long rlim_t
;
477 int set_max_file_descriptors(rlim_t limit
, int *max
);
478 int switch_id(const char *user
);
480 char *get_user_homedir(const char *username
);
483 int spawn_func(void (*func
)(void *), void *data
);
484 void spawn_exit(void) ATTR_NORETURN
;
486 #if defined(ENABLE_THREADS) && defined(MS_WINDOWS)
487 #define USE_WIN32_THREADS
488 #define TOR_IS_MULTITHREADED 1
489 #elif (defined(ENABLE_THREADS) && defined(HAVE_PTHREAD_H) && \
490 defined(HAVE_PTHREAD_CREATE))
492 #define TOR_IS_MULTITHREADED 1
494 #undef TOR_IS_MULTITHREADED
497 /* Because we use threads instead of processes on most platforms (Windows,
498 * Linux, etc), we need locking for them. On platforms with poor thread
499 * support or broken gethostbyname_r, these functions are no-ops. */
501 /** A generic lock structure for multithreaded builds. */
502 typedef struct tor_mutex_t
{
503 #if defined(USE_WIN32_THREADS)
504 CRITICAL_SECTION mutex
;
505 #elif defined(USE_PTHREADS)
506 pthread_mutex_t mutex
;
512 #ifdef TOR_IS_MULTITHREADED
513 tor_mutex_t
*tor_mutex_new(void);
514 void tor_mutex_init(tor_mutex_t
*m
);
515 void tor_mutex_acquire(tor_mutex_t
*m
);
516 void tor_mutex_release(tor_mutex_t
*m
);
517 void tor_mutex_free(tor_mutex_t
*m
);
518 void tor_mutex_uninit(tor_mutex_t
*m
);
519 unsigned long tor_get_thread_id(void);
520 void tor_threads_init(void);
522 #define tor_mutex_new() ((tor_mutex_t*)tor_malloc(sizeof(int)))
523 #define tor_mutex_init(m) STMT_NIL
524 #define tor_mutex_acquire(m) STMT_NIL
525 #define tor_mutex_release(m) STMT_NIL
526 #define tor_mutex_free(m) STMT_BEGIN tor_free(m); STMT_END
527 #define tor_mutex_uninit(m) STMT_NIL
528 #define tor_get_thread_id() (1UL)
529 #define tor_threads_init() STMT_NIL
532 void set_main_thread(void);
533 int in_main_thread(void);
535 #ifdef TOR_IS_MULTITHREADED
537 typedef struct tor_cond_t tor_cond_t
;
538 tor_cond_t
*tor_cond_new(void);
539 void tor_cond_free(tor_cond_t
*cond
);
540 int tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
);
541 void tor_cond_signal_one(tor_cond_t
*cond
);
542 void tor_cond_signal_all(tor_cond_t
*cond
);
546 /* Platform-specific helpers. */
548 char *format_win32_error(DWORD err
);
551 /*for some reason my compiler doesn't have these version flags defined
552 a nice homework assignment for someone one day is to define the rest*/
553 //these are the values as given on MSDN
556 #ifndef VER_SUITE_EMBEDDEDNT
557 #define VER_SUITE_EMBEDDEDNT 0x00000040
560 #ifndef VER_SUITE_SINGLEUSERTS
561 #define VER_SUITE_SINGLEUSERTS 0x00000100