File: ipa_hostname.c

package info (click to toggle)
freeipa 4.12.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 100,668 kB
  • sloc: python: 298,952; javascript: 71,606; ansic: 49,369; sh: 6,547; makefile: 2,553; xml: 343; sed: 16
file content (98 lines) | stat: -rw-r--r-- 2,323 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

/*
 * Copyright (C) 2020  FreeIPA Contributors see COPYING for license
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#include "ipa_hostname.h"

static int
_get_fqdn(char *fqdn)
{
    char hostname[IPA_HOST_FQDN_LEN];
    char *canonname = NULL;
    struct addrinfo hints;
    struct addrinfo *ai = NULL;
    int r;

    r = gethostname(hostname, IPA_HOST_FQDN_LEN - 1);
    if (r != 0) {
        goto error;
    }

    memset(&hints, 0, sizeof(struct addrinfo));
    /* use IPv4 or IPv6 */
    hints.ai_family = AF_UNSPEC;
    /* optimize, RAW and STREAM return same kind of information */
    hints.ai_socktype = SOCK_DGRAM;
    /* any protocol */
    hints.ai_protocol = 0;
    /* get canonical name
     * only use IPv4/6 when at least one interface for proto is configured */
    hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    r = getaddrinfo(hostname, NULL, &hints, &ai);
    if (r != 0) {
        /* getaddrinfo() for gethostname() should never fail. The
         * nss-myhostname provider should always add a positive match. */
        errno = ENOENT;
        goto error;
    }

    /* only the first addrinfo struct holds a canonical name value */
    canonname = ai->ai_canonname;

    /* check that canon name is filled and not too long */
    if (!canonname) {
        errno = ENOENT;
        goto error;
    }
    if (strlen(canonname) > (IPA_HOST_FQDN_LEN - 1)) {
        errno = ENAMETOOLONG;
        goto error;
    }
#if 0
    /* refuse non-qualified short names and localhost */
    if ((strchr(canonname, '.') == NULL) ||
            (strcasecmp(canonname, "localhost.localdomain") == 0)) {
        errno = EINVAL;
        goto error;
    }
#endif

    strncpy(fqdn, canonname, IPA_HOST_FQDN_LEN);
    /* Make double sure it is terminated */
    fqdn[IPA_HOST_FQDN_LEN - 1] = '\0';
    freeaddrinfo(ai);
    return 0;

  error:
    if (ai != NULL) {
        freeaddrinfo(ai);
    }
    return -1;
}


const char* ipa_gethostfqdn()
{
    static char cached_fqdn[IPA_HOST_FQDN_LEN] = {0};

    if (*cached_fqdn == '\0') {
        int res = _get_fqdn(cached_fqdn);
        if (res != 0) {
            return NULL;
        }
    }
    return (const char*)cached_fqdn;
}