ldap_escape.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * $Id$
  3. *
  4. * Kamailio LDAP Module
  5. *
  6. * Copyright (C) 2007 University of North Carolina
  7. *
  8. * Original author: Christian Schlatter, [email protected]
  9. *
  10. *
  11. * This file is part of Kamailio, a free SIP server.
  12. *
  13. * Kamailio is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version
  17. *
  18. * Kamailio is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program; if not, write to the Free Software
  25. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26. *
  27. * History:
  28. * --------
  29. * 2007-02-18: Initial version
  30. */
  31. #include <stdio.h>
  32. #include <ctype.h>
  33. #include "ldap_escape.h"
  34. static const char hex[] = "0123456789ABCDEF";
  35. /*
  36. * escape string following RFC 4515 (LDAP filter syntax) escaping rules:
  37. *
  38. * * --> \2a
  39. * ( --> \28
  40. * ) --> \29
  41. * \ --> \5c
  42. *
  43. * and percent encode '?' according RFC 4516 (LDAP URL), Section 2.1
  44. * if url_encode equals TRUE
  45. *
  46. * ? --> %3F
  47. *
  48. */
  49. int ldap_rfc4515_escape(str *sin, str *sout, int url_encode)
  50. {
  51. char *src, *dst;
  52. if (sin == NULL || sout == NULL || sin->s == NULL || sout->s == NULL
  53. || sin->len <= 0 || sout->len < 3*sin->len+1)
  54. {
  55. return -1;
  56. }
  57. src = sin->s;
  58. dst = sout->s;
  59. while (src < (sin->s + sin->len))
  60. {
  61. switch (*src)
  62. {
  63. case '*':
  64. *dst++ = '\\';
  65. *dst++ = '2';
  66. *dst = 'a';
  67. break;
  68. case '(':
  69. *dst++ = '\\';
  70. *dst++ = '2';
  71. *dst = '8';
  72. break;
  73. case ')':
  74. *dst++ = '\\';
  75. *dst++ = '2';
  76. *dst = '9';
  77. break;
  78. case '\\':
  79. *dst++ = '\\';
  80. *dst++ = '5';
  81. *dst = 'c';
  82. break;
  83. case '?':
  84. if (url_encode)
  85. {
  86. *dst++ = '%';
  87. *dst++ = '3';
  88. *dst = 'F';
  89. } else
  90. {
  91. *dst = *src;
  92. }
  93. break;
  94. default:
  95. *dst = *src;
  96. }
  97. src++;
  98. dst++;
  99. }
  100. *dst = 0;
  101. sout->len = dst - sout->s;
  102. return 0;
  103. }