diff options
author | Sergey Poznyakoff <gray@gnu.org> | 2020-02-13 13:10:50 +0200 |
---|---|---|
committer | Sergey Poznyakoff <gray@gnu.org> | 2020-02-13 13:10:50 +0200 |
commit | 47bed8e5bc0e1a58e10c6237d27ce578bb50d7d6 (patch) | |
tree | f70dd9a2b162f971893af8a97d5d16173edb9d45 /src/ping903q.c | |
parent | 20176da3ca91d36c9a206925057b08d73278d8b7 (diff) | |
download | ping903-47bed8e5bc0e1a58e10c6237d27ce578bb50d7d6.tar.gz ping903-47bed8e5bc0e1a58e10c6237d27ce578bb50d7d6.tar.bz2 |
ping903q: resolve supplied argument before querying; improve error handling
Diffstat (limited to 'src/ping903q.c')
-rw-r--r-- | src/ping903q.c | 43 |
1 files changed, 37 insertions, 6 deletions
diff --git a/src/ping903q.c b/src/ping903q.c index ba5caa1..fdef668 100644 --- a/src/ping903q.c +++ b/src/ping903q.c @@ -446,6 +446,34 @@ print_host_status(struct json_value *obj, void *unused) return alive ? EX_NAGIOS_OK : EX_NAGIOS_CRITICAL; } +static char * +resolve_host(char const *name) +{ + struct addrinfo hints, *res; + char hbuf[NI_MAXHOST]; + int rc; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_protocol = IPPROTO_TCP; + rc = getaddrinfo(name, NULL, &hints, &res); + if (rc) + abend("%s: %s", name, gai_strerror(rc)); + if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf), + NULL, 0, NI_NUMERICHOST)) { + /* shouldn't happen */ + abend("%s: can't resolve hostname", name); + } + freeaddrinfo(res); + return estrdup(hbuf); +} + +static char *std_headers[] = { + "Accept: application/json", + "User-Agent: ping903q (" PACKAGE_STRING ")", + NULL +}; + static void query_host(char const *name, int (*report)(struct json_value *, void *), void *report_data) @@ -456,11 +484,14 @@ query_host(char const *name, int (*report)(struct json_value *, void *), char url[1024]; char const *hval; char *p; - ssize_t n = snprintf(url, sizeof(url), "/host/%s", name); + char *ipstr = resolve_host(name); + ssize_t n; + + n = snprintf(url, sizeof(url), "/host/%s", ipstr); if (n < 0 || n == sizeof(url)) { abend("bad host name or IP"); } - http_query("GET", url, NULL); + http_query("GET", url, std_headers); http_resp_init(&resp); http_recv(&resp); if (resp.code != 200) { @@ -473,12 +504,12 @@ query_host(char const *name, int (*report)(struct json_value *, void *), } rc = json_parse_string(resp.content, &obj, &p); - if (rc != JSON_E_NOERR) { + if (rc != JSON_E_NOERR) abend("%s near %s", json_strerror(rc), p); - } - if (obj->type != json_object) { + if (obj->type == json_null) + abend("%s (%s): host is not being monitored", name, ipstr); + if (obj->type != json_object) abend("returned entity has wrong type"); - } exit(report(obj, report_data)); } |