2 * This file Copyright (C) Mnemosyne LLC
4 * This file is licensed by the GPL version 2. Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
10 * $Id: utils.h 12032 2011-02-24 15:38:58Z jordan $
17 #include <stddef.h> /* size_t */
18 #include <stdio.h> /* FILE* */
19 #include <string.h> /* memcpy()* */
20 #include <stdlib.h> /* malloc() */
21 #include <time.h> /* time_t */
32 * @addtogroup utils Utilities
46 #define UNUSED __attribute__ ( ( unused ) )
52 #ifndef TR_GNUC_PRINTF
54 #define TR_GNUC_PRINTF( fmt, args ) __attribute__ ( ( format ( printf, fmt, args ) ) )
56 #define TR_GNUC_PRINTF( fmt, args )
60 #ifndef TR_GNUC_NONNULL
62 #define TR_GNUC_NONNULL( ... ) __attribute__((nonnull (__VA_ARGS__)))
64 #define TR_GNUC_NONNULL( ... )
68 #ifndef TR_GNUC_NULL_TERMINATED
69 #if __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 3 )
70 #define TR_GNUC_NULL_TERMINATED __attribute__ ( ( __sentinel__ ) )
71 #define TR_GNUC_HOT __attribute ( ( hot ) )
73 #define TR_GNUC_NULL_TERMINATED
78 #if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 )
79 #define TR_GNUC_PURE __attribute__ ( ( __pure__ ) )
80 #define TR_GNUC_MALLOC __attribute__ ( ( __malloc__ ) )
83 #define TR_GNUC_MALLOC
91 const char * tr_strip_positional_args( const char * fmt
);
94 #if defined( HAVE_LIBINTL_H ) && !defined( SYS_DARWIN )
96 #define _( a ) gettext ( a )
102 /* #define DISABLE_GETTEXT */
103 #ifndef DISABLE_GETTEXT
104 #if defined(WIN32) || defined(TR_LIGHTWEIGHT)
105 #define DISABLE_GETTEXT
108 #ifdef DISABLE_GETTEXT
110 #define _( a ) tr_strip_positional_args( a )
117 #define TR_MAX_MSG_LOG 10000
119 extern tr_msg_level __tr_message_level
;
121 static inline tr_msg_level
tr_getMessageLevel( void )
123 return __tr_message_level
;
126 static inline tr_bool
tr_msgLoggingIsActive( tr_msg_level level
)
128 return tr_getMessageLevel() >= level
;
131 void tr_msg( const char * file
, int line
,
133 const char * torrent
,
134 const char * fmt
, ... ) TR_GNUC_PRINTF( 5, 6 );
136 #define tr_nerr( n, ... ) \
138 if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
139 tr_msg( __FILE__, __LINE__, TR_MSG_ERR, n, __VA_ARGS__ ); \
142 #define tr_ninf( n, ... ) \
144 if( tr_msgLoggingIsActive( TR_MSG_INF) ) \
145 tr_msg( __FILE__, __LINE__, TR_MSG_INF, n, __VA_ARGS__ ); \
148 #define tr_ndbg( n, ... ) \
150 if( tr_msgLoggingIsActive( TR_MSG_DBG) ) \
151 tr_msg( __FILE__, __LINE__, TR_MSG_DBG, n, __VA_ARGS__ ); \
154 #define tr_torerr( tor, ... ) \
156 if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
157 tr_msg( __FILE__, __LINE__, TR_MSG_ERR, tor->info.name, __VA_ARGS__ ); \
160 #define tr_torinf( tor, ... ) \
162 if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
163 tr_msg( __FILE__, __LINE__, TR_MSG_INF, tor->info.name, __VA_ARGS__ ); \
166 #define tr_tordbg( tor, ... ) \
168 if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
169 tr_msg( __FILE__, __LINE__, TR_MSG_DBG, tor->info.name, __VA_ARGS__ ); \
172 #define tr_err( ... ) \
174 if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
175 tr_msg( __FILE__, __LINE__, TR_MSG_ERR, NULL, __VA_ARGS__ ); \
178 #define tr_inf( ... ) \
180 if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
181 tr_msg( __FILE__, __LINE__, TR_MSG_INF, NULL, __VA_ARGS__ ); \
184 #define tr_dbg( ... ) \
186 if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
187 tr_msg( __FILE__, __LINE__, TR_MSG_DBG, NULL, __VA_ARGS__ ); \
192 FILE* tr_getLog( void );
194 /** @brief return true if deep logging has been enabled by the user; false otherwise */
195 tr_bool
tr_deepLoggingIsActive( void );
197 void tr_deepLog( const char * file
,
201 ... ) TR_GNUC_PRINTF( 4, 5 ) TR_GNUC_NONNULL(1,4);
203 /** @brief set the buffer with the current time formatted for deep logging. */
204 char* tr_getLogTimeStr( char * buf
, int buflen
) TR_GNUC_NONNULL(1);
208 * @brief Rich Salz's classic implementation of shell-style pattern matching for ?, \, [], and * characters.
209 * @return 1 if the pattern matches, 0 if it doesn't, or -1 if an error occured
211 int tr_wildmat( const char * text
, const char * pattern
) TR_GNUC_NONNULL(1,2);
213 /** @brief Portability wrapper for basename() that uses the system implementation if available */
214 char* tr_basename( const char * path
) TR_GNUC_MALLOC
;
216 /** @brief Portability wrapper for dirname() that uses the system implementation if available */
217 char* tr_dirname( const char * path
) TR_GNUC_MALLOC
;
220 * @brief Portability wrapper for mkdir()
222 * A portability wrapper around mkdir().
223 * On WIN32, the `permissions' argument is unused.
225 * @return zero on success, or -1 if an error occurred
226 * (in which case errno is set appropriately).
228 int tr_mkdir( const char * path
, int permissions
) TR_GNUC_NONNULL(1);
231 * Like mkdir, but makes parent directories as needed.
233 * @return zero on success, or -1 if an error occurred
234 * (in which case errno is set appropriately).
236 int tr_mkdirp( const char * path
, int permissions
) TR_GNUC_NONNULL(1);
240 * @brief Loads a file and returns its contents.
241 * On failure, NULL is returned and errno is set.
243 uint8_t* tr_loadFile( const char * filename
, size_t * size
) TR_GNUC_MALLOC
247 /** @brief build a filename from a series of elements using the
248 platform's correct directory separator. */
249 char* tr_buildPath( const char * first_element
, ... ) TR_GNUC_NULL_TERMINATED
255 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of seconds and microseconds
258 * @param microseconds
260 void tr_timerAdd( struct event
* timer
, int seconds
, int microseconds
) TR_GNUC_NONNULL(1);
263 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of milliseconds
265 * @param milliseconds
267 void tr_timerAddMsec( struct event
* timer
, int milliseconds
) TR_GNUC_NONNULL(1);
270 /** @brief return the current date in milliseconds */
271 uint64_t tr_time_msec( void );
273 /** @brief sleep the specified number of milliseconds */
274 void tr_wait_msec( long int delay_milliseconds
);
277 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
278 * @return a newly-allocated string that must be freed with tr_free()
279 * @param str the string to make a clean copy of
280 * @param len the length of the string to copy. If -1, the entire string is used.
282 char* tr_utf8clean( const char * str
, int len
) TR_GNUC_MALLOC
;
289 /* Sometimes the system defines MAX/MIN, sometimes not.
290 In the latter case, define those here since we will use them */
292 #define MAX( a, b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )
295 #define MIN( a, b ) ( ( a ) > ( b ) ? ( b ) : ( a ) )
302 /** @brief Portability wrapper around malloc() in which `0' is a safe argument */
303 void* tr_malloc( size_t size
);
305 /** @brief Portability wrapper around calloc() in which `0' is a safe argument */
306 void* tr_malloc0( size_t size
);
308 /** @brief Portability wrapper around free() in which `NULL' is a safe argument */
309 void tr_free( void * p
);
312 void evbuffer_ref_cleanup_tr_free( const void * data UNUSED
, size_t datalen UNUSED
, void * extra
)
318 * @brief make a newly-allocated copy of a chunk of memory
319 * @param src the memory to copy
320 * @param byteCount the number of bytes to copy
321 * @return a newly-allocated copy of `src' that can be freed with tr_free()
323 void* tr_memdup( const void * src
, size_t byteCount
);
325 #define tr_new( struct_type, n_structs ) \
326 ( (struct_type *) tr_malloc ( sizeof ( struct_type ) * ( ( size_t) ( n_structs ) ) ) )
328 #define tr_new0( struct_type, n_structs ) \
329 ( (struct_type *) tr_malloc0 ( sizeof ( struct_type ) * ( ( size_t) ( n_structs ) ) ) )
331 #define tr_renew( struct_type, mem, n_structs ) \
332 ( (struct_type *) realloc ( ( mem ), sizeof ( struct_type ) * ( ( size_t) ( n_structs ) ) ) )
334 void* tr_valloc( size_t bufLen
);
337 * @brief make a newly-allocated copy of a substring
338 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
339 * @param len length of the substring to copy. if a length less than zero is passed in, strlen( len ) is used
340 * @return a newly-allocated copy of `in' that can be freed with tr_free()
342 char* tr_strndup( const void * in
, int len
) TR_GNUC_MALLOC
;
345 * @brief make a newly-allocated copy of a string
346 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
347 * @return a newly-allocated copy of `in' that can be freed with tr_free()
349 char* tr_strdup( const void * in
);
352 * @brief like strcmp() but gracefully handles NULL strings
354 int tr_strcmp0( const char * str1
, const char * str2
);
360 char* evbuffer_free_to_str( struct evbuffer
* buf
);
362 /** @brief similar to bsearch() but returns the index of the lower bound */
363 int tr_lowerBound( const void * key
,
367 int (* compar
)(const void* key
, const void* arrayMember
),
368 tr_bool
* exact_match
) TR_GNUC_HOT
TR_GNUC_NONNULL(1,5,6);
372 * @brief sprintf() a string into a newly-allocated buffer large enough to hold it
373 * @return a newly-allocated string that can be freed with tr_free()
375 char* tr_strdup_printf( const char * fmt
, ... ) TR_GNUC_PRINTF( 1, 2 )
379 * @brief Translate a block of bytes into base64
380 * @return a newly-allocated string that can be freed with tr_free()
382 char* tr_base64_encode( const void * input
,
384 int * outlen
) TR_GNUC_MALLOC
;
387 * @brief Translate a block of bytes from base64 into raw form
388 * @return a newly-allocated string that can be freed with tr_free()
390 char* tr_base64_decode( const void * input
,
392 int * outlen
) TR_GNUC_MALLOC
;
394 /** @brief Portability wrapper for strlcpy() that uses the system implementation if available */
395 size_t tr_strlcpy( char * dst
, const void * src
, size_t siz
);
397 /** @brief Portability wrapper for snprintf() that uses the system implementation if available */
398 int tr_snprintf( char * buf
, size_t buflen
,
399 const char * fmt
, ... ) TR_GNUC_PRINTF( 3, 4 ) TR_GNUC_NONNULL(1,3);
401 /** @brief Convenience wrapper around strerorr() guaranteed to not return NULL
403 const char* tr_strerror( int );
405 /** @brief strips leading and trailing whitspace from a string
406 @return the stripped string */
407 char* tr_strstrip( char * str
);
409 /** @brief Returns true if the string ends with the specified case-insensitive suffix */
410 tr_bool
tr_str_has_suffix( const char *str
, const char *suffix
);
413 /** @brief Portability wrapper for memmem() that uses the system implementation if available */
414 const char* tr_memmem( const char * haystack
, size_t haystack_len
,
415 const char * needle
, size_t needle_len
);
417 /** @brief Portability wrapper for strsep() that uses the system implementation if available */
418 char* tr_strsep( char ** str
, const char * delim
);
424 typedef void ( tr_set_func
)( void * element
, void * userData
);
427 * @brief find the differences and commonalities in two sorted sets
428 * @param a the first set
429 * @param aCount the number of elements in the set 'a'
430 * @param b the second set
431 * @param bCount the number of elements in the set 'b'
432 * @param compare the sorting method for both sets
433 * @param elementSize the sizeof the element in the two sorted sets
434 * @param in_a called for items in set 'a' but not set 'b'
435 * @param in_b called for items in set 'b' but not set 'a'
436 * @param in_both called for items that are in both sets
437 * @param userData user data passed along to in_a, in_b, and in_both
439 void tr_set_compare( const void * a
, size_t aCount
,
440 const void * b
, size_t bCount
,
441 int compare( const void * a
, const void * b
),
445 tr_set_func in_both_cb
,
448 int compareInt( const void * va
, const void * vb
);
450 void tr_sha1_to_hex( char * out
, const uint8_t * sha1
) TR_GNUC_NONNULL(1,2);
452 void tr_hex_to_sha1( uint8_t * out
, const char * hex
) TR_GNUC_NONNULL(1,2);
454 /** @brief convenience function to determine if an address is an IP address (IPv4 or IPv6) */
455 tr_bool
tr_addressIsIP( const char * address
);
457 /** @brief return TRUE if the url is a http or https url that Transmission understands */
458 tr_bool
tr_urlIsValidTracker( const char * url
) TR_GNUC_NONNULL(1);
460 /** @brief return TRUE if the url is a [ http, https, ftp, ftps ] url that Transmission understands */
461 tr_bool
tr_urlIsValid( const char * url
, int url_len
) TR_GNUC_NONNULL(1);
463 /** @brief parse a URL into its component parts
464 @return zero on success or an error number if an error occurred */
465 int tr_urlParse( const char * url
,
467 char ** setme_scheme
,
470 char ** setme_path
) TR_GNUC_NONNULL(1);
473 /** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
474 @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
475 double tr_getRatio( uint64_t numerator
, uint64_t denominator
);
478 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
479 * newly-allocated array of all the integers in the set.
480 * @return a newly-allocated array of integers that must be freed with tr_free(),
481 * or NULL if a fragment of the string can't be parsed.
483 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
485 int* tr_parseNumberRange( const char * str
,
487 int * setmeCount
) TR_GNUC_MALLOC
TR_GNUC_NONNULL(1);
491 * @brief truncate a double value at a given number of decimal places.
493 * this can be used to prevent a printf() call from rounding up:
494 * call with the decimal_places argument equal to the number of
495 * decimal places in the printf()'s precision:
497 * - printf("%.2f%%", 99.999 ) ==> "100.00%"
499 * - printf("%.2f%%", tr_truncd(99.999, 2)) ==> "99.99%"
501 * | These should match |
502 * +------------------------+
504 double tr_truncd( double x
, int decimal_places
);
506 /* return a percent formatted string of either x.xx, xx.x or xxx */
507 char* tr_strpercent( char * buf
, double x
, size_t buflen
);
510 * @param buf the buffer to write the string to
511 * @param buflef buf's size
512 * @param ratio the ratio to convert to a string
513 * @param the string represntation of "infinity"
515 char* tr_strratio( char * buf
, size_t buflen
, double ratio
, const char * infinity
) TR_GNUC_NONNULL(1,4);
517 /* return a truncated double as a string */
518 char* tr_strtruncd( char * buf
, double x
, int precision
, size_t buflen
);
520 /** @brief Portability wrapper for localtime_r() that uses the system implementation if available */
521 struct tm
* tr_localtime_r( const time_t *_clock
, struct tm
*_result
);
526 * @return 0 on success; otherwise, return -1 and set errno
528 int tr_moveFile( const char * oldpath
, const char * newpath
,
529 tr_bool
* renamed
) TR_GNUC_NONNULL(1,2);
531 /** @brief Test to see if the two filenames point to the same file. */
532 tr_bool
tr_is_same_file( const char * filename1
, const char * filename2
);
534 /** @brief convenience function to remove an item from an array */
535 void tr_removeElementFromArray( void * array
,
536 unsigned int index_to_remove
,
537 size_t sizeof_element
,
544 /** @brief Private libtransmission variable that's visible only for inlining in tr_time() */
545 extern time_t __tr_current_time
;
548 * @brief very inexpensive form of time(NULL)
549 * @return the current epoch time in seconds
551 * This function returns a second counter that is updated once per second.
552 * If something blocks the libtransmission thread for more than a second,
553 * that counter may be thrown off, so this function is not guaranteed
554 * to always be accurate. However, it is *much* faster when 100% accuracy
557 static inline time_t tr_time( void ) { return __tr_current_time
; }
559 /** @brief Private libtransmission function to update tr_time()'s counter */
560 static inline void tr_timeUpdate( time_t now
) { __tr_current_time
= now
; }
562 /** @brief Portability wrapper for realpath() that uses the system implementation if available */
563 char* tr_realpath( const char *path
, char * resolved_path
);
569 /* example: tr_formatter_size_init( 1024, _("KiB"), _("MiB"), _("GiB"), _("TiB") ); */
571 void tr_formatter_size_init( unsigned int kilo
, const char * kb
, const char * mb
,
572 const char * gb
, const char * tb
);
574 void tr_formatter_speed_init( unsigned int kilo
, const char * kb
, const char * mb
,
575 const char * gb
, const char * tb
);
577 void tr_formatter_mem_init( unsigned int kilo
, const char * kb
, const char * mb
,
578 const char * gb
, const char * tb
);
580 extern unsigned int tr_speed_K
;
581 extern unsigned int tr_mem_K
;
582 extern unsigned int tr_size_K
;
584 /* format a speed from KBps into a user-readable string. */
585 char* tr_formatter_speed_KBps( char * buf
, double KBps
, size_t buflen
);
587 /* format a memory size from bytes into a user-readable string. */
588 char* tr_formatter_mem_B( char * buf
, int64_t bytes
, size_t buflen
);
590 /* format a memory size from MB into a user-readable string. */
591 static inline char* tr_formatter_mem_MB( char * buf
, double MBps
, size_t buflen
) { return tr_formatter_mem_B( buf
, MBps
* tr_mem_K
* tr_mem_K
, buflen
); }
593 /* format a file size from bytes into a user-readable string. */
594 char* tr_formatter_size_B( char * buf
, int64_t bytes
, size_t buflen
);
596 void tr_formatter_get_units( struct tr_benc
* dict
);