aboutsummaryrefslogtreecommitdiff
path: root/client/acronc/async_dns.c
blob: 2e221cf5e224a74b3bcd74bff4710f94ce1069f7 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Created by yuuta on 7/24/22.
 */

#include "handler.h"
#include "log.h"

#include <uv.h>

static uv_getaddrinfo_t resolv;

static struct addrinfo *ai = NULL;
static struct addrinfo *ai_current = NULL;
static void (*cb)(int status,
           const struct addrinfo *,
           void (*on_connect_result)(bool)) = NULL;

static void on_conn(bool res) {
    if (res) {
        uv_freeaddrinfo(ai);
        ai = NULL;
        ai_current = NULL;
        cb = NULL;
        return;
    }
    ai_current = ai_current->ai_next;
    if (!ai_current) {
        /* No more result available. */
        cb(1, NULL, NULL);
        uv_freeaddrinfo(ai);
        ai = NULL;
        ai_current = NULL;
        cb = NULL;
        return;
    }
    cb(0, ai_current, &on_conn);
}

static void on_resolv(uv_getaddrinfo_t *req, int status, struct addrinfo *res) {
    LOGDV("on_resolv(req = %p): status = %d, res = %p",
          req,
          status,
          res);
    if (status) {
        LOGEV("Cannot resolve host: %s", uv_strerror(status));
        cb(status, NULL, NULL);
        return;
    }
    ai = res;
    ai_current = res;
    cb(0, ai_current, &on_conn);
}

int a_dns(const char *host,
          uint16_t port,
          void (*c)(int status,
                  const struct addrinfo *,
                  void (*on_connect_result)(bool))) {
    int r;
    char service[6];
    snprintf(service, 6, "%u", port);
    cb = c;
    if ((r = uv_getaddrinfo(loop, &resolv, on_resolv, host, service, NULL))) return r;
    return 0;
}