util.h 10.2 KB
Newer Older
Nick Mathewson's avatar
Nick Mathewson committed
1
/* Copyright 2003-2004 Roger Dingledine
2
 * Copyright 2004-2007 Roger Dingledine, Nick Mathewson */
3
4
5
/* See LICENSE for licensing information */
/* $Id$ */

6
7
8
/**
 * \file util.h
 * \brief Headers for util.c
9
 **/
10

11
12
#ifndef __UTIL_H
#define __UTIL_H
13
#define UTIL_H_ID "$Id$"
14

15
16
#include "orconfig.h"
#include "torint.h"
17
#include "compat.h"
18
#include <stdio.h>
19
#include <stdlib.h>
20
21
22
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
Nick Mathewson's avatar
Nick Mathewson committed
23
24
25
#ifdef HAVE_TIME_H
#include <time.h>
#endif
26

27
/* Replace assert() with a variant that sends failures to the log before
28
29
 * calling assert() normally.
 */
30
#ifdef NDEBUG
Roger Dingledine's avatar
Roger Dingledine committed
31
/* Nobody should ever want to build with NDEBUG set.  99% of our asserts will
32
33
34
35
36
37
38
39
 * be outside the critical path anyway, so it's silly to disable bugchecking
 * throughout the entire program just because a few asserts are slowing you
 * down.  Profile, optimize the critical path, and keep debugging on.
 *
 * And I'm not just saying that because some of our asserts check
 * security-critical properties.
 */
#error "Sorry; we don't support building with NDEBUG."
40
#else
41
#ifdef __GNUC__
42
43
/* Give an int-valued version of !x that won't confuse PREDICT_UNLIKELY. */
#define IS_FALSE_AS_INT(x) ((x) == ((typeof(x)) 0))
44
#else
45
#define IS_FALSE_AS_INT(x) !(x)
46
#endif
47

48
49
/** Like assert(3), but send assertion failures to the log as well as to
 * stderr. */
50
#define tor_assert(expr) do {                                           \
51
    if (PREDICT_UNLIKELY(IS_FALSE_AS_INT(expr))) {                      \
52
      log(LOG_ERR, LD_BUG, "%s:%d: %s: Assertion %s failed; aborting.", \
53
          _SHORT_FILE_, __LINE__, __func__, #expr);                     \
54
      fprintf(stderr,"%s:%d %s: Assertion %s failed; aborting.\n",      \
55
              _SHORT_FILE_, __LINE__, __func__, #expr);                 \
56
      abort();                                                          \
57
    } } while (0)
58
#endif
59

60
#ifdef USE_DMALLOC
61
62
#define DMALLOC_PARAMS , const char *file, const int line
#define DMALLOC_ARGS , _SHORT_FILE_, __LINE__
63
64
65
66
67
#else
#define DMALLOC_PARAMS
#define DMALLOC_ARGS
#endif

68
69
70
71
72
/** Define this if you want Tor to crash when any problem comes up,
 * so you can get a coredump and track things down. */
// #define tor_fragile_assert() tor_assert(0)
#define tor_fragile_assert()

73
/* Memory management */
74
75
void *_tor_malloc(size_t size DMALLOC_PARAMS) ATTR_MALLOC;
void *_tor_malloc_zero(size_t size DMALLOC_PARAMS) ATTR_MALLOC;
76
void *_tor_realloc(void *ptr, size_t size DMALLOC_PARAMS);
77
78
79
80
81
char *_tor_strdup(const char *s DMALLOC_PARAMS) ATTR_MALLOC ATTR_NONNULL((1));
char *_tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  ATTR_MALLOC ATTR_NONNULL((1));
void *_tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  ATTR_MALLOC ATTR_NONNULL((1));
82
void _tor_free(void *mem);
83
84
85
86
#ifdef USE_DMALLOC
extern int dmalloc_free(const char *file, const int line, void *pnt,
                        const int func_id);
#define tor_free(p) do { \
87
    if (PREDICT_LIKELY((p)!=NULL)) {                \
88
89
90
91
92
      dmalloc_free(_SHORT_FILE_, __LINE__, (p), 0); \
      (p)=NULL;                                     \
    }                                               \
  } while (0)
#else
93
94
95
96
97
98
#define tor_free(p) do {                                       \
    if (PREDICT_LIKELY((p)!=NULL)) {                           \
      free(p);                                                 \
      (p)=NULL;                                                \
    }                                                          \
  } while (0)
99
#endif
100

101
102
103
104
105
#define tor_malloc(size)       _tor_malloc(size DMALLOC_ARGS)
#define tor_malloc_zero(size)  _tor_malloc_zero(size DMALLOC_ARGS)
#define tor_realloc(ptr, size) _tor_realloc(ptr, size DMALLOC_ARGS)
#define tor_strdup(s)          _tor_strdup(s DMALLOC_ARGS)
#define tor_strndup(s, n)      _tor_strndup(s, n DMALLOC_ARGS)
106
#define tor_memdup(s, n)       _tor_memdup(s, n DMALLOC_ARGS)
107

108
/** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
109
#if defined(__GNUC__) && __GNUC__ > 3
110
111
112
113
114
#define STRUCT_OFFSET(tp, member) __builtin_offsetof(tp, member)
#else
 #define STRUCT_OFFSET(tp, member) \
   ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
#endif
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/** Macro: yield a pointer to the field at position <b>off</b> within the
 * structure <b>st</b>.  Example:
 * <pre>
 *   struct a { int foo; int bar; } x;
 *   off_t bar_offset = STRUCT_OFFSET(struct a, bar);
 *   int *bar_p = STRUCT_VAR_P(&x, bar_offset);
 *   *bar_p = 3;
 * </pre>
 */
#define STRUCT_VAR_P(st, off) ((void*) ( ((char*)(st)) + (off) ) )

/** Macro: yield a pointer to an enclosing structure given a pointer to
 * a substructure at offset <b>off</b>. Example:
 * <pre>
 *   struct base { ... };
 *   struct subtype { int x; struct base b; } x;
 *   struct base *bp = &x.base;
 *   struct *sp = SUBTYPE_P(bp, struct subtype, b);
 * </pre>
 */
#define SUBTYPE_P(p, subtype, basemember) \
  ((void*) ( ((char*)(p)) - STRUCT_OFFSET(subtype, basemember) ))

139
140
141
142
143
144
/* Logic */
/** Macro: true if two values have the same boolean value. */
#define bool_eq(a,b) (!(a)==!(b))
/** Macro: true if two values have different boolean values. */
#define bool_neq(a,b) (!(a)!=!(b))

145
/* String manipulation */
146

147
/** Allowable characters in a hexadecimal string. */
148
#define HEX_CHARACTERS "0123456789ABCDEFabcdef"
149
150
151
152
153
154
155
156
157
158
159
void tor_strlower(char *s) ATTR_NONNULL((1));
void tor_strupper(char *s) ATTR_NONNULL((1));
int tor_strisprint(const char *s) ATTR_PURE ATTR_NONNULL((1));
int tor_strisnonupper(const char *s) ATTR_PURE ATTR_NONNULL((1));
int strcmpstart(const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1,2));
int strcasecmpstart(const char *s1, const char *s2)
  ATTR_PURE ATTR_NONNULL((1,2));
int strcmpend(const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1,2));
int strcasecmpend(const char *s1, const char *s2)
  ATTR_PURE ATTR_NONNULL((1,2));
int tor_strstrip(char *s, const char *strip) ATTR_NONNULL((1,2));
160
int tor_strpartition(char *dest, size_t dest_len,
161
                     const char *s, const char *insert, size_t n);
162
163
164
165
long tor_parse_long(const char *s, int base, long min,
                    long max, int *ok, char **next);
unsigned long tor_parse_ulong(const char *s, int base, unsigned long min,
                              unsigned long max, int *ok, char **next);
166
167
uint64_t tor_parse_uint64(const char *s, int base, uint64_t min,
                         uint64_t max, int *ok, char **next);
168
169
const char *hex_str(const char *from, size_t fromlen) ATTR_NONNULL((1));
const char *eat_whitespace(const char *s) ATTR_PURE;
170
const char *eat_whitespace_eos(const char *s, const char *eos) ATTR_PURE;
171
172
173
174
175
const char *eat_whitespace_no_nl(const char *s) ATTR_PURE;
const char *find_whitespace(const char *s) ATTR_PURE;
int tor_mem_is_zero(const char *mem, size_t len) ATTR_PURE;
int tor_digest_is_zero(const char *digest) ATTR_PURE;
char *esc_for_log(const char *string) ATTR_MALLOC;
176
const char *escaped(const char *string);
177
178
179
struct smartlist_t;
void wrap_string(struct smartlist_t *out, const char *string, size_t width,
                 const char *prefix0, const char *prefixRest);
180

181
182
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen);
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen);
183

184
/* Time helpers */
185
long tv_udiff(const struct timeval *start, const struct timeval *end);
186
void tv_addms(struct timeval *a, long ms);
187
188
void tv_add(struct timeval *a, const struct timeval *b);
int tv_cmp(const struct timeval *a, const struct timeval *b);
Nick Mathewson's avatar
Nick Mathewson committed
189
time_t tor_timegm(struct tm *tm);
190
#define RFC1123_TIME_LEN 29
191
192
193
void format_rfc1123_time(char *buf, time_t t);
int parse_rfc1123_time(const char *buf, time_t *t);
#define ISO_TIME_LEN 19
194
void format_local_iso_time(char *buf, time_t t);
195
196
void format_iso_time(char *buf, time_t t);
int parse_iso_time(const char *buf, time_t *t);
197

198
/* File helpers */
199
200
int write_all(int fd, const char *buf, size_t count, int isSocket);
int read_all(int fd, char *buf, size_t count, int isSocket);
Roger Dingledine's avatar
Roger Dingledine committed
201

202
203
204
/** Return values from file_status(); see that function's documentation
 * for details. */
typedef enum { FN_ERROR, FN_NOENT, FN_FILE, FN_DIR } file_status_t;
205
file_status_t file_status(const char *filename);
206

207
208
/** Possible behaviors for check_private_dir() on encountering a nonexistent
 * directory; see that function's documentation for details. */
209
210
typedef enum { CPD_NONE, CPD_CREATE, CPD_CHECK } cpd_check_t;
int check_private_dir(const char *dirname, cpd_check_t check);
211
int write_str_to_file(const char *fname, const char *str, int bin);
212
213
int write_bytes_to_file(const char *fname, const char *str, size_t len,
                        int bin);
214
215
/** An ad-hoc type to hold a string of characters and a count; used by
 * write_chunks_to_file. */
216
217
218
219
220
221
222
223
224
typedef struct sized_chunk_t {
  const char *bytes;
  size_t len;
} sized_chunk_t;
int write_chunks_to_file(const char *fname, const struct smartlist_t *chunks,
                         int bin);
int append_bytes_to_file(const char *fname, const char *str, size_t len,
                         int bin);

225
226
/** Flag for read_file_to_str: open the file in binary mode. */
#define RFTS_BIN            1
227
/** Flag for read_file_to_str: it's okay if the file doesn't exist. */
228
229
#define RFTS_IGNORE_MISSING 2

230
struct stat;
231
char *read_file_to_str(const char *filename, int flags, struct stat *stat_out)
232
  ATTR_MALLOC;
233
char *parse_line_from_str(char *line, char **key_out, char **value_out);
234
char *expand_filename(const char *filename);
235
struct smartlist_t *tor_listdir(const char *dirname);
236
int path_is_relative(const char *filename) ATTR_PURE;
237

238
/* Net helpers */
239
int is_internal_IP(uint32_t ip, int for_listening) ATTR_PURE;
240
241
int parse_addr_port(int severity, const char *addrport, char **address,
                    uint32_t *addr, uint16_t *port_out);
242
243
int parse_port_range(const char *port, uint16_t *port_min_out,
                     uint16_t *port_max_out);
244
245
246
int parse_addr_and_port_range(const char *s, uint32_t *addr_out,
                              uint32_t *mask_out, uint16_t *port_min_out,
                              uint16_t *port_max_out);
247
int addr_mask_get_bits(uint32_t mask);
248
249
#define INET_NTOA_BUF_LEN 16
int tor_inet_ntoa(struct in_addr *in, char *buf, size_t buf_len);
250
char *tor_dup_addr(uint32_t addr) ATTR_MALLOC;
251
int get_interface_address(int severity, uint32_t *addr);
252

253
/* Process helpers */
254
255
void start_daemon(void);
void finish_daemon(const char *desired_cwd);
256
void write_pidfile(char *filename);
257

258
#endif
259