File: host_strduptrim.c

package info (click to toggle)
xtruss 0.0~git20241011.27fafffe-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,172 kB
  • sloc: ansic: 17,121; sh: 20; makefile: 2
file content (51 lines) | stat: -rw-r--r-- 1,439 bytes parent folder | download | duplicates (3)
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
48
49
50
51
/*
 * Trim square brackets off the outside of an IPv6 address literal.
 * Leave all other strings unchanged. Returns a fresh dynamically
 * allocated string.
 */

#include <ctype.h>
#include <string.h>

#include "defs.h"
#include "misc.h"

char *host_strduptrim(const char *s)
{
    if (s[0] == '[') {
        const char *p = s+1;
        int colons = 0;
        while (*p && *p != ']') {
            if (isxdigit((unsigned char)*p))
                /* OK */;
            else if (*p == ':')
                colons++;
            else
                break;
            p++;
        }
        if (*p == '%') {
            /*
             * This delimiter character introduces an RFC 4007 scope
             * id suffix (e.g. suffixing the address literal with
             * %eth1 or %2 or some such). There's no syntax
             * specification for the scope id, so just accept anything
             * except the closing ].
             */
            p += strcspn(p, "]");
        }
        if (*p == ']' && !p[1] && colons > 1) {
            /*
             * This looks like an IPv6 address literal (hex digits and
             * at least two colons, plus optional scope id, contained
             * in square brackets). Trim off the brackets.
             */
            return dupprintf("%.*s", (int)(p - (s+1)), s+1);
        }
    }

    /*
     * Any other shape of string is simply duplicated.
     */
    return dupstr(s);
}