belle_sip_utils.c 28.3 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 21 22

#define _CRT_RAND_S
#include <stdlib.h>

23
#include "belle_sip_internal.h"
jehan's avatar
jehan committed
24

25
#include <time.h>
jehan's avatar
jehan committed
26
#include "clock_gettime.h" /*for apple*/
jehan's avatar
jehan committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40

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);

41
belle_sip_log_function_t belle_sip_logv_out=__belle_sip_logv_out;
jehan's avatar
jehan committed
42 43 44 45 46

/**
 *@param func: your logging function, compatible with the OrtpLogFunc prototype.
 *
**/
47
void belle_sip_set_log_handler(belle_sip_log_function_t func){
jehan's avatar
jehan committed
48 49 50 51
        belle_sip_logv_out=func;
}


Simon Morlat's avatar
Simon Morlat committed
52
unsigned int __belle_sip_log_mask=BELLE_SIP_LOG_WARNING|BELLE_SIP_LOG_ERROR|BELLE_SIP_LOG_FATAL;
jehan's avatar
jehan committed
53 54

/**
Simon Morlat's avatar
Simon Morlat committed
55 56
 * @ 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
57
**/
Simon Morlat's avatar
Simon Morlat committed
58 59
void belle_sip_set_log_level(int level){
        __belle_sip_log_mask=(level<<1)-1;
jehan's avatar
jehan committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 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
}

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;
#ifndef WIN32
        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. */
#ifndef WIN32
                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;
}

113
belle_sip_error_code belle_sip_snprintf(char *buff, size_t buff_size, size_t *offset, const char *fmt, ...) {
114
	belle_sip_error_code ret;
Ghislain MARY's avatar
Ghislain MARY committed
115 116
	va_list args;
	va_start(args, fmt);
117 118 119 120 121 122 123 124 125
	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
126 127 128 129 130 131 132 133 134 135 136
	ret = vsnprintf(buff + *offset, buff_size - *offset, fmt, args);
	if ((ret < 0)
		|| (ret >= (buff_size - *offset))) {
			error = BELLE_SIP_BUFFER_OVERFLOW;
		*offset = buff_size;
	} else {
		*offset += ret;
	}
	return error;
}

jehan's avatar
jehan committed
137 138 139 140 141 142 143 144 145 146 147
#if     defined(WIN32) || defined(_WIN32_WCE)
#define ENDLINE "\r\n"
#else
#define ENDLINE "\n"
#endif

#if     defined(WIN32) || defined(_WIN32_WCE)
void belle_sip_logv(int level, const char *fmt, va_list args)
{
        if (belle_sip_logv_out!=NULL && belle_sip_log_level_enabled(level))
                belle_sip_logv_out(level,fmt,args);
Simon Morlat's avatar
Simon Morlat committed
148
        if ((level)==BELLE_SIP_LOG_FATAL) abort();
jehan's avatar
jehan committed
149 150 151 152 153 154 155 156
}
#endif

static void __belle_sip_logv_out(belle_sip_log_level lev, const char *fmt, va_list args){
        const char *lname="undef";
        char *msg;
        if (__log_file==NULL) __log_file=stderr;
        switch(lev){
Simon Morlat's avatar
Simon Morlat committed
157
                case BELLE_SIP_LOG_DEBUG:
jehan's avatar
jehan committed
158 159
                        lname="debug";
                        break;
Simon Morlat's avatar
Simon Morlat committed
160
                case BELLE_SIP_LOG_MESSAGE:
jehan's avatar
jehan committed
161 162
                        lname="message";
                        break;
Simon Morlat's avatar
Simon Morlat committed
163
                case BELLE_SIP_LOG_WARNING:
jehan's avatar
jehan committed
164 165
                        lname="warning";
                        break;
Simon Morlat's avatar
Simon Morlat committed
166
                case BELLE_SIP_LOG_ERROR:
jehan's avatar
jehan committed
167 168
                        lname="error";
                        break;
Simon Morlat's avatar
Simon Morlat committed
169
                case BELLE_SIP_LOG_FATAL:
jehan's avatar
jehan committed
170 171 172 173 174 175 176
                        lname="fatal";
                        break;
                default:
                        belle_sip_fatal("Bad level !");
        }
        msg=belle_sip_strdup_vprintf(fmt,args);
#if defined(_MSC_VER) && !defined(_WIN32_WCE)
177
	#ifndef _UNICODE
178 179
        OutputDebugStringA(msg);
        OutputDebugStringA("\r\n");
180 181 182 183 184
	#else
		{
			int len=strlen(msg);
			wchar_t *tmp=(wchar_t*)belle_sip_malloc((len+1)*sizeof(wchar_t));
			mbstowcs(tmp,msg,len);
185 186
			OutputDebugStringW(tmp);
			OutputDebugStringW(L"\r\n");
187 188 189
			belle_sip_free(tmp);
		}
	#endif
jehan's avatar
jehan committed
190 191 192 193 194 195
#endif
        fprintf(__log_file,"belle-sip-%s-%s" ENDLINE,lname,msg);
        fflush(__log_file);
        free(msg);
}

196
belle_sip_list_t* belle_sip_list_new(void *data){
197
	belle_sip_list_t* new_elem=belle_sip_new0(belle_sip_list_t);
jehan's avatar
jehan committed
198 199 200 201
	new_elem->data=data;
	return new_elem;
}

202
belle_sip_list_t*  belle_sip_list_append_link(belle_sip_list_t* elem,belle_sip_list_t *new_elem){
203
	belle_sip_list_t* it=elem;
204 205
	if (elem==NULL)  return new_elem;
	if (new_elem==NULL)  return elem;
jehan's avatar
jehan committed
206 207 208 209 210 211
	while (it->next!=NULL) it=belle_sip_list_next(it);
	it->next=new_elem;
	new_elem->prev=it;
	return elem;
}

212 213 214 215 216
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);
}

217 218
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
219 220 221 222 223 224 225
	if (elem!=NULL) {
		new_elem->next=elem;
		elem->prev=new_elem;
	}
	return new_elem;
}

226 227 228 229 230 231 232
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
233

234 235
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
236
	if (it==NULL) return second;
237
	if (second==NULL) return first;
jehan's avatar
jehan committed
238 239 240 241 242 243
	while(it->next!=NULL) it=belle_sip_list_next(it);
	it->next=second;
	second->prev=it;
	return first;
}

244 245 246
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
247 248 249 250
	if (list==NULL) return NULL;
	while(elem->next!=NULL) {
		tmp = elem;
		elem = elem->next;
251
		belle_sip_free(tmp);
jehan's avatar
jehan committed
252
	}
253
	belle_sip_free(elem);
jehan's avatar
jehan committed
254 255 256
	return NULL;
}

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
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;
}


273 274
belle_sip_list_t*  belle_sip_list_remove(belle_sip_list_t* first, void *data){
	belle_sip_list_t* it;
jehan's avatar
jehan committed
275
	it=belle_sip_list_find(first,data);
Simon Morlat's avatar
Simon Morlat committed
276
	if (it) return belle_sip_list_delete_link(first,it);
jehan's avatar
jehan committed
277 278 279 280 281 282
	else {
		belle_sip_warning("belle_sip_list_remove: no element with %p data was in the list", data);
		return first;
	}
}

283
int belle_sip_list_size(const belle_sip_list_t* first){
jehan's avatar
jehan committed
284 285 286 287 288 289 290 291
	int n=0;
	while(first!=NULL){
		++n;
		first=first->next;
	}
	return n;
}

292
void belle_sip_list_for_each(const belle_sip_list_t* list, void (*func)(void *)){
jehan's avatar
jehan committed
293 294 295 296 297
	for(;list!=NULL;list=list->next){
		func(list->data);
	}
}

298
void belle_sip_list_for_each2(const belle_sip_list_t* list, void (*func)(void *, void *), void *user_data){
jehan's avatar
jehan committed
299 300 301 302 303
	for(;list!=NULL;list=list->next){
		func(list->data,user_data);
	}
}

304
belle_sip_list_t * belle_sip_list_pop_front(belle_sip_list_t *list, void **front_data){
305 306
	belle_sip_list_t *front_elem=list;
	if (front_elem==NULL){
307 308 309
		*front_data=NULL;
		return NULL;
	}
310 311 312
	*front_data=front_elem->data;
	list=belle_sip_list_remove_link(list,front_elem);
	belle_sip_free(front_elem);
313 314 315
	return list;
}

316 317
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
318 319 320 321 322 323 324 325 326 327 328 329 330 331
	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
332 333
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);
334
	belle_sip_free(elem);
Simon Morlat's avatar
Simon Morlat committed
335 336 337
	return ret;
}

338
belle_sip_list_t* belle_sip_list_find(belle_sip_list_t* list, void *data){
jehan's avatar
jehan committed
339 340 341 342 343 344
	for(;list!=NULL;list=list->next){
		if (list->data==data) return list;
	}
	return NULL;
}

345
belle_sip_list_t* belle_sip_list_find_custom(belle_sip_list_t* list, belle_sip_compare_func compare_func, const void *user_data){
jehan's avatar
jehan committed
346 347 348 349 350 351
	for(;list!=NULL;list=list->next){
		if (compare_func(list->data,user_data)==0) return list;
	}
	return NULL;
}

Simon Morlat's avatar
Simon Morlat committed
352 353 354 355 356 357 358 359
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;
}

360
void * belle_sip_list_nth_data(const belle_sip_list_t* list, int index){
jehan's avatar
jehan committed
361 362 363 364 365 366 367 368
	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;
}

369
int belle_sip_list_position(const belle_sip_list_t* list, belle_sip_list_t* elem){
jehan's avatar
jehan committed
370 371 372 373 374 375 376 377
	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;
}

378
int belle_sip_list_index(const belle_sip_list_t* list, void *data){
jehan's avatar
jehan committed
379 380 381 382 383 384 385 386
	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;
}

387 388 389 390
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
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	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;
}

414 415
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
416 417 418 419 420 421
	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{
422
				belle_sip_list_t* nelem=belle_sip_list_new(data);
jehan's avatar
jehan committed
423 424 425 426 427 428 429 430 431 432
				nelem->prev=elem->prev;
				nelem->next=elem;
				elem->prev->next=nelem;
				elem->prev=nelem;
			}
		}
	}
	return list;
}

433 434 435
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
436 437 438 439 440 441
	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
442 443 444 445 446 447 448 449 450 451
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
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
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);
    }

497
	return result;
jehan's avatar
jehan committed
498
}
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

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
518 519 520 521
char * belle_sip_strdup(const char *s){
	return strdup(s);
}

Simon Morlat's avatar
Simon Morlat committed
522
#ifndef WIN32
jehan's avatar
jehan committed
523 524

static int find_best_clock_id () {
525
	struct timespec ts;
jehan's avatar
jehan committed
526 527 528 529
	static int clock_id=-1;
#ifndef ANDROID
#define DEFAULT_CLOCK_MODE CLOCK_MONOTONIC
#else
530
#define DEFAULT_CLOCK_MODE CLOCK_REALTIME /*monotonic clock stop during sleep mode*/
jehan's avatar
jehan committed
531 532 533
#endif
	if (clock_id==-1) {
		if (clock_gettime(DEFAULT_CLOCK_MODE,&ts)!=1){
jehan's avatar
jehan committed
534
			clock_id=DEFAULT_CLOCK_MODE;
jehan's avatar
jehan committed
535
		} else if (clock_gettime(CLOCK_REALTIME,&ts)!=1){
536
			clock_id=CLOCK_REALTIME;
jehan's avatar
jehan committed
537 538
		} else {
			belle_sip_fatal("Cannot find suitable clock mode");
539
		}
jehan's avatar
jehan committed
540 541 542 543 544 545 546
	}
	return clock_id;
}
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));
547 548 549 550
		return 0;
	}
	return (ts.tv_sec*1000LL) + (ts.tv_nsec/1000000LL);
}
Simon Morlat's avatar
Simon Morlat committed
551 552
#else
uint64_t belle_sip_time_ms(void){
553
#ifdef WINAPI_FAMILY_PHONE_APP
Ghislain MARY's avatar
Ghislain MARY committed
554 555
	return GetTickCount64();
#else
Simon Morlat's avatar
Simon Morlat committed
556
	return GetTickCount();
Ghislain MARY's avatar
Ghislain MARY committed
557
#endif
Simon Morlat's avatar
Simon Morlat committed
558 559
}
#endif
560

jehan's avatar
jehan committed
561 562 563 564 565 566 567 568
/**
 * 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
569 570
	lPair->name=name?belle_sip_strdup(name):NULL;
	lPair->value=value?belle_sip_strdup(value):NULL;
jehan's avatar
jehan committed
571 572 573
	return lPair;
}

jehan's avatar
jehan committed
574 575 576
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);
577
	belle_sip_free(pair);
jehan's avatar
jehan committed
578 579 580 581 582
}

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
583 584 585
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
586

587
char* _belle_sip_str_dup_and_unquote_string(const char* quoted_string) {
588 589 590 591 592
	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
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

char *belle_sip_unquote_strdup(const char *str){
	const char *p;
	if (str==NULL) return NULL;
	
	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);
}

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
#if defined(WIN32) && !defined(_MSC_VER)
#include <wincrypt.h>
static int belle_sip_wincrypto_random(unsigned int *rand_number){
	static HCRYPTPROV hProv=(HCRYPTPROV)-1;
	static int initd=0;
	
	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;
	
	if (!CryptGenRandom(hProv,4,(BYTE*)rand_number)){
		belle_sip_error("CryptGenRandom() failed.");
		return -1;
	}
	return 0;
}
#endif

Simon Morlat's avatar
Simon Morlat committed
638
unsigned int belle_sip_random(void){
Simon Morlat's avatar
Simon Morlat committed
639
#if  defined(__linux) || defined(__APPLE__)
Simon Morlat's avatar
Simon Morlat committed
640 641 642 643 644 645 646 647
	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");
Simon Morlat's avatar
Simon Morlat committed
648 649
#elif defined(WIN32)
	static int initd=0;
650 651 652 653 654 655 656 657 658 659 660 661 662
	unsigned int ret;
#ifdef _MSC_VER
	/*rand_s() is pretty nice and simple function but is not wrapped by mingw.*/
	
	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
663
	if (!initd) {
664
		srand((unsigned int)belle_sip_time_ms());
Simon Morlat's avatar
Simon Morlat committed
665
		initd=1;
666
		belle_sip_warning("Random generator is using rand(), this is unsecure !");
Simon Morlat's avatar
Simon Morlat committed
667 668
	}
	return rand()<<16 | rand();
Simon Morlat's avatar
Simon Morlat committed
669
#endif
670
	/*fallback to UNIX random()*/
Simon Morlat's avatar
Simon Morlat committed
671
#ifndef WIN32
Simon Morlat's avatar
Simon Morlat committed
672
	return (unsigned int) random();
Simon Morlat's avatar
Simon Morlat committed
673
#endif
Simon Morlat's avatar
Simon Morlat committed
674 675
}

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

Simon Morlat's avatar
Simon Morlat committed
678 679 680 681
/**
 * Write a random text token of supplied size.
**/
char * belle_sip_random_token(char *ret, size_t size){
682
	unsigned int val=0;
683 684 685 686
	unsigned int i;
	
	for(i=0;i<size-1;++i){
		if (i%5==0) val=belle_sip_random();
Simon Morlat's avatar
Simon Morlat committed
687 688 689 690 691 692 693
		ret[i]=symbols[val & 63];
		val=val>>6;
	}
	ret[i]=0;
	return ret;
}

694 695 696 697
/**
 * Write random bytes of supplied size.
**/
unsigned char * belle_sip_random_bytes(unsigned char *ret, size_t size){
698
	unsigned int val=0;
699 700 701 702 703 704 705 706 707
	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
708 709 710 711 712 713 714 715 716 717 718 719 720 721
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;
722 723
	size_t byte_index=reader->bit_index/8;
	size_t bit_index=reader->bit_index % 8;
Simon Morlat's avatar
Simon Morlat committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
	int shift=32-bit_index-count;
	
	if (count>=24){
		belle_sip_error("This bit reader cannot read more than 24 bits at once.");
		return -1;
	}
	
	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++]);
	
	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;
	
	bits_reader_init(&bitctx,hash,hash_len);
	
757
	for(i=0;i<(int)size-1;++i){
Simon Morlat's avatar
Simon Morlat committed
758 759 760 761
		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
762 763 764 765 766
	}
	ret[i]=0;
	return ret;
}

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
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
782

jehan's avatar
jehan committed
783 784
int belle_sip_get_char (const char*a,int n,char*out) {
	if (*a=='%' && n>2) {
785
		unsigned int tmp;
786 787
		sscanf(a+1,"%02x",&tmp);
		*out=(char)tmp;
jehan's avatar
jehan committed
788 789 790 791 792 793
		return 3;
	} else {
		*out=*a;
		return 1;
	}
}
794

795
char* belle_sip_to_unescaped_string(const char* buff) {
796
	char *output_buff=belle_sip_malloc(strlen(buff)+1);
797 798
	unsigned int i;
	unsigned int out_buff_index=0;
799 800 801
	
	for(i=0; buff[i]!='\0'; out_buff_index++) {
		i+=belle_sip_get_char(buff+i,3,output_buff+out_buff_index);
802 803
	}
	output_buff[out_buff_index]='\0';
804
	return output_buff;
805
}
806

807 808 809 810 811 812 813
#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;
	}
}
814

815 816 817
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);
}
818

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
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]);
}
*/

837
static const char *get_sip_uri_username_noescapes() {
838
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
Guillaume Beraudo's avatar
Guillaume Beraudo committed
839
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
840
		// concurrent initialization should not be an issue
jehan's avatar
jehan committed
841 842 843 844 845 846
		/*user             =  1*( unreserved / escaped / user-unreserved )
		 unreserved  =  alphanum / mark
		 mark        =  "-" / "_" / "." / "!" / "~" / "*" / "'"
		 / "(" / ")"
		user-unreserved  =  "&" / "=" / "+" / "$" / "," / ";" / "?" / "/"
		*/
847
		noescapes_add_alfanums(noescapes);
jehan's avatar
jehan committed
848 849 850 851 852
		/*mark*/
		noescapes_add_list(noescapes, "-_.!~*'()");
		/*user-unreserved*/
		noescapes_add_list(noescapes, "&=+$,;?/");

853 854 855 856 857
		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized
//		print_noescapes_map(noescapes, "uri_username");
	}
	return noescapes;
}
jehan's avatar
jehan committed
858 859 860 861 862
/*
 *
 * password         =  *( unreserved / escaped /
                    "&" / "=" / "+" / "$" / "," )
 * */
863
static const char *get_sip_uri_userpasswd_noescapes() {
jehan's avatar
jehan committed
864 865 866 867 868 869 870 871 872 873 874 875
	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;
}
876

877
static const char *get_sip_uri_parameter_noescapes() {
878
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
Guillaume Beraudo's avatar
Guillaume Beraudo committed
879
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
880 881 882 883 884 885 886 887 888 889 890 891 892
		/*
		 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
893 894 895 896
		//param-unreserved  =

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

897 898 899 900 901 902 903 904 905 906 907 908
		// 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;
}
909
static const char *get_sip_uri_header_noescapes() {
jehan's avatar
jehan committed
910
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
jehan's avatar
jehan committed
911
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
jehan's avatar
jehan committed
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
		/*
		 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;
}
939 940

static char* belle_sip_escape(const char* buff, const char *noescapes) {
941 942 943
	char output_buff[BELLE_SIP_MAX_TO_STRING_SIZE];
	unsigned int i;
	unsigned int out_buff_index=0;
944 945 946 947 948 949 950
	for(i=0; buff[i] != '\0' && out_buff_index < sizeof(output_buff)-4; i++) {
		/*-4 to make sure last param can be stored in escaped form*/
		const char c = buff[i];
		if (noescapes[(unsigned int) c] == 1) {
			output_buff[out_buff_index++]=c;
		} else {
			out_buff_index+=sprintf(output_buff+out_buff_index,"%%%02x", c);
951 952 953 954 955
		}
	}
	output_buff[out_buff_index]='\0';
	return belle_sip_strdup(output_buff);
}
956 957

char* belle_sip_uri_to_escaped_username(const char* buff) {
958
	return belle_sip_escape(buff, get_sip_uri_username_noescapes());
959
}
jehan's avatar
jehan committed
960
char* belle_sip_uri_to_escaped_userpasswd(const char* buff) {
961
	return belle_sip_escape(buff, get_sip_uri_userpasswd_noescapes());
jehan's avatar
jehan committed
962
}
963
char* belle_sip_uri_to_escaped_parameter(const char* buff) {
964
	return belle_sip_escape(buff, get_sip_uri_parameter_noescapes());
965
}
jehan's avatar
jehan committed
966
char* belle_sip_uri_to_escaped_header(const char* buff) {
967
	return belle_sip_escape(buff, get_sip_uri_header_noescapes());
jehan's avatar
jehan committed
968
}
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992


/*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, "-_.!~*'()");
993
		noescapes_add_list(noescapes, "=&"); // otherwise how to pass parameters?
994 995 996 997 998 999 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 1027 1028 1029 1030 1031 1032 1033
		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
   single slash "/" character.  Within a path segment, the characters
   "/", ";", "=", and "?" are reserved.  Each path segment may include a
   sequence of parameters, indicated by the semicolon ";" character.
   The parameters are not significant to the parsing of relative
   references.

		*/
		/*unreserved*/
		noescapes_add_alfanums(noescapes);
		/*mark*/
		noescapes_add_list(noescapes, "-_.!~*'()");
		/*pchar*/
		noescapes_add_list(noescapes, ":@&=+$,");
		/*;*/
		noescapes_add_list(noescapes, ";");
1034
		noescapes_add_list(noescapes, "/");
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

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

char* belle_generic_uri_to_escaped_query(const char* buff) {
	return belle_sip_escape(buff, get_generic_uri_query_noescapes());
}
char* belle_generic_uri_to_escaped_path(const char* buff) {
	return belle_sip_escape(buff, get_generic_uri_path_noescapes());
}