source: trunk/libtransmission/utils.h @ 13470

Last change on this file since 13470 was 13470, checked in by livings124, 10 years ago

Whoops! Revert new changes committed in r13469

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