1 /*
2 * This file Copyright (C) 2009-2017 Mnemosyne LLC
3 *
4 * It may be used under the GNU GPL versions 2 or 3
5 * or any future license endorsed by Mnemosyne LLC.
6 *
7 */
8
9 #pragma once
10
11 #include <inttypes.h>
12 #include <stdarg.h>
13 #include <stddef.h> /* size_t */
14 #include <time.h> /* time_t */
15
16 #ifdef __cplusplus
17 extern "C"
18 {
19 #endif
20
21 /***
22 ****
23 ***/
24
25 struct evbuffer;
26 struct event;
27 struct timeval;
28
29 struct tr_error;
30
31 /**
32 * @addtogroup utils Utilities
33 * @{
34 */
35
36 char const* tr_strip_positional_args(char const* fmt);
37
38 #if !defined(_)
39 #if defined(HAVE_LIBINTL_H) && !defined(__APPLE__)
40 #include <libintl.h>
41 #define _(a) gettext(a)
42 #else
43 #define _(a) (a)
44 #endif
45 #endif
46
47 /* #define DISABLE_GETTEXT */
48 #ifndef DISABLE_GETTEXT
49 #if defined(_WIN32) || defined(TR_LIGHTWEIGHT)
50 #define DISABLE_GETTEXT
51 #endif
52 #endif
53 #ifdef DISABLE_GETTEXT
54 #undef _
55 #define _(a) tr_strip_positional_args(a)
56 #endif
57
58 /****
59 *****
60 ****/
61
62 #define TR_N_ELEMENTS(ary) (sizeof(ary) / sizeof(*(ary)))
63
64 /**
65 * @brief Rich Salz's classic implementation of shell-style pattern matching for ?, \, [], and * characters.
66 * @return 1 if the pattern matches, 0 if it doesn't, or -1 if an error occured
67 */
68 bool tr_wildmat(char const* text, char const* pattern) TR_GNUC_NONNULL(1, 2);
69
70 /**
71 * @brief Loads a file and returns its contents.
72 * On failure, NULL is returned and errno is set.
73 */
74 uint8_t* tr_loadFile(char const* filename, size_t* size, struct tr_error** error) TR_GNUC_MALLOC TR_GNUC_NONNULL(1);
75
76 /** @brief build a filename from a series of elements using the
77 platform's correct directory separator. */
78 char* tr_buildPath(char const* first_element, ...) TR_GNUC_NULL_TERMINATED TR_GNUC_MALLOC;
79
80 /**
81 * @brief Get available disk space (in bytes) for the specified folder.
82 * @return zero or positive integer on success, -1 in case of error.
83 */
84 int64_t tr_getDirFreeSpace(char const* path);
85
86 /**
87 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of seconds and microseconds
88 * @param timer the timer to set
89 * @param seconds seconds to wait
90 * @param microseconds microseconds to wait
91 */
92 void tr_timerAdd(struct event* timer, int seconds, int microseconds) TR_GNUC_NONNULL(1);
93
94 /**
95 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of milliseconds
96 * @param timer the timer to set
97 * @param milliseconds milliseconds to wait
98 */
99 void tr_timerAddMsec(struct event* timer, int milliseconds) TR_GNUC_NONNULL(1);
100
101 /** @brief return the current date in milliseconds */
102 uint64_t tr_time_msec(void);
103
104 /** @brief sleep the specified number of milliseconds */
105 void tr_wait_msec(long int delay_milliseconds);
106
107 /**
108 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
109 * @return a newly-allocated string that must be freed with tr_free()
110 * @param str the string to make a clean copy of
111 * @param len the length of the string to copy. If -1, the entire string is used.
112 */
113 char* tr_utf8clean(char const* str, size_t len) TR_GNUC_MALLOC;
114
115 #ifdef _WIN32
116
117 char* tr_win32_native_to_utf8(wchar_t const* text, int text_size);
118 char* tr_win32_native_to_utf8_ex(wchar_t const* text, int text_size, int extra_chars_before, int extra_chars_after,
119 int* real_result_size);
120 wchar_t* tr_win32_utf8_to_native(char const* text, int text_size);
121 wchar_t* tr_win32_utf8_to_native_ex(char const* text, int text_size, int extra_chars_before, int extra_chars_after,
122 int* real_result_size);
123 char* tr_win32_format_message(uint32_t code);
124
125 void tr_win32_make_args_utf8(int* argc, char*** argv);
126
127 int tr_main_win32(int argc, char** argv, int (* real_main)(int, char**));
128
129 /* *INDENT-OFF* */
130 #define tr_main(...) \
131 main_impl(__VA_ARGS__); \
132 int main(int argc, char* argv[]) \
133 { \
134 return tr_main_win32(argc, argv, &main_impl); \
135 } \
136 int main_impl(__VA_ARGS__)
137 /* *INDENT-ON* */
138
139 #else
140
141 #define tr_main main
142
143 #endif
144
145 /***
146 ****
147 ***/
148
149 /** @brief Portability wrapper around malloc() in which `0' is a safe argument */
150 void* tr_malloc(size_t size);
151
152 /** @brief Portability wrapper around calloc() in which `0' is a safe argument */
153 void* tr_malloc0(size_t size);
154
155 /** @brief Portability wrapper around reallocf() in which `0' is a safe argument */
156 void* tr_realloc(void* p, size_t size);
157
158 /** @brief Portability wrapper around free() in which `NULL' is a safe argument */
159 void tr_free(void* p);
160
161 /** @brief Free pointers in a NULL-terminated array (the array itself is not freed) */
162 void tr_free_ptrv(void* const* p);
163
164 /**
165 * @brief make a newly-allocated copy of a chunk of memory
166 * @param src the memory to copy
167 * @param byteCount the number of bytes to copy
168 * @return a newly-allocated copy of `src' that can be freed with tr_free()
169 */
170 void* tr_memdup(void const* src, size_t byteCount);
171
172 /* *INDENT-OFF* */
173 #define tr_new(struct_type, n_structs) \
174 ((struct_type*)tr_malloc(sizeof(struct_type) * (size_t)(n_structs)))
175
176 #define tr_new0(struct_type, n_structs) \
177 ((struct_type*)tr_malloc0(sizeof(struct_type) * (size_t)(n_structs)))
178
179 #define tr_renew(struct_type, mem, n_structs) \
180 ((struct_type*)tr_realloc((mem), sizeof(struct_type) * (size_t)(n_structs)))
181 /* *INDENT-ON* */
182
183 void* tr_valloc(size_t bufLen);
184
185 /**
186 * @brief make a newly-allocated copy of a substring
187 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
188 * @param len length of the substring to copy. if a length less than zero is passed in, strlen(len) is used
189 * @return a newly-allocated copy of `in' that can be freed with tr_free()
190 */
191 char* tr_strndup(void const* in, size_t len) TR_GNUC_MALLOC;
192
193 /**
194 * @brief make a newly-allocated copy of a string
195 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
196 * @return a newly-allocated copy of `in' that can be freed with tr_free()
197 */
198 char* tr_strdup(void const* in);
199
200 /**
201 * @brief like strcmp() but gracefully handles NULL strings
202 */
203 int tr_strcmp0(char const* str1, char const* str2);
204
tr_str_is_empty(char const * value)205 static inline bool tr_str_is_empty(char const* value)
206 {
207 return value == NULL || *value == '\0';
208 }
209
210 /**
211 * @brief like memcmp() but gracefully handles NULL pointers
212 */
213 int tr_memcmp0(void const* lhs, void const* rhs, size_t size);
214
215 char* evbuffer_free_to_str(struct evbuffer* buf, size_t* result_len);
216
217 /** @brief similar to bsearch() but returns the index of the lower bound */
218 int tr_lowerBound(void const* key, void const* base, size_t nmemb, size_t size, tr_voidptr_compare_func compar,
219 bool* exact_match) TR_GNUC_HOT TR_GNUC_NONNULL(1, 5, 6);
220
221 /** @brief moves the best k items to the first slots in the array. O(n) */
222 void tr_quickfindFirstK(void* base, size_t nmemb, size_t size, tr_voidptr_compare_func compar, size_t k);
223
224 /**
225 * @brief sprintf() a string into a newly-allocated buffer large enough to hold it
226 * @return a newly-allocated string that can be freed with tr_free()
227 */
228 char* tr_strdup_printf(char const* fmt, ...) TR_GNUC_MALLOC TR_GNUC_PRINTF(1, 2);
229 char* tr_strdup_vprintf(char const* fmt, va_list args) TR_GNUC_MALLOC TR_GNUC_PRINTF(1, 0);
230
231 /** @brief Portability wrapper for strlcpy() that uses the system implementation if available */
232 size_t tr_strlcpy(char* dst, void const* src, size_t siz);
233
234 /** @brief Portability wrapper for snprintf() that uses the system implementation if available */
235 int tr_snprintf(char* buf, size_t buflen, char const* fmt, ...) TR_GNUC_PRINTF(3, 4) TR_GNUC_NONNULL(1, 3);
236
237 /** @brief Convenience wrapper around strerorr() guaranteed to not return NULL
238 @param errnum the error number to describe */
239 char const* tr_strerror(int errnum);
240
241 /** @brief strips leading and trailing whitspace from a string
242 @return the stripped string */
243 char* tr_strstrip(char* str);
244
245 /** @brief Returns true if the string ends with the specified case-insensitive suffix */
246 bool tr_str_has_suffix(char const* str, char const* suffix);
247
248 /** @brief Portability wrapper for memmem() that uses the system implementation if available */
249 char const* tr_memmem(char const* haystack, size_t haystack_len, char const* needle, size_t needle_len);
250
251 /** @brief Portability wrapper for strcasestr() that uses the system implementation if available */
252 char const* tr_strcasestr(char const* haystack, char const* needle);
253
254 /** @brief Portability wrapper for strsep() that uses the system implementation if available */
255 char* tr_strsep(char** str, char const* delim);
256
257 /** @brief Concatenates array of strings with delimiter in between elements */
258 char* tr_strjoin(char const* const* arr, size_t len, char const* delim);
259
260 /***
261 ****
262 ***/
263
264 int compareInt(void const* va, void const* vb);
265
266 void tr_binary_to_hex(void const* input, char* output, size_t byte_length) TR_GNUC_NONNULL(1, 2);
267 void tr_hex_to_binary(char const* input, void* output, size_t byte_length) TR_GNUC_NONNULL(1, 2);
268
269 /** @brief convenience function to determine if an address is an IP address (IPv4 or IPv6) */
270 bool tr_addressIsIP(char const* address);
271
272 /** @brief return true if the url is a http or https or UDP url that Transmission understands */
273 bool tr_urlIsValidTracker(char const* url);
274
275 /** @brief return true if the url is a [ http, https, ftp, sftp ] url that Transmission understands */
276 bool tr_urlIsValid(char const* url, size_t url_len);
277
278 /** @brief parse a URL into its component parts
279 @return True on success or false if an error occurred */
280 bool tr_urlParse(char const* url, size_t url_len, char** setme_scheme, char** setme_host, int* setme_port,
281 char** setme_path) TR_GNUC_NONNULL(1);
282
283 /** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
284 @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
285 double tr_getRatio(uint64_t numerator, uint64_t denominator);
286
287 /**
288 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
289 * newly-allocated array of all the integers in the set.
290 * @return a newly-allocated array of integers that must be freed with tr_free(),
291 * or NULL if a fragment of the string can't be parsed.
292 *
293 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
294 */
295 int* tr_parseNumberRange(char const* str, size_t str_len, int* setmeCount) TR_GNUC_MALLOC TR_GNUC_NONNULL(1);
296
297 /**
298 * @brief truncate a double value at a given number of decimal places.
299 *
300 * this can be used to prevent a printf() call from rounding up:
301 * call with the decimal_places argument equal to the number of
302 * decimal places in the printf()'s precision:
303 *
304 * - printf("%.2f%%", 99.999) ==> "100.00%"
305 *
306 * - printf("%.2f%%", tr_truncd(99.999, 2)) ==> "99.99%"
307 * ^ ^
308 * | These should match |
309 * +------------------------+
310 */
311 double tr_truncd(double x, int decimal_places);
312
313 /* return a percent formatted string of either x.xx, xx.x or xxx */
314 char* tr_strpercent(char* buf, double x, size_t buflen);
315
316 /**
317 * @param buf the buffer to write the string to
318 * @param buflen buf's size
319 * @param ratio the ratio to convert to a string
320 * @param infinity the string represntation of "infinity"
321 */
322 char* tr_strratio(char* buf, size_t buflen, double ratio, char const* infinity) TR_GNUC_NONNULL(1, 4);
323
324 /** @brief Portability wrapper for localtime_r() that uses the system implementation if available */
325 struct tm* tr_localtime_r(time_t const* _clock, struct tm* _result);
326
327 /** @brief Portability wrapper for gettimeofday(), with tz argument dropped */
328 int tr_gettimeofday(struct timeval* tv);
329
330 /**
331 * @brief move a file
332 * @return `True` on success, `false` otherwise (with `error` set accordingly).
333 */
334 bool tr_moveFile(char const* oldpath, char const* newpath, struct tr_error** error) TR_GNUC_NONNULL(1, 2);
335
336 /** @brief convenience function to remove an item from an array */
337 void tr_removeElementFromArray(void* array, unsigned int index_to_remove, size_t sizeof_element, size_t nmemb);
338
339 /***
340 ****
341 ***/
342
343 /** @brief Private libtransmission variable that's visible only for inlining in tr_time() */
344 extern time_t __tr_current_time;
345
346 /**
347 * @brief very inexpensive form of time(NULL)
348 * @return the current epoch time in seconds
349 *
350 * This function returns a second counter that is updated once per second.
351 * If something blocks the libtransmission thread for more than a second,
352 * that counter may be thrown off, so this function is not guaranteed
353 * to always be accurate. However, it is *much* faster when 100% accuracy
354 * isn't needed
355 */
tr_time(void)356 static inline time_t tr_time(void)
357 {
358 return __tr_current_time;
359 }
360
361 /** @brief Private libtransmission function to update tr_time()'s counter */
tr_timeUpdate(time_t now)362 static inline void tr_timeUpdate(time_t now)
363 {
364 __tr_current_time = now;
365 }
366
367 /** @brief Portability wrapper for htonll() that uses the system implementation if available */
368 uint64_t tr_htonll(uint64_t);
369
370 /** @brief Portability wrapper for htonll() that uses the system implementation if available */
371 uint64_t tr_ntohll(uint64_t);
372
373 /***
374 ****
375 ***/
376
377 /* example: tr_formatter_size_init(1024, _("KiB"), _("MiB"), _("GiB"), _("TiB")); */
378
379 void tr_formatter_size_init(unsigned int kilo, char const* kb, char const* mb, char const* gb, char const* tb);
380
381 void tr_formatter_speed_init(unsigned int kilo, char const* kb, char const* mb, char const* gb, char const* tb);
382
383 void tr_formatter_mem_init(unsigned int kilo, char const* kb, char const* mb, char const* gb, char const* tb);
384
385 extern unsigned int tr_speed_K;
386 extern unsigned int tr_mem_K;
387 extern unsigned int tr_size_K;
388
389 /* format a speed from KBps into a user-readable string. */
390 char* tr_formatter_speed_KBps(char* buf, double KBps, size_t buflen);
391
392 /* format a memory size from bytes into a user-readable string. */
393 char* tr_formatter_mem_B(char* buf, int64_t bytes, size_t buflen);
394
395 /* format a memory size from MB into a user-readable string. */
tr_formatter_mem_MB(char * buf,double MBps,size_t buflen)396 static inline char* tr_formatter_mem_MB(char* buf, double MBps, size_t buflen)
397 {
398 return tr_formatter_mem_B(buf, (int64_t)(MBps * tr_mem_K * tr_mem_K), buflen);
399 }
400
401 /* format a file size from bytes into a user-readable string. */
402 char* tr_formatter_size_B(char* buf, int64_t bytes, size_t buflen);
403
404 void tr_formatter_get_units(void* dict);
405
406 /***
407 ****
408 ***/
409
410 /** @brief Check if environment variable exists. */
411 bool tr_env_key_exists(char const* key);
412
413 /** @brief Get environment variable value as int. */
414 int tr_env_get_int(char const* key, int default_value);
415
416 /** @brief Get environment variable value as string (should be freed afterwards). */
417 char* tr_env_get_string(char const* key, char const* default_value);
418
419 /***
420 ****
421 ***/
422
423 void tr_net_init(void);
424
425 /***
426 ****
427 ***/
428
429 #ifdef __cplusplus
430 }
431 #endif
432
433 /** @} */
434