belle_sip_utils.c 34.2 KB
Newer Older
jehan's avatar
jehan committed
1 2 3
/*
	belle-sip - SIP (RFC3261) library.
    Copyright (C) 2010  Belledonne Communications SARL
jehan's avatar
jehan committed
4

jehan's avatar
jehan committed
5 6
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
7
    the Free Software Foundation, either version 2 of the License, or
jehan's avatar
jehan committed
8 9 10 11 12 13 14 15 16 17
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
18

Simon Morlat's avatar
Simon Morlat committed
19 20

#define _CRT_RAND_S
21
#include <stddef.h>
Simon Morlat's avatar
Simon Morlat committed
22
#include <stdlib.h>
23
#include <sys/stat.h>
24
#include "belle_sip_internal.h"
jehan's avatar
jehan committed
25

jehan's avatar
jehan committed
26
#include "clock_gettime.h" /*for apple*/
jehan's avatar
jehan committed
27

28
#ifndef _WIN32
29
#include <unistd.h>
Simon Morlat's avatar
Simon Morlat committed
30
#include <sys/time.h> /*for gettimeofday*/
31
#include <dirent.h> /* available on POSIX system only */
32 33
#else
#include <direct.h>
Simon Morlat's avatar
Simon Morlat committed
34 35
#endif

jehan's avatar
jehan committed
36 37 38 39 40 41 42 43 44 45 46 47 48
static FILE *__log_file=0;

/**
 *@param file a FILE pointer where to output the belle logs.
 *
**/
void belle_sip_set_log_file(FILE *file)
{
        __log_file=file;
}

static void __belle_sip_logv_out(belle_sip_log_level lev, const char *fmt, va_list args);

49
belle_sip_log_function_t belle_sip_logv_out=__belle_sip_logv_out;
jehan's avatar
jehan committed
50 51 52 53 54

/**
 *@param func: your logging function, compatible with the OrtpLogFunc prototype.
 *
**/
55
void belle_sip_set_log_handler(belle_sip_log_function_t func){
jehan's avatar
jehan committed
56 57 58
        belle_sip_logv_out=func;
}

59 60 61
belle_sip_log_function_t belle_sip_get_log_handler(){
        return belle_sip_logv_out;
}
jehan's avatar
jehan committed
62

Simon Morlat's avatar
Simon Morlat committed
63
unsigned int __belle_sip_log_mask=BELLE_SIP_LOG_WARNING|BELLE_SIP_LOG_ERROR|BELLE_SIP_LOG_FATAL;
jehan's avatar
jehan committed
64 65

/**
Simon Morlat's avatar
Simon Morlat committed
66 67
 * @ param level: either BELLE_SIP_LOG_DEBUG, BELLE_SIP_LOG_MESSAGE, BELLE_SIP_LOG_WARNING, BELLE_SIP_LOG_ERROR
 * BELLE_SIP_LOG_FATAL .
jehan's avatar
jehan committed
68
**/
Simon Morlat's avatar
Simon Morlat committed
69 70
void belle_sip_set_log_level(int level){
        __belle_sip_log_mask=(level<<1)-1;
jehan's avatar
jehan committed
71 72 73 74 75 76 77
}

char * belle_sip_strdup_vprintf(const char *fmt, va_list ap)
{
        /* Guess we need no more than 100 bytes. */
        int n, size = 200;
        char *p,*np;
78
#ifndef _WIN32
jehan's avatar
jehan committed
79 80 81 82 83 84 85
        va_list cap;/*copy of our argument list: a va_list cannot be re-used (SIGSEGV on linux 64 bits)*/
#endif
        if ((p = (char *) malloc (size)) == NULL)
                return NULL;
        while (1)
        {
                /* Try to print in the allocated space. */
86
#ifndef _WIN32
jehan's avatar
jehan committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
                va_copy(cap,ap);
                n = vsnprintf (p, size, fmt, cap);
                va_end(cap);
#else
                /*this works on 32 bits, luckily*/
                n = vsnprintf (p, size, fmt, ap);
#endif
                /* If that worked, return the string. */
                if (n > -1 && n < size)
                        return p;
                //printf("Reallocing space.\n");
                /* Else try again with more space. */
                if (n > -1)     /* glibc 2.1 */
                        size = n + 1;   /* precisely what is needed */
                else            /* glibc 2.0 */
                        size *= 2;      /* twice the old size */
                if ((np = (char *) realloc (p, size)) == NULL)
                  {
                    free(p);
                    return NULL;
                  }
                else
                  {
                    p = np;
                  }
        }
}

char *belle_sip_strdup_printf(const char *fmt,...){
        char *ret;
        va_list args;
        va_start (args, fmt);
        ret=belle_sip_strdup_vprintf(fmt, args);
        va_end (args);
        return ret;
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
char * belle_sip_strcat_vprintf(char* dst, const char *fmt, va_list ap){
	char *ret;
	unsigned long dstlen, retlen;

	ret=belle_sip_strdup_vprintf(fmt, ap);
	dstlen = strlen(dst);
	retlen = strlen(ret);

	if ((dst = belle_sip_realloc(dst, dstlen+retlen+1)) != NULL){
		strncat(dst,ret,retlen);
		dst[dstlen+retlen] = '\0';
		belle_sip_free(ret);
		return dst;
	} else {
		belle_sip_free(ret);
		return NULL;
	}
}

char *belle_sip_strcat_printf(char* dst, const char *fmt,...){
	char *ret;
	va_list args;
	va_start (args, fmt);
	ret=belle_sip_strcat_vprintf(dst, fmt, args);
	va_end (args);
	return ret;
}

152
belle_sip_error_code belle_sip_snprintf(char *buff, size_t buff_size, size_t *offset, const char *fmt, ...) {
153
	belle_sip_error_code ret;
Ghislain MARY's avatar
Ghislain MARY committed
154 155
	va_list args;
	va_start(args, fmt);
156 157 158 159 160 161 162 163 164
	ret = belle_sip_snprintf_valist(buff, buff_size, offset, fmt, args);
	va_end(args);

	return ret;
}

belle_sip_error_code belle_sip_snprintf_valist(char *buff, size_t buff_size, size_t *offset, const char *fmt, va_list args) {
	int ret;
	belle_sip_error_code error = BELLE_SIP_OK;
Ghislain MARY's avatar
Ghislain MARY committed
165 166
	ret = vsnprintf(buff + *offset, buff_size - *offset, fmt, args);
	if ((ret < 0)
167
		|| (ret >= (int)(buff_size - *offset))) {
Ghislain MARY's avatar
Ghislain MARY committed
168 169 170 171 172 173 174 175
			error = BELLE_SIP_BUFFER_OVERFLOW;
		*offset = buff_size;
	} else {
		*offset += ret;
	}
	return error;
}

176
#if defined(_WIN32) || defined(_WIN32_WCE)
jehan's avatar
jehan committed
177 178 179 180 181
#define ENDLINE "\r\n"
#else
#define ENDLINE "\n"
#endif

182
#if defined(_WIN32) || defined(_WIN32_WCE)
jehan's avatar
jehan committed
183 184
void belle_sip_logv(int level, const char *fmt, va_list args)
{
Simon Morlat's avatar
Simon Morlat committed
185 186 187
	if (belle_sip_logv_out!=NULL && belle_sip_log_level_enabled(level))
		belle_sip_logv_out(level,fmt,args);
	if ((level)==BELLE_SIP_LOG_FATAL) abort();
jehan's avatar
jehan committed
188 189 190
}
#endif

Simon Morlat's avatar
Simon Morlat committed
191

192
#ifdef _WIN32
Simon Morlat's avatar
Simon Morlat committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
static int belle_sip_gettimeofday (struct timeval *tv, void* tz)
{
	union
	{
		__int64 ns100; /*time since 1 Jan 1601 in 100ns units */
		FILETIME fileTime;
	} now;

	GetSystemTimeAsFileTime (&now.fileTime);
	tv->tv_usec = (long) ((now.ns100 / 10LL) % 1000000LL);
	tv->tv_sec = (long) ((now.ns100 - 116444736000000000LL) / 10000000LL);
	return 0;
}
#else
#define belle_sip_gettimeofday gettimeofday
#endif

jehan's avatar
jehan committed
210
static void __belle_sip_logv_out(belle_sip_log_level lev, const char *fmt, va_list args){
Simon Morlat's avatar
Simon Morlat committed
211 212 213 214
	const char *lname="undef";
	char *msg;
	struct timeval tp;
	struct tm *lt;
215
#ifndef _WIN32
Simon Morlat's avatar
Simon Morlat committed
216
	struct tm tmstorage;
217
#endif
Simon Morlat's avatar
Simon Morlat committed
218
	time_t curtime;
219

Simon Morlat's avatar
Simon Morlat committed
220 221
	belle_sip_gettimeofday(&tp,NULL);
	curtime=tp.tv_sec;
222
#ifdef _WIN32
Simon Morlat's avatar
Simon Morlat committed
223 224 225 226
	lt = localtime(&curtime);
#else
	lt = localtime_r(&curtime,&tmstorage);
#endif
227

Simon Morlat's avatar
Simon Morlat committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
	if (__log_file==NULL) __log_file=stderr;
	switch(lev){
		case BELLE_SIP_LOG_DEBUG:
			lname="debug";
			break;
		case BELLE_SIP_LOG_MESSAGE:
			lname="message";
			break;
		case BELLE_SIP_LOG_WARNING:
			lname="warning";
			break;
		case BELLE_SIP_LOG_ERROR:
			lname="error";
			break;
		case BELLE_SIP_LOG_FATAL:
			lname="fatal";
			break;
		default:
			belle_sip_fatal("Bad level !");
	}
	msg=belle_sip_strdup_vprintf(fmt,args);
jehan's avatar
jehan committed
249
#if defined(_MSC_VER) && !defined(_WIN32_WCE)
250
	#ifndef _UNICODE
Simon Morlat's avatar
Simon Morlat committed
251 252
	OutputDebugStringA(msg);
	OutputDebugStringA("\r\n");
253
	#else
Simon Morlat's avatar
Simon Morlat committed
254 255
	{
		int len=strlen(msg);
256
		wchar_t *tmp=(wchar_t*)belle_sip_malloc0((len+1)*sizeof(wchar_t));
Simon Morlat's avatar
Simon Morlat committed
257 258 259 260 261
		mbstowcs(tmp,msg,len);
		OutputDebugStringW(tmp);
		OutputDebugStringW(L"\r\n");
		belle_sip_free(tmp);
	}
262
	#endif
jehan's avatar
jehan committed
263
#endif
264
	fprintf(__log_file,"%i-%.2i-%.2i %.2i:%.2i:%.2i:%.3i belle-sip-%s-%s" ENDLINE,1900+lt->tm_year,lt->tm_mon+1,lt->tm_mday,lt->tm_hour,lt->tm_min,lt->tm_sec,(int)(tp.tv_usec/1000), lname,msg);
Simon Morlat's avatar
Simon Morlat committed
265 266
	fflush(__log_file);
	free(msg);
jehan's avatar
jehan committed
267 268
}

269
belle_sip_list_t* belle_sip_list_new(void *data){
270
	belle_sip_list_t* new_elem=belle_sip_new0(belle_sip_list_t);
jehan's avatar
jehan committed
271 272 273 274
	new_elem->data=data;
	return new_elem;
}

275
belle_sip_list_t*  belle_sip_list_append_link(belle_sip_list_t* elem,belle_sip_list_t *new_elem){
276
	belle_sip_list_t* it=elem;
277 278
	if (elem==NULL)  return new_elem;
	if (new_elem==NULL)  return elem;
jehan's avatar
jehan committed
279 280 281 282 283 284
	while (it->next!=NULL) it=belle_sip_list_next(it);
	it->next=new_elem;
	new_elem->prev=it;
	return elem;
}

285 286 287 288 289
belle_sip_list_t*  belle_sip_list_append(belle_sip_list_t* elem, void * data){
	belle_sip_list_t* new_elem=belle_sip_list_new(data);
	return belle_sip_list_append_link(elem,new_elem);
}

290 291
belle_sip_list_t*  belle_sip_list_prepend(belle_sip_list_t* elem, void *data){
	belle_sip_list_t* new_elem=belle_sip_list_new(data);
jehan's avatar
jehan committed
292 293 294 295 296 297 298
	if (elem!=NULL) {
		new_elem->next=elem;
		elem->prev=new_elem;
	}
	return new_elem;
}

299 300 301 302 303 304 305
belle_sip_list_t * belle_sip_list_last_elem(const belle_sip_list_t *l){
	if (l==NULL) return NULL;
	while(l->next){
		l=l->next;
	}
	return (belle_sip_list_t*)l;
}
jehan's avatar
jehan committed
306

307 308
belle_sip_list_t*  belle_sip_list_concat(belle_sip_list_t* first, belle_sip_list_t* second){
	belle_sip_list_t* it=first;
jehan's avatar
jehan committed
309
	if (it==NULL) return second;
310
	if (second==NULL) return first;
jehan's avatar
jehan committed
311 312 313 314 315 316
	while(it->next!=NULL) it=belle_sip_list_next(it);
	it->next=second;
	second->prev=it;
	return first;
}

317 318 319
belle_sip_list_t*  belle_sip_list_free(belle_sip_list_t* list){
	belle_sip_list_t* elem = list;
	belle_sip_list_t* tmp;
jehan's avatar
jehan committed
320 321 322 323
	if (list==NULL) return NULL;
	while(elem->next!=NULL) {
		tmp = elem;
		elem = elem->next;
324
		belle_sip_free(tmp);
jehan's avatar
jehan committed
325
	}
326
	belle_sip_free(elem);
jehan's avatar
jehan committed
327 328 329
	return NULL;
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
belle_sip_list_t * belle_sip_list_free_with_data(belle_sip_list_t *list, void (*freefunc)(void*)){
	belle_sip_list_t* elem = list;
	belle_sip_list_t* tmp;
	if (list==NULL) return NULL;
	while(elem->next!=NULL) {
		tmp = elem;
		elem = elem->next;
		freefunc(tmp->data);
		belle_sip_free(tmp);
	}
	freefunc(elem->data);
	belle_sip_free(elem);
	return NULL;
}


346
belle_sip_list_t*  _belle_sip_list_remove(belle_sip_list_t* first, void *data, int warn_if_not_found){
347
	belle_sip_list_t* it;
jehan's avatar
jehan committed
348
	it=belle_sip_list_find(first,data);
Simon Morlat's avatar
Simon Morlat committed
349
	if (it) return belle_sip_list_delete_link(first,it);
350
	else if (warn_if_not_found){
jehan's avatar
jehan committed
351 352
		belle_sip_warning("belle_sip_list_remove: no element with %p data was in the list", data);
	}
353 354 355 356 357
	return first;
}

belle_sip_list_t*  belle_sip_list_remove(belle_sip_list_t* first, void *data){
	return _belle_sip_list_remove(first, data, TRUE);
jehan's avatar
jehan committed
358 359
}

360
int belle_sip_list_size(const belle_sip_list_t* first){
jehan's avatar
jehan committed
361 362 363 364 365 366 367 368
	int n=0;
	while(first!=NULL){
		++n;
		first=first->next;
	}
	return n;
}

369
void belle_sip_list_for_each(const belle_sip_list_t* list, void (*func)(void *)){
jehan's avatar
jehan committed
370 371 372 373 374
	for(;list!=NULL;list=list->next){
		func(list->data);
	}
}

375
void belle_sip_list_for_each2(const belle_sip_list_t* list, void (*func)(void *, void *), void *user_data){
jehan's avatar
jehan committed
376 377 378 379 380
	for(;list!=NULL;list=list->next){
		func(list->data,user_data);
	}
}

381
belle_sip_list_t * belle_sip_list_pop_front(belle_sip_list_t *list, void **front_data){
382 383
	belle_sip_list_t *front_elem=list;
	if (front_elem==NULL){
384 385 386
		*front_data=NULL;
		return NULL;
	}
387 388 389
	*front_data=front_elem->data;
	list=belle_sip_list_remove_link(list,front_elem);
	belle_sip_free(front_elem);
390 391 392
	return list;
}

393 394
belle_sip_list_t* belle_sip_list_remove_link(belle_sip_list_t* list, belle_sip_list_t* elem){
	belle_sip_list_t* ret;
jehan's avatar
jehan committed
395 396 397 398 399 400 401 402 403 404 405 406 407 408
	if (elem==list){
		ret=elem->next;
		elem->prev=NULL;
		elem->next=NULL;
		if (ret!=NULL) ret->prev=NULL;
		return ret;
	}
	elem->prev->next=elem->next;
	if (elem->next!=NULL) elem->next->prev=elem->prev;
	elem->next=NULL;
	elem->prev=NULL;
	return list;
}

Simon Morlat's avatar
Simon Morlat committed
409 410
belle_sip_list_t * belle_sip_list_delete_link(belle_sip_list_t* list, belle_sip_list_t* elem){
	belle_sip_list_t *ret=belle_sip_list_remove_link(list,elem);
411
	belle_sip_free(elem);
Simon Morlat's avatar
Simon Morlat committed
412 413 414
	return ret;
}

415
belle_sip_list_t* belle_sip_list_find(belle_sip_list_t* list, void *data){
jehan's avatar
jehan committed
416 417 418 419 420 421
	for(;list!=NULL;list=list->next){
		if (list->data==data) return list;
	}
	return NULL;
}

Ghislain MARY's avatar
Ghislain MARY committed
422
belle_sip_list_t* belle_sip_list_find_custom(const belle_sip_list_t* list, belle_sip_compare_func compare_func, const void *user_data){
jehan's avatar
jehan committed
423
	for(;list!=NULL;list=list->next){
Ghislain MARY's avatar
Ghislain MARY committed
424
		if (compare_func(list->data,user_data)==0) return (belle_sip_list_t *)list;
jehan's avatar
jehan committed
425 426 427 428
	}
	return NULL;
}

Simon Morlat's avatar
Simon Morlat committed
429 430 431 432 433 434 435 436
belle_sip_list_t *belle_sip_list_delete_custom(belle_sip_list_t *list, belle_sip_compare_func compare_func, const void *user_data){
	belle_sip_list_t *elem=belle_sip_list_find_custom(list,compare_func,user_data);
	if (elem!=NULL){
		list=belle_sip_list_delete_link(list,elem);
	}
	return list;
}

437
void * belle_sip_list_nth_data(const belle_sip_list_t* list, int index){
jehan's avatar
jehan committed
438 439 440 441 442 443 444 445
	int i;
	for(i=0;list!=NULL;list=list->next,++i){
		if (i==index) return list->data;
	}
	belle_sip_error("belle_sip_list_nth_data: no such index in list.");
	return NULL;
}

446
int belle_sip_list_position(const belle_sip_list_t* list, belle_sip_list_t* elem){
jehan's avatar
jehan committed
447 448 449 450 451 452 453 454
	int i;
	for(i=0;list!=NULL;list=list->next,++i){
		if (elem==list) return i;
	}
	belle_sip_error("belle_sip_list_position: no such element in list.");
	return -1;
}

455
int belle_sip_list_index(const belle_sip_list_t* list, void *data){
jehan's avatar
jehan committed
456 457 458 459 460 461 462 463
	int i;
	for(i=0;list!=NULL;list=list->next,++i){
		if (data==list->data) return i;
	}
	belle_sip_error("belle_sip_list_index: no such element in list.");
	return -1;
}

464 465 466 467
belle_sip_list_t* belle_sip_list_insert_sorted(belle_sip_list_t* list, void *data, int (*compare_func)(const void *, const void*)){
	belle_sip_list_t* it,*previt=NULL;
	belle_sip_list_t* nelem;
	belle_sip_list_t* ret=list;
jehan's avatar
jehan committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
	if (list==NULL) return belle_sip_list_append(list,data);
	else{
		nelem=belle_sip_list_new(data);
		for(it=list;it!=NULL;it=it->next){
			previt=it;
			if (compare_func(data,it->data)<=0){
				nelem->prev=it->prev;
				nelem->next=it;
				if (it->prev!=NULL)
					it->prev->next=nelem;
				else{
					ret=nelem;
				}
				it->prev=nelem;
				return ret;
			}
		}
		previt->next=nelem;
		nelem->prev=previt;
	}
	return ret;
}

491 492
belle_sip_list_t* belle_sip_list_insert(belle_sip_list_t* list, belle_sip_list_t* before, void *data){
	belle_sip_list_t* elem;
jehan's avatar
jehan committed
493 494 495 496 497 498
	if (list==NULL || before==NULL) return belle_sip_list_append(list,data);
	for(elem=list;elem!=NULL;elem=belle_sip_list_next(elem)){
		if (elem==before){
			if (elem->prev==NULL)
				return belle_sip_list_prepend(list,data);
			else{
499
				belle_sip_list_t* nelem=belle_sip_list_new(data);
jehan's avatar
jehan committed
500 501 502 503 504 505 506 507 508 509
				nelem->prev=elem->prev;
				nelem->next=elem;
				elem->prev->next=nelem;
				elem->prev=nelem;
			}
		}
	}
	return list;
}

510 511 512
belle_sip_list_t* belle_sip_list_copy(const belle_sip_list_t* list){
	belle_sip_list_t* copy=NULL;
	const belle_sip_list_t* iter;
jehan's avatar
jehan committed
513 514 515 516 517 518
	for(iter=list;iter!=NULL;iter=belle_sip_list_next(iter)){
		copy=belle_sip_list_append(copy,iter->data);
	}
	return copy;
}

jehan's avatar
jehan committed
519 520 521 522 523 524 525 526 527 528
belle_sip_list_t* belle_sip_list_copy_with_data(const belle_sip_list_t* list, void* (*copyfunc)(void*)){
	belle_sip_list_t* copy=NULL;
	const belle_sip_list_t* iter;
	for(iter=list;iter!=NULL;iter=belle_sip_list_next(iter)){
		copy=belle_sip_list_append(copy,copyfunc(iter->data));
	}
	return copy;
}


jehan's avatar
jehan committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
char * belle_sip_concat (const char *str, ...) {
  va_list ap;
  size_t allocated = 100;
  char *result = (char *) malloc (allocated);

  if (result != NULL)
    {
      char *newp;
      char *wp;
      const char* s;

      va_start (ap, str);

      wp = result;
      for (s = str; s != NULL; s = va_arg (ap, const char *)) {
          size_t len = strlen (s);

          /* Resize the allocated memory if necessary.  */
          if (wp + len + 1 > result + allocated)
            {
              allocated = (allocated + len) * 2;
              newp = (char *) realloc (result, allocated);
              if (newp == NULL)
                {
                  free (result);
                  return NULL;
                }
              wp = newp + (wp - result);
              result = newp;
            }
          memcpy (wp, s, len);
          wp +=len;
        }

      /* Terminate the result string.  */
      *wp++ = '\0';

      /* Resize memory to the optimal size.  */
      newp = realloc (result, wp - result);
      if (newp != NULL)
        result = newp;

      va_end (ap);
    }

574
	return result;
jehan's avatar
jehan committed
575
}
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

void *belle_sip_malloc(size_t size){
	return malloc(size);
}

void *belle_sip_malloc0(size_t size){
	void *p=malloc(size);
	memset(p,0,size);
	return p;
}

void *belle_sip_realloc(void *ptr, size_t size){
	return realloc(ptr,size);
}

void belle_sip_free(void *ptr){
	free(ptr);
}

Simon Morlat's avatar
Simon Morlat committed
595 596 597 598
char * belle_sip_strdup(const char *s){
	return strdup(s);
}

599
#ifndef _WIN32
jehan's avatar
jehan committed
600 601

static int find_best_clock_id () {
602
#if 0
603
	struct timespec ts;
jehan's avatar
jehan committed
604 605 606 607
	static int clock_id=-1;
#ifndef ANDROID
#define DEFAULT_CLOCK_MODE CLOCK_MONOTONIC
#else
608
#define DEFAULT_CLOCK_MODE CLOCK_REALTIME /*monotonic clock stop during sleep mode*/
jehan's avatar
jehan committed
609 610 611
#endif
	if (clock_id==-1) {
		if (clock_gettime(DEFAULT_CLOCK_MODE,&ts)!=1){
jehan's avatar
jehan committed
612
			clock_id=DEFAULT_CLOCK_MODE;
jehan's avatar
jehan committed
613
		} else if (clock_gettime(CLOCK_REALTIME,&ts)!=1){
614
			clock_id=CLOCK_REALTIME;
jehan's avatar
jehan committed
615 616
		} else {
			belle_sip_fatal("Cannot find suitable clock mode");
617
		}
jehan's avatar
jehan committed
618 619
	}
	return clock_id;
620 621 622 623 624 625 626 627 628 629
#else
	/* Tt seems that both Linux, iOS, and MacOS stop incrementing the CLOCK_MONOTONIC during sleep time.
	 * This is a real problem, because all refreshable requests (SUBSCRIBE, REGISTER, PUBLISH) won't be sent on time due to 
	 * system going to sleep. Let's take an example: a REGISTER is sent at T0 with expire 3600, then the macbook suspends at T0+60s.
	 * When the macbook resumes at T0+8000, nothing happens. The REGISTER refresh will be sent at T0+8000+3600-60.
	 * The only reason for seeing the register is if the network address has changed, in which case it will trigger a shutdown of all sockets.
	 * As a result, we fallback to CLOCK_REALTIME until the OS correctly implement CLOCK_MONOTONIC according to POSIX specifications
	 */
	return CLOCK_REALTIME;
#endif
jehan's avatar
jehan committed
630 631 632 633 634
}
uint64_t belle_sip_time_ms(void){
	struct timespec ts;
	if (clock_gettime(find_best_clock_id(),&ts)==-1){
		belle_sip_error("clock_gettime() error for clock_id=%i: %s",find_best_clock_id(),strerror(errno));
635 636 637 638
		return 0;
	}
	return (ts.tv_sec*1000LL) + (ts.tv_nsec/1000000LL);
}
Simon Morlat's avatar
Simon Morlat committed
639 640
#else
uint64_t belle_sip_time_ms(void){
641
#ifdef BELLE_SIP_WINDOWS_DESKTOP
Simon Morlat's avatar
Simon Morlat committed
642
	return GetTickCount();
Ghislain MARY's avatar
Ghislain MARY committed
643 644
#else
	return GetTickCount64();
Ghislain MARY's avatar
Ghislain MARY committed
645
#endif
Simon Morlat's avatar
Simon Morlat committed
646 647
}
#endif
648

jehan's avatar
jehan committed
649 650 651 652 653 654 655 656
/**
 * parser parameter pair
 */



belle_sip_param_pair_t* belle_sip_param_pair_new(const char* name,const char* value) {
	belle_sip_param_pair_t* lPair = (belle_sip_param_pair_t*)belle_sip_new0(belle_sip_param_pair_t);
jehan's avatar
jehan committed
657 658
	lPair->name=name?belle_sip_strdup(name):NULL;
	lPair->value=value?belle_sip_strdup(value):NULL;
jehan's avatar
jehan committed
659 660 661
	return lPair;
}

jehan's avatar
jehan committed
662 663 664
void belle_sip_param_pair_destroy(belle_sip_param_pair_t*  pair) {
	if (pair->name) belle_sip_free(pair->name);
	if (pair->value) belle_sip_free(pair->value);
665
	belle_sip_free(pair);
jehan's avatar
jehan committed
666 667 668 669 670
}

int belle_sip_param_pair_comp_func(const belle_sip_param_pair_t *a, const char*b) {
	return strcmp(a->name,b);
}
jehan's avatar
jehan committed
671 672 673
int belle_sip_param_pair_case_comp_func(const belle_sip_param_pair_t *a, const char*b) {
	return strcasecmp(a->name,b);
}
jehan's avatar
jehan committed
674

675
char* _belle_sip_str_dup_and_unquote_string(const char* quoted_string) {
676 677 678 679 680
	size_t value_size = strlen(quoted_string);
	char* unquoted_string = belle_sip_malloc0(value_size-2+1);
	strncpy(unquoted_string,quoted_string+1,value_size-2);
	return unquoted_string;
}
jehan's avatar
jehan committed
681

682 683 684 685

char *belle_sip_unquote_strdup(const char *str){
	const char *p;
	if (str==NULL) return NULL;
686

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
	for(p=str;*p!='\0';++p){
		switch(*p){
			case ' ':
			case '\t':
			break;
			case '"':
				return _belle_sip_str_dup_and_unquote_string(p);
			default:
				return belle_sip_strdup(str);
			break;
		}
	}
	return belle_sip_strdup(str);
}

702
#if defined(_WIN32) && !defined(_MSC_VER)
703 704 705 706
#include <wincrypt.h>
static int belle_sip_wincrypto_random(unsigned int *rand_number){
	static HCRYPTPROV hProv=(HCRYPTPROV)-1;
	static int initd=0;
707

708 709 710 711 712 713 714 715 716
	if (!initd){
		if (!CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)){
			belle_sip_error("Could not acquire a windows crypto context");
			return -1;
		}
		initd=TRUE;
	}
	if (hProv==(HCRYPTPROV)-1)
		return -1;
717

718 719 720 721 722 723 724 725
	if (!CryptGenRandom(hProv,4,(BYTE*)rand_number)){
		belle_sip_error("CryptGenRandom() failed.");
		return -1;
	}
	return 0;
}
#endif

Simon Morlat's avatar
Simon Morlat committed
726
unsigned int belle_sip_random(void){
Simon Morlat's avatar
Simon Morlat committed
727
#if  defined(__linux) || defined(__APPLE__)
Simon Morlat's avatar
Simon Morlat committed
728 729 730 731 732 733 734 735
	static int fd=-1;
	if (fd==-1) fd=open("/dev/urandom",O_RDONLY);
	if (fd!=-1){
		unsigned int tmp;
		if (read(fd,&tmp,4)!=4){
			belle_sip_error("Reading /dev/urandom failed.");
		}else return tmp;
	}else belle_sip_error("Could not open /dev/urandom");
736
#elif defined(_WIN32)
Simon Morlat's avatar
Simon Morlat committed
737
	static int initd=0;
738 739 740
	unsigned int ret;
#ifdef _MSC_VER
	/*rand_s() is pretty nice and simple function but is not wrapped by mingw.*/
741

742 743 744 745 746 747 748 749 750
	if (rand_s(&ret)==0){
		return ret;
	}
#else
	if (belle_sip_wincrypto_random(&ret)==0){
		return ret;
	}
#endif
	/* Windows's rand() is unsecure but is used as a fallback*/
Simon Morlat's avatar
Simon Morlat committed
751
	if (!initd) {
752
		srand((unsigned int)belle_sip_time_ms());
Simon Morlat's avatar
Simon Morlat committed
753
		initd=1;
754
		belle_sip_warning("Random generator is using rand(), this is unsecure !");
Simon Morlat's avatar
Simon Morlat committed
755 756
	}
	return rand()<<16 | rand();
Simon Morlat's avatar
Simon Morlat committed
757
#endif
758
	/*fallback to UNIX random()*/
759
#ifndef _WIN32
Simon Morlat's avatar
Simon Morlat committed
760
	return (unsigned int) random();
Simon Morlat's avatar
Simon Morlat committed
761
#endif
Simon Morlat's avatar
Simon Morlat committed
762 763
}

Simon Morlat's avatar
Simon Morlat committed
764 765
static const char *symbols="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789-~";

Simon Morlat's avatar
Simon Morlat committed
766 767 768 769
/**
 * Write a random text token of supplied size.
**/
char * belle_sip_random_token(char *ret, size_t size){
770
	unsigned int val=0;
771
	unsigned int i;
772

773 774
	for(i=0;i<size-1;++i){
		if (i%5==0) val=belle_sip_random();
Simon Morlat's avatar
Simon Morlat committed
775 776 777 778 779 780 781
		ret[i]=symbols[val & 63];
		val=val>>6;
	}
	ret[i]=0;
	return ret;
}

782 783 784 785
/**
 * Write random bytes of supplied size.
**/
unsigned char * belle_sip_random_bytes(unsigned char *ret, size_t size){
786
	unsigned int val=0;
787 788 789 790 791 792 793 794 795
	unsigned int i;
	for(i=0;i<size;++i){
		if (i%4==0) val=belle_sip_random();
		ret[i]=val & 0xff;
		val=val>>8;
	}
	return ret;
}

Simon Morlat's avatar
Simon Morlat committed
796 797 798 799 800 801 802 803 804 805 806 807 808 809
typedef struct bits_reader{
	const uint8_t *buffer;
	size_t buf_size;
	int bit_index;
}bits_reader_t;

static void bits_reader_init(bits_reader_t *reader, const uint8_t *buffer, size_t bufsize){
	reader->buffer=buffer;
	reader->buf_size=bufsize;
	reader->bit_index=0;
}

static int bits_reader_read(bits_reader_t *reader, int count, unsigned int *ret){
	unsigned int tmp;
810 811
	size_t byte_index=reader->bit_index/8;
	size_t bit_index=reader->bit_index % 8;
Simon Morlat's avatar
Simon Morlat committed
812
	int shift=32-bit_index-count;
813

Simon Morlat's avatar
Simon Morlat committed
814 815 816 817
	if (count>=24){
		belle_sip_error("This bit reader cannot read more than 24 bits at once.");
		return -1;
	}
818

Simon Morlat's avatar
Simon Morlat committed
819 820 821 822 823 824 825 826 827 828 829 830
	if (byte_index<reader->buf_size)
		tmp=((unsigned int)reader->buffer[byte_index++])<<24;
	else{
		belle_sip_error("Bit reader goes end of stream.");
		return -1;
	}
	if (byte_index<reader->buf_size)
		tmp|=((unsigned int)reader->buffer[byte_index++])<<16;
	if (byte_index<reader->buf_size)
		tmp|=((unsigned int)reader->buffer[byte_index++])<<8;
	if (byte_index<reader->buf_size)
		tmp|=((unsigned int)reader->buffer[byte_index++]);
831

Simon Morlat's avatar
Simon Morlat committed
832 833 834 835 836 837 838 839 840 841
	tmp=tmp>>shift;
	tmp=tmp & ((1<<count)-1);
	reader->bit_index+=count;
	*ret=tmp;
	return 0;
}

char * belle_sip_octets_to_text(const uint8_t *hash, size_t hash_len, char *ret, size_t size){
	int i;
	bits_reader_t bitctx;
842

Simon Morlat's avatar
Simon Morlat committed
843
	bits_reader_init(&bitctx,hash,hash_len);
844

845
	for(i=0;i<(int)size-1;++i){
Simon Morlat's avatar
Simon Morlat committed
846 847 848 849
		unsigned int val=0;
		if (bits_reader_read(&bitctx,6,&val)==0){
			ret[i]=symbols[val];
		}else break;
Simon Morlat's avatar
Simon Morlat committed
850 851 852 853 854
	}
	ret[i]=0;
	return ret;
}

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
void belle_sip_util_copy_headers(belle_sip_message_t *orig, belle_sip_message_t *dest, const char*header, int multiple){
	const belle_sip_list_t *elem;
	elem=belle_sip_message_get_headers(orig,header);
	for (;elem!=NULL;elem=elem->next){
		belle_sip_header_t *ref_header=(belle_sip_header_t*)elem->data;
		if (ref_header){
			ref_header=(belle_sip_header_t*)belle_sip_object_clone((belle_sip_object_t*)ref_header);
			if (!multiple){
				belle_sip_message_set_header(dest,ref_header);
				break;
			}else
				belle_sip_message_add_header(dest,ref_header);
		}
	}
}
jehan's avatar
jehan committed
870

jehan's avatar
jehan committed
871 872
int belle_sip_get_char (const char*a,int n,char*out) {
	if (*a=='%' && n>2) {
873
		unsigned int tmp;
874 875
		sscanf(a+1,"%02x",&tmp);
		*out=(char)tmp;
jehan's avatar
jehan committed
876 877 878 879 880 881
		return 3;
	} else {
		*out=*a;
		return 1;
	}
}
882

883
char* belle_sip_to_unescaped_string(const char* buff) {
884
	char *output_buff=belle_sip_malloc(strlen(buff)+1);
885 886
	unsigned int i;
	unsigned int out_buff_index=0;
887

888 889
	for(i=0; buff[i]!='\0'; out_buff_index++) {
		i+=belle_sip_get_char(buff+i,3,output_buff+out_buff_index);
890 891
	}
	output_buff[out_buff_index]='\0';
892
	return output_buff;
893
}
894

895 896 897 898 899 900 901
#define BELLE_SIP_NO_ESCAPES_SIZE 257
static void noescapes_add_list(char noescapes[BELLE_SIP_NO_ESCAPES_SIZE], const char *allowed) {
	while (*allowed) {
		noescapes[(unsigned int) *allowed] = 1;
		++allowed;
	}
}
902

903 904 905
static void noescapes_add_range(char noescapes[BELLE_SIP_NO_ESCAPES_SIZE], char first, char last) {
	memset(noescapes + (unsigned int)first, 1, last-first+1);
}
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
static void noescapes_add_alfanums(char noescapes[BELLE_SIP_NO_ESCAPES_SIZE]) {
	noescapes_add_range(noescapes, '0', '9');
	noescapes_add_range(noescapes, 'A', 'Z');
	noescapes_add_range(noescapes, 'a', 'z');
}

/*
static void print_noescapes_map(char noescapes[BELLE_SIP_NO_ESCAPES_SIZE], const char *name) {
	unsigned int i;
	printf("Noescapes %s :", name);
	for (i=' '; i <= '~'; ++i) {
		if (noescapes[i] == 1) printf ("%c", i);
		//if (noescapes[i] == 1) printf ("%c %d - %d\n", i, (char)i, noescapes[i]);
	}
	printf ("init: %d\n", noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1]);
}
*/

925
static const char *get_sip_uri_username_noescapes() {
926
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
Guillaume Beraudo's avatar
Guillaume Beraudo committed
927
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
928
		// concurrent initialization should not be an issue
jehan's avatar
jehan committed
929 930 931 932 933 934
		/*user             =  1*( unreserved / escaped / user-unreserved )
		 unreserved  =  alphanum / mark
		 mark        =  "-" / "_" / "." / "!" / "~" / "*" / "'"
		 / "(" / ")"
		user-unreserved  =  "&" / "=" / "+" / "$" / "," / ";" / "?" / "/"
		*/
935
		noescapes_add_alfanums(noescapes);
jehan's avatar
jehan committed
936 937 938 939 940
		/*mark*/
		noescapes_add_list(noescapes, "-_.!~*'()");
		/*user-unreserved*/
		noescapes_add_list(noescapes, "&=+$,;?/");

941 942 943 944 945
		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized
//		print_noescapes_map(noescapes, "uri_username");
	}
	return noescapes;
}
jehan's avatar
jehan committed
946 947 948 949 950
/*
 *
 * password         =  *( unreserved / escaped /
                    "&" / "=" / "+" / "$" / "," )
 * */
951
static const char *get_sip_uri_userpasswd_noescapes() {
jehan's avatar
jehan committed
952 953 954 955 956 957 958 959 960 961 962 963
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
		// unreserved
		noescapes_add_alfanums(noescapes);
		noescapes_add_list(noescapes, "-_.!~*'()");
		noescapes_add_list(noescapes, "&=+$,");

		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized

	}
	return noescapes;
}
964

965
static const char *get_sip_uri_parameter_noescapes() {
966
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
Guillaume Beraudo's avatar
Guillaume Beraudo committed
967
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
968 969 970 971 972 973 974 975 976 977 978 979 980
		/*
		 other-param       =  pname [ "=" pvalue ]
		 pname             =  1*paramchar
		 pvalue            =  1*paramchar
		 paramchar         =  param-unreserved / unreserved / escaped
		 param-unreserved  =  "[" / "]" / "/" / ":" / "&" / "+" / "$"
		 unreserved  =  alphanum / mark
		 mark        =  "-" / "_" / "." / "!" / "~" / "*" / "'"
		 / "(" / ")"
		 escaped     =  "%" HEXDIG HEXDIG
		 token       =  1*(alphanum / "-" / "." / "!" / "%" / "*"
		 / "_" / "+" / "`" / "'" / "~" )
		 */
jehan's avatar
jehan committed
981 982 983 984
		//param-unreserved  =

		noescapes_add_list(noescapes,"[]/:&+$");

985 986 987 988 989 990 991 992 993 994 995 996
		// token
		noescapes_add_alfanums(noescapes);
		noescapes_add_list(noescapes, "-.!%*_+`'~");

		// unreserved
		noescapes_add_list(noescapes, "-_.!~*'()");

		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized
//		print_noescapes_map(noescapes, "uri_parameter");
	}
	return noescapes;
}
997
static const char *get_sip_uri_header_noescapes() {
jehan's avatar
jehan committed
998
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
jehan's avatar
jehan committed
999
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
jehan's avatar
jehan committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
		/*
		 unreserved  =  alphanum / mark
		 mark        =  "-" / "_" / "." / "!" / "~" / "*" / "'"
		 / "(" / ")"
		 escaped     =  "%" HEXDIG HEXDIG

		 //....
		header          =  hname "=" hvalue
		hname           =  1*( hnv-unreserved / unreserved / escaped )
		hvalue          =  *( hnv-unreserved / unreserved / escaped )
		hnv-unreserved  =  "[" / "]" / "/" / "?" / ":" / "+" / "$"

		 */

		// unreserved
		//alphanum
		noescapes_add_alfanums(noescapes);
		//mark
		noescapes_add_list(noescapes, "-_.!~*'()");

		noescapes_add_list(noescapes, "[]/?:+$");
		//hnv-unreserved
		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized
//		print_noescapes_map(noescapes, "uri_parameter");
	}
	return noescapes;
}
1027 1028

static char* belle_sip_escape(const char* buff, const char *noescapes) {
1029 1030 1031 1032
	size_t outbuf_size=strlen(buff);
	size_t orig_size=outbuf_size;
	char *output_buff=(char*)belle_sip_malloc(outbuf_size+1);
	int i;
1033
	size_t out_buff_index=0;
1034

1035
	for(i=0; buff[i] != '\0'; i++) {
1036
		int c = ((unsigned char*)buff)[i];
1037 1038 1039 1040 1041
		if (outbuf_size<out_buff_index-3){
			outbuf_size+=MAX(orig_size/2,3);
			output_buff=belle_sip_realloc(output_buff,outbuf_size+1);
		}
		if (noescapes[c] == 1) {
1042 1043
			output_buff[out_buff_index++]=c;
		} else {
1044
			out_buff_index+=snprintf(output_buff+out_buff_index,outbuf_size-out_buff_index,"%%%02x", c);
1045 1046 1047
		}
	}
	output_buff[out_buff_index]='\0';
1048
	return output_buff;
1049
}
1050 1051

char* belle_sip_uri_to_escaped_username(const char* buff) {
1052
	return belle_sip_escape(buff, get_sip_uri_username_noescapes());
1053
}
jehan's avatar
jehan committed
1054
char* belle_sip_uri_to_escaped_userpasswd(const char* buff) {
1055
	return belle_sip_escape(buff, get_sip_uri_userpasswd_noescapes());
jehan's avatar
jehan committed
1056
}
1057
char* belle_sip_uri_to_escaped_parameter(const char* buff) {
1058
	return belle_sip_escape(buff, get_sip_uri_parameter_noescapes());
1059
}
jehan's avatar
jehan committed
1060
char* belle_sip_uri_to_escaped_header(const char* buff) {
1061
	return belle_sip_escape(buff, get_sip_uri_header_noescapes());
jehan's avatar
jehan committed
1062
}
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086


/*uri (I.E RFC 2396)*/
static const char *get_generic_uri_query_noescapes() {
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
		/*
	    uric          = reserved | unreserved | escaped
		reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
		                "$" | ","
		unreserved    = alphanum | mark
		mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
		                      "(" | ")"

		3.4. Query Component
      	  query         = *uric
   	   Within a query component, the characters ";", "/", "?", ":", "@",
   	   "&", "=", "+", ",", and "$" are reserved.

		*/
		/*unreserved*/
		noescapes_add_alfanums(noescapes);
		/*mark*/
		noescapes_add_list(noescapes, "-_.!~*'()");
1087
		noescapes_add_list(noescapes, "=&"); // otherwise how to pass parameters?
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized
	}
	return noescapes;
}

static const char *get_generic_uri_path_noescapes() {
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
		/*
	    3.3. Path Component

   The path component contains data, specific to the authority (or the
   scheme if there is no authority component), identifying the resource
   within the scope of that scheme and authority.

      path          = [ abs_path | opaque_part ]

      path_segments = segment *( "/" segment )
      segment       = *pchar *( ";" param )
      param         = *pchar

      pchar         = unreserved | escaped |
                      ":" | "@" | "&" | "=" | "+" | "$" | ","

   The path may consist of a sequence of path segments separated by a