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>
59 #define snprintf _snprintf
60 /* this is not exported as W .... */
61 #define SHGetPathFromIDListW SHGetPathFromIDList
62 /* wcecompat has vasprintf */
63 #define HAVE_VASPRINTF
70 #ifndef NULL_REP_IS_ZERO_BYTES
71 #error "It seems your platform does not represent NULL as zero. We can't cope."
74 #if 'a'!=97 || 'z'!=122 || 'A'!=65 || ' '!=32
75 #error "It seems that you encode characters in something other than ASCII."
78 /* ===== Compiler compatibility */
80 /* GCC can check printf types on arbitrary functions. */
82 #define CHECK_PRINTF(formatIdx, firstArg) \
83 __attribute__ ((format(printf, formatIdx, firstArg)))
85 #define CHECK_PRINTF(formatIdx, firstArg)
88 /* inline is __inline on windows. */
90 #define INLINE __inline
95 /* Try to get a reasonable __func__ substitute in place. */
97 /* MSVC compilers before VC7 don't have __func__ at all; later ones call it
100 #define __func__ "???"
102 #define __func__ __FUNCTION__
106 /* For platforms where autoconf works, make sure __func__ is defined
108 #ifndef HAVE_MACRO__func__
109 #ifdef HAVE_MACRO__FUNCTION__
110 #define __func__ __FUNCTION__
111 #elif HAVE_MACRO__FUNC__
112 #define __func__ __FUNC__
114 #define __func__ "???"
116 #endif /* ifndef MAVE_MACRO__func__ */
117 #endif /* if not windows */
119 #if defined(_MSC_VER) && (_MSC_VER < 1300)
120 /* MSVC versions before 7 apparently don't believe that you can cast uint64_t
121 * to double and really mean it. */
122 extern INLINE
double U64_TO_DBL(uint64_t x
) {
123 int64_t i
= (int64_t) x
;
124 return (i
< 0) ? ((double) INT64_MAX
) : (double) i
;
126 #define DBL_TO_U64(x) ((uint64_t)(int64_t) (x))
128 #define U64_TO_DBL(x) ((double) (x))
129 #define DBL_TO_U64(x) ((uint64_t) (x))
132 /* GCC has several useful attributes. */
133 #if defined(__GNUC__) && __GNUC__ >= 3
134 #define ATTR_NORETURN __attribute__((noreturn))
135 #define ATTR_PURE __attribute__((pure))
136 #define ATTR_CONST __attribute__((const))
137 #define ATTR_MALLOC __attribute__((malloc))
138 #define ATTR_NORETURN __attribute__((noreturn))
139 /* Alas, nonnull is not at present a good idea for us. We'd like to get
140 * warnings when we pass NULL where we shouldn't (which nonnull does, albeit
141 * spottily), but we don't want to tell the compiler to make optimizations
142 * with the assumption that the argument can't be NULL (since this would make
143 * many of our checks go away, and make our code less robust against
144 * programming errors). Unfortunately, nonnull currently does both of these
145 * things, and there's no good way to split them up.
147 * #define ATTR_NONNULL(x) __attribute__((nonnull x)) */
148 #define ATTR_NONNULL(x)
150 /** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
151 * of <b>exp</b> will probably be true.
153 * In other words, "if (PREDICT_LIKELY(foo))" is the same as "if (foo)",
154 * except that it tells the compiler that the branch will be taken most of the
155 * time. This can generate slightly better code with some CPUs.
157 #define PREDICT_LIKELY(exp) __builtin_expect(!!(exp), 1)
158 /** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
159 * of <b>exp</b> will probably be false.
161 * In other words, "if (PREDICT_UNLIKELY(foo))" is the same as "if (foo)",
162 * except that it tells the compiler that the branch will usually not be
163 * taken. This can generate slightly better code with some CPUs.
165 #define PREDICT_UNLIKELY(exp) __builtin_expect(!!(exp), 0)
167 #define ATTR_NORETURN
171 #define ATTR_NORETURN
172 #define ATTR_NONNULL(x)
173 #define PREDICT_LIKELY(exp) (exp)
174 #define PREDICT_UNLIKELY(exp) (exp)
177 /** Expands to a syntactically valid empty statement. */
178 #define STMT_NIL (void)0
181 /** STMT_BEGIN and STMT_END are used to wrap blocks inside macros so that
182 * the macro can be used as if it were a single C statement. */
183 #define STMT_BEGIN (void) ({
185 #elif defined(sun) || defined(__sun__)
186 #define STMT_BEGIN if (1) {
187 #define STMT_END } else STMT_NIL
189 #define STMT_BEGIN do {
190 #define STMT_END } while (0)
193 /* ===== String compatibility */
195 /* Windows names string functions differently from most other platforms. */
196 #define strncasecmp _strnicmp
197 #define strcasecmp _stricmp
200 size_t strlcat(char *dst
, const char *src
, size_t siz
) ATTR_NONNULL((1,2));
203 size_t strlcpy(char *dst
, const char *src
, size_t siz
) ATTR_NONNULL((1,2));
207 /** Casts the uint64_t value in <b>a</b> to the right type for an argument
209 #define U64_PRINTF_ARG(a) (a)
210 /** Casts the uint64_t* value in <b>a</b> to the right type for an argument
212 #define U64_SCANF_ARG(a) (a)
213 /** Expands to a literal uint64_t-typed constant for the value <b>n</b>. */
214 #define U64_LITERAL(n) (n ## ui64)
215 #define I64_PRINTF_ARG(a) (a)
216 #define I64_SCANF_ARG(a) (a)
217 #define I64_LITERAL(n) (n ## i64)
219 #define U64_PRINTF_ARG(a) ((long long unsigned int)(a))
220 #define U64_SCANF_ARG(a) ((long long unsigned int*)(a))
221 #define U64_LITERAL(n) (n ## llu)
222 #define I64_PRINTF_ARG(a) ((long long signed int)(a))
223 #define I64_SCANF_ARG(a) ((long long signed int*)(a))
224 #define I64_LITERAL(n) (n ## ll)
227 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
228 /** The formatting string used to put a uint64_t value in a printf() or
229 * scanf() function. See also U64_PRINTF_ARG and U64_SCANF_ARG. */
230 #define U64_FORMAT "%I64u"
231 #define I64_FORMAT "%I64d"
233 #define U64_FORMAT "%llu"
234 #define I64_FORMAT "%lld"
237 /** Represents an mmaped file. Allocated via tor_mmap_file; freed with
238 * tor_munmap_file. */
239 typedef struct tor_mmap_t
{
240 const char *data
; /**< Mapping of the file's contents. */
241 size_t size
; /**< Size of the file. */
243 /* None of the fields below should be accessed from outside compat.c */
244 #ifdef HAVE_SYS_MMAN_H
245 size_t mapping_size
; /**< Size of the actual mapping. (This is this file
246 * size, rounded up to the nearest page.) */
247 #elif defined MS_WINDOWS
254 tor_mmap_t
*tor_mmap_file(const char *filename
) ATTR_NONNULL((1));
255 void tor_munmap_file(tor_mmap_t
*handle
) ATTR_NONNULL((1));
257 int tor_snprintf(char *str
, size_t size
, const char *format
, ...)
258 CHECK_PRINTF(3,4) ATTR_NONNULL((1,3));
259 int tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
262 int tor_asprintf(char **strp
, const char *fmt
, ...)
264 int tor_vasprintf(char **strp
, const char *fmt
, va_list args
);
266 const void *tor_memmem(const void *haystack
, size_t hlen
, const void *needle
,
267 size_t nlen
) ATTR_PURE
ATTR_NONNULL((1,3));
268 static const void *tor_memstr(const void *haystack
, size_t hlen
,
269 const char *needle
) ATTR_PURE
ATTR_NONNULL((1,3));
270 static INLINE
const void *
271 tor_memstr(const void *haystack
, size_t hlen
, const char *needle
)
273 return tor_memmem(haystack
, hlen
, needle
, strlen(needle
));
276 /* Much of the time when we're checking ctypes, we're doing spec compliance,
277 * which all assumes we're doing ASCII. */
278 #define DECLARE_CTYPE_FN(name) \
279 static int TOR_##name(char c); \
280 extern const uint32_t TOR_##name##_TABLE[]; \
281 static INLINE int TOR_##name(char c) { \
283 return !!(TOR_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
285 DECLARE_CTYPE_FN(ISALPHA
)
286 DECLARE_CTYPE_FN(ISALNUM
)
287 DECLARE_CTYPE_FN(ISSPACE
)
288 DECLARE_CTYPE_FN(ISDIGIT
)
289 DECLARE_CTYPE_FN(ISXDIGIT
)
290 DECLARE_CTYPE_FN(ISPRINT
)
291 DECLARE_CTYPE_FN(ISLOWER
)
292 DECLARE_CTYPE_FN(ISUPPER
)
293 extern const char TOR_TOUPPER_TABLE
[];
294 extern const char TOR_TOLOWER_TABLE
[];
295 #define TOR_TOLOWER(c) (TOR_TOLOWER_TABLE[(uint8_t)c])
296 #define TOR_TOUPPER(c) (TOR_TOUPPER_TABLE[(uint8_t)c])
298 char *tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
);
300 #define tor_strtok_r(str, sep, lasts) strtok_r(str, sep, lasts)
302 #define tor_strtok_r(str, sep, lasts) tor_strtok_r_impl(str, sep, lasts)
306 #define _SHORT_FILE_ (tor_fix_source_file(__FILE__))
307 const char *tor_fix_source_file(const char *fname
);
309 #define _SHORT_FILE_ (__FILE__)
310 #define tor_fix_source_file(s) (s)
313 /* ===== Time compatibility */
314 #if !defined(HAVE_GETTIMEOFDAY) && !defined(HAVE_STRUCT_TIMEVAL_TV_SEC)
317 unsigned int tv_usec
;
321 void tor_gettimeofday(struct timeval
*timeval
);
323 #ifdef HAVE_LOCALTIME_R
324 #define tor_localtime_r localtime_r
326 struct tm
*tor_localtime_r(const time_t *timep
, struct tm
*result
);
330 #define tor_gmtime_r gmtime_r
332 struct tm
*tor_gmtime_r(const time_t *timep
, struct tm
*result
);
335 /* ===== File compatibility */
336 int replace_file(const char *from
, const char *to
);
337 int touch_file(const char *fname
);
339 typedef struct tor_lockfile_t tor_lockfile_t
;
340 tor_lockfile_t
*tor_lockfile_lock(const char *filename
, int blocking
,
342 void tor_lockfile_unlock(tor_lockfile_t
*lockfile
);
344 off_t
tor_fd_getpos(int fd
);
345 int tor_fd_seekend(int fd
);
348 #define PATH_SEPARATOR "\\"
350 #define PATH_SEPARATOR "/"
353 /* ===== Net compatibility */
355 #if (SIZEOF_SOCKLEN_T == 0)
356 typedef int socklen_t
;
359 int tor_close_socket(int s
);
360 int tor_open_socket(int domain
, int type
, int protocol
);
361 int tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
);
362 int get_n_open_sockets(void);
364 #define tor_socket_send(s, buf, len, flags) send(s, buf, len, flags)
365 #define tor_socket_recv(s, buf, len, flags) recv(s, buf, len, flags)
367 /* Define struct in6_addr on platforms that do not have it. Generally,
368 * these platforms are ones without IPv6 support, but we want to have
369 * a working in6_addr there anyway, so we can use it to parse IPv6
371 #if !defined(HAVE_STRUCT_IN6_ADDR)
375 uint8_t u6_addr8
[16];
376 uint16_t u6_addr16
[8];
377 uint32_t u6_addr32
[4];
379 #define s6_addr in6_u.u6_addr8
380 #define s6_addr16 in6_u.u6_addr16
381 #define s6_addr32 in6_u.u6_addr32
385 #if defined(__APPLE__) || defined(__darwin__) || defined(__FreeBSD__) \
386 || defined(__NetBSD__) || defined(__OpenBSD__)
387 /* Many BSD variants seem not to define these. */
389 #define s6_addr16 __u6_addr.__u6_addr16
392 #define s6_addr32 __u6_addr.__u6_addr32
396 #ifndef HAVE_SA_FAMILY_T
397 typedef uint16_t sa_family_t
;
400 /* Apparently, MS and Solaris don't define s6_addr16 or s6_addr32. */
401 #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR32
402 #define S6_ADDR32(x) ((uint32_t*)(x).s6_addr32)
404 #define S6_ADDR32(x) ((uint32_t*)((char*)&(x).s6_addr))
406 #ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR16
407 #define S6_ADDR16(x) ((uint16_t*)(x).s6_addr16)
409 #define S6_ADDR16(x) ((uint16_t*)((char*)&(x).s6_addr))
412 /* Define struct sockaddr_in6 on platforms that do not have it. See notes
413 * on struct in6_addr. */
414 #if !defined(HAVE_STRUCT_SOCKADDR_IN6)
415 struct sockaddr_in6
{
416 sa_family_t sin6_family
;
418 // uint32_t sin6_flowinfo;
419 struct in6_addr sin6_addr
;
420 // uint32_t sin6_scope_id;
424 int tor_inet_aton(const char *cp
, struct in_addr
*addr
) ATTR_NONNULL((1,2));
425 const char *tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
);
426 int tor_inet_pton(int af
, const char *src
, void *dst
);
427 int tor_lookup_hostname(const char *name
, uint32_t *addr
) ATTR_NONNULL((1,2));
428 void set_socket_nonblocking(int socket
);
429 int tor_socketpair(int family
, int type
, int protocol
, int fd
[2]);
430 int network_init(void);
432 /* For stupid historical reasons, windows sockets have an independent
433 * set of errnos, and an independent way to get them. Also, you can't
434 * always believe WSAEWOULDBLOCK. Use the macros below to compare
435 * errnos against expected values, and use tor_socket_errno to find
436 * the actual errno after a socket operation fails.
438 #if defined(MS_WINDOWS)
439 /** Return true if e is EAGAIN or the local equivalent. */
440 #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == WSAEWOULDBLOCK)
441 /** Return true if e is EINPROGRESS or the local equivalent. */
442 #define ERRNO_IS_EINPROGRESS(e) ((e) == WSAEINPROGRESS)
443 /** Return true if e is EINPROGRESS or the local equivalent as returned by
444 * a call to connect(). */
445 #define ERRNO_IS_CONN_EINPROGRESS(e) \
446 ((e) == WSAEINPROGRESS || (e)== WSAEINVAL || (e) == WSAEWOULDBLOCK)
447 /** Return true if e is EAGAIN or another error indicating that a call to
448 * accept() has no pending connections to return. */
449 #define ERRNO_IS_ACCEPT_EAGAIN(e) ERRNO_IS_EAGAIN(e)
450 /** Return true if e is EMFILE or another error indicating that a call to
451 * accept() has failed because we're out of fds or something. */
452 #define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
453 ((e) == WSAEMFILE || (e) == WSAENOBUFS)
454 /** Return true if e is EADDRINUSE or the local equivalent. */
455 #define ERRNO_IS_EADDRINUSE(e) ((e) == WSAEADDRINUSE)
456 int tor_socket_errno(int sock
);
457 const char *tor_socket_strerror(int e
);
459 #define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN)
460 #define ERRNO_IS_EINPROGRESS(e) ((e) == EINPROGRESS)
461 #define ERRNO_IS_CONN_EINPROGRESS(e) ((e) == EINPROGRESS)
462 #define ERRNO_IS_ACCEPT_EAGAIN(e) ((e) == EAGAIN || (e) == ECONNABORTED)
463 #define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
464 ((e) == EMFILE || (e) == ENFILE || (e) == ENOBUFS || (e) == ENOMEM)
465 #define ERRNO_IS_EADDRINUSE(e) ((e) == EADDRINUSE)
466 #define tor_socket_errno(sock) (errno)
467 #define tor_socket_strerror(e) strerror(e)
470 /** Specified SOCKS5 status codes. */
472 SOCKS5_SUCCEEDED
= 0x00,
473 SOCKS5_GENERAL_ERROR
= 0x01,
474 SOCKS5_NOT_ALLOWED
= 0x02,
475 SOCKS5_NET_UNREACHABLE
= 0x03,
476 SOCKS5_HOST_UNREACHABLE
= 0x04,
477 SOCKS5_CONNECTION_REFUSED
= 0x05,
478 SOCKS5_TTL_EXPIRED
= 0x06,
479 SOCKS5_COMMAND_NOT_SUPPORTED
= 0x07,
480 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED
= 0x08,
481 } socks5_reply_status_t
;
483 /* ===== OS compatibility */
484 const char *get_uname(void);
486 uint16_t get_uint16(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
487 uint32_t get_uint32(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
488 uint64_t get_uint64(const char *cp
) ATTR_PURE
ATTR_NONNULL((1));
489 void set_uint16(char *cp
, uint16_t v
) ATTR_NONNULL((1));
490 void set_uint32(char *cp
, uint32_t v
) ATTR_NONNULL((1));
491 void set_uint64(char *cp
, uint64_t v
) ATTR_NONNULL((1));
493 /* These uint8 variants are defined to make the code more uniform. */
494 #define get_uint8(cp) (*(const uint8_t*)(cp))
495 static void set_uint8(char *cp
, uint8_t v
);
497 set_uint8(char *cp
, uint8_t v
)
502 #if !defined(HAVE_RLIM_T)
503 typedef unsigned long rlim_t
;
505 int set_max_file_descriptors(rlim_t limit
, int *max
);
506 int switch_id(const char *user
);
508 char *get_user_homedir(const char *username
);
511 int spawn_func(void (*func
)(void *), void *data
);
512 void spawn_exit(void) ATTR_NORETURN
;
514 #if defined(ENABLE_THREADS) && defined(MS_WINDOWS)
515 #define USE_WIN32_THREADS
516 #define TOR_IS_MULTITHREADED 1
517 #elif (defined(ENABLE_THREADS) && defined(HAVE_PTHREAD_H) && \
518 defined(HAVE_PTHREAD_CREATE))
520 #define TOR_IS_MULTITHREADED 1
522 #undef TOR_IS_MULTITHREADED
525 /* Because we use threads instead of processes on most platforms (Windows,
526 * Linux, etc), we need locking for them. On platforms with poor thread
527 * support or broken gethostbyname_r, these functions are no-ops. */
529 /** A generic lock structure for multithreaded builds. */
530 typedef struct tor_mutex_t
{
531 #if defined(USE_WIN32_THREADS)
532 CRITICAL_SECTION mutex
;
533 #elif defined(USE_PTHREADS)
534 pthread_mutex_t mutex
;
540 int tor_mlockall(void);
542 #ifdef TOR_IS_MULTITHREADED
543 tor_mutex_t
*tor_mutex_new(void);
544 void tor_mutex_init(tor_mutex_t
*m
);
545 void tor_mutex_acquire(tor_mutex_t
*m
);
546 void tor_mutex_release(tor_mutex_t
*m
);
547 void tor_mutex_free(tor_mutex_t
*m
);
548 void tor_mutex_uninit(tor_mutex_t
*m
);
549 unsigned long tor_get_thread_id(void);
550 void tor_threads_init(void);
552 #define tor_mutex_new() ((tor_mutex_t*)tor_malloc(sizeof(int)))
553 #define tor_mutex_init(m) STMT_NIL
554 #define tor_mutex_acquire(m) STMT_NIL
555 #define tor_mutex_release(m) STMT_NIL
556 #define tor_mutex_free(m) STMT_BEGIN tor_free(m); STMT_END
557 #define tor_mutex_uninit(m) STMT_NIL
558 #define tor_get_thread_id() (1UL)
559 #define tor_threads_init() STMT_NIL
562 void set_main_thread(void);
563 int in_main_thread(void);
565 #ifdef TOR_IS_MULTITHREADED
567 typedef struct tor_cond_t tor_cond_t
;
568 tor_cond_t
*tor_cond_new(void);
569 void tor_cond_free(tor_cond_t
*cond
);
570 int tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
);
571 void tor_cond_signal_one(tor_cond_t
*cond
);
572 void tor_cond_signal_all(tor_cond_t
*cond
);
576 /** Macros for MIN/MAX. Never use these when the arguments could have
578 * {With GCC extensions we could probably define a safer MIN/MAX. But
579 * depending on that safety would be dangerous, since not every platform
583 #define MAX(a,b) ( ((a)<(b)) ? (b) : (a) )
586 #define MIN(a,b) ( ((a)>(b)) ? (b) : (a) )
589 /* Platform-specific helpers. */
591 char *format_win32_error(DWORD err
);
594 /*for some reason my compiler doesn't have these version flags defined
595 a nice homework assignment for someone one day is to define the rest*/
596 //these are the values as given on MSDN
599 #ifndef VER_SUITE_EMBEDDEDNT
600 #define VER_SUITE_EMBEDDEDNT 0x00000040
603 #ifndef VER_SUITE_SINGLEUSERTS
604 #define VER_SUITE_SINGLEUSERTS 0x00000100