Clean up Section 1 of rend-spec.txt.
[tor/rransom.git] / src / common / util.h
blobba38f4c7ed2f4a186c7040ae400abfb4e9aba599
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 */
6 /**
7 * \file util.h
8 * \brief Headers for util.c
9 **/
11 #ifndef _TOR_UTIL_H
12 #define _TOR_UTIL_H
14 #include "orconfig.h"
15 #include "torint.h"
16 #include "compat.h"
17 #include <stdio.h>
18 #include <stdlib.h>
20 #ifndef O_BINARY
21 #define O_BINARY 0
22 #endif
23 #ifndef O_TEXT
24 #define O_TEXT 0
25 #endif
27 /* Replace assert() with a variant that sends failures to the log before
28 * calling assert() normally.
30 #ifdef NDEBUG
31 /* Nobody should ever want to build with NDEBUG set. 99% of our asserts will
32 * be outside the critical path anyway, so it's silly to disable bug-checking
33 * throughout the entire program just because a few asserts are slowing you
34 * down. Profile, optimize the critical path, and keep debugging on.
36 * And I'm not just saying that because some of our asserts check
37 * security-critical properties.
39 #error "Sorry; we don't support building with NDEBUG."
40 #endif
42 /** Like assert(3), but send assertion failures to the log as well as to
43 * stderr. */
44 #define tor_assert(expr) STMT_BEGIN \
45 if (PREDICT_UNLIKELY(!(expr))) { \
46 log_err(LD_BUG, "%s:%d: %s: Assertion %s failed; aborting.", \
47 _SHORT_FILE_, __LINE__, __func__, #expr); \
48 fprintf(stderr,"%s:%d %s: Assertion %s failed; aborting.\n", \
49 _SHORT_FILE_, __LINE__, __func__, #expr); \
50 abort(); \
51 } STMT_END
53 /* If we're building with dmalloc, we want all of our memory allocation
54 * functions to take an extra file/line pair of arguments. If not, not.
55 * We define DMALLOC_PARAMS to the extra parameters to insert in the
56 * function prototypes, and DMALLOC_ARGS to the extra arguments to add
57 * to calls. */
58 #ifdef USE_DMALLOC
59 #define DMALLOC_PARAMS , const char *file, const int line
60 #define DMALLOC_ARGS , _SHORT_FILE_, __LINE__
61 #else
62 #define DMALLOC_PARAMS
63 #define DMALLOC_ARGS
64 #endif
66 /** Define this if you want Tor to crash when any problem comes up,
67 * so you can get a coredump and track things down. */
68 // #define tor_fragile_assert() tor_assert(0)
69 #define tor_fragile_assert()
71 /* Memory management */
72 void *_tor_malloc(size_t size DMALLOC_PARAMS) ATTR_MALLOC;
73 void *_tor_malloc_zero(size_t size DMALLOC_PARAMS) ATTR_MALLOC;
74 void *_tor_malloc_roundup(size_t *size DMALLOC_PARAMS) ATTR_MALLOC;
75 void *_tor_realloc(void *ptr, size_t size DMALLOC_PARAMS);
76 char *_tor_strdup(const char *s DMALLOC_PARAMS) ATTR_MALLOC ATTR_NONNULL((1));
77 char *_tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
78 ATTR_MALLOC ATTR_NONNULL((1));
79 void *_tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
80 ATTR_MALLOC ATTR_NONNULL((1));
81 void _tor_free(void *mem);
82 #ifdef USE_DMALLOC
83 extern int dmalloc_free(const char *file, const int line, void *pnt,
84 const int func_id);
85 #define tor_free(p) STMT_BEGIN \
86 if (PREDICT_LIKELY((p)!=NULL)) { \
87 dmalloc_free(_SHORT_FILE_, __LINE__, (p), 0); \
88 (p)=NULL; \
89 } \
90 STMT_END
91 #else
92 /** Release memory allocated by tor_malloc, tor_realloc, tor_strdup, etc.
93 * Unlike the free() function, tor_free() will still work on NULL pointers,
94 * and it sets the pointer value to NULL after freeing it.
96 * This is a macro. If you need a function pointer to release memory from
97 * tor_malloc(), use _tor_free().
99 #define tor_free(p) STMT_BEGIN \
100 if (PREDICT_LIKELY((p)!=NULL)) { \
101 free(p); \
102 (p)=NULL; \
104 STMT_END
105 #endif
107 #define tor_malloc(size) _tor_malloc(size DMALLOC_ARGS)
108 #define tor_malloc_zero(size) _tor_malloc_zero(size DMALLOC_ARGS)
109 #define tor_malloc_roundup(szp) _tor_malloc_roundup(szp DMALLOC_ARGS)
110 #define tor_realloc(ptr, size) _tor_realloc(ptr, size DMALLOC_ARGS)
111 #define tor_strdup(s) _tor_strdup(s DMALLOC_ARGS)
112 #define tor_strndup(s, n) _tor_strndup(s, n DMALLOC_ARGS)
113 #define tor_memdup(s, n) _tor_memdup(s, n DMALLOC_ARGS)
115 void tor_log_mallinfo(int severity);
117 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
118 #if defined(__GNUC__) && __GNUC__ > 3
119 #define STRUCT_OFFSET(tp, member) __builtin_offsetof(tp, member)
120 #else
121 #define STRUCT_OFFSET(tp, member) \
122 ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
123 #endif
125 /** Macro: yield a pointer to the field at position <b>off</b> within the
126 * structure <b>st</b>. Example:
127 * <pre>
128 * struct a { int foo; int bar; } x;
129 * off_t bar_offset = STRUCT_OFFSET(struct a, bar);
130 * int *bar_p = STRUCT_VAR_P(&x, bar_offset);
131 * *bar_p = 3;
132 * </pre>
134 #define STRUCT_VAR_P(st, off) ((void*) ( ((char*)(st)) + (off) ) )
136 /** Macro: yield a pointer to an enclosing structure given a pointer to
137 * a substructure at offset <b>off</b>. Example:
138 * <pre>
139 * struct base { ... };
140 * struct subtype { int x; struct base b; } x;
141 * struct base *bp = &x.base;
142 * struct *sp = SUBTYPE_P(bp, struct subtype, b);
143 * </pre>
145 #define SUBTYPE_P(p, subtype, basemember) \
146 ((void*) ( ((char*)(p)) - STRUCT_OFFSET(subtype, basemember) ))
148 /* Logic */
149 /** Macro: true if two values have the same boolean value. */
150 #define bool_eq(a,b) (!(a)==!(b))
151 /** Macro: true if two values have different boolean values. */
152 #define bool_neq(a,b) (!(a)!=!(b))
154 /* Math functions */
155 double tor_mathlog(double d) ATTR_CONST;
156 long tor_lround(double d) ATTR_CONST;
157 int tor_log2(uint64_t u64) ATTR_CONST;
158 uint64_t round_to_power_of_2(uint64_t u64);
159 unsigned round_to_next_multiple_of(unsigned number, unsigned divisor);
160 uint32_t round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor);
161 uint64_t round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor);
163 /* String manipulation */
165 /** Allowable characters in a hexadecimal string. */
166 #define HEX_CHARACTERS "0123456789ABCDEFabcdef"
167 void tor_strlower(char *s) ATTR_NONNULL((1));
168 void tor_strupper(char *s) ATTR_NONNULL((1));
169 int tor_strisprint(const char *s) ATTR_PURE ATTR_NONNULL((1));
170 int tor_strisnonupper(const char *s) ATTR_PURE ATTR_NONNULL((1));
171 int strcmpstart(const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1,2));
172 int strcmp_len(const char *s1, const char *s2, size_t len)
173 ATTR_PURE ATTR_NONNULL((1,2));
174 int strcasecmpstart(const char *s1, const char *s2)
175 ATTR_PURE ATTR_NONNULL((1,2));
176 int strcmpend(const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1,2));
177 int strcasecmpend(const char *s1, const char *s2)
178 ATTR_PURE ATTR_NONNULL((1,2));
179 int memcmpstart(const void *mem, size_t memlen,
180 const char *prefix) ATTR_PURE;
182 void tor_strstrip(char *s, const char *strip) ATTR_NONNULL((1,2));
183 long tor_parse_long(const char *s, int base, long min,
184 long max, int *ok, char **next);
185 unsigned long tor_parse_ulong(const char *s, int base, unsigned long min,
186 unsigned long max, int *ok, char **next);
187 double tor_parse_double(const char *s, double min, double max, int *ok,
188 char **next);
189 uint64_t tor_parse_uint64(const char *s, int base, uint64_t min,
190 uint64_t max, int *ok, char **next);
191 const char *hex_str(const char *from, size_t fromlen) ATTR_NONNULL((1));
192 const char *eat_whitespace(const char *s) ATTR_PURE;
193 const char *eat_whitespace_eos(const char *s, const char *eos) ATTR_PURE;
194 const char *eat_whitespace_no_nl(const char *s) ATTR_PURE;
195 const char *eat_whitespace_eos_no_nl(const char *s, const char *eos) ATTR_PURE;
196 const char *find_whitespace(const char *s) ATTR_PURE;
197 const char *find_whitespace_eos(const char *s, const char *eos) ATTR_PURE;
198 const char *find_str_at_start_of_line(const char *haystack, const char *needle)
199 ATTR_PURE;
200 int tor_mem_is_zero(const char *mem, size_t len) ATTR_PURE;
201 int tor_digest_is_zero(const char *digest) ATTR_PURE;
202 int tor_digest256_is_zero(const char *digest) ATTR_PURE;
203 char *esc_for_log(const char *string) ATTR_MALLOC;
204 const char *escaped(const char *string);
205 struct smartlist_t;
206 void wrap_string(struct smartlist_t *out, const char *string, size_t width,
207 const char *prefix0, const char *prefixRest);
208 int tor_vsscanf(const char *buf, const char *pattern, va_list ap);
209 int tor_sscanf(const char *buf, const char *pattern, ...)
210 #ifdef __GNUC__
211 __attribute__((format(scanf, 2, 3)))
212 #endif
215 int hex_decode_digit(char c);
216 void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen);
217 int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen);
219 /* Time helpers */
220 double tv_to_double(const struct timeval *tv);
221 int64_t tv_to_msec(const struct timeval *tv);
222 int64_t tv_to_usec(const struct timeval *tv);
223 long tv_udiff(const struct timeval *start, const struct timeval *end);
224 long tv_mdiff(const struct timeval *start, const struct timeval *end);
225 time_t tor_timegm(struct tm *tm);
226 #define RFC1123_TIME_LEN 29
227 void format_rfc1123_time(char *buf, time_t t);
228 int parse_rfc1123_time(const char *buf, time_t *t);
229 #define ISO_TIME_LEN 19
230 void format_local_iso_time(char *buf, time_t t);
231 void format_iso_time(char *buf, time_t t);
232 int parse_iso_time(const char *buf, time_t *t);
233 int parse_http_time(const char *buf, struct tm *tm);
234 int format_time_interval(char *out, size_t out_len, long interval);
236 /* Cached time */
237 #ifdef TIME_IS_FAST
238 #define approx_time() time(NULL)
239 #define update_approx_time(t) STMT_NIL
240 #else
241 time_t approx_time(void);
242 void update_approx_time(time_t now);
243 #endif
245 /* Fuzzy time. */
246 void ftime_set_maximum_sloppiness(int seconds);
247 void ftime_set_estimated_skew(int seconds);
248 /* typedef struct ftime_t { time_t earliest; time_t latest; } ftime_t; */
249 /* void ftime_get_window(time_t now, ftime_t *ft_out); */
250 int ftime_maybe_after(time_t now, time_t when);
251 int ftime_maybe_before(time_t now, time_t when);
252 int ftime_definitely_after(time_t now, time_t when);
253 int ftime_definitely_before(time_t now, time_t when);
255 /* File helpers */
256 ssize_t write_all(int fd, const char *buf, size_t count, int isSocket);
257 ssize_t read_all(int fd, char *buf, size_t count, int isSocket);
259 /** Return values from file_status(); see that function's documentation
260 * for details. */
261 typedef enum { FN_ERROR, FN_NOENT, FN_FILE, FN_DIR } file_status_t;
262 file_status_t file_status(const char *filename);
264 /** Possible behaviors for check_private_dir() on encountering a nonexistent
265 * directory; see that function's documentation for details. */
266 typedef enum { CPD_NONE, CPD_CREATE, CPD_CHECK } cpd_check_t;
267 int check_private_dir(const char *dirname, cpd_check_t check);
268 #define OPEN_FLAGS_REPLACE (O_WRONLY|O_CREAT|O_TRUNC)
269 #define OPEN_FLAGS_APPEND (O_WRONLY|O_CREAT|O_APPEND)
270 typedef struct open_file_t open_file_t;
271 int start_writing_to_file(const char *fname, int open_flags, int mode,
272 open_file_t **data_out);
273 FILE *start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
274 open_file_t **data_out);
275 FILE *fdopen_file(open_file_t *file_data);
276 int finish_writing_to_file(open_file_t *file_data);
277 int abort_writing_to_file(open_file_t *file_data);
278 int write_str_to_file(const char *fname, const char *str, int bin);
279 int write_bytes_to_file(const char *fname, const char *str, size_t len,
280 int bin);
281 /** An ad-hoc type to hold a string of characters and a count; used by
282 * write_chunks_to_file. */
283 typedef struct sized_chunk_t {
284 const char *bytes;
285 size_t len;
286 } sized_chunk_t;
287 int write_chunks_to_file(const char *fname, const struct smartlist_t *chunks,
288 int bin);
289 int append_bytes_to_file(const char *fname, const char *str, size_t len,
290 int bin);
292 /** Flag for read_file_to_str: open the file in binary mode. */
293 #define RFTS_BIN 1
294 /** Flag for read_file_to_str: it's okay if the file doesn't exist. */
295 #define RFTS_IGNORE_MISSING 2
297 struct stat;
298 char *read_file_to_str(const char *filename, int flags, struct stat *stat_out)
299 ATTR_MALLOC;
300 const char *parse_config_line_from_str(const char *line,
301 char **key_out, char **value_out);
302 char *expand_filename(const char *filename);
303 struct smartlist_t *tor_listdir(const char *dirname);
304 int path_is_relative(const char *filename) ATTR_PURE;
306 /* Process helpers */
307 void start_daemon(void);
308 void finish_daemon(const char *desired_cwd);
309 void write_pidfile(char *filename);
311 const char *libor_get_digests(void);
313 #endif