ldap_escape.c 2.1 KB

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