ut.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /*
  2. *$Id$
  3. *
  4. * - various general purpose functions
  5. *
  6. * Copyright (C) 2001-2003 FhG Fokus
  7. *
  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.
  11. *
  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.
  19. *
  20. * History
  21. * ------
  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
  37. * for sign (andrei)
  38. */
  39. /** various general purpose/helper functions.
  40. * @file
  41. */
  42. #ifndef ut_h
  43. #define ut_h
  44. #include "comp_defs.h"
  45. #include <sys/types.h>
  46. #include <sys/select.h>
  47. #include <sys/time.h>
  48. #include <limits.h>
  49. #include <time.h>
  50. #include <unistd.h>
  51. #include <ctype.h>
  52. #include <string.h>
  53. #include <strings.h>
  54. #include "compiler_opt.h"
  55. #include "config.h"
  56. #include "dprint.h"
  57. #include "str.h"
  58. #include "mem/mem.h"
  59. #include "mem/shm_mem.h"
  60. /* zero-string wrapper */
  61. #define ZSW(_c) ((_c)?(_c):"")
  62. /* returns string beginning and length without insignificant chars */
  63. #define trim_len( _len, _begin, _mystr ) \
  64. do{ static char _c; \
  65. (_len)=(_mystr).len; \
  66. while ((_len) && ((_c=(_mystr).s[(_len)-1])==0 || _c=='\r' || \
  67. _c=='\n' || _c==' ' || _c=='\t' )) \
  68. (_len)--; \
  69. (_begin)=(_mystr).s; \
  70. while ((_len) && ((_c=*(_begin))==' ' || _c=='\t')) { \
  71. (_len)--;\
  72. (_begin)++; \
  73. } \
  74. }while(0)
  75. #define trim_r( _mystr ) \
  76. do{ static char _c; \
  77. while( ((_mystr).len) && ( ((_c=(_mystr).s[(_mystr).len-1]))==0 ||\
  78. _c=='\r' || _c=='\n' ) \
  79. ) \
  80. (_mystr).len--; \
  81. }while(0)
  82. #define translate_pointer( _new_buf , _org_buf , _p) \
  83. ( (_p)?(_new_buf + (_p-_org_buf)):(0) )
  84. #define via_len(_via) \
  85. ((_via)->bsize-((_via)->name.s-\
  86. ((_via)->hdr.s+(_via)->hdr.len)))
  87. /* rounds to sizeof(type), but type must have a 2^k size (e.g. short, int,
  88. * long, void*) */
  89. #define ROUND2TYPE(s, type) \
  90. (((s)+(sizeof(type)-1))&(~(sizeof(type)-1)))
  91. /* rounds to sizeof(char*) - the first 4 byte multiple on 32 bit archs
  92. * and the first 8 byte multiple on 64 bit archs */
  93. #define ROUND_POINTER(s) ROUND2TYPE(s, char*)
  94. /* rounds to sizeof(long) - the first 4 byte multiple on 32 bit archs
  95. * and the first 8 byte multiple on 64 bit archs (equiv. to ROUND_POINTER)*/
  96. #define ROUND_LONG(s) ROUND2TYPE(s, long)
  97. /* rounds to sizeof(int) - the first t byte multiple on 32 and 64 bit archs */
  98. #define ROUND_INT(s) ROUND2TYPE(s, int)
  99. /* rounds to sizeof(short) - the first 2 byte multiple */
  100. #define ROUND_SHORT(s) ROUND2TYPE(s, short)
  101. /* params: v - either a variable name, structure member or a type
  102. * returns an unsigned long containing the maximum possible value that will
  103. * fit in v, if v is unsigned or converted to an unsigned version
  104. * example: MAX_UVAR_VALUE(unsigned short); MAX_UVAR_VALUE(i);
  105. * MAX_UVAR_VALUE(((struct foo*)0)->bar) */
  106. #define MAX_UVAR_VALUE(v) \
  107. (((unsigned long)(-1))>>((sizeof(unsigned long)-sizeof(v))*8UL))
  108. #define MIN_int(a, b) (((a)<(b))?(a):(b))
  109. #define MAX_int(a, b) (((a)>(b))?(a):(b))
  110. #define MIN_unsigned(a, b) (unsigned)(((unsigned)(a)<(unsigned)(b))?(a):(b))
  111. #define MAX_unsigned(a, b) (unsigned)(((unsigned)(a)>(unsigned)(b))?(a):(b))
  112. #if 0
  113. #define MIN_int(a, b) ((b)+(((a)-(b))& -((a)<(b))))
  114. #define MAX_int(a, b) ((a)-(((a)-(b))& -((b)>(a))))
  115. /* depend on signed right shift result which depends on the compiler */
  116. #define MIN_int(a, b) ((b)+(((a)-(b))&(((a)-(b))>>(sizeof(int)*8-1))))
  117. #define MAX_int(a, b) ((a)-(((a)-(b))&(((a)-(b))>>(sizeof(int)*8-1))))
  118. #endif
  119. #define append_str(_dest,_src,_len) \
  120. do{ \
  121. memcpy( (_dest) , (_src) , (_len) ); \
  122. (_dest) += (_len) ; \
  123. }while(0); \
  124. /*! append _c char to _dest string */
  125. #define append_chr(_dest,_c) \
  126. *((_dest)++) = _c;
  127. #define is_in_str(p, in) (p < in->s + in->len && *p)
  128. /* links a value to a msgid */
  129. struct msgid_var{
  130. union{
  131. char char_val;
  132. int int_val;
  133. long long_val;
  134. }u;
  135. unsigned int msgid;
  136. };
  137. /* return the value or 0 if the msg_id doesn't match */
  138. #define get_msgid_val(var, id, type)\
  139. ((type)((type)((var).msgid!=(id))-1)&((var).u.type##_val))
  140. #define set_msgid_val(var, id, type, value)\
  141. do{\
  142. (var).msgid=(id); \
  143. (var).u.type##_val=(value); \
  144. }while(0)
  145. /* char to hex conversion table */
  146. static char fourbits2char[16] = { '0', '1', '2', '3', '4', '5',
  147. '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  148. /* converts a str to an u. short, returns the u. short and sets *err on
  149. * error and if err!=null
  150. */
  151. static inline unsigned short str2s(const char* s, unsigned int len, int *err)
  152. {
  153. unsigned short ret;
  154. int i;
  155. unsigned char *limit;
  156. unsigned char* str;
  157. /*init*/
  158. str=(unsigned char*)s;
  159. ret=i=0;
  160. limit=str+len;
  161. for(;str<limit ;str++){
  162. if ( (*str <= '9' ) && (*str >= '0') ){
  163. ret=ret*10+*str-'0';
  164. i++;
  165. if (i>5) goto error_digits;
  166. }else{
  167. /* error unknown char */
  168. goto error_char;
  169. }
  170. }
  171. if (err) *err=0;
  172. return ret;
  173. error_digits:
  174. if (err) *err=1;
  175. return 0;
  176. error_char:
  177. if (err) *err=1;
  178. return 0;
  179. }
  180. static inline int btostr( char *p, unsigned char val)
  181. {
  182. unsigned int a,b,i =0;
  183. if ( (a=val/100)!=0 )
  184. *(p+(i++)) = a+'0'; /*first digit*/
  185. if ( (b=val%100/10)!=0 || a)
  186. *(p+(i++)) = b+'0'; /*second digit*/
  187. *(p+(i++)) = '0'+val%10; /*third digit*/
  188. return i;
  189. }
  190. #define INT2STR_MAX_LEN (19+1+1+1) /* 2^64~= 16*10^18 =>
  191. 19+1 digits + sign + \0 */
  192. /*
  193. * returns a pointer to a static buffer containing l in asciiz (with base "base") & sets len
  194. * left padded with 0 to "size"
  195. */
  196. static inline char* int2str_base_0pad(unsigned int l, int* len, int base,
  197. int size)
  198. {
  199. static char r[INT2STR_MAX_LEN];
  200. int i, j;
  201. if (base < 2) {
  202. BUG("base underflow\n");
  203. return NULL;
  204. }
  205. if (base > 36) {
  206. BUG("base overflow\n");
  207. return NULL;
  208. }
  209. i=INT2STR_MAX_LEN-2;
  210. j=i-size;
  211. r[INT2STR_MAX_LEN-1]=0; /* null terminate */
  212. do{
  213. r[i]=l%base;
  214. if (r[i]<10)
  215. r[i]+='0';
  216. else
  217. r[i]+='a'-10;
  218. i--;
  219. l/=base;
  220. }while((l || i>j) && (i>=0));
  221. if (l && (i<0)){
  222. BUG("result buffer overflow\n");
  223. }
  224. if (len) *len=(INT2STR_MAX_LEN-2)-i;
  225. return &r[i+1];
  226. }
  227. /* returns a pointer to a static buffer containing l in asciiz (with base "base") & sets len */
  228. static inline char* int2str_base(unsigned int l, int* len, int base)
  229. {
  230. return int2str_base_0pad(l, len, base, 0);
  231. }
  232. /** unsigned long to str conversion using a provided buffer.
  233. * Converts/prints an unsigned long to a string. The result buffer must be
  234. * provided and its length must be at least INT2STR_MAX_LEN.
  235. * @param l - unsigned long to be converted
  236. * @param r - pointer to result buffer
  237. * @param r_size - result buffer size, must be at least INT2STR_MAX_LEN.
  238. * @param *len - length of the written string, _without_ the terminating 0.
  239. * @return pointer _inside_ r, to the converted string (note: the string
  240. * is written from the end of the buffer and not from the start and hence
  241. * the returned pointer will most likely not be equal to r). In case of error
  242. * it returns 0 (the only error being insufficient provided buffer size).
  243. */
  244. static inline char* int2strbuf(unsigned long l, char *r, int r_size, int* len)
  245. {
  246. int i;
  247. if(unlikely(r_size<INT2STR_MAX_LEN)) {
  248. if (len)
  249. *len = 0;
  250. return 0; /* => if someone misuses it => crash (feature no. 1) */
  251. }
  252. i=INT2STR_MAX_LEN-2;
  253. r[INT2STR_MAX_LEN-1]=0; /* null terminate */
  254. do{
  255. r[i]=l%10+'0';
  256. i--;
  257. l/=10;
  258. }while(l && (i>=0));
  259. if (l && (i<0)){
  260. LM_CRIT("overflow\n");
  261. }
  262. if (len) *len=(INT2STR_MAX_LEN-2)-i;
  263. return &r[i+1];
  264. }
  265. extern char ut_buf_int2str[INT2STR_MAX_LEN];
  266. /** interger(long) to string conversion.
  267. * This version uses a static buffer (shared with sint2str()).
  268. * WARNING: other function calls might overwrite the static buffer, so
  269. * either always save the result immediately or use int2strbuf(...).
  270. * @param l - unsigned long to be converted/printed.
  271. * @param *len - will be filled with the final length (without the terminating
  272. * 0).
  273. * @return a pointer to a static buffer containing l in asciiz & sets len.
  274. */
  275. static inline char* int2str(unsigned long l, int* len)
  276. {
  277. return int2strbuf(l, ut_buf_int2str, INT2STR_MAX_LEN, len);
  278. }
  279. /** signed long to str conversion using a provided buffer.
  280. * Converts a long to a signed string. The result buffer must be provided
  281. * and its length must be at least INT2STR_MAX_LEN.
  282. * @param l - long to be converted
  283. * @param r - pointer to result buffer
  284. * @param r_size - result buffer size, must be at least INT2STR_MAX_LEN.
  285. * @param *len - length of the written string, _without_ the terminating 0.
  286. * @return pointer _inside_ r, to the converted string (note: the string
  287. * is written from the end of the buffer and not from the start and hence
  288. * the returned pointer will most likely not be equal to r). In case of error
  289. * it returns 0 (the only error being insufficient provided buffer size).
  290. */
  291. static inline char* sint2strbuf(long l, char* r, int r_size, int* len)
  292. {
  293. int sign;
  294. char *p;
  295. int p_len;
  296. sign = 0;
  297. if(l<0) {
  298. sign = 1;
  299. l = -l;
  300. }
  301. p = int2strbuf((unsigned long)l, r, r_size, &p_len);
  302. if(sign && p_len<(r_size-1)) {
  303. *(--p) = '-';
  304. p_len++;;
  305. }
  306. if (likely(len))
  307. *len = p_len;
  308. return p;
  309. }
  310. /** Signed INTeger-TO-STRing: converts a long to a string.
  311. * This version uses a static buffer, shared with int2str().
  312. * WARNING: other function calls might overwrite the static buffer, so
  313. * either always save the result immediately or use sint2strbuf(...).
  314. * @param l - long to be converted/printed.
  315. * @param *len - will be filled with the final length (without the terminating
  316. * 0).
  317. * @return a pointer to a static buffer containing l in asciiz & sets len.
  318. */
  319. static inline char* sint2str(long l, int* len)
  320. {
  321. return sint2strbuf(l, ut_buf_int2str, INT2STR_MAX_LEN, len);
  322. }
  323. #define USHORT2SBUF_MAX_LEN 5 /* 65535*/
  324. /* converts an unsigned short (16 bits) to asciiz
  325. * returns bytes written or 0 on error
  326. * the passed len must be at least USHORT2SBUF_MAX chars or error
  327. * would be returned.
  328. * (optimized for port conversion (4 or 5 digits most of the time)*/
  329. static inline int ushort2sbuf(unsigned short u, char* buf, int len)
  330. {
  331. int offs;
  332. unsigned char a, b, c, d;
  333. if (unlikely(len<USHORT2SBUF_MAX_LEN))
  334. return 0;
  335. offs=0;
  336. a=u/10000; u%=10000;
  337. buf[offs]=a+'0'; offs+=(a!=0);
  338. b=u/1000; u%=1000;
  339. buf[offs]=b+'0'; offs+=((offs|b)!=0);
  340. c=u/100; u%=100;
  341. buf[offs]=c+'0'; offs+=((offs|c)!=0);
  342. d=u/10; u%=10;
  343. buf[offs]=d+'0'; offs+=((offs|d)!=0);
  344. buf[offs]=(unsigned char)u+'0';
  345. return offs+1;
  346. }
  347. #define USHORT2STR_MAX_LEN (USHORT2SBUF_MAX_LEN+1) /* 65535\0*/
  348. /* converts an unsigned short (16 bits) to asciiz
  349. * (optimized for port conversiob (4 or 5 digits most of the time)*/
  350. static inline char* ushort2str(unsigned short u)
  351. {
  352. static char buf[USHORT2STR_MAX_LEN];
  353. int len;
  354. len=ushort2sbuf(u, buf, sizeof(buf)-1);
  355. buf[len]=0;
  356. return buf;
  357. }
  358. /* fast memchr version */
  359. static inline char* q_memchr(char* p, int c, unsigned int size)
  360. {
  361. char* end;
  362. end=p+size;
  363. for(;p<end;p++){
  364. if (*p==(unsigned char)c) return p;
  365. }
  366. return 0;
  367. }
  368. /* fast reverse char search */
  369. static inline char* q_memrchr(char* p, int c, unsigned int size)
  370. {
  371. char* end;
  372. end=p+size-1;
  373. for(;end>=p;end--) {
  374. if (*end==(unsigned char)c) return end;
  375. }
  376. return 0;
  377. }
  378. /* returns -1 on error, 1! on success (consistent with int2reverse_hex) */
  379. inline static int reverse_hex2int( char *c, int len, unsigned int* res)
  380. {
  381. char *pc;
  382. char mychar;
  383. *res=0;
  384. for (pc=c+len-1; len>0; pc--, len--) {
  385. *res <<= 4 ;
  386. mychar=*pc;
  387. if ( mychar >='0' && mychar <='9') *res+=mychar -'0';
  388. else if (mychar >='a' && mychar <='f') *res+=mychar -'a'+10;
  389. else if (mychar >='A' && mychar <='F') *res+=mychar -'A'+10;
  390. else return -1;
  391. }
  392. return 1;
  393. }
  394. inline static int int2reverse_hex( char **c, int *size, unsigned int nr )
  395. {
  396. unsigned short digit;
  397. if (*size && nr==0) {
  398. **c = '0';
  399. (*c)++;
  400. (*size)--;
  401. return 1;
  402. }
  403. while (*size && nr ) {
  404. digit = nr & 0xf ;
  405. **c= digit >= 10 ? digit + 'a' - 10 : digit + '0';
  406. nr >>= 4;
  407. (*c)++;
  408. (*size)--;
  409. }
  410. return nr ? -1 /* number not processed; too little space */ : 1;
  411. }
  412. /* double output length assumed ; does NOT zero-terminate */
  413. inline static int string2hex(
  414. /* input */ unsigned char *str, int len,
  415. /* output */ char *hex )
  416. {
  417. int orig_len;
  418. if (len==0) {
  419. *hex='0';
  420. return 1;
  421. }
  422. orig_len=len;
  423. while ( len ) {
  424. *hex=fourbits2char[(*str) >> 4];
  425. hex++;
  426. *hex=fourbits2char[(*str) & 0xf];
  427. hex++;
  428. len--;
  429. str++;
  430. }
  431. return orig_len-len;
  432. }
  433. /* portable sleep in microseconds (no interrupt handling now) */
  434. inline static void sleep_us( unsigned int nusecs )
  435. {
  436. struct timeval tval;
  437. tval.tv_sec =nusecs/1000000;
  438. tval.tv_usec=nusecs%1000000;
  439. select(0, NULL, NULL, NULL, &tval );
  440. }
  441. /* portable determination of max_path */
  442. inline static int pathmax(void)
  443. {
  444. #ifdef PATH_MAX
  445. static int pathmax=PATH_MAX;
  446. #else
  447. static int pathmax=0;
  448. #endif
  449. if (pathmax==0) { /* init */
  450. pathmax=pathconf("/", _PC_PATH_MAX);
  451. pathmax=(pathmax<=0)?PATH_MAX_GUESS:pathmax+1;
  452. }
  453. return pathmax;
  454. }
  455. inline static int hex2int(char hex_digit)
  456. {
  457. if (hex_digit>='0' && hex_digit<='9')
  458. return hex_digit-'0';
  459. if (hex_digit>='a' && hex_digit<='f')
  460. return hex_digit-'a'+10;
  461. if (hex_digit>='A' && hex_digit<='F')
  462. return hex_digit-'A'+10;
  463. /* no valid hex digit ... */
  464. LM_ERR("'%c' is no hex char\n", hex_digit );
  465. return -1;
  466. }
  467. /* Un-escape URI user -- it takes a pointer to original user
  468. str, as well as the new, unescaped one, which MUST have
  469. an allocated buffer linked to the 'str' structure ;
  470. (the buffer can be allocated with the same length as
  471. the original string -- the output string is always
  472. shorter (if escaped characters occur) or same-long
  473. as the original one).
  474. only printable characters are permitted
  475. <0 is returned on an unescaping error, length of the
  476. unescaped string otherwise
  477. */
  478. inline static int un_escape(str *user, str *new_user )
  479. {
  480. int i, j, value;
  481. int hi, lo;
  482. if( new_user==0 || new_user->s==0) {
  483. LM_CRIT("invalid param\n");
  484. return -1;
  485. }
  486. new_user->len = 0;
  487. j = 0;
  488. for (i = 0; i < user->len; i++) {
  489. if (user->s[i] == '%') {
  490. if (i + 2 >= user->len) {
  491. LM_ERR("escape sequence too short in '%.*s' @ %d\n",
  492. user->len, user->s, i );
  493. goto error;
  494. }
  495. hi=hex2int(user->s[i + 1]);
  496. if (hi<0) {
  497. LM_ERR("non-hex high digit in an escape sequence in"
  498. " '%.*s' @ %d\n",
  499. user->len, user->s, i+1 );
  500. goto error;
  501. }
  502. lo=hex2int(user->s[i + 2]);
  503. if (lo<0) {
  504. LM_ERR("non-hex low digit in an escape sequence in "
  505. "'%.*s' @ %d\n",
  506. user->len, user->s, i+2 );
  507. goto error;
  508. }
  509. value=(hi<<4)+lo;
  510. if (value < 32 || value > 126) {
  511. LM_ERR("non-ASCII escaped character in '%.*s' @ %d\n",
  512. user->len, user->s, i );
  513. goto error;
  514. }
  515. new_user->s[j] = value;
  516. i+=2; /* consume the two hex digits, for cycle will move to the next char */
  517. } else {
  518. new_user->s[j] = user->s[i];
  519. }
  520. j++; /* good -- we translated another character */
  521. }
  522. new_user->len = j;
  523. return j;
  524. error:
  525. new_user->len = j;
  526. return -1;
  527. }
  528. /*
  529. * Convert a string to lower case
  530. */
  531. static inline void strlower(str* _s)
  532. {
  533. int i;
  534. if (_s == NULL) return ;
  535. if (_s->len < 0) return ;
  536. if (_s->s == NULL) return ;
  537. for(i = 0; i < _s->len; i++) {
  538. _s->s[i] = tolower(_s->s[i]);
  539. }
  540. }
  541. /*
  542. * Convert a str into integer
  543. */
  544. static inline int str2int(str* _s, unsigned int* _r)
  545. {
  546. int i;
  547. if (_s == NULL) return -1;
  548. if (_r == NULL) return -1;
  549. if (_s->len < 0) return -1;
  550. if (_s->s == NULL) return -1;
  551. *_r = 0;
  552. for(i = 0; i < _s->len; i++) {
  553. if ((_s->s[i] >= '0') && (_s->s[i] <= '9')) {
  554. *_r *= 10;
  555. *_r += _s->s[i] - '0';
  556. } else {
  557. return -1;
  558. }
  559. }
  560. return 0;
  561. }
  562. /*
  563. * Convert an str to signed integer
  564. */
  565. static inline int str2sint(str* _s, int* _r)
  566. {
  567. int i;
  568. int sign;
  569. if (_s == NULL) return -1;
  570. if (_r == NULL) return -1;
  571. if (_s->len < 0) return -1;
  572. if (_s->s == NULL) return -1;
  573. *_r = 0;
  574. sign = 1;
  575. i = 0;
  576. if (_s->s[0] == '+') {
  577. i++;
  578. } else if (_s->s[0] == '-') {
  579. sign = -1;
  580. i++;
  581. }
  582. for(; i < _s->len; i++) {
  583. if ((_s->s[i] >= '0') && (_s->s[i] <= '9')) {
  584. *_r *= 10;
  585. *_r += _s->s[i] - '0';
  586. } else {
  587. return -1;
  588. }
  589. }
  590. *_r *= sign;
  591. return 0;
  592. }
  593. #ifdef SHM_MEM
  594. /**
  595. * \brief Make a copy of a str structure using shm_malloc
  596. * \param dst destination
  597. * \param src source
  598. * \return 0 on success, -1 on failure
  599. */
  600. static inline int shm_str_dup(str* dst, const str* src)
  601. {
  602. /* NULL checks */
  603. if (dst == NULL || src == NULL) {
  604. LM_ERR("NULL src or dst\n");
  605. return -1;
  606. }
  607. /**
  608. * fallback actions:
  609. * - dst->len=0
  610. * - dst->s is allocated sizeof(void*) size
  611. * - return 0 (i.e. success)
  612. */
  613. /* fallback checks */
  614. if (src->len < 0 || src->s == NULL) {
  615. LM_WARN("shm_str_dup fallback; dup called for src->s == NULL or src->len < 0\n");
  616. dst->len = 0;
  617. } else {
  618. dst->len = src->len;
  619. }
  620. dst->s = (char*)shm_malloc(dst->len);
  621. if (dst->s == NULL) {
  622. SHM_MEM_ERROR;
  623. return -1;
  624. }
  625. /* avoid memcpy from NULL source - undefined behaviour */
  626. if (src->s == NULL) {
  627. LM_WARN("shm_str_dup fallback; skip memcpy for src->s == NULL\n");
  628. return 0;
  629. }
  630. memcpy(dst->s, src->s, dst->len);
  631. return 0;
  632. }
  633. #endif /* SHM_MEM */
  634. /**
  635. * \brief Make a copy of a str structure using pkg_malloc
  636. * \param dst destination
  637. * \param src source
  638. * \return 0 on success, -1 on failure
  639. */
  640. static inline int pkg_str_dup(str* dst, const str* src)
  641. {
  642. /* NULL checks */
  643. if (dst == NULL || src == NULL) {
  644. LM_ERR("NULL src or dst\n");
  645. return -1;
  646. }
  647. /**
  648. * fallback actions:
  649. * - dst->len=0
  650. * - dst->s is allocated sizeof(void*) size
  651. * - return 0 (i.e. success)
  652. */
  653. /* fallback checks */
  654. if (src->len < 0 || src->s == NULL) {
  655. LM_WARN("pkg_str_dup fallback; dup called for src->s == NULL or src->len < 0\n");
  656. dst->len = 0;
  657. } else {
  658. dst->len = src->len;
  659. }
  660. dst->s = (char*)pkg_malloc(dst->len);
  661. if (dst->s == NULL) {
  662. PKG_MEM_ERROR;
  663. return -1;
  664. }
  665. /* avoid memcpy from NULL source - undefined behaviour */
  666. if (src->s == NULL) {
  667. LM_WARN("pkg_str_dup fallback; skip memcpy for src->s == NULL\n");
  668. return 0;
  669. }
  670. memcpy(dst->s, src->s, dst->len);
  671. return 0;
  672. }
  673. /**
  674. * \brief Compare two str's case sensitive
  675. * \param str1 first str
  676. * \param str2 second str
  677. * \return 0 if both are equal, positive if str1 is greater, negative if str2 is greater, -2 on errors
  678. */
  679. static inline int str_strcmp(const str *str1, const str *str2)
  680. {
  681. if(str1==NULL || str2==NULL || str1->s ==NULL || str2->s==NULL || str1->len<0 || str2->len<0)
  682. {
  683. LM_ERR("bad parameters\n");
  684. return -2;
  685. }
  686. if (str1->len < str2->len)
  687. return -1;
  688. else if (str1->len > str2->len)
  689. return 1;
  690. else
  691. return strncmp(str1->s, str2->s, str1->len);
  692. }
  693. /**
  694. * \brief Compare two str's case insensitive
  695. * \param str1 first str
  696. * \param str2 second str
  697. * \return 0 if both are equal, positive if str1 is greater, negative if str2 is greater, -2 on errors
  698. */
  699. static inline int str_strcasecmp(const str *str1, const str *str2)
  700. {
  701. if(str1==NULL || str2==NULL || str1->s ==NULL || str2->s==NULL || str1->len<0 || str2->len<0)
  702. {
  703. LM_ERR("bad parameters\n");
  704. return -2;
  705. }
  706. if (str1->len < str2->len)
  707. return -1;
  708. else if (str1->len > str2->len)
  709. return 1;
  710. else
  711. return strncasecmp(str1->s, str2->s, str1->len);
  712. }
  713. #ifndef MIN
  714. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  715. #endif
  716. #ifndef MAX
  717. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  718. #endif
  719. /* INTeger-TO-Buffer-STRing : convers an unsigned long to a string
  720. * IMPORTANT: the provided buffer must be at least INT2STR_MAX_LEN size !! */
  721. static inline char* int2bstr(unsigned long l, char *s, int* len)
  722. {
  723. int i;
  724. i=INT2STR_MAX_LEN-2;
  725. s[INT2STR_MAX_LEN-1]=0;
  726. /* null terminate */
  727. do{
  728. s[i]=l%10+'0';
  729. i--;
  730. l/=10;
  731. }while(l && (i>=0));
  732. if (l && (i<0)){
  733. LM_CRIT("overflow error\n");
  734. }
  735. if (len) *len=(INT2STR_MAX_LEN-2)-i;
  736. return &s[i+1];
  737. }
  738. inline static int hexstr2int(char *c, int len, unsigned int *val)
  739. {
  740. char *pc;
  741. int r;
  742. char mychar;
  743. r=0;
  744. for (pc=c; pc<c+len; pc++) {
  745. r <<= 4 ;
  746. mychar=*pc;
  747. if ( mychar >='0' && mychar <='9') r+=mychar -'0';
  748. else if (mychar >='a' && mychar <='f') r+=mychar -'a'+10;
  749. else if (mychar >='A' && mychar <='F') r+=mychar -'A'+10;
  750. else return -1;
  751. }
  752. *val = r;
  753. return 0;
  754. }
  755. /*
  756. * Convert a str (base 10 or 16) into integer
  757. */
  758. static inline int strno2int( str *val, unsigned int *mask )
  759. {
  760. /* hexa or decimal*/
  761. if (val->len>2 && val->s[0]=='0' && val->s[1]=='x') {
  762. return hexstr2int( val->s+2, val->len-2, mask);
  763. } else {
  764. return str2int( val, mask);
  765. }
  766. }
  767. /* converts a username into uid:gid,
  768. * returns -1 on error & 0 on success */
  769. int user2uid(int* uid, int* gid, char* user);
  770. /* converts a group name into a gid
  771. * returns -1 on error, 0 on success */
  772. int group2gid(int* gid, char* group);
  773. /*
  774. * Replacement of timegm (does not exists on all platforms
  775. * Taken from
  776. * http://lists.samba.org/archive/samba-technical/2002-November/025737.html
  777. */
  778. time_t _timegm(struct tm* t);
  779. /* Convert time_t value that is relative to local timezone to UTC */
  780. time_t local2utc(time_t in);
  781. /* Convert time_t value in UTC to to value relative to local time zone */
  782. time_t utc2local(time_t in);
  783. /*
  784. * Return str as zero terminated string allocated
  785. * using pkg_malloc
  786. */
  787. char* as_asciiz(str* s);
  788. /* return system version (major.minor.minor2) as
  789. * (major<<16)|(minor)<<8|(minor2)
  790. * (if some of them are missing, they are set to 0)
  791. * if the parameters are not null they are set to the coresp. part */
  792. unsigned int get_sys_version(int* major, int* minor, int* minor2);
  793. /** Converts relative pathnames to absolute pathnames. This function returns
  794. * the full pathname of a file in parameter. If the file pathname does not
  795. * start with / then it will be converted into an absolute pathname. The
  796. * function gets the absolute directory pathname from \c base and appends \c
  797. * file to it. The first parameter can be NULL, in this case the function will
  798. * use the location of the main SER configuration file as reference.
  799. * @param base filename to be used as reference when \c file is relative. It
  800. * must be absolute. The location of the SER configuration file
  801. * will be used as reference if you set the value of this
  802. * parameter to NULL.
  803. * @param file A pathname to be converted to absolute.
  804. * @return A string containing absolute pathname, the string must be freed
  805. * with free. NULL on error.
  806. */
  807. char* get_abs_pathname(str* base, str* file);
  808. /**
  809. * search for needle in text
  810. */
  811. char *str_search(str *text, str *needle);
  812. /*
  813. * ser_memmem() returns the location of the first occurrence of data
  814. * pattern b2 of size len2 in memory block b1 of size len1 or
  815. * NULL if none is found. Obtained from NetBSD.
  816. */
  817. void * ser_memmem(const void *b1, const void *b2, size_t len1, size_t len2);
  818. /*
  819. * ser_memrmem() returns the location of the last occurrence of data
  820. * pattern b2 of size len2 in memory block b1 of size len1 or
  821. * NULL if none is found.
  822. */
  823. void * ser_memrmem(const void *b1, const void *b2, size_t len1, size_t len2);
  824. #endif