utils.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * $Id$
  3. *
  4. * Copyright (C) 2013 Konstantin Mosesov
  5. *
  6. * This file is part of Kamailio, a free SIP server.
  7. *
  8. * This file is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version
  12. *
  13. *
  14. * This file is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  22. *
  23. */
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <time.h>
  27. #include "utils.h"
  28. #include "../../sr_module.h"
  29. char **split(char *str, char *sep)
  30. {
  31. char **buf = NULL;
  32. char *token = NULL;
  33. char *saveptr = NULL;
  34. int i;
  35. buf = (char **)pkg_realloc(NULL, sizeof(char *));
  36. if (!buf)
  37. {
  38. LM_ERR("pkg_realloc() has failed. Not enough memory!\n");
  39. return NULL;
  40. }
  41. memset(&buf, 0, sizeof(char *));
  42. if (str == NULL)
  43. return buf;
  44. if (strncmp(str, sep, strlen(sep)) <= 0)
  45. {
  46. // string doesn't contains a separator
  47. buf[0] = strdup(str);
  48. return buf;
  49. }
  50. token = strdup(str);
  51. for (i=0; token != NULL; token = saveptr, i++)
  52. {
  53. token = strtok_r(token, (const char *)sep, &saveptr);
  54. if (token == NULL || !strcmp(token, ""))
  55. break;
  56. buf = (char **)pkg_realloc(buf, (i+1) * sizeof(char *));
  57. if (!buf)
  58. {
  59. LM_ERR("pkg_realloc() has failed. Not enough memory!\n");
  60. return NULL;
  61. }
  62. buf[i] = strdup(token);
  63. }
  64. buf[i] = NULL;
  65. free(token);
  66. return buf;
  67. }