summaryrefslogtreecommitdiff
path: root/src/libs6dns/s6dns_message_get_domain_internal.c
blob: fd36e18b9fde54d4be82e9321e16da03aa5b0c01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* ISC license. */

#include <string.h>
#include <errno.h>
#include <skalibs/error.h>
#include "s6dns-message-internal.h"

size_t s6dns_message_get_domain_internal (char *out, size_t outmax, char const *s, unsigned int len, unsigned int *pos)
{
  size_t w = 0 ; /* writing head */
  unsigned int r = *pos ; /* reading head */
  unsigned int jumps = 0 ;
  int hasjumped = 0 ;
  for (;;)
  {
    unsigned char c ;
    if (r >= len) return (errno = EPROTO, 0) ;
    c = s[r] ;
    if (c < 64) /* normal label */
    {
      if (r + ++c > len) return (errno = EPROTO, 0) ;
      if (out)
      {
        if (w + c > outmax) return (errno = ENAMETOOLONG, 0) ;
        memcpy(out + w, s + r, c) ;
      }
      w += c ; r += c ; if (!hasjumped) *pos += c ;
      if (c == 1) break ;
    }
    else if (c >= 192) /* pointer */
    {
      if (r + 1 >= len) return (errno = EPROTO, 0) ;
      if (hasjumped)
      {
        if (++jumps > 1000) return (errno = EPROTO, 0) ;
      }
      else
      {
        *pos += 2 ;
        hasjumped = 1 ;
      }
      r = (((unsigned int)c & 63) << 8) | (unsigned char)(s[r + 1]) ;
    }
    else return (errno = EPROTONOSUPPORT, 0) ; /* unsupported extension */
  }
  return w ;
}