belle_sip_utils.c 32.8 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

Simon Morlat's avatar
Simon Morlat committed
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 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 113 114 115 116 117 118 119 120 121 122 123
}

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

124
belle_sip_error_code belle_sip_snprintf(char *buff, size_t buff_size, size_t *offset, const char *fmt, ...) {
125
	belle_sip_error_code ret;
Ghislain MARY's avatar
Ghislain MARY committed
126 127
	va_list args;
	va_start(args, fmt);
128 129 130 131 132 133 134 135 136
	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
137 138 139 140 141 142 143 144 145 146 147
	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
148 149 150 151 152 153 154 155 156
#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)
{
Simon Morlat's avatar
Simon Morlat committed
157 158 159
	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
160 161 162
}
#endif

Simon Morlat's avatar
Simon Morlat committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

#ifdef WIN32
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
182
static void __belle_sip_logv_out(belle_sip_log_level lev, const char *fmt, va_list args){
Simon Morlat's avatar
Simon Morlat committed
183 184 185 186 187 188
	const char *lname="undef";
	char *msg;
	struct timeval tp;
	struct tm *lt;
#ifndef WIN32
	struct tm tmstorage;
189
#endif
Simon Morlat's avatar
Simon Morlat committed
190
	time_t curtime;
191

Simon Morlat's avatar
Simon Morlat committed
192 193 194 195 196 197 198
	belle_sip_gettimeofday(&tp,NULL);
	curtime=tp.tv_sec;
#ifdef WIN32
	lt = localtime(&curtime);
#else
	lt = localtime_r(&curtime,&tmstorage);
#endif
199

Simon Morlat's avatar
Simon Morlat committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
	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
221
#if defined(_MSC_VER) && !defined(_WIN32_WCE)
222
	#ifndef _UNICODE
Simon Morlat's avatar
Simon Morlat committed
223 224
	OutputDebugStringA(msg);
	OutputDebugStringA("\r\n");
225
	#else
Simon Morlat's avatar
Simon Morlat committed
226 227 228 229 230 231 232 233
	{
		int len=strlen(msg);
		wchar_t *tmp=(wchar_t*)belle_sip_malloc((len+1)*sizeof(wchar_t));
		mbstowcs(tmp,msg,len);
		OutputDebugStringW(tmp);
		OutputDebugStringW(L"\r\n");
		belle_sip_free(tmp);
	}
234
	#endif
jehan's avatar
jehan committed
235
#endif
236
	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
237 238
	fflush(__log_file);
	free(msg);
jehan's avatar
jehan committed
239 240
}

241
belle_sip_list_t* belle_sip_list_new(void *data){
242
	belle_sip_list_t* new_elem=belle_sip_new0(belle_sip_list_t);
jehan's avatar
jehan committed
243 244 245 246
	new_elem->data=data;
	return new_elem;
}

247
belle_sip_list_t*  belle_sip_list_append_link(belle_sip_list_t* elem,belle_sip_list_t *new_elem){
248
	belle_sip_list_t* it=elem;
249 250
	if (elem==NULL)  return new_elem;
	if (new_elem==NULL)  return elem;
jehan's avatar
jehan committed
251 252 253 254 255 256
	while (it->next!=NULL) it=belle_sip_list_next(it);
	it->next=new_elem;
	new_elem->prev=it;
	return elem;
}

257 258 259 260 261
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);
}

262 263
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
264 265 266 267 268 269 270
	if (elem!=NULL) {
		new_elem->next=elem;
		elem->prev=new_elem;
	}
	return new_elem;
}

271 272 273 274 275 276 277
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
278

279 280
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
281
	if (it==NULL) return second;
282
	if (second==NULL) return first;
jehan's avatar
jehan committed
283 284 285 286 287 288
	while(it->next!=NULL) it=belle_sip_list_next(it);
	it->next=second;
	second->prev=it;
	return first;
}

289 290 291
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
292 293 294 295
	if (list==NULL) return NULL;
	while(elem->next!=NULL) {
		tmp = elem;
		elem = elem->next;
296
		belle_sip_free(tmp);
jehan's avatar
jehan committed
297
	}
298
	belle_sip_free(elem);
jehan's avatar
jehan committed
299 300 301
	return NULL;
}

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
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;
}


318
belle_sip_list_t*  _belle_sip_list_remove(belle_sip_list_t* first, void *data, int warn_if_not_found){
319
	belle_sip_list_t* it;
jehan's avatar
jehan committed
320
	it=belle_sip_list_find(first,data);
Simon Morlat's avatar
Simon Morlat committed
321
	if (it) return belle_sip_list_delete_link(first,it);
322
	else if (warn_if_not_found){
jehan's avatar
jehan committed
323 324
		belle_sip_warning("belle_sip_list_remove: no element with %p data was in the list", data);
	}
325 326 327 328 329
	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
330 331
}

332
int belle_sip_list_size(const belle_sip_list_t* first){
jehan's avatar
jehan committed
333 334 335 336 337 338 339 340
	int n=0;
	while(first!=NULL){
		++n;
		first=first->next;
	}
	return n;
}

341
void belle_sip_list_for_each(const belle_sip_list_t* list, void (*func)(void *)){
jehan's avatar
jehan committed
342 343 344 345 346
	for(;list!=NULL;list=list->next){
		func(list->data);
	}
}

347
void belle_sip_list_for_each2(const belle_sip_list_t* list, void (*func)(void *, void *), void *user_data){
jehan's avatar
jehan committed
348 349 350 351 352
	for(;list!=NULL;list=list->next){
		func(list->data,user_data);
	}
}

353
belle_sip_list_t * belle_sip_list_pop_front(belle_sip_list_t *list, void **front_data){
354 355
	belle_sip_list_t *front_elem=list;
	if (front_elem==NULL){
356 357 358
		*front_data=NULL;
		return NULL;
	}
359 360 361
	*front_data=front_elem->data;
	list=belle_sip_list_remove_link(list,front_elem);
	belle_sip_free(front_elem);
362 363 364
	return list;
}

365 366
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
367 368 369 370 371 372 373 374 375 376 377 378 379 380
	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
381 382
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);
383
	belle_sip_free(elem);
Simon Morlat's avatar
Simon Morlat committed
384 385 386
	return ret;
}

387
belle_sip_list_t* belle_sip_list_find(belle_sip_list_t* list, void *data){
jehan's avatar
jehan committed
388 389 390 391 392 393
	for(;list!=NULL;list=list->next){
		if (list->data==data) return list;
	}
	return NULL;
}

Ghislain MARY's avatar
Ghislain MARY committed
394
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
395
	for(;list!=NULL;list=list->next){
Ghislain MARY's avatar
Ghislain MARY committed
396
		if (compare_func(list->data,user_data)==0) return (belle_sip_list_t *)list;
jehan's avatar
jehan committed
397 398 399 400
	}
	return NULL;
}

Simon Morlat's avatar
Simon Morlat committed
401 402 403 404 405 406 407 408
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;
}

409
void * belle_sip_list_nth_data(const belle_sip_list_t* list, int index){
jehan's avatar
jehan committed
410 411 412 413 414 415 416 417
	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;
}

418
int belle_sip_list_position(const belle_sip_list_t* list, belle_sip_list_t* elem){
jehan's avatar
jehan committed
419 420 421 422 423 424 425 426
	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;
}

427
int belle_sip_list_index(const belle_sip_list_t* list, void *data){
jehan's avatar
jehan committed
428 429 430 431 432 433 434 435
	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;
}

436 437 438 439
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
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	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;
}

463 464
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
465 466 467 468 469 470
	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{
471
				belle_sip_list_t* nelem=belle_sip_list_new(data);
jehan's avatar
jehan committed
472 473 474 475 476 477 478 479 480 481
				nelem->prev=elem->prev;
				nelem->next=elem;
				elem->prev->next=nelem;
				elem->prev=nelem;
			}
		}
	}
	return list;
}

482 483 484
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
485 486 487 488 489 490
	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
491 492 493 494 495 496 497 498 499 500
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
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
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);
    }

546
	return result;
jehan's avatar
jehan committed
547
}
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

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
567 568 569 570
char * belle_sip_strdup(const char *s){
	return strdup(s);
}

Simon Morlat's avatar
Simon Morlat committed
571
#ifndef WIN32
jehan's avatar
jehan committed
572 573

static int find_best_clock_id () {
574
	struct timespec ts;
jehan's avatar
jehan committed
575 576 577 578
	static int clock_id=-1;
#ifndef ANDROID
#define DEFAULT_CLOCK_MODE CLOCK_MONOTONIC
#else
579
#define DEFAULT_CLOCK_MODE CLOCK_REALTIME /*monotonic clock stop during sleep mode*/
jehan's avatar
jehan committed
580 581 582
#endif
	if (clock_id==-1) {
		if (clock_gettime(DEFAULT_CLOCK_MODE,&ts)!=1){
jehan's avatar
jehan committed
583
			clock_id=DEFAULT_CLOCK_MODE;
jehan's avatar
jehan committed
584
		} else if (clock_gettime(CLOCK_REALTIME,&ts)!=1){
585
			clock_id=CLOCK_REALTIME;
jehan's avatar
jehan committed
586 587
		} else {
			belle_sip_fatal("Cannot find suitable clock mode");
588
		}
jehan's avatar
jehan committed
589 590 591 592 593 594 595
	}
	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));
596 597 598 599
		return 0;
	}
	return (ts.tv_sec*1000LL) + (ts.tv_nsec/1000000LL);
}
Simon Morlat's avatar
Simon Morlat committed
600 601
#else
uint64_t belle_sip_time_ms(void){
Ghislain MARY's avatar
Ghislain MARY committed
602
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
Simon Morlat's avatar
Simon Morlat committed
603
	return GetTickCount();
Ghislain MARY's avatar
Ghislain MARY committed
604 605
#else
	return GetTickCount64();
Ghislain MARY's avatar
Ghislain MARY committed
606
#endif
Simon Morlat's avatar
Simon Morlat committed
607 608
}
#endif
609

jehan's avatar
jehan committed
610 611 612 613 614 615 616 617
/**
 * 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
618 619
	lPair->name=name?belle_sip_strdup(name):NULL;
	lPair->value=value?belle_sip_strdup(value):NULL;
jehan's avatar
jehan committed
620 621 622
	return lPair;
}

jehan's avatar
jehan committed
623 624 625
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);
626
	belle_sip_free(pair);
jehan's avatar
jehan committed
627 628 629 630 631
}

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
632 633 634
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
635

636
char* _belle_sip_str_dup_and_unquote_string(const char* quoted_string) {
637 638 639 640 641
	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
642

643 644 645 646

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

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
	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);
}

663 664 665 666 667
#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;
668

669 670 671 672 673 674 675 676 677
	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;
678

679 680 681 682 683 684 685 686
	if (!CryptGenRandom(hProv,4,(BYTE*)rand_number)){
		belle_sip_error("CryptGenRandom() failed.");
		return -1;
	}
	return 0;
}
#endif

Simon Morlat's avatar
Simon Morlat committed
687
unsigned int belle_sip_random(void){
Simon Morlat's avatar
Simon Morlat committed
688
#if  defined(__linux) || defined(__APPLE__)
Simon Morlat's avatar
Simon Morlat committed
689 690 691 692 693 694 695 696
	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
697 698
#elif defined(WIN32)
	static int initd=0;
699 700 701
	unsigned int ret;
#ifdef _MSC_VER
	/*rand_s() is pretty nice and simple function but is not wrapped by mingw.*/
702

703 704 705 706 707 708 709 710 711
	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
712
	if (!initd) {
713
		srand((unsigned int)belle_sip_time_ms());
Simon Morlat's avatar
Simon Morlat committed
714
		initd=1;
715
		belle_sip_warning("Random generator is using rand(), this is unsecure !");
Simon Morlat's avatar
Simon Morlat committed
716 717
	}
	return rand()<<16 | rand();
Simon Morlat's avatar
Simon Morlat committed
718
#endif
719
	/*fallback to UNIX random()*/
Simon Morlat's avatar
Simon Morlat committed
720
#ifndef WIN32
Simon Morlat's avatar
Simon Morlat committed
721
	return (unsigned int) random();
Simon Morlat's avatar
Simon Morlat committed
722
#endif
Simon Morlat's avatar
Simon Morlat committed
723 724
}

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

Simon Morlat's avatar
Simon Morlat committed
727 728 729 730
/**
 * Write a random text token of supplied size.
**/
char * belle_sip_random_token(char *ret, size_t size){
731
	unsigned int val=0;
732
	unsigned int i;
733

734 735
	for(i=0;i<size-1;++i){
		if (i%5==0) val=belle_sip_random();
Simon Morlat's avatar
Simon Morlat committed
736 737 738 739 740 741 742
		ret[i]=symbols[val & 63];
		val=val>>6;
	}
	ret[i]=0;
	return ret;
}

743 744 745 746
/**
 * Write random bytes of supplied size.
**/
unsigned char * belle_sip_random_bytes(unsigned char *ret, size_t size){
747
	unsigned int val=0;
748 749 750 751 752 753 754 755 756
	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
757 758 759 760 761 762 763 764 765 766 767 768 769 770
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;
771 772
	size_t byte_index=reader->bit_index/8;
	size_t bit_index=reader->bit_index % 8;
Simon Morlat's avatar
Simon Morlat committed
773
	int shift=32-bit_index-count;
774

Simon Morlat's avatar
Simon Morlat committed
775 776 777 778
	if (count>=24){
		belle_sip_error("This bit reader cannot read more than 24 bits at once.");
		return -1;
	}
779

Simon Morlat's avatar
Simon Morlat committed
780 781 782 783 784 785 786 787 788 789 790 791
	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++]);
792

Simon Morlat's avatar
Simon Morlat committed
793 794 795 796 797 798 799 800 801 802
	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;
803

Simon Morlat's avatar
Simon Morlat committed
804
	bits_reader_init(&bitctx,hash,hash_len);
805

806
	for(i=0;i<(int)size-1;++i){
Simon Morlat's avatar
Simon Morlat committed
807 808 809 810
		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
811 812 813 814 815
	}
	ret[i]=0;
	return ret;
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
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
831

jehan's avatar
jehan committed
832 833
int belle_sip_get_char (const char*a,int n,char*out) {
	if (*a=='%' && n>2) {
834
		unsigned int tmp;
835 836
		sscanf(a+1,"%02x",&tmp);
		*out=(char)tmp;
jehan's avatar
jehan committed
837 838 839 840 841 842
		return 3;
	} else {
		*out=*a;
		return 1;
	}
}
843

844
char* belle_sip_to_unescaped_string(const char* buff) {
845
	char *output_buff=belle_sip_malloc(strlen(buff)+1);
846 847
	unsigned int i;
	unsigned int out_buff_index=0;
848

849 850
	for(i=0; buff[i]!='\0'; out_buff_index++) {
		i+=belle_sip_get_char(buff+i,3,output_buff+out_buff_index);
851 852
	}
	output_buff[out_buff_index]='\0';
853
	return output_buff;
854
}
855

856 857 858 859 860 861 862
#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;
	}
}
863

864 865 866
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);
}
867

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
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]);
}
*/

886
static const char *get_sip_uri_username_noescapes() {
887
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
Guillaume Beraudo's avatar
Guillaume Beraudo committed
888
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
889
		// concurrent initialization should not be an issue
jehan's avatar
jehan committed
890 891 892 893 894 895
		/*user             =  1*( unreserved / escaped / user-unreserved )
		 unreserved  =  alphanum / mark
		 mark        =  "-" / "_" / "." / "!" / "~" / "*" / "'"
		 / "(" / ")"
		user-unreserved  =  "&" / "=" / "+" / "$" / "," / ";" / "?" / "/"
		*/
896
		noescapes_add_alfanums(noescapes);
jehan's avatar
jehan committed
897 898 899 900 901
		/*mark*/
		noescapes_add_list(noescapes, "-_.!~*'()");
		/*user-unreserved*/
		noescapes_add_list(noescapes, "&=+$,;?/");

902 903 904 905 906
		noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] = 1; // initialized
//		print_noescapes_map(noescapes, "uri_username");
	}
	return noescapes;
}
jehan's avatar
jehan committed
907 908 909 910 911
/*
 *
 * password         =  *( unreserved / escaped /
                    "&" / "=" / "+" / "$" / "," )
 * */
912
static const char *get_sip_uri_userpasswd_noescapes() {
jehan's avatar
jehan committed
913 914 915 916 917 918 919 920 921 922 923 924
	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;
}
925

926
static const char *get_sip_uri_parameter_noescapes() {
927
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
Guillaume Beraudo's avatar
Guillaume Beraudo committed
928
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
929 930 931 932 933 934 935 936 937 938 939 940 941
		/*
		 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
942 943 944 945
		//param-unreserved  =

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

946 947 948 949 950 951 952 953 954 955 956 957
		// 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;
}
958
static const char *get_sip_uri_header_noescapes() {
jehan's avatar
jehan committed
959
	static char noescapes[BELLE_SIP_NO_ESCAPES_SIZE] = {0};
jehan's avatar
jehan committed
960
	if (noescapes[BELLE_SIP_NO_ESCAPES_SIZE-1] == 0) {
jehan's avatar
jehan committed
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
		/*
		 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;
}
988 989

static char* belle_sip_escape(const char* buff, const char *noescapes) {
990 991 992 993 994
	size_t outbuf_size=strlen(buff);
	size_t orig_size=outbuf_size;
	char *output_buff=(char*)belle_sip_malloc(outbuf_size+1);
	int i;
	int out_buff_index=0;
995

996
	for(i=0; buff[i] != '\0'; i++) {
997
		int c = ((unsigned char*)buff)[i];
998 999 1000 1001 1002
		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) {
1003 1004
			output_buff[out_buff_index++]=c;
		} else {
1005
			out_buff_index+=snprintf(output_buff+out_buff_index,outbuf_size-out_buff_index,"%%%02x", c);
1006 1007 1008
		}
	}
	output_buff[out_buff_index]='\0';
1009
	return output_buff;
1010
}
1011 1012

char* belle_sip_uri_to_escaped_username(const char* buff) {
1013
	return belle_sip_escape(buff, get_sip_uri_username_noescapes());
1014
}
jehan's avatar
jehan committed
1015
char* belle_sip_uri_to_escaped_userpasswd(const char* buff) {
1016
	return belle_sip_escape(buff, get_sip_uri_userpasswd_noescapes());
jehan's avatar
jehan committed
1017
}
1018
char* belle_sip_uri_to_escaped_parameter(const char* buff) {
1019
	return belle_sip_escape(buff, get_sip_uri_parameter_noescapes());
1020
}
jehan's avatar
jehan committed
1021
char* belle_sip_uri_to_escaped_header(const char* buff) {
1022
	return belle_sip_escape(buff, get_sip_uri_header_noescapes());
jehan's avatar
jehan committed
1023
}
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047


/*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, "-_.!~*'()");
1048
		noescapes_add_list(noescapes, "=&"); // otherwise how to pass parameters?
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 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 1087 1088
		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, ";");
1089
		noescapes_add_list(noescapes, "/");
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

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

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 1128 1129 1130 1131 1132
char* belle_sip_string_to_backslash_less_unescaped_string(const char* buff) {
	char *output_buff=belle_sip_malloc(strlen(buff)+1);
	unsigned int i;
	unsigned int out_buff_index=0;

	for(i=0; buff[i] != '\0'; i++) {
		if (buff[i] == '\\') {
			i++;/*skip \*/
		}
		/*make sure to only remove one \ in case of \\*/
		output_buff[out_buff_index++]=buff[i];
	}
	output_buff[out_buff_index]='\0';
	return output_buff;
}
char* belle_sip_display_name_to_backslashed_escaped_string(const char* buff) {
	char output_buff[BELLE_SIP_MAX_TO_STRING_SIZE];
	unsigned int i;
	unsigned int out_buff_index=0;
	for(i=0; buff[i] != '\0' && out_buff_index < sizeof(output_buff)-2; i++) {
		/*-3 to make sure last param can be stored in escaped form*/
		const char c = buff[i];
		if (c == '\"' || c == '\\') {
			output_buff[out_buff_index++]='\\'; /*insert escape character*/
		}
		output_buff[out_buff_index++]=c;
	}
	output_buff[out_buff_index]='\0';
	return belle_sip_strdup(output_buff);
}
1133 1134 1135

belle_sip_list_t *belle_sip_parse_directory(const char *path, const char *file_type) {
	belle_sip_list_t* file_list = NULL;
1136 1137 1138 1139 1140 1141 1142 1143
#ifdef WIN32
	WIN32_FIND_DATA FileData;
	HANDLE hSearch;
	BOOL fFinished = FALSE;
	char szDirPath[1024];
#ifdef UNICODE
	wchar_t wszDirPath[1024];
#endif
1144

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	if (file_type == NULL) {
		file_type = ".*";
	}
	snprintf(szDirPath, sizeof(szDirPath), "%s\\*%s", path, file_type);
#ifdef UNICODE
	mbstowcs(wszDirPath, szDirPath, sizeof(wszDirPath));
	hSearch = FindFirstFileExW(wszDirPath, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0);
#else
	hSearch = FindFirstFileExA(szDirPath, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0);
#endif
	if (hSearch == INVALID_HANDLE_VALUE) {
		belle_sip_message("No file (*%s) found in [%s] [%d].", file_type, szDirPath, (int)GetLastError());
		return NULL;
	}
	snprintf(szDirPath, sizeof(szDirPath), "%s", path);
	while (!fFinished) {
		char szFilePath[1024];
1162
#ifdef UNICODE
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
		char filename[512];
		wcstombs(filename, FileData.cFileName, sizeof(filename));
		snprintf(szFilePath, sizeof(szFilePath), "%s\\%s", szDirPath, filename);
#else
		snprintf(szFilePath, sizeof(szFilePath), "%s\\%s", szDirPath, FileData.cFileName);
#endif
		file_list = belle_sip_list_append(file_list, belle_sip_strdup(szFilePath));
		if (!FindNextFile(hSearch, &FileData)) {
			if (GetLastError() == ERROR_NO_MORE_FILES) {
				fFinished = TRUE;
			}
			else {
				belle_sip_error("Couldn't find next (*%s) file.", file_type);
				fFinished = TRUE;
1177 1178
			}
		}
1179 1180 1181 1182 1183 1184
	}
	/* Close the search handle. */
	FindClose(hSearch);
#else
	DIR *dir;
	struct dirent *ent;
1185 1186 1187
	struct dirent *result;
	long int name_max;
	int res;
1188 1189 1190

	if ((dir = opendir(path)) == NULL) {
		belle_sip_error("Could't open [%s] directory.", path);
1191 1192
		return NULL;
	}
1193

1194 1195 1196 1197 1198
	/* allocate the directory entry structure */
	name_max = pathconf(path, _PC_NAME_MAX);
	if (name_max == -1) name_max = 255;
	ent = malloc(offsetof(struct dirent, d_name) + name_max + 1);

1199
	/* loop on all directory files */
1200 1201
	res = readdir_r(dir, ent, &result);
	while ((res == 0) && (result != NULL)) {
1202 1203 1204
		/* filter on file type if given */
		if (file_type==NULL
			|| (strncmp(ent->d_name+strlen(ent->d_name)-strlen(file_type), file_type, strlen(file_type))==0) ) {
1205 1206
			char *name_with_path=belle_sip_strdup_printf("%s/%s",path,ent->d_name);
			file_list = belle_sip_list_append(file_list, name_with_path);
1207
		}
1208 1209 1210 1211
		res = readdir_r(dir, ent, &result);
	}
	if (res != 0) {
		belle_sip_error("Error while reading the [%s] directory: %s.", path, strerror(errno));
1212
	}
1213
	free(ent);