host_strduptrim.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Trim square brackets off the outside of an IPv6 address literal.
  3. * Leave all other strings unchanged. Returns a fresh dynamically
  4. * allocated string.
  5. */
  6. #include <ctype.h>
  7. #include <string.h>
  8. #include "defs.h"
  9. #include "misc.h"
  10. char *host_strduptrim(const char *s)
  11. {
  12. if (s[0] == '[') {
  13. const char *p = s+1;
  14. int colons = 0;
  15. while (*p && *p != ']') {
  16. if (isxdigit((unsigned char)*p))
  17. /* OK */;
  18. else if (*p == ':')
  19. colons++;
  20. else
  21. break;
  22. p++;
  23. }
  24. if (*p == '%') {
  25. /*
  26. * This delimiter character introduces an RFC 4007 scope
  27. * id suffix (e.g. suffixing the address literal with
  28. * %eth1 or %2 or some such). There's no syntax
  29. * specification for the scope id, so just accept anything
  30. * except the closing ].
  31. */
  32. p += strcspn(p, "]");
  33. }
  34. if (*p == ']' && !p[1] && colons > 1) {
  35. /*
  36. * This looks like an IPv6 address literal (hex digits and
  37. * at least two colons, plus optional scope id, contained
  38. * in square brackets). Trim off the brackets.
  39. */
  40. return dupprintf("%.*s", (int)(p - (s+1)), s+1);
  41. }
  42. }
  43. /*
  44. * Any other shape of string is simply duplicated.
  45. */
  46. return dupstr(s);
  47. }