4 * - various general purpose functions
6 * Copyright (C) 2001-2003 FhG Fokus
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 * 2003-01-18 un_escape function introduced for convenience of code needing
23 * the complex&slow feature of unescaping
24 * 2003-01-28 scratchpad removed (jiri)
25 * 2003-01-29 pathmax added (jiri)
26 * 2003-02-13 strlower added (janakj)
27 * 2003-02-28 scratchpad compatibility abandoned (jiri)
28 * 2003-03-30 str2int and str2float added (janakj)
29 * 2003-04-26 ZSW (jiri)
30 * 2004-03-08 updated int2str (64 bits, INT2STR_MAX_LEN used) (andrei)
31 * 2005-11-29 reverse_hex2int/int2reverse_hex switched to unsigned int (andrei)
32 * 2005-12-09 added msgid_var (andrei)
33 * 2007-05-14 added get_sys_ver() (andrei)
34 * 2007-06-05 added MAX_UVAR_VALUE(), MAX_int(a,b) MIN_int(a,b) (andrei)
35 * 2008-05-21 added ushort2sbuf(), ushort2str() (andrei)
36 * 2009-03-16 added sint2strbuf() and incremented INST2STR_MAX_LEN to account
39 /** various general purpose/helper functions.
47 #include "comp_defs.h"
49 #include <sys/types.h>
50 #include <sys/select.h>
59 #include "compiler_opt.h"
64 #include "mem/shm_mem.h"
68 /* zero-string wrapper */
69 #define ZSW(_c) ((_c)?(_c):"")
71 /* returns string beginning and length without insignificant chars */
72 #define trim_len( _len, _begin, _mystr ) \
74 (_len)=(_mystr).len; \
75 while ((_len) && ((_c=(_mystr).s[(_len)-1])==0 || _c=='\r' || \
76 _c=='\n' || _c==' ' || _c=='\t' )) \
78 (_begin)=(_mystr).s; \
79 while ((_len) && ((_c=*(_begin))==' ' || _c=='\t')) { \
85 #define trim_r( _mystr ) \
87 while( ((_mystr).len) && ( ((_c=(_mystr).s[(_mystr).len-1]))==0 ||\
88 _c=='\r' || _c=='\n' ) \
94 #define translate_pointer( _new_buf , _org_buf , _p) \
95 ( (_p)?(_new_buf + (_p-_org_buf)):(0) )
97 #define via_len(_via) \
98 ((_via)->bsize-((_via)->name.s-\
99 ((_via)->hdr.s+(_via)->hdr.len)))
103 /* rounds to sizeof(type), but type must have a 2^k size (e.g. short, int,
105 #define ROUND2TYPE(s, type) \
106 (((s)+(sizeof(type)-1))&(~(sizeof(type)-1)))
109 /* rounds to sizeof(char*) - the first 4 byte multiple on 32 bit archs
110 * and the first 8 byte multiple on 64 bit archs */
111 #define ROUND_POINTER(s) ROUND2TYPE(s, char*)
113 /* rounds to sizeof(long) - the first 4 byte multiple on 32 bit archs
114 * and the first 8 byte multiple on 64 bit archs (equiv. to ROUND_POINTER)*/
115 #define ROUND_LONG(s) ROUND2TYPE(s, long)
117 /* rounds to sizeof(int) - the first t byte multiple on 32 and 64 bit archs */
118 #define ROUND_INT(s) ROUND2TYPE(s, int)
120 /* rounds to sizeof(short) - the first 2 byte multiple */
121 #define ROUND_SHORT(s) ROUND2TYPE(s, short)
124 /* params: v - either a variable name, structure member or a type
125 * returns an unsigned long containing the maximum possible value that will
126 * fit in v, if v is unsigned or converted to an unsigned version
127 * example: MAX_UVAR_VALUE(unsigned short); MAX_UVAR_VALUE(i);
128 * MAX_UVAR_VALUE(((struct foo*)0)->bar) */
129 #define MAX_UVAR_VALUE(v) \
130 (((unsigned long)(-1))>>((sizeof(unsigned long)-sizeof(v))*8UL))
133 #define MIN_int(a, b) (((a)<(b))?(a):(b))
134 #define MAX_int(a, b) (((a)>(b))?(a):(b))
136 #define MIN_unsigned(a, b) (unsigned)(((unsigned)(a)<(unsigned)(b))?(a):(b))
137 #define MAX_unsigned(a, b) (unsigned)(((unsigned)(a)>(unsigned)(b))?(a):(b))
140 #define MIN_int(a, b) ((b)+(((a)-(b))& -((a)<(b))))
141 #define MAX_int(a, b) ((a)-(((a)-(b))& -((b)>(a))))
143 /* depend on signed right shift result which depends on the compiler */
144 #define MIN_int(a, b) ((b)+(((a)-(b))&(((a)-(b))>>(sizeof(int)*8-1))))
145 #define MAX_int(a, b) ((a)-(((a)-(b))&(((a)-(b))>>(sizeof(int)*8-1))))
149 #define append_str(_dest,_src,_len) \
151 memcpy( (_dest) , (_src) , (_len) ); \
152 (_dest) += (_len) ; \
156 /*! append _c char to _dest string */
157 #define append_chr(_dest,_c) \
161 /* links a value to a msgid */
171 /* return the value or 0 if the msg_id doesn't match */
172 #define get_msgid_val(var, id, type)\
173 ((type)((type)((var).msgid!=(id))-1)&((var).u.type##_val))
175 #define set_msgid_val(var, id, type, value)\
178 (var).u.type##_val=(value); \
181 /* char to hex conversion table */
182 static char fourbits2char[16] = { '0', '1', '2', '3', '4', '5',
183 '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
186 /* converts a str to an u. short, returns the u. short and sets *err on
187 * error and if err!=null
189 static inline unsigned short str2s(const char* s, unsigned int len,
194 unsigned char *limit;
199 str=(unsigned char*)s;
204 for(;str<limit ;str++){
205 if ( (*str <= '9' ) && (*str >= '0') ){
208 if (i>5) goto error_digits;
210 /* error unknown char */
218 /*DBG("str2s: ERROR: too many letters in [%.*s]\n", (int)len, init); */
222 /*DBG("str2s: ERROR: unexpected char %c in %.*s\n", *str, (int)len, init);
230 static inline int btostr( char *p, unsigned char val)
232 unsigned int a,b,i =0;
234 if ( (a=val/100)!=0 )
235 *(p+(i++)) = a+'0'; /*first digit*/
236 if ( (b=val%100/10)!=0 || a)
237 *(p+(i++)) = b+'0'; /*second digit*/
238 *(p+(i++)) = '0'+val%10; /*third digit*/
244 #define INT2STR_MAX_LEN (19+1+1+1) /* 2^64~= 16*10^18 =>
245 19+1 digits + sign + \0 */
248 * returns a pointer to a static buffer containing l in asciiz (with base "base") & sets len
249 * left padded with 0 to "size"
251 static inline char* int2str_base_0pad(unsigned int l, int* len, int base,
254 static char r[INT2STR_MAX_LEN];
258 BUG("base underflow\n");
262 BUG("base overflow\n");
267 r[INT2STR_MAX_LEN-1]=0; /* null terminate */
276 }while((l || i>j) && (i>=0));
278 BUG("result buffer overflow\n");
280 if (len) *len=(INT2STR_MAX_LEN-2)-i;
284 /* returns a pointer to a static buffer containing l in asciiz (with base "base") & sets len */
285 static inline char* int2str_base(unsigned int l, int* len, int base)
287 return int2str_base_0pad(l, len, base, 0);
292 /** unsigned long to str conversion using a provided buffer.
293 * Converts/prints an unsigned long to a string. The result buffer must be
294 * provided and its length must be at least INT2STR_MAX_LEN.
295 * @param l - unsigned long to be converted
296 * @param r - pointer to result buffer
297 * @param r_size - result buffer size, must be at least INT2STR_MAX_LEN.
298 * @param *len - length of the written string, _without_ the terminating 0.
299 * @return pointer _inside_ r, to the converted string (note: the string
300 * is written from the end of the buffer and not from the start and hence
301 * the returned pointer will most likely not be equal to r). In case of error
302 * it returns 0 (the only error being insufficient provided buffer size).
304 static inline char* int2strbuf(unsigned long l, char *r, int r_size, int* len)
308 if(unlikely(r_size<INT2STR_MAX_LEN)) {
311 return 0; /* => if someone misuses it => crash (feature no. 1) */
314 r[INT2STR_MAX_LEN-1]=0; /* null terminate */
321 LOG(L_CRIT, "BUG: int2str: overflow\n");
323 if (len) *len=(INT2STR_MAX_LEN-2)-i;
327 extern char ut_buf_int2str[INT2STR_MAX_LEN];
328 /** interger(long) to string conversion.
329 * This version uses a static buffer (shared with sint2str()).
330 * WARNING: other function calls might overwrite the static buffer, so
331 * either always save the result immediately or use int2strbuf(...).
332 * @param l - unsigned long to be converted/printed.
333 * @param *len - will be filled with the final length (without the terminating
335 * @return a pointer to a static buffer containing l in asciiz & sets len.
337 static inline char* int2str(unsigned long l, int* len)
339 return int2strbuf(l, ut_buf_int2str, INT2STR_MAX_LEN, len);
344 /** signed long to str conversion using a provided buffer.
345 * Converts a long to a signed string. The result buffer must be provided
346 * and its length must be at least INT2STR_MAX_LEN.
347 * @param l - long to be converted
348 * @param r - pointer to result buffer
349 * @param r_size - result buffer size, must be at least INT2STR_MAX_LEN.
350 * @param *len - length of the written string, _without_ the terminating 0.
351 * @return pointer _inside_ r, to the converted string (note: the string
352 * is written from the end of the buffer and not from the start and hence
353 * the returned pointer will most likely not be equal to r). In case of error
354 * it returns 0 (the only error being insufficient provided buffer size).
356 static inline char* sint2strbuf(long l, char* r, int r_size, int* len)
367 p = int2strbuf((unsigned long)l, r, r_size, &p_len);
368 if(sign && p_len<(r_size-1)) {
378 /** Signed INTeger-TO-STRing: converts a long to a string.
379 * This version uses a static buffer, shared with int2str().
380 * WARNING: other function calls might overwrite the static buffer, so
381 * either always save the result immediately or use sint2strbuf(...).
382 * @param l - long to be converted/printed.
383 * @param *len - will be filled with the final length (without the terminating
385 * @return a pointer to a static buffer containing l in asciiz & sets len.
387 static inline char* sint2str(long l, int* len)
389 return sint2strbuf(l, ut_buf_int2str, INT2STR_MAX_LEN, len);
394 #define USHORT2SBUF_MAX_LEN 5 /* 65535*/
395 /* converts an unsigned short (16 bits) to asciiz
396 * returns bytes written or 0 on error
397 * the passed len must be at least USHORT2SBUF_MAX chars or error
399 * (optimized for port conversion (4 or 5 digits most of the time)*/
400 static inline int ushort2sbuf(unsigned short u, char* buf, int len)
403 unsigned char a, b, c, d;
405 if (unlikely(len<USHORT2SBUF_MAX_LEN))
409 buf[offs]=a+'0'; offs+=(a!=0);
411 buf[offs]=b+'0'; offs+=((offs|b)!=0);
413 buf[offs]=c+'0'; offs+=((offs|c)!=0);
415 buf[offs]=d+'0'; offs+=((offs|d)!=0);
416 buf[offs]=(unsigned char)u+'0';
422 #define USHORT2STR_MAX_LEN (USHORT2SBUF_MAX_LEN+1) /* 65535\0*/
423 /* converts an unsigned short (16 bits) to asciiz
424 * (optimized for port conversiob (4 or 5 digits most of the time)*/
425 static inline char* ushort2str(unsigned short u)
427 static char buf[USHORT2STR_MAX_LEN];
430 len=ushort2sbuf(u, buf, sizeof(buf)-1);
437 /* faster memchr version */
438 static inline char* q_memchr(char* p, int c, unsigned int size)
444 if (*p==(unsigned char)c) return p;
450 /* returns -1 on error, 1! on success (consistent with int2reverse_hex) */
451 inline static int reverse_hex2int( char *c, int len, unsigned int* res)
457 for (pc=c+len-1; len>0; pc--, len--) {
460 if ( mychar >='0' && mychar <='9') *res+=mychar -'0';
461 else if (mychar >='a' && mychar <='f') *res+=mychar -'a'+10;
462 else if (mychar >='A' && mychar <='F') *res+=mychar -'A'+10;
468 inline static int int2reverse_hex( char **c, int *size, unsigned int nr )
470 unsigned short digit;
472 if (*size && nr==0) {
479 while (*size && nr ) {
481 **c= digit >= 10 ? digit + 'a' - 10 : digit + '0';
486 return nr ? -1 /* number not processed; too little space */ : 1;
489 /* double output length assumed ; does NOT zero-terminate */
490 inline static int string2hex(
491 /* input */ unsigned char *str, int len,
492 /* output */ char *hex )
504 *hex=fourbits2char[(*str) >> 4];
506 *hex=fourbits2char[(*str) & 0xf];
515 /* portable sleep in microseconds (no interrupt handling now) */
517 inline static void sleep_us( unsigned int nusecs )
520 tval.tv_sec =nusecs/1000000;
521 tval.tv_usec=nusecs%1000000;
522 select(0, NULL, NULL, NULL, &tval );
526 /* portable determination of max_path */
527 inline static int pathmax()
530 static int pathmax=PATH_MAX;
532 static int pathmax=0;
534 if (pathmax==0) { /* init */
535 pathmax=pathconf("/", _PC_PATH_MAX);
536 pathmax=(pathmax<=0)?PATH_MAX_GUESS:pathmax+1;
541 inline static int hex2int(char hex_digit)
543 if (hex_digit>='0' && hex_digit<='9')
544 return hex_digit-'0';
545 if (hex_digit>='a' && hex_digit<='f')
546 return hex_digit-'a'+10;
547 if (hex_digit>='A' && hex_digit<='F')
548 return hex_digit-'A'+10;
549 /* no valid hex digit ... */
550 LOG(L_ERR, "ERROR: hex2int: '%c' is no hex char\n", hex_digit );
554 /* Un-escape URI user -- it takes a pointer to original user
555 str, as well as the new, unescaped one, which MUST have
556 an allocated buffer linked to the 'str' structure ;
557 (the buffer can be allocated with the same length as
558 the original string -- the output string is always
559 shorter (if escaped characters occur) or same-long
560 as the original one).
562 only printable characters are permitted
564 <0 is returned on an unescaping error, length of the
565 unescaped string otherwise
567 inline static int un_escape(str *user, str *new_user )
572 if( new_user==0 || new_user->s==0) {
573 LOG(L_CRIT, "BUG: un_escape: called with invalid param\n");
580 for (i = 0; i < user->len; i++) {
581 if (user->s[i] == '%') {
582 if (i + 2 >= user->len) {
583 LOG(L_ERR, "ERROR: un_escape: escape sequence too short in"
585 user->len, user->s, i );
588 hi=hex2int(user->s[i + 1]);
590 LOG(L_ERR, "ERROR: un_escape: non-hex high digit in an escape sequence in"
592 user->len, user->s, i+1 );
595 lo=hex2int(user->s[i + 2]);
597 LOG(L_ERR, "ERROR: non-hex low digit in an escape sequence in "
599 user->len, user->s, i+2 );
603 if (value < 32 || value > 126) {
604 LOG(L_ERR, "ERROR: non-ASCII escaped character in '%.*s' @ %d\n",
605 user->len, user->s, i );
608 new_user->s[j] = value;
609 i+=2; /* consume the two hex digits, for cycle will move to the next char */
611 new_user->s[j] = user->s[i];
613 j++; /* good -- we translated another character */
625 * Convert a string to lower case
627 static inline void strlower(str* _s)
631 for(i = 0; i < _s->len; i++) {
632 _s->s[i] = tolower(_s->s[i]);
638 * Convert a str into integer
640 static inline int str2int(str* _s, unsigned int* _r)
645 for(i = 0; i < _s->len; i++) {
646 if ((_s->s[i] >= '0') && (_s->s[i] <= '9')) {
648 *_r += _s->s[i] - '0';
658 * Convert an str to signed integer
660 static inline int str2sint(str* _s, int* _r)
665 if (_s->len == 0) return -1;
670 if (_s->s[0] == '+') {
672 } else if (_s->s[0] == '-') {
676 for(; i < _s->len; i++) {
677 if ((_s->s[i] >= '0') && (_s->s[i] <= '9')) {
679 *_r += _s->s[i] - '0';
693 * \brief Make a copy of a str structure using shm_malloc
694 * \param dst destination
696 * \return 0 on success, -1 on failure
698 static inline int shm_str_dup(str* dst, const str* src)
700 dst->s = shm_malloc(src->len);
706 memcpy(dst->s, src->s, src->len);
715 * \brief Make a copy of a str structure using pkg_malloc
716 * \param dst destination
718 * \return 0 on success, -1 on failure
720 static inline int pkg_str_dup(str* dst, const str* src)
722 dst->s = pkg_malloc(src->len);
729 memcpy(dst->s, src->s, src->len);
735 * \brief Compare two str's case sensitive
736 * \param str1 first str
737 * \param str2 second str
738 * \return 0 if both are equal, positive if str1 is greater, negative if str2 is greater, -2 on errors
740 static inline int str_strcmp(const str *str1, const str *str2)
742 if(str1==NULL || str2==NULL || str1->s ==NULL || str2->s==NULL || str1->len<0 || str2->len<0)
744 LM_ERR("bad parameters\n");
748 if (str1->len < str2->len)
750 else if (str1->len > str2->len)
753 return strncmp(str1->s, str2->s, str1->len);
757 * \brief Compare two str's case insensitive
758 * \param str1 first str
759 * \param str2 second str
760 * \return 0 if both are equal, positive if str1 is greater, negative if str2 is greater, -2 on errors
762 static inline int str_strcasecmp(const str *str1, const str *str2)
764 if(str1==NULL || str2==NULL || str1->s ==NULL || str2->s==NULL || str1->len<0 || str2->len<0)
766 LM_ERR("bad parameters\n");
769 if (str1->len < str2->len)
771 else if (str1->len > str2->len)
774 return strncasecmp(str1->s, str2->s, str1->len);
777 /* converts a username into uid:gid,
778 * returns -1 on error & 0 on success */
779 int user2uid(int* uid, int* gid, char* user);
781 /* converts a group name into a gid
782 * returns -1 on error, 0 on success */
783 int group2gid(int* gid, char* group);
786 * Replacement of timegm (does not exists on all platforms
788 * http://lists.samba.org/archive/samba-technical/2002-November/025737.html
790 time_t _timegm(struct tm* t);
792 /* Convert time_t value that is relative to local timezone to UTC */
793 time_t local2utc(time_t in);
795 /* Convert time_t value in UTC to to value relative to local time zone */
796 time_t utc2local(time_t in);
799 * Return str as zero terminated string allocated
802 char* as_asciiz(str* s);
805 /* return system version (major.minor.minor2) as
806 * (major<<16)|(minor)<<8|(minor2)
807 * (if some of them are missing, they are set to 0)
808 * if the parameters are not null they are set to the coresp. part */
809 unsigned int get_sys_version(int* major, int* minor, int* minor2);
811 /** Converts relative pathnames to absolute pathnames. This function returns
812 * the full pathname of a file in parameter. If the file pathname does not
813 * start with / then it will be converted into an absolute pathname. The
814 * function gets the absolute directory pathname from \c base and appends \c
815 * file to it. The first parameter can be NULL, in this case the function will
816 * use the location of the main SER configuration file as reference.
817 * @param base filename to be used as reference when \c file is relative. It
818 * must be absolute. The location of the SER configuration file
819 * will be used as reference if you set the value of this
821 * @param file A pathname to be converted to absolute.
822 * @return A string containing absolute pathname, the string must be freed
823 * with free. NULL on error.
825 char* get_abs_pathname(str* base, str* file);
828 * search for needle in text
830 char *str_search(str *text, str *needle);