source: trunk/libtransmission/utils.h @ 12176

Last change on this file since 12176 was 12176, checked in by jordan, 11 years ago

(trunk libT) move the single-use utility function "evbuffer_ref_cleanup_tr_free()" from a public header into a private function to limit its visibility/scope

  • Property svn:keywords set to Date Rev Author Id
File size: 19.4 KB
Line 
1/*
2 * This file Copyright (C) Mnemosyne LLC
3 *
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.
9 *
10 * $Id: utils.h 12176 2011-03-16 17:42:32Z jordan $
11 */
12
13#ifndef TR_UTILS_H
14#define TR_UTILS_H 1
15
16#include <inttypes.h>
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 */
22
23#ifdef __cplusplus
24extern "C" {
25#endif
26
27/***
28****
29***/
30
31/**
32 * @addtogroup utils Utilities
33 * @{
34 */
35
36#ifndef FALSE
37 #define FALSE 0
38#endif
39
40#ifndef TRUE
41 #define TRUE 1
42#endif
43
44#ifndef UNUSED
45 #ifdef __GNUC__
46  #define UNUSED __attribute__ ( ( unused ) )
47 #else
48  #define UNUSED
49 #endif
50#endif
51
52#ifndef TR_GNUC_PRINTF
53 #ifdef __GNUC__
54  #define TR_GNUC_PRINTF( fmt, args ) __attribute__ ( ( format ( printf, fmt, args ) ) )
55 #else
56  #define TR_GNUC_PRINTF( fmt, args )
57 #endif
58#endif
59
60#ifndef TR_GNUC_NONNULL
61 #ifdef __GNUC__
62  #define TR_GNUC_NONNULL( ... ) __attribute__((nonnull (__VA_ARGS__)))
63 #else
64  #define TR_GNUC_NONNULL( ... )
65 #endif
66#endif
67
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 ) )
72 #else
73  #define TR_GNUC_NULL_TERMINATED
74  #define TR_GNUC_HOT
75 #endif
76#endif
77
78#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 )
79 #define TR_GNUC_PURE __attribute__ ( ( __pure__ ) )
80 #define TR_GNUC_MALLOC __attribute__ ( ( __malloc__ ) )
81#else
82 #define TR_GNUC_PURE
83 #define TR_GNUC_MALLOC
84#endif
85
86
87/***
88****
89***/
90
91const char * tr_strip_positional_args( const char * fmt );
92
93#if !defined( _ )
94 #if defined( HAVE_LIBINTL_H ) && !defined( SYS_DARWIN )
95  #include <libintl.h>
96  #define _( a ) gettext ( a )
97 #else
98  #define _( a ) ( a )
99 #endif
100#endif
101
102/* #define DISABLE_GETTEXT */
103#ifndef DISABLE_GETTEXT
104 #if defined(WIN32) || defined(TR_LIGHTWEIGHT)
105   #define DISABLE_GETTEXT
106 #endif
107#endif
108#ifdef DISABLE_GETTEXT
109 #undef _
110 #define _( a ) tr_strip_positional_args( a )
111#endif
112
113/****
114*****
115****/
116
117#define TR_MAX_MSG_LOG 10000
118
119extern tr_msg_level __tr_message_level;
120
121static inline tr_msg_level tr_getMessageLevel( void )
122{
123    return __tr_message_level;
124}
125
126static inline tr_bool tr_msgLoggingIsActive( tr_msg_level level )
127{
128    return tr_getMessageLevel() >= level;
129}
130
131void tr_msg( const char * file, int line,
132             tr_msg_level level,
133             const char * torrent,
134             const char * fmt, ... ) TR_GNUC_PRINTF( 5, 6 );
135
136#define tr_nerr( n, ... ) \
137    do { \
138        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
139            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, n, __VA_ARGS__ ); \
140    } while( 0 )
141
142#define tr_ninf( n, ... ) \
143    do { \
144        if( tr_msgLoggingIsActive( TR_MSG_INF) ) \
145            tr_msg( __FILE__, __LINE__, TR_MSG_INF, n, __VA_ARGS__ ); \
146    } while( 0 )
147
148#define tr_ndbg( n, ... ) \
149    do { \
150        if( tr_msgLoggingIsActive( TR_MSG_DBG) ) \
151            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, n, __VA_ARGS__ ); \
152    } while( 0 )
153
154#define tr_torerr( tor, ... ) \
155    do { \
156        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
157            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, tor->info.name, __VA_ARGS__ ); \
158    } while( 0 )
159
160#define tr_torinf( tor, ... ) \
161    do { \
162        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
163            tr_msg( __FILE__, __LINE__, TR_MSG_INF, tor->info.name, __VA_ARGS__ ); \
164    } while( 0 )
165
166#define tr_tordbg( tor, ... ) \
167    do { \
168        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
169            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, tor->info.name, __VA_ARGS__ ); \
170    } while( 0 )
171
172#define tr_err( ... ) \
173    do { \
174        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
175            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, NULL, __VA_ARGS__ ); \
176    } while( 0 )
177
178#define tr_inf( ... ) \
179    do { \
180        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
181            tr_msg( __FILE__, __LINE__, TR_MSG_INF, NULL, __VA_ARGS__ ); \
182    } while( 0 )
183
184#define tr_dbg( ... ) \
185    do { \
186        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
187            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, NULL, __VA_ARGS__ ); \
188    } while( 0 )
189
190
191
192FILE*          tr_getLog( void );
193
194/** @brief return true if deep logging has been enabled by the user; false otherwise */
195tr_bool tr_deepLoggingIsActive( void );
196
197void           tr_deepLog( const char * file,
198                           int          line,
199                           const char * name,
200                           const char * fmt,
201                           ... ) TR_GNUC_PRINTF( 4, 5 ) TR_GNUC_NONNULL(1,4);
202
203/** @brief set the buffer with the current time formatted for deep logging. */
204char* tr_getLogTimeStr( char * buf, int buflen ) TR_GNUC_NONNULL(1);
205
206
207/**
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
210 */
211int tr_wildmat( const char * text, const char * pattern ) TR_GNUC_NONNULL(1,2);
212
213/** @brief Portability wrapper for basename() that uses the system implementation if available */
214char* tr_basename( const char * path ) TR_GNUC_MALLOC;
215
216/** @brief Portability wrapper for dirname() that uses the system implementation if available */
217char* tr_dirname( const char * path ) TR_GNUC_MALLOC;
218
219/**
220 * @brief Portability wrapper for mkdir()
221 *
222 * A portability wrapper around mkdir().
223 * On WIN32, the `permissions' argument is unused.
224 *
225 * @return zero on success, or -1 if an error occurred
226 * (in which case errno is set appropriately).
227 */
228int tr_mkdir( const char * path, int permissions ) TR_GNUC_NONNULL(1);
229
230/**
231 * Like mkdir, but makes parent directories as needed.
232 *
233 * @return zero on success, or -1 if an error occurred
234 * (in which case errno is set appropriately).
235 */
236int tr_mkdirp( const char * path, int permissions ) TR_GNUC_NONNULL(1);
237
238
239/**
240 * @brief Loads a file and returns its contents.
241 * On failure, NULL is returned and errno is set.
242 */
243uint8_t* tr_loadFile( const char * filename, size_t * size ) TR_GNUC_MALLOC
244                                                             TR_GNUC_NONNULL(1);
245
246
247/** @brief build a filename from a series of elements using the
248           platform's correct directory separator. */
249char* tr_buildPath( const char * first_element, ... ) TR_GNUC_NULL_TERMINATED
250                                                      TR_GNUC_MALLOC;
251
252struct event;
253
254/**
255 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of seconds and microseconds
256 * @param timer
257 * @param seconds
258 * @param microseconds
259 */
260void tr_timerAdd( struct event * timer, int seconds, int microseconds ) TR_GNUC_NONNULL(1);
261
262/**
263 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of milliseconds
264 * @param timer
265 * @param milliseconds
266 */
267void tr_timerAddMsec( struct event * timer, int milliseconds ) TR_GNUC_NONNULL(1);
268
269
270/** @brief return the current date in milliseconds */
271uint64_t tr_time_msec( void );
272
273/** @brief sleep the specified number of milliseconds */
274void tr_wait_msec( long int delay_milliseconds );
275
276/**
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.
281 */
282char* tr_utf8clean( const char * str, int len ) TR_GNUC_MALLOC;
283
284
285/***
286****
287***/
288
289/* Sometimes the system defines MAX/MIN, sometimes not.
290   In the latter case, define those here since we will use them */
291#ifndef MAX
292 #define MAX( a, b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )
293#endif
294#ifndef MIN
295 #define MIN( a, b ) ( ( a ) > ( b ) ? ( b ) : ( a ) )
296#endif
297
298/***
299****
300***/
301
302/** @brief Portability wrapper around malloc() in which `0' is a safe argument */
303void* tr_malloc( size_t size );
304
305/** @brief Portability wrapper around calloc() in which `0' is a safe argument */
306void* tr_malloc0( size_t size );
307
308/** @brief Portability wrapper around free() in which `NULL' is a safe argument */
309void tr_free( void * p );
310
311/**
312 * @brief make a newly-allocated copy of a chunk of memory
313 * @param src the memory to copy
314 * @param byteCount the number of bytes to copy
315 * @return a newly-allocated copy of `src' that can be freed with tr_free()
316 */
317void* tr_memdup( const void * src, size_t byteCount );
318
319#define tr_new( struct_type, n_structs )           \
320    ( (struct_type *) tr_malloc ( sizeof ( struct_type ) * ( ( size_t) ( n_structs ) ) ) )
321
322#define tr_new0( struct_type, n_structs )          \
323    ( (struct_type *) tr_malloc0 ( sizeof ( struct_type ) * ( ( size_t) ( n_structs ) ) ) )
324
325#define tr_renew( struct_type, mem, n_structs )    \
326    ( (struct_type *) realloc ( ( mem ), sizeof ( struct_type ) * ( ( size_t) ( n_structs ) ) ) )
327
328void* tr_valloc( size_t bufLen );
329
330/**
331 * @brief make a newly-allocated copy of a substring
332 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
333 * @param len length of the substring to copy. if a length less than zero is passed in, strlen( len ) is used
334 * @return a newly-allocated copy of `in' that can be freed with tr_free()
335 */
336char* tr_strndup( const void * in, int len ) TR_GNUC_MALLOC;
337
338/**
339 * @brief make a newly-allocated copy of a string
340 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
341 * @return a newly-allocated copy of `in' that can be freed with tr_free()
342 */
343char* tr_strdup( const void * in );
344
345/**
346 * @brief like strcmp() but gracefully handles NULL strings
347 */
348int tr_strcmp0( const char * str1, const char * str2 );
349
350
351
352struct evbuffer;
353
354char* evbuffer_free_to_str( struct evbuffer * buf );
355
356/** @brief similar to bsearch() but returns the index of the lower bound */
357int tr_lowerBound( const void * key,
358                   const void * base,
359                   size_t       nmemb,
360                   size_t       size,
361                   int       (* compar)(const void* key, const void* arrayMember),
362                   tr_bool    * exact_match ) TR_GNUC_HOT TR_GNUC_NONNULL(1,5,6);
363
364
365/**
366 * @brief sprintf() a string into a newly-allocated buffer large enough to hold it
367 * @return a newly-allocated string that can be freed with tr_free()
368 */
369char* tr_strdup_printf( const char * fmt, ... ) TR_GNUC_PRINTF( 1, 2 )
370                                                TR_GNUC_MALLOC;
371
372/**
373 * @brief Translate a block of bytes into base64
374 * @return a newly-allocated string that can be freed with tr_free()
375 */
376char* tr_base64_encode( const void * input,
377                        int          inlen,
378                        int        * outlen ) TR_GNUC_MALLOC;
379
380/**
381 * @brief Translate a block of bytes from base64 into raw form
382 * @return a newly-allocated string that can be freed with tr_free()
383 */
384char* tr_base64_decode( const void * input,
385                        int          inlen,
386                        int        * outlen ) TR_GNUC_MALLOC;
387
388/** @brief Portability wrapper for strlcpy() that uses the system implementation if available */
389size_t tr_strlcpy( char * dst, const void * src, size_t siz );
390
391/** @brief Portability wrapper for snprintf() that uses the system implementation if available */
392int tr_snprintf( char * buf, size_t buflen,
393                 const char * fmt, ... ) TR_GNUC_PRINTF( 3, 4 ) TR_GNUC_NONNULL(1,3);
394
395/** @brief Convenience wrapper around strerorr() guaranteed to not return NULL
396    @param errno */
397const char* tr_strerror( int );
398
399/** @brief strips leading and trailing whitspace from a string
400    @return the stripped string */
401char* tr_strstrip( char * str );
402
403/** @brief Returns true if the string ends with the specified case-insensitive suffix */
404tr_bool tr_str_has_suffix( const char *str, const char *suffix );
405
406
407/** @brief Portability wrapper for memmem() that uses the system implementation if available */
408const char* tr_memmem( const char * haystack, size_t haystack_len,
409                       const char * needle, size_t needle_len );
410
411/** @brief Portability wrapper for strsep() that uses the system implementation if available */
412char* tr_strsep( char ** str, const char * delim );
413
414/***
415****
416***/
417
418typedef void ( tr_set_func )( void * element, void * userData );
419
420/**
421 * @brief find the differences and commonalities in two sorted sets
422 * @param a the first set
423 * @param aCount the number of elements in the set 'a'
424 * @param b the second set
425 * @param bCount the number of elements in the set 'b'
426 * @param compare the sorting method for both sets
427 * @param elementSize the sizeof the element in the two sorted sets
428 * @param in_a called for items in set 'a' but not set 'b'
429 * @param in_b called for items in set 'b' but not set 'a'
430 * @param in_both called for items that are in both sets
431 * @param userData user data passed along to in_a, in_b, and in_both
432 */
433void tr_set_compare( const void * a, size_t aCount,
434                     const void * b, size_t bCount,
435                     int compare( const void * a, const void * b ),
436                     size_t elementSize,
437                     tr_set_func in_a_cb,
438                     tr_set_func in_b_cb,
439                     tr_set_func in_both_cb,
440                     void * userData );
441
442int compareInt( const void * va, const void * vb );
443
444void tr_sha1_to_hex( char * out, const uint8_t * sha1 ) TR_GNUC_NONNULL(1,2);
445
446void tr_hex_to_sha1( uint8_t * out, const char * hex ) TR_GNUC_NONNULL(1,2);
447
448/** @brief convenience function to determine if an address is an IP address (IPv4 or IPv6) */
449tr_bool tr_addressIsIP( const char * address );
450
451/** @brief return TRUE if the url is a http or https url that Transmission understands */
452tr_bool tr_urlIsValidTracker( const char * url ) TR_GNUC_NONNULL(1);
453
454/** @brief return TRUE if the url is a [ http, https, ftp, ftps ] url that Transmission understands */
455tr_bool tr_urlIsValid( const char * url, int url_len ) TR_GNUC_NONNULL(1);
456
457/** @brief parse a URL into its component parts
458    @return zero on success or an error number if an error occurred */
459int  tr_urlParse( const char * url,
460                  int          url_len,
461                  char      ** setme_scheme,
462                  char      ** setme_host,
463                  int        * setme_port,
464                  char      ** setme_path ) TR_GNUC_NONNULL(1);
465
466
467/** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
468    @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
469double tr_getRatio( uint64_t numerator, uint64_t denominator );
470
471/**
472 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
473 *        newly-allocated array of all the integers in the set.
474 * @return a newly-allocated array of integers that must be freed with tr_free(),
475 *         or NULL if a fragment of the string can't be parsed.
476 *
477 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
478 */
479int* tr_parseNumberRange( const char * str,
480                          int str_len,
481                          int * setmeCount ) TR_GNUC_MALLOC TR_GNUC_NONNULL(1);
482
483
484/**
485 * @brief truncate a double value at a given number of decimal places.
486 *
487 * this can be used to prevent a printf() call from rounding up:
488 * call with the decimal_places argument equal to the number of
489 * decimal places in the printf()'s precision:
490 *
491 * - printf("%.2f%%",           99.999    ) ==> "100.00%"
492 *
493 * - printf("%.2f%%", tr_truncd(99.999, 2)) ==>  "99.99%"
494 *             ^                        ^
495 *             |   These should match   |
496 *             +------------------------+
497 */
498double tr_truncd( double x, int decimal_places );
499
500/* return a percent formatted string of either x.xx, xx.x or xxx */
501char* tr_strpercent( char * buf, double x, size_t buflen );
502
503/**
504 * @param buf the buffer to write the string to
505 * @param buflef buf's size
506 * @param ratio the ratio to convert to a string
507 * @param the string represntation of "infinity"
508 */
509char* tr_strratio( char * buf, size_t buflen, double ratio, const char * infinity ) TR_GNUC_NONNULL(1,4);
510
511/* return a truncated double as a string */
512char* tr_strtruncd( char * buf, double x, int precision, size_t buflen );
513
514/** @brief Portability wrapper for localtime_r() that uses the system implementation if available */
515struct tm * tr_localtime_r( const time_t *_clock, struct tm *_result );
516
517
518/**
519 * @brief move a file
520 * @return 0 on success; otherwise, return -1 and set errno
521 */
522int tr_moveFile( const char * oldpath, const char * newpath,
523                 tr_bool * renamed ) TR_GNUC_NONNULL(1,2);
524
525/** @brief Test to see if the two filenames point to the same file. */
526tr_bool tr_is_same_file( const char * filename1, const char * filename2 );
527
528/** @brief convenience function to remove an item from an array */
529void tr_removeElementFromArray( void         * array,
530                                unsigned int   index_to_remove,
531                                size_t         sizeof_element,
532                                size_t         nmemb );
533
534/***
535****
536***/
537
538/** @brief Private libtransmission variable that's visible only for inlining in tr_time() */
539extern time_t __tr_current_time;
540
541/**
542 * @brief very inexpensive form of time(NULL)
543 * @return the current epoch time in seconds
544 *
545 * This function returns a second counter that is updated once per second.
546 * If something blocks the libtransmission thread for more than a second,
547 * that counter may be thrown off, so this function is not guaranteed
548 * to always be accurate. However, it is *much* faster when 100% accuracy
549 * isn't needed
550 */
551static inline time_t tr_time( void ) { return __tr_current_time; }
552
553/** @brief Private libtransmission function to update tr_time()'s counter */
554static inline void tr_timeUpdate( time_t now ) { __tr_current_time = now; }
555
556/** @brief Portability wrapper for realpath() that uses the system implementation if available */
557char* tr_realpath( const char *path, char * resolved_path );
558
559/** @brief Portability wrapper for htonll() that uses the system implementation if available */
560uint64_t tr_htonll( uint64_t );
561
562/** @brief Portability wrapper for htonll() that uses the system implementation if available */
563uint64_t tr_ntohll( uint64_t );
564
565/***
566****
567***/
568
569/* example: tr_formatter_size_init( 1024, _("KiB"), _("MiB"), _("GiB"), _("TiB") ); */
570
571void tr_formatter_size_init( unsigned int kilo, const char * kb, const char * mb,
572                                                const char * gb, const char * tb );
573
574void tr_formatter_speed_init( unsigned int kilo, const char * kb, const char * mb,
575                                                 const char * gb, const char * tb );
576
577void tr_formatter_mem_init( unsigned int kilo, const char * kb, const char * mb,
578                                               const char * gb, const char * tb );
579
580extern unsigned int tr_speed_K;
581extern unsigned int tr_mem_K;
582extern unsigned int tr_size_K;
583
584/* format a speed from KBps into a user-readable string. */
585char* tr_formatter_speed_KBps( char * buf, double KBps, size_t buflen );
586
587/* format a memory size from bytes into a user-readable string. */
588char* tr_formatter_mem_B( char * buf, int64_t bytes, size_t buflen );
589
590/* format a memory size from MB into a user-readable string. */
591static 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 ); }
592
593/* format a file size from bytes into a user-readable string. */
594char* tr_formatter_size_B( char * buf, int64_t bytes, size_t buflen );
595
596void tr_formatter_get_units( struct tr_benc * dict );
597
598/***
599****
600***/
601
602#ifdef __cplusplus
603}
604#endif
605
606/** @} */
607
608#endif
Note: See TracBrowser for help on using the repository browser.