compat.h 22.4 KB
Newer Older
Nick Mathewson's avatar
Nick Mathewson committed
1
/* Copyright (c) 2003-2004, Roger Dingledine
2
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3
 * Copyright (c) 2007-2012, The Tor Project, Inc. */
4
5
/* See LICENSE for licensing information */

6
7
#ifndef TOR_COMPAT_H
#define TOR_COMPAT_H
8
9
10

#include "orconfig.h"
#include "torint.h"
11
#ifdef _WIN32
12
#ifndef _WIN32_WINNT
13
#define _WIN32_WINNT 0x0501
14
#endif
15
#define WIN32_LEAN_AND_MEAN
16
#if defined(_MSC_VER) && (_MSC_VER < 1300)
17
18
19
20
21
22
#include <winsock.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#endif
23
24
25
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
26
27
28
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
29
30
31
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
32
33
34
#ifdef HAVE_TIME_H
#include <time.h>
#endif
35
36
37
#ifdef HAVE_STRING_H
#include <string.h>
#endif
38
#if defined(HAVE_PTHREAD_H) && !defined(_WIN32)
39
40
#include <pthread.h>
#endif
41
#include <stdarg.h>
42
43
44
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
45
46
47
48
49
50
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
51
52
#ifdef HAVE_NETINET6_IN6_H
#include <netinet6/in6.h>
53
#endif
54

55
56
#include <stdio.h>

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#if defined (WINCE)
#include <fcntl.h>
#include <io.h>
#include <math.h>
#include <projects.h>
#define snprintf _snprintf
/* this is not exported as W .... */
#define SHGetPathFromIDListW SHGetPathFromIDList
/* wcecompat has vasprintf */
#define HAVE_VASPRINTF
/* no service here */
#ifdef NT_SERVICE
#undef NT_SERVICE
#endif
#endif // WINCE

73
74
75
76
#ifndef NULL_REP_IS_ZERO_BYTES
#error "It seems your platform does not represent NULL as zero. We can't cope."
#endif

77
78
79
80
#if 'a'!=97 || 'z'!=122 || 'A'!=65 || ' '!=32
#error "It seems that you encode characters in something other than ASCII."
#endif

81
82
83
84
85
/* ===== Compiler compatibility */

/* GCC can check printf types on arbitrary functions. */
#ifdef __GNUC__
#define CHECK_PRINTF(formatIdx, firstArg) \
86
   __attribute__ ((format(printf, formatIdx, firstArg)))
87
88
89
90
91
#else
#define CHECK_PRINTF(formatIdx, firstArg)
#endif

/* inline is __inline on windows. */
92
#ifdef _WIN32
93
94
95
96
97
#define INLINE __inline
#else
#define INLINE inline
#endif

98
99
100
101
102
103
104
105
/* Try to get a reasonable __func__ substitute in place. */
#if defined(_MSC_VER)
/* MSVC compilers before VC7 don't have __func__ at all; later ones call it
 * __FUNCTION__. */
#if _MSC_VER < 1300
#define __func__ "???"
#else
#define __func__ __FUNCTION__
106
107
#endif

108
109
110
111
112
113
114
115
116
117
#else
/* For platforms where autoconf works, make sure __func__ is defined
 * sanely. */
#ifndef HAVE_MACRO__func__
#ifdef HAVE_MACRO__FUNCTION__
#define __func__ __FUNCTION__
#elif HAVE_MACRO__FUNC__
#define __func__ __FUNC__
#else
#define __func__ "???"
118
#endif
119
#endif /* ifndef MAVE_MACRO__func__ */
Nick Mathewson's avatar
Nick Mathewson committed
120
#endif /* if not windows */
121

122
123
124
#if defined(_MSC_VER) && (_MSC_VER < 1300)
/* MSVC versions before 7 apparently don't believe that you can cast uint64_t
 * to double and really mean it. */
Nick Mathewson's avatar
Nick Mathewson committed
125
extern INLINE double U64_TO_DBL(uint64_t x) {
126
127
128
129
130
131
132
133
134
  int64_t i = (int64_t) x;
  return (i < 0) ? ((double) INT64_MAX) : (double) i;
}
#define DBL_TO_U64(x) ((uint64_t)(int64_t) (x))
#else
#define U64_TO_DBL(x) ((double) (x))
#define DBL_TO_U64(x) ((uint64_t) (x))
#endif

135
/* GCC has several useful attributes. */
136
#if defined(__GNUC__) && __GNUC__ >= 3
137
#define ATTR_NORETURN __attribute__((noreturn))
138
#define ATTR_CONST __attribute__((const))
139
#define ATTR_MALLOC __attribute__((malloc))
140
#define ATTR_NORETURN __attribute__((noreturn))
141
142
143
144
145
146
147
148
149
150
151
/* Alas, nonnull is not at present a good idea for us.  We'd like to get
 * warnings when we pass NULL where we shouldn't (which nonnull does, albeit
 * spottily), but we don't want to tell the compiler to make optimizations
 * with the assumption that the argument can't be NULL (since this would make
 * many of our checks go away, and make our code less robust against
 * programming errors).  Unfortunately, nonnull currently does both of these
 * things, and there's no good way to split them up.
 *
 * #define ATTR_NONNULL(x) __attribute__((nonnull x)) */
#define ATTR_NONNULL(x)

152
/** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
153
154
155
156
157
158
 * of <b>exp</b> will probably be true.
 *
 * In other words, "if (PREDICT_LIKELY(foo))" is the same as "if (foo)",
 * except that it tells the compiler that the branch will be taken most of the
 * time.  This can generate slightly better code with some CPUs.
 */
159
#define PREDICT_LIKELY(exp) __builtin_expect(!!(exp), 1)
160
/** Macro: Evaluates to <b>exp</b> and hints the compiler that the value
161
162
163
164
165
166
 * of <b>exp</b> will probably be false.
 *
 * In other words, "if (PREDICT_UNLIKELY(foo))" is the same as "if (foo)",
 * except that it tells the compiler that the branch will usually not be
 * taken.  This can generate slightly better code with some CPUs.
 */
167
#define PREDICT_UNLIKELY(exp) __builtin_expect(!!(exp), 0)
168
169
#else
#define ATTR_NORETURN
170
#define ATTR_CONST
171
#define ATTR_MALLOC
172
#define ATTR_NORETURN
173
#define ATTR_NONNULL(x)
174
175
#define PREDICT_LIKELY(exp) (exp)
#define PREDICT_UNLIKELY(exp) (exp)
176
177
#endif

178
/** Expands to a syntactically valid empty statement.  */
179
#define STMT_NIL (void)0
180

181
182
183
184
/** Expands to a syntactically valid empty statement, explicitly (void)ing its
 * argument. */
#define STMT_VOID(a) while (0) { (void)(a); }

185
#ifdef __GNUC__
186
187
/** STMT_BEGIN and STMT_END are used to wrap blocks inside macros so that
 * the macro can be used as if it were a single C statement. */
188
189
#define STMT_BEGIN (void) ({
#define STMT_END })
190
#elif defined(sun) || defined(__sun__)
191
192
193
194
#define STMT_BEGIN if (1) {
#define STMT_END } else STMT_NIL
#else
#define STMT_BEGIN do {
195
#define STMT_END } while (0)
196
197
#endif

198
/* ===== String compatibility */
199
#ifdef _WIN32
200
/* Windows names string functions differently from most other platforms. */
valerino's avatar
valerino committed
201
202
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
203
#endif
204
#ifndef HAVE_STRLCAT
205
size_t strlcat(char *dst, const char *src, size_t siz) ATTR_NONNULL((1,2));
206
207
#endif
#ifndef HAVE_STRLCPY
208
size_t strlcpy(char *dst, const char *src, size_t siz) ATTR_NONNULL((1,2));
209
#endif
210

211
#ifdef _MSC_VER
212
213
/** Casts the uint64_t value in <b>a</b> to the right type for an argument
 * to printf. */
214
#define U64_PRINTF_ARG(a) (a)
215
216
/** Casts the uint64_t* value in <b>a</b> to the right type for an argument
 * to scanf. */
217
#define U64_SCANF_ARG(a) (a)
218
/** Expands to a literal uint64_t-typed constant for the value <b>n</b>. */
219
#define U64_LITERAL(n) (n ## ui64)
220
221
222
#define I64_PRINTF_ARG(a) (a)
#define I64_SCANF_ARG(a) (a)
#define I64_LITERAL(n) (n ## i64)
223
#else
224
#define U64_PRINTF_ARG(a) ((long long unsigned int)(a))
Roger Dingledine's avatar
Roger Dingledine committed
225
#define U64_SCANF_ARG(a) ((long long unsigned int*)(a))
226
#define U64_LITERAL(n) (n ## llu)
227
228
229
#define I64_PRINTF_ARG(a) ((long long signed int)(a))
#define I64_SCANF_ARG(a) ((long long signed int*)(a))
#define I64_LITERAL(n) (n ## ll)
230
#endif
231

232
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
233
234
/** The formatting string used to put a uint64_t value in a printf() or
 * scanf() function.  See also U64_PRINTF_ARG and U64_SCANF_ARG. */
235
#define U64_FORMAT "%I64u"
Mike Perry's avatar
Mike Perry committed
236
#define I64_FORMAT "%I64d"
237
238
#else
#define U64_FORMAT "%llu"
Mike Perry's avatar
Mike Perry committed
239
#define I64_FORMAT "%lld"
240
241
#endif

242
243
244
245
246
247
248
249
250
251
252
253
254
#if (SIZEOF_INTPTR_T == SIZEOF_INT)
#define INTPTR_T_FORMAT "%d"
#define INTPTR_PRINTF_ARG(x) ((int)(x))
#elif (SIZEOF_INTPTR_T == SIZEOF_LONG)
#define INTPTR_T_FORMAT "%ld"
#define INTPTR_PRINTF_ARG(x) ((long)(x))
#elif (SIZEOF_INTPTR_T == 8)
#define INTPTR_T_FORMAT I64_FORMAT
#define INTPTR_PRINTF_ARG(x) I64_PRINTF_ARG(x)
#else
#error Unknown: SIZEOF_INTPTR_T
#endif

255
256
/** Represents an mmaped file. Allocated via tor_mmap_file; freed with
 * tor_munmap_file. */
257
typedef struct tor_mmap_t {
258
259
  const char *data; /**< Mapping of the file's contents. */
  size_t size; /**< Size of the file. */
260
261
262
263
264

  /* None of the fields below should be accessed from outside compat.c */
#ifdef HAVE_SYS_MMAN_H
  size_t mapping_size; /**< Size of the actual mapping. (This is this file
                        * size, rounded up to the nearest page.) */
265
#elif defined _WIN32
266
267
268
  HANDLE mmap_handle;
#endif

269
} tor_mmap_t;
270

271
272
tor_mmap_t *tor_mmap_file(const char *filename) ATTR_NONNULL((1));
void tor_munmap_file(tor_mmap_t *handle) ATTR_NONNULL((1));
273

274
int tor_snprintf(char *str, size_t size, const char *format, ...)
275
276
  CHECK_PRINTF(3,4) ATTR_NONNULL((1,3));
int tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
277
  CHECK_PRINTF(3,0) ATTR_NONNULL((1,3));
278

279
280
int tor_asprintf(char **strp, const char *fmt, ...)
  CHECK_PRINTF(2,3);
281
282
int tor_vasprintf(char **strp, const char *fmt, va_list args)
  CHECK_PRINTF(2,0);
283

Nick Mathewson's avatar
Nick Mathewson committed
284
const void *tor_memmem(const void *haystack, size_t hlen, const void *needle,
Sebastian Hahn's avatar
Sebastian Hahn committed
285
                       size_t nlen) ATTR_NONNULL((1,3));
286
static const void *tor_memstr(const void *haystack, size_t hlen,
Sebastian Hahn's avatar
Sebastian Hahn committed
287
                           const char *needle) ATTR_NONNULL((1,3));
288
289
290
291
292
static INLINE const void *
tor_memstr(const void *haystack, size_t hlen, const char *needle)
{
  return tor_memmem(haystack, hlen, needle, strlen(needle));
}
Nick Mathewson's avatar
Nick Mathewson committed
293

294
295
296
297
/* Much of the time when we're checking ctypes, we're doing spec compliance,
 * which all assumes we're doing ASCII. */
#define DECLARE_CTYPE_FN(name)                                          \
  static int TOR_##name(char c);                                        \
298
  extern const uint32_t TOR_##name##_TABLE[];                           \
299
300
301
302
303
304
305
306
307
308
309
310
  static INLINE int TOR_##name(char c) {                                \
    uint8_t u = c;                                                      \
    return !!(TOR_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31)));      \
  }
DECLARE_CTYPE_FN(ISALPHA)
DECLARE_CTYPE_FN(ISALNUM)
DECLARE_CTYPE_FN(ISSPACE)
DECLARE_CTYPE_FN(ISDIGIT)
DECLARE_CTYPE_FN(ISXDIGIT)
DECLARE_CTYPE_FN(ISPRINT)
DECLARE_CTYPE_FN(ISLOWER)
DECLARE_CTYPE_FN(ISUPPER)
311
312
extern const char TOR_TOUPPER_TABLE[];
extern const char TOR_TOLOWER_TABLE[];
313
314
#define TOR_TOLOWER(c) (TOR_TOLOWER_TABLE[(uint8_t)c])
#define TOR_TOUPPER(c) (TOR_TOUPPER_TABLE[(uint8_t)c])
315

316
317
char *tor_strtok_r_impl(char *str, const char *sep, char **lasts);
#ifdef HAVE_STRTOK_R
318
#define tor_strtok_r(str, sep, lasts) strtok_r(str, sep, lasts)
319
#else
320
#define tor_strtok_r(str, sep, lasts) tor_strtok_r_impl(str, sep, lasts)
321
322
#endif

323
#ifdef _WIN32
324
#define SHORT_FILE__ (tor_fix_source_file(__FILE__))
325
326
const char *tor_fix_source_file(const char *fname);
#else
327
#define SHORT_FILE__ (__FILE__)
328
329
#define tor_fix_source_file(s) (s)
#endif
330

331
332
/* ===== Time compatibility */
#if !defined(HAVE_GETTIMEOFDAY) && !defined(HAVE_STRUCT_TIMEVAL_TV_SEC)
333
/** Implementation of timeval for platforms that don't have it. */
334
335
336
337
338
339
340
341
struct timeval {
  time_t tv_sec;
  unsigned int tv_usec;
};
#endif

void tor_gettimeofday(struct timeval *timeval);

342
343
344
struct tm *tor_localtime_r(const time_t *timep, struct tm *result);
struct tm *tor_gmtime_r(const time_t *timep, struct tm *result);

345
346
347
348
349
350
#ifndef timeradd
/** Replacement for timeradd on platforms that do not have it: sets tvout to
 * the sum of tv1 and tv2. */
#define timeradd(tv1,tv2,tvout) \
  do {                                                  \
    (tvout)->tv_sec = (tv1)->tv_sec + (tv2)->tv_sec;    \
351
    (tvout)->tv_usec = (tv1)->tv_usec + (tv2)->tv_usec; \
352
353
354
355
356
357
358
359
360
361
362
363
364
    if ((tvout)->tv_usec >= 1000000) {                  \
      (tvout)->tv_usec -= 1000000;                      \
      (tvout)->tv_sec++;                                \
    }                                                   \
  } while (0)
#endif

#ifndef timersub
/** Replacement for timersub on platforms that do not have it: sets tvout to
 * tv1 minus tv2. */
#define timersub(tv1,tv2,tvout) \
  do {                                                  \
    (tvout)->tv_sec = (tv1)->tv_sec - (tv2)->tv_sec;    \
365
    (tvout)->tv_usec = (tv1)->tv_usec - (tv2)->tv_usec; \
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    if ((tvout)->tv_usec < 0) {                         \
      (tvout)->tv_usec += 1000000;                      \
      (tvout)->tv_sec--;                                \
    }                                                   \
  } while (0)
#endif

#ifndef timercmp
/** Replacement for timersub on platforms that do not have it: returns true
 * iff the relational operator "op" makes the expression tv1 op tv2 true.
 *
 * Note that while this definition should work for all boolean opeators, some
 * platforms' native timercmp definitions do not support >=, <=, or ==.  So
 * don't use those.
 */
#define timercmp(tv1,tv2,op)                    \
  (((tv1)->tv_sec == (tv2)->tv_sec) ?           \
   ((tv1)->tv_usec op (tv2)->tv_usec) :         \
   ((tv1)->tv_sec op (tv2)->tv_sec))
#endif
Nick Mathewson's avatar
Nick Mathewson committed
386

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

391
int replace_file(const char *from, const char *to);
392
int touch_file(const char *fname);
393

394
395
396
397
398
typedef struct tor_lockfile_t tor_lockfile_t;
tor_lockfile_t *tor_lockfile_lock(const char *filename, int blocking,
                                  int *locked_out);
void tor_lockfile_unlock(tor_lockfile_t *lockfile);

399
400
401
off_t tor_fd_getpos(int fd);
int tor_fd_seekend(int fd);

402
#ifdef _WIN32
403
404
405
406
407
#define PATH_SEPARATOR "\\"
#else
#define PATH_SEPARATOR "/"
#endif

408
/* ===== Net compatibility */
409

410
411
412
413
#if (SIZEOF_SOCKLEN_T == 0)
typedef int socklen_t;
#endif

414
#ifdef _WIN32
415
416
417
/* XXX Actually, this should arguably be SOCKET; we use intptr_t here so that
 * any inadvertant checks for the socket being <= 0 or > 0 will probably
 * still work. */
418
#define tor_socket_t intptr_t
419
#define TOR_SOCKET_T_FORMAT INTPTR_T_FORMAT
Nick Mathewson's avatar
Nick Mathewson committed
420
#define SOCKET_OK(s) ((SOCKET)(s) != INVALID_SOCKET)
421
#define TOR_INVALID_SOCKET INVALID_SOCKET
422
#else
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
429
/** Error/uninitialized value for a tor_socket_t. */
#define TOR_INVALID_SOCKET (-1)
430
431
432
433
#endif

int tor_close_socket(tor_socket_t s);
tor_socket_t tor_open_socket(int domain, int type, int protocol);
434
tor_socket_t tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr,
435
                                  socklen_t *len);
436
int get_n_open_sockets(void);
437

438
439
440
#define tor_socket_send(s, buf, len, flags) send(s, buf, len, flags)
#define tor_socket_recv(s, buf, len, flags) recv(s, buf, len, flags)

Robert Ransom's avatar
Robert Ransom committed
441
/** Implementation of struct in6_addr for platforms that do not have it.
442
443
 * Generally, these platforms are ones without IPv6 support, but we want to
 * have a working in6_addr there anyway, so we can use it to parse IPv6
444
445
 * addresses. */
#if !defined(HAVE_STRUCT_IN6_ADDR)
446
447
struct in6_addr
{
448
449
450
451
452
453
454
455
  union {
    uint8_t u6_addr8[16];
    uint16_t u6_addr16[8];
    uint32_t u6_addr32[4];
  } in6_u;
#define s6_addr   in6_u.u6_addr8
#define s6_addr16 in6_u.u6_addr16
#define s6_addr32 in6_u.u6_addr32
456
457
458
};
#endif

459
460
/** @{ */
/** Many BSD variants seem not to define these. */
461
#if defined(__APPLE__) || defined(__darwin__) || defined(__FreeBSD__) \
462
    || defined(__NetBSD__) || defined(__OpenBSD__)
463
464
465
466
467
468
469
#ifndef s6_addr16
#define s6_addr16 __u6_addr.__u6_addr16
#endif
#ifndef s6_addr32
#define s6_addr32 __u6_addr.__u6_addr32
#endif
#endif
470
/** @} */
471

472
473
474
475
#ifndef HAVE_SA_FAMILY_T
typedef uint16_t sa_family_t;
#endif

476
477
478
/** @{ */
/** Apparently, MS and Solaris don't define s6_addr16 or s6_addr32; these
 * macros get you a pointer to s6_addr32 or local equivalent. */
479
#ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR32
480
#define S6_ADDR32(x) ((uint32_t*)(x).s6_addr32)
481
482
483
#else
#define S6_ADDR32(x) ((uint32_t*)((char*)&(x).s6_addr))
#endif
484
485
486
487
488
#ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR16
#define S6_ADDR16(x) ((uint16_t*)(x).s6_addr16)
#else
#define S6_ADDR16(x) ((uint16_t*)((char*)&(x).s6_addr))
#endif
489
/** @} */
490

491
492
/** Implementation of struct sockaddr_in6 on platforms that do not have
 * it. See notes on struct in6_addr. */
493
#if !defined(HAVE_STRUCT_SOCKADDR_IN6)
494
struct sockaddr_in6 {
495
  sa_family_t sin6_family;
496
497
498
499
500
501
502
  uint16_t sin6_port;
  // uint32_t sin6_flowinfo;
  struct in6_addr sin6_addr;
  // uint32_t sin6_scope_id;
};
#endif

503
int tor_inet_aton(const char *cp, struct in_addr *addr) ATTR_NONNULL((1,2));
504
505
const char *tor_inet_ntop(int af, const void *src, char *dst, size_t len);
int tor_inet_pton(int af, const char *src, void *dst);
506
int tor_lookup_hostname(const char *name, uint32_t *addr) ATTR_NONNULL((1,2));
507
508
void set_socket_nonblocking(tor_socket_t socket);
int tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2]);
509
int network_init(void);
510

511
512
513
514
515
516
/* For stupid historical reasons, windows sockets have an independent
 * set of errnos, and an independent way to get them.  Also, you can't
 * always believe WSAEWOULDBLOCK.  Use the macros below to compare
 * errnos against expected values, and use tor_socket_errno to find
 * the actual errno after a socket operation fails.
 */
517
#if defined(_WIN32)
518
519
/** Expands to WSA<b>e</b> on Windows, and to <b>e</b> elsewhere. */
#define SOCK_ERRNO(e) WSA##e
520
521
522
523
524
525
/** Return true if e is EAGAIN or the local equivalent. */
#define ERRNO_IS_EAGAIN(e)           ((e) == EAGAIN || (e) == WSAEWOULDBLOCK)
/** Return true if e is EINPROGRESS or the local equivalent. */
#define ERRNO_IS_EINPROGRESS(e)      ((e) == WSAEINPROGRESS)
/** Return true if e is EINPROGRESS or the local equivalent as returned by
 * a call to connect(). */
526
527
#define ERRNO_IS_CONN_EINPROGRESS(e) \
  ((e) == WSAEINPROGRESS || (e)== WSAEINVAL || (e) == WSAEWOULDBLOCK)
528
529
530
531
532
533
534
/** Return true if e is EAGAIN or another error indicating that a call to
 * accept() has no pending connections to return. */
#define ERRNO_IS_ACCEPT_EAGAIN(e)    ERRNO_IS_EAGAIN(e)
/** Return true if e is EMFILE or another error indicating that a call to
 * accept() has failed because we're out of fds or something. */
#define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
  ((e) == WSAEMFILE || (e) == WSAENOBUFS)
535
536
/** Return true if e is EADDRINUSE or the local equivalent. */
#define ERRNO_IS_EADDRINUSE(e)      ((e) == WSAEADDRINUSE)
537
int tor_socket_errno(tor_socket_t sock);
538
539
const char *tor_socket_strerror(int e);
#else
540
#define SOCK_ERRNO(e) e
541
542
543
544
545
546
#define ERRNO_IS_EAGAIN(e)           ((e) == EAGAIN)
#define ERRNO_IS_EINPROGRESS(e)      ((e) == EINPROGRESS)
#define ERRNO_IS_CONN_EINPROGRESS(e) ((e) == EINPROGRESS)
#define ERRNO_IS_ACCEPT_EAGAIN(e)    ((e) == EAGAIN || (e) == ECONNABORTED)
#define ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e) \
  ((e) == EMFILE || (e) == ENFILE || (e) == ENOBUFS || (e) == ENOMEM)
547
#define ERRNO_IS_EADDRINUSE(e)       ((e) == EADDRINUSE)
548
549
550
551
#define tor_socket_errno(sock)       (errno)
#define tor_socket_strerror(e)       strerror(e)
#endif

552
553
554
555
556
557
558
559
560
561
562
563
564
/** Specified SOCKS5 status codes. */
typedef enum {
  SOCKS5_SUCCEEDED                  = 0x00,
  SOCKS5_GENERAL_ERROR              = 0x01,
  SOCKS5_NOT_ALLOWED                = 0x02,
  SOCKS5_NET_UNREACHABLE            = 0x03,
  SOCKS5_HOST_UNREACHABLE           = 0x04,
  SOCKS5_CONNECTION_REFUSED         = 0x05,
  SOCKS5_TTL_EXPIRED                = 0x06,
  SOCKS5_COMMAND_NOT_SUPPORTED      = 0x07,
  SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
} socks5_reply_status_t;

565
566
567
568
569
/* ===== Insecure rng */
void tor_init_weak_random(unsigned seed);
long tor_weak_random(void);
#define TOR_RAND_MAX (RAND_MAX)

570
571
572
/* ===== OS compatibility */
const char *get_uname(void);

Sebastian Hahn's avatar
Sebastian Hahn committed
573
574
575
uint16_t get_uint16(const void *cp) ATTR_NONNULL((1));
uint32_t get_uint32(const void *cp) ATTR_NONNULL((1));
uint64_t get_uint64(const void *cp) ATTR_NONNULL((1));
Nick Mathewson's avatar
Nick Mathewson committed
576
577
578
void set_uint16(void *cp, uint16_t v) ATTR_NONNULL((1));
void set_uint32(void *cp, uint32_t v) ATTR_NONNULL((1));
void set_uint64(void *cp, uint64_t v) ATTR_NONNULL((1));
579

580
581
/* These uint8 variants are defined to make the code more uniform. */
#define get_uint8(cp) (*(const uint8_t*)(cp))
Nick Mathewson's avatar
Nick Mathewson committed
582
static void set_uint8(void *cp, uint8_t v);
583
static INLINE void
Nick Mathewson's avatar
Nick Mathewson committed
584
set_uint8(void *cp, uint8_t v)
585
586
587
588
{
  *(uint8_t*)cp = v;
}

589
590
591
592
#if !defined(HAVE_RLIM_T)
typedef unsigned long rlim_t;
#endif
int set_max_file_descriptors(rlim_t limit, int *max);
593
int tor_disable_debugger_attach(void);
594
int switch_id(const char *user);
595
596
597
#ifdef HAVE_PWD_H
char *get_user_homedir(const char *username);
#endif
598

599
int get_parent_directory(char *fname);
600
char *make_path_absolute(char *fname);
601

602
603
char **get_environment(void);

604
int spawn_func(void (*func)(void *), void *data);
605
void spawn_exit(void) ATTR_NORETURN;
606

607
#if defined(ENABLE_THREADS) && defined(_WIN32)
608
609
#define USE_WIN32_THREADS
#define TOR_IS_MULTITHREADED 1
610
611
#elif (defined(ENABLE_THREADS) && defined(HAVE_PTHREAD_H) && \
       defined(HAVE_PTHREAD_CREATE))
612
#define USE_PTHREADS
613
614
615
616
617
#define TOR_IS_MULTITHREADED 1
#else
#undef TOR_IS_MULTITHREADED
#endif

618
619
int compute_num_cpus(void);

Roger Dingledine's avatar
Roger Dingledine committed
620
621
622
/* Because we use threads instead of processes on most platforms (Windows,
 * Linux, etc), we need locking for them.  On platforms with poor thread
 * support or broken gethostbyname_r, these functions are no-ops. */
623

624
625
626
/** A generic lock structure for multithreaded builds. */
typedef struct tor_mutex_t {
#if defined(USE_WIN32_THREADS)
627
  /** Windows-only: on windows, we implement locks with CRITICAL_SECTIONS. */
628
629
  CRITICAL_SECTION mutex;
#elif defined(USE_PTHREADS)
630
631
  /** Pthreads-only: with pthreads, we implement locks with
   * pthread_mutex_t. */
632
633
  pthread_mutex_t mutex;
#else
634
  /** No-threads only: Dummy variable so that tor_mutex_t takes up space. */
635
636
637
638
  int _unused;
#endif
} tor_mutex_t;

639
640
int tor_mlockall(void);

641
642
#ifdef TOR_IS_MULTITHREADED
tor_mutex_t *tor_mutex_new(void);
643
void tor_mutex_init(tor_mutex_t *m);
644
645
646
void tor_mutex_acquire(tor_mutex_t *m);
void tor_mutex_release(tor_mutex_t *m);
void tor_mutex_free(tor_mutex_t *m);
647
void tor_mutex_uninit(tor_mutex_t *m);
648
unsigned long tor_get_thread_id(void);
649
void tor_threads_init(void);
650
651
#else
#define tor_mutex_new() ((tor_mutex_t*)tor_malloc(sizeof(int)))
652
#define tor_mutex_init(m) STMT_NIL
653
#define tor_mutex_acquire(m) STMT_VOID(m)
654
655
#define tor_mutex_release(m) STMT_NIL
#define tor_mutex_free(m) STMT_BEGIN tor_free(m); STMT_END
656
#define tor_mutex_uninit(m) STMT_NIL
657
#define tor_get_thread_id() (1UL)
658
#define tor_threads_init() STMT_NIL
659
660
#endif

661
662
663
void set_main_thread(void);
int in_main_thread(void);

664
#ifdef TOR_IS_MULTITHREADED
665
#if 0
666
667
typedef struct tor_cond_t tor_cond_t;
tor_cond_t *tor_cond_new(void);
668
void tor_cond_free(tor_cond_t *cond);
669
670
671
672
int tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex);
void tor_cond_signal_one(tor_cond_t *cond);
void tor_cond_signal_all(tor_cond_t *cond);
#endif
673
#endif
674

675
676
677
678
679
680
681
682
683
684
685
686
687
/** Macros for MIN/MAX.  Never use these when the arguments could have
 * side-effects.
 * {With GCC extensions we could probably define a safer MIN/MAX.  But
 * depending on that safety would be dangerous, since not every platform
 * has it.}
 **/
#ifndef MAX
#define MAX(a,b) ( ((a)<(b)) ? (b) : (a) )
#endif
#ifndef MIN
#define MIN(a,b) ( ((a)>(b)) ? (b) : (a) )
#endif

688
/* Platform-specific helpers. */
689
#ifdef _WIN32
690
691
692
char *format_win32_error(DWORD err);
#endif

693
694
695
/*for some reason my compiler doesn't have these version flags defined
  a nice homework assignment for someone one day is to define the rest*/
//these are the values as given on MSDN
696
#ifdef _WIN32
697
698
699
700
701
702
703
704
705
706
707

#ifndef VER_SUITE_EMBEDDEDNT
#define VER_SUITE_EMBEDDEDNT 0x00000040
#endif

#ifndef VER_SUITE_SINGLEUSERTS
#define VER_SUITE_SINGLEUSERTS 0x00000100
#endif

#endif

708
#endif
709