2 * Copyright (c) 2004-2005,2018
5 * Copyright (c) 2001-2003
6 * Fraunhofer Institute for Open Communication Systems (FhG Fokus).
9 * Author: Harti Brandt <harti@freebsd.org>
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * $Begemot: bsnmp/lib/snmpclient.c,v 1.36 2005/10/06 07:14:58 brandt_h Exp $
35 * Support functions for SNMP clients.
37 #include <sys/param.h>
39 #include <sys/queue.h>
40 #include <sys/socket.h>
55 #elif defined(HAVE_INTTYPES_H)
63 #include <arpa/inet.h>
68 #include "snmpclient.h"
74 struct snmp_client snmp_client;
76 /* List of all outstanding requests */
82 snmp_send_cb_f callback;
85 LIST_ENTRY(sent_pdu) entries;
87 LIST_HEAD(sent_pdu_list, sent_pdu);
89 static struct sent_pdu_list sent_pdus;
92 * Prototype table entry. All C-structure produced by the table function must
93 * start with these two fields. This relies on the fact, that all TAILQ_ENTRY
94 * are compatible with each other in the sense implied by ANSI-C.
97 TAILQ_ENTRY(entry) link;
100 TAILQ_HEAD(table, entry);
103 * working list entry. This list is used to hold the Index part of the
104 * table row's. The entry list and the work list parallel each other.
107 TAILQ_ENTRY(work) link;
108 struct asn_oid index;
110 TAILQ_HEAD(worklist, work);
116 const struct snmp_table *descr;
118 struct worklist worklist;
119 uint32_t last_change;
122 snmp_table_cb_f callback;
128 * Set the error string
131 seterr(struct snmp_client *sc, const char *fmt, ...)
136 vsnprintf(sc->error, sizeof(sc->error), fmt, ap);
141 * Free the entire table and work list. If table is NULL only the worklist
145 table_free(struct tabwork *work, int all)
149 const struct snmp_table_entry *d;
152 while ((w = TAILQ_FIRST(&work->worklist)) != NULL) {
153 TAILQ_REMOVE(&work->worklist, w, link);
160 while ((e = TAILQ_FIRST(work->table)) != NULL) {
161 for (i = 0; work->descr->entries[i].syntax != SNMP_SYNTAX_NULL;
163 d = &work->descr->entries[i];
164 if (d->syntax == SNMP_SYNTAX_OCTETSTRING &&
165 (e->found & ((uint64_t)1 << i)))
166 free(*(void **)(void *)
167 ((u_char *)e + d->offset));
169 TAILQ_REMOVE(work->table, e, link);
175 * Find the correct table entry for the given variable. If non exists,
178 static struct entry *
179 table_find(struct tabwork *work, const struct asn_oid *var)
181 struct entry *e, *e1;
189 asn_slice_oid(&oid, var, work->descr->table.len + 2, var->len);
191 e = TAILQ_FIRST(work->table);
192 w = TAILQ_FIRST(&work->worklist);
194 if (asn_compare_oid(&w->index, &oid) == 0)
196 e = TAILQ_NEXT(e, link);
197 w = TAILQ_NEXT(w, link);
200 /* Not found create new one */
201 if ((e = malloc(work->descr->entry_size)) == NULL) {
202 seterr(&snmp_client, "no memory for table entry");
205 if ((w = malloc(sizeof(*w))) == NULL) {
206 seterr(&snmp_client, "no memory for table entry");
211 memset(e, 0, work->descr->entry_size);
214 p = work->descr->table.len + 2;
215 for (i = 0; i < work->descr->index_size; i++) {
216 switch (work->descr->entries[i].syntax) {
218 case SNMP_SYNTAX_INTEGER:
219 if (var->len < p + 1) {
220 seterr(&snmp_client, "bad index: need integer");
223 if (var->subs[p] > INT32_MAX) {
225 "bad index: integer too large");
228 *(int32_t *)(void *)((u_char *)e +
229 work->descr->entries[i].offset) = var->subs[p++];
232 case SNMP_SYNTAX_OCTETSTRING:
233 if (var->len < p + 1) {
235 "bad index: need string length");
238 len = var->subs[p++];
239 if (var->len < p + len) {
241 "bad index: string too short");
244 if ((ptr = malloc(len + 1)) == NULL) {
246 "no memory for index string");
249 for (j = 0; j < len; j++) {
250 if (var->subs[p] > UCHAR_MAX) {
252 "bad index: char too large");
256 ptr[j] = var->subs[p++];
259 *(u_char **)(void *)((u_char *)e +
260 work->descr->entries[i].offset) = ptr;
261 *(size_t *)(void *)((u_char *)e +
262 work->descr->entries[i].offset + sizeof(u_char *))
266 case SNMP_SYNTAX_OID:
267 if (var->len < p + 1) {
269 "bad index: need oid length");
272 oid.len = var->subs[p++];
273 if (var->len < p + oid.len) {
275 "bad index: oid too short");
278 for (j = 0; j < oid.len; j++)
279 oid.subs[j] = var->subs[p++];
280 *(struct asn_oid *)(void *)((u_char *)e +
281 work->descr->entries[i].offset) = oid;
284 case SNMP_SYNTAX_IPADDRESS:
285 if (var->len < p + 4) {
287 "bad index: need ip-address");
290 for (j = 0; j < 4; j++) {
291 if (var->subs[p] > 0xff) {
293 "bad index: ipaddress too large");
297 work->descr->entries[i].offset)[j] =
302 case SNMP_SYNTAX_GAUGE:
303 if (var->len < p + 1) {
305 "bad index: need unsigned");
308 if (var->subs[p] > UINT32_MAX) {
310 "bad index: unsigned too large");
313 *(uint32_t *)(void *)((u_char *)e +
314 work->descr->entries[i].offset) = var->subs[p++];
317 case SNMP_SYNTAX_COUNTER:
318 case SNMP_SYNTAX_TIMETICKS:
319 case SNMP_SYNTAX_COUNTER64:
320 case SNMP_SYNTAX_NULL:
321 case SNMP_SYNTAX_NOSUCHOBJECT:
322 case SNMP_SYNTAX_NOSUCHINSTANCE:
323 case SNMP_SYNTAX_ENDOFMIBVIEW:
326 e->found |= (uint64_t)1 << i;
329 /* link into the correct place */
330 e1 = TAILQ_FIRST(work->table);
331 w1 = TAILQ_FIRST(&work->worklist);
333 if (asn_compare_oid(&w1->index, &w->index) > 0)
335 e1 = TAILQ_NEXT(e1, link);
336 w1 = TAILQ_NEXT(w1, link);
339 TAILQ_INSERT_TAIL(work->table, e, link);
340 TAILQ_INSERT_TAIL(&work->worklist, w, link);
342 TAILQ_INSERT_BEFORE(e1, e, link);
343 TAILQ_INSERT_BEFORE(w1, w, link);
350 * Error happend. Free all octet string index parts and the entry
353 for (i = 0; i < work->descr->index_size; i++) {
354 if (work->descr->entries[i].syntax == SNMP_SYNTAX_OCTETSTRING &&
355 (e->found & ((uint64_t)1 << i)))
356 free(*(void **)(void *)((u_char *)e +
357 work->descr->entries[i].offset));
368 table_value(const struct snmp_table *descr, struct entry *e,
369 const struct snmp_value *b)
374 for (i = descr->index_size;
375 descr->entries[i].syntax != SNMP_SYNTAX_NULL; i++)
376 if (descr->entries[i].subid ==
377 b->var.subs[descr->table.len + 1])
379 if (descr->entries[i].syntax == SNMP_SYNTAX_NULL)
383 if (b->syntax != descr->entries[i].syntax) {
384 seterr(&snmp_client, "bad syntax (%u instead of %u)", b->syntax,
385 descr->entries[i].syntax);
391 case SNMP_SYNTAX_INTEGER:
392 *(int32_t *)(void *)((u_char *)e + descr->entries[i].offset) =
396 case SNMP_SYNTAX_OCTETSTRING:
397 if ((ptr = malloc(b->v.octetstring.len + 1)) == NULL) {
398 seterr(&snmp_client, "no memory for string");
401 memcpy(ptr, b->v.octetstring.octets, b->v.octetstring.len);
402 ptr[b->v.octetstring.len] = '\0';
403 *(u_char **)(void *)((u_char *)e + descr->entries[i].offset) =
405 *(size_t *)(void *)((u_char *)e + descr->entries[i].offset +
406 sizeof(u_char *)) = b->v.octetstring.len;
409 case SNMP_SYNTAX_OID:
410 *(struct asn_oid *)(void *)((u_char *)e + descr->entries[i].offset) =
414 case SNMP_SYNTAX_IPADDRESS:
415 memcpy((u_char *)e + descr->entries[i].offset,
419 case SNMP_SYNTAX_COUNTER:
420 case SNMP_SYNTAX_GAUGE:
421 case SNMP_SYNTAX_TIMETICKS:
422 *(uint32_t *)(void *)((u_char *)e + descr->entries[i].offset) =
426 case SNMP_SYNTAX_COUNTER64:
427 *(uint64_t *)(void *)((u_char *)e + descr->entries[i].offset) =
431 case SNMP_SYNTAX_NULL:
432 case SNMP_SYNTAX_NOSUCHOBJECT:
433 case SNMP_SYNTAX_NOSUCHINSTANCE:
434 case SNMP_SYNTAX_ENDOFMIBVIEW:
437 e->found |= (uint64_t)1 << i;
443 * Initialize the first PDU to send
446 table_init_pdu(const struct snmp_table *descr, struct snmp_pdu *pdu)
448 if (snmp_client.version == SNMP_V1)
449 snmp_pdu_create(pdu, SNMP_PDU_GETNEXT);
451 snmp_pdu_create(pdu, SNMP_PDU_GETBULK);
452 pdu->error_index = 10;
454 if (descr->last_change.len != 0) {
455 pdu->bindings[pdu->nbindings].syntax = SNMP_SYNTAX_NULL;
456 pdu->bindings[pdu->nbindings].var = descr->last_change;
458 if (pdu->version != SNMP_V1)
461 pdu->bindings[pdu->nbindings].var = descr->table;
462 pdu->bindings[pdu->nbindings].syntax = SNMP_SYNTAX_NULL;
470 * -2 - Last change changed - again
474 table_check_response(struct tabwork *work, const struct snmp_pdu *resp)
476 const struct snmp_value *b;
479 if (resp->error_status != SNMP_ERR_NOERROR) {
480 if (snmp_client.version == SNMP_V1 &&
481 resp->error_status == SNMP_ERR_NOSUCHNAME &&
483 ((work->descr->last_change.len == 0) ? 1 : 2))
487 seterr(&snmp_client, "error fetching table: status=%d index=%d",
488 resp->error_status, resp->error_index);
492 for (b = resp->bindings; b < resp->bindings + resp->nbindings; b++) {
493 if (work->descr->last_change.len != 0 && b == resp->bindings) {
494 if (!asn_is_suboid(&work->descr->last_change, &b->var) ||
495 b->var.len != work->descr->last_change.len + 1 ||
496 b->var.subs[work->descr->last_change.len] != 0) {
498 "last_change: bad response");
501 if (b->syntax != SNMP_SYNTAX_TIMETICKS) {
503 "last_change: bad syntax %u", b->syntax);
507 work->last_change = b->v.uint32;
510 } else if (work->last_change != b->v.uint32) {
511 if (++work->iter >= work->descr->max_iter) {
513 "max iteration count exceeded");
522 if (!asn_is_suboid(&work->descr->table, &b->var) ||
523 b->syntax == SNMP_SYNTAX_ENDOFMIBVIEW)
526 if ((e = table_find(work, &b->var)) == NULL)
528 if (table_value(work->descr, e, b))
535 * Check table consistency
538 table_check_cons(struct tabwork *work)
542 TAILQ_FOREACH(e, work->table, link)
543 if ((e->found & work->descr->req_mask) !=
544 work->descr->req_mask) {
545 if (work->descr->last_change.len == 0) {
546 if (++work->iter >= work->descr->max_iter) {
548 "max iteration count exceeded");
553 seterr(&snmp_client, "inconsistency detected %llx %llx",
554 e->found, work->descr->req_mask);
561 * Fetch a table. Returns 0 if ok, -1 on errors.
562 * This is the synchronous variant.
565 snmp_table_fetch(const struct snmp_table *descr, void *list)
567 struct snmp_pdu resp;
572 work.table = (struct table *)list;
574 TAILQ_INIT(work.table);
575 TAILQ_INIT(&work.worklist);
576 work.callback = NULL;
581 * We come to this label when the code detects that the table
582 * has changed while fetching it.
585 work.last_change = 0;
586 table_init_pdu(descr, &work.pdu);
589 if (snmp_dialog(&work.pdu, &resp)) {
590 table_free(&work, 1);
593 if ((ret = table_check_response(&work, &resp)) == 0) {
594 snmp_pdu_free(&resp);
598 snmp_pdu_free(&resp);
599 table_free(&work, 1);
603 snmp_pdu_free(&resp);
607 work.pdu.bindings[work.pdu.nbindings - 1].var =
608 resp.bindings[resp.nbindings - 1].var;
610 snmp_pdu_free(&resp);
613 if ((ret = table_check_cons(&work)) == -1) {
614 table_free(&work, 1);
618 table_free(&work, 1);
624 table_free(&work, 0);
632 table_cb(struct snmp_pdu *req __unused, struct snmp_pdu *resp, void *arg)
634 struct tabwork *work = arg;
639 seterr(&snmp_client, "no response to fetch table request");
641 work->callback(work->table, work->arg, -1);
646 if ((ret = table_check_response(work, resp)) == 0) {
650 if ((ret = table_check_cons(work)) == -1) {
653 work->callback(work->table, work->arg, -1);
662 work->last_change = 0;
663 table_init_pdu(work->descr, &work->pdu);
664 if (snmp_pdu_send(&work->pdu, table_cb, work) == -1) {
665 work->callback(work->table, work->arg, -1);
675 work->callback(work->table, work->arg, 0);
684 work->callback(work->table, work->arg, -1);
697 work->pdu.bindings[work->pdu.nbindings - 1].var =
698 resp->bindings[resp->nbindings - 1].var;
702 if (snmp_pdu_send(&work->pdu, table_cb, work) == -1) {
704 work->callback(work->table, work->arg, -1);
711 snmp_table_fetch_async(const struct snmp_table *descr, void *list,
712 snmp_table_cb_f func, void *arg)
714 struct tabwork *work;
716 if ((work = malloc(sizeof(*work))) == NULL) {
717 seterr(&snmp_client, "%s", strerror(errno));
722 work->table = (struct table *)list;
724 TAILQ_INIT(work->table);
725 TAILQ_INIT(&work->worklist);
727 work->callback = func;
731 * Start by sending the first PDU
734 work->last_change = 0;
735 table_init_pdu(descr, &work->pdu);
737 if (snmp_pdu_send(&work->pdu, table_cb, work) == -1) {
746 * Append an index to an oid
749 snmp_oid_append(struct asn_oid *oid, const char *fmt, ...)
764 while (*fmt != '\0') {
767 /* just an integer more */
768 if (oid->len + 1 > ASN_MAXOIDLEN) {
769 warnx("%s: OID too long for integer", __func__);
773 oid->subs[oid->len++] = va_arg(va, asn_subid_t);
777 /* append an IP address */
778 if (oid->len + 4 > ASN_MAXOIDLEN) {
779 warnx("%s: OID too long for ip-addr", __func__);
783 ina = va_arg(va, struct in_addr);
784 ina.s_addr = ntohl(ina.s_addr);
785 oid->subs[oid->len++] = (ina.s_addr >> 24) & 0xff;
786 oid->subs[oid->len++] = (ina.s_addr >> 16) & 0xff;
787 oid->subs[oid->len++] = (ina.s_addr >> 8) & 0xff;
788 oid->subs[oid->len++] = (ina.s_addr >> 0) & 0xff;
792 /* append a null-terminated string,
793 * length is computed */
794 str = (const u_char *)va_arg(va, const char *);
795 len = strlen((const char *)str);
796 if (oid->len + len + 1 > ASN_MAXOIDLEN) {
797 warnx("%s: OID too long for string", __func__);
801 oid->subs[oid->len++] = len;
803 oid->subs[oid->len++] = *str++;
807 /* the integer value between ( and ) is stored
809 size = strtol(fmt, &nextptr, 10);
816 /* append `size` characters */
817 str = (const u_char *)va_arg(va, const char *);
818 if (oid->len + size > ASN_MAXOIDLEN) {
819 warnx("%s: OID too long for string", __func__);
824 oid->subs[oid->len++] = *str++;
828 /* get size and the octets from the arguments */
829 size = va_arg(va, size_t);
830 str = va_arg(va, const u_char *);
831 if (oid->len + size + 1 > ASN_MAXOIDLEN) {
832 warnx("%s: OID too long for string", __func__);
836 oid->subs[oid->len++] = size;
838 oid->subs[oid->len++] = *str++;
850 * Initialize a client structure
853 snmp_client_init(struct snmp_client *c)
855 memset(c, 0, sizeof(*c));
857 c->version = SNMP_V2c;
858 c->trans = SNMP_TRANS_UDP;
862 strcpy(c->read_community, "public");
863 strcpy(c->write_community, "private");
865 c->security_model = SNMP_SECMODEL_USM;
866 strcpy(c->cname, "");
868 c->timeout.tv_sec = 3;
869 c->timeout.tv_usec = 0;
872 c->txbuflen = c->rxbuflen = 10000;
876 c->max_reqid = INT32_MAX;
880 c->engine.max_msg_size = 1500; /* XXX */
885 * Open UDP client socket
888 open_client_udp(const char *host, const char *port)
892 struct addrinfo hints, *res0, *res;
894 /* copy host- and portname */
895 if (snmp_client.chost == NULL) {
896 if ((snmp_client.chost = malloc(1 + sizeof(DEFAULT_HOST)))
898 seterr(&snmp_client, "%s", strerror(errno));
901 strcpy(snmp_client.chost, DEFAULT_HOST);
904 if ((ptr = malloc(1 + strlen(host))) == NULL) {
905 seterr(&snmp_client, "%s", strerror(errno));
908 free(snmp_client.chost);
909 snmp_client.chost = ptr;
910 strcpy(snmp_client.chost, host);
912 if (snmp_client.cport == NULL) {
913 if ((snmp_client.cport = malloc(1 + sizeof(DEFAULT_PORT)))
915 seterr(&snmp_client, "%s", strerror(errno));
918 strcpy(snmp_client.cport, DEFAULT_PORT);
921 if ((ptr = malloc(1 + strlen(port))) == NULL) {
922 seterr(&snmp_client, "%s", strerror(errno));
925 free(snmp_client.cport);
926 snmp_client.cport = ptr;
927 strcpy(snmp_client.cport, port);
930 /* open connection */
931 memset(&hints, 0, sizeof(hints));
932 hints.ai_flags = AI_CANONNAME;
933 hints.ai_family = snmp_client.trans == SNMP_TRANS_UDP ? AF_INET:
935 hints.ai_socktype = SOCK_DGRAM;
936 hints.ai_protocol = 0;
937 error = getaddrinfo(snmp_client.chost, snmp_client.cport, &hints, &res0);
939 seterr(&snmp_client, "%s: %s", snmp_client.chost,
940 gai_strerror(error));
945 if ((snmp_client.fd = socket(res->ai_family, res->ai_socktype,
946 res->ai_protocol)) == -1) {
947 if ((res = res->ai_next) == NULL) {
948 seterr(&snmp_client, "%s", strerror(errno));
952 } else if (connect(snmp_client.fd, res->ai_addr,
953 res->ai_addrlen) == -1) {
954 if ((res = res->ai_next) == NULL) {
955 seterr(&snmp_client, "%s", strerror(errno));
957 (void)close(snmp_client.fd);
971 (void)remove(snmp_client.local_path);
978 open_client_local(const char *path)
980 struct sockaddr_un sa;
984 if (snmp_client.chost == NULL) {
985 if ((snmp_client.chost = malloc(1 + sizeof(DEFAULT_LOCAL)))
987 seterr(&snmp_client, "%s", strerror(errno));
990 strcpy(snmp_client.chost, DEFAULT_LOCAL);
993 if ((ptr = malloc(1 + strlen(path))) == NULL) {
994 seterr(&snmp_client, "%s", strerror(errno));
997 free(snmp_client.chost);
998 snmp_client.chost = ptr;
999 strcpy(snmp_client.chost, path);
1002 if (snmp_client.trans == SNMP_TRANS_LOC_DGRAM)
1005 stype = SOCK_STREAM;
1007 if ((snmp_client.fd = socket(PF_LOCAL, stype, 0)) == -1) {
1008 seterr(&snmp_client, "%s", strerror(errno));
1012 snprintf(snmp_client.local_path, sizeof(snmp_client.local_path),
1013 "%s", SNMP_LOCAL_PATH);
1015 if (mktemp(snmp_client.local_path) == NULL) {
1016 seterr(&snmp_client, "%s", strerror(errno));
1017 (void)close(snmp_client.fd);
1018 snmp_client.fd = -1;
1022 sa.sun_family = AF_LOCAL;
1023 sa.sun_len = sizeof(sa);
1024 strcpy(sa.sun_path, snmp_client.local_path);
1026 if (bind(snmp_client.fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
1027 seterr(&snmp_client, "%s", strerror(errno));
1028 (void)close(snmp_client.fd);
1029 snmp_client.fd = -1;
1030 (void)remove(snmp_client.local_path);
1033 atexit(remove_local);
1035 sa.sun_family = AF_LOCAL;
1036 sa.sun_len = offsetof(struct sockaddr_un, sun_path) +
1037 strlen(snmp_client.chost);
1038 strncpy(sa.sun_path, snmp_client.chost, sizeof(sa.sun_path) - 1);
1039 sa.sun_path[sizeof(sa.sun_path) - 1] = '\0';
1041 if (connect(snmp_client.fd, (struct sockaddr *)&sa, sa.sun_len) == -1) {
1042 seterr(&snmp_client, "%s", strerror(errno));
1043 (void)close(snmp_client.fd);
1044 snmp_client.fd = -1;
1045 (void)remove(snmp_client.local_path);
1055 snmp_open(const char *host, const char *port, const char *readcomm,
1056 const char *writecomm)
1058 struct timeval tout;
1061 if (snmp_client.fd != -1) {
1063 seterr(&snmp_client, "%s", strerror(errno));
1067 /* copy community strings */
1068 if (readcomm != NULL)
1069 strlcpy(snmp_client.read_community, readcomm,
1070 sizeof(snmp_client.read_community));
1071 if (writecomm != NULL)
1072 strlcpy(snmp_client.write_community, writecomm,
1073 sizeof(snmp_client.write_community));
1075 switch (snmp_client.trans) {
1077 case SNMP_TRANS_UDP:
1078 case SNMP_TRANS_UDP6:
1079 if (open_client_udp(host, port) != 0)
1083 case SNMP_TRANS_LOC_DGRAM:
1084 case SNMP_TRANS_LOC_STREAM:
1085 if (open_client_local(host) != 0)
1090 seterr(&snmp_client, "bad transport mapping");
1095 if (setsockopt(snmp_client.fd, SOL_SOCKET, SO_SNDTIMEO,
1096 &tout, sizeof(struct timeval)) == -1) {
1097 seterr(&snmp_client, "%s", strerror(errno));
1098 (void)close(snmp_client.fd);
1099 snmp_client.fd = -1;
1100 if (snmp_client.local_path[0] != '\0')
1101 (void)remove(snmp_client.local_path);
1105 /* initialize list */
1106 LIST_INIT(&sent_pdus);
1115 * closes connection to snmp server
1116 * - function cannot fail
1117 * - clears connection
1118 * - clears list of sent pdus
1128 struct sent_pdu *p1;
1130 if (snmp_client.fd != -1) {
1131 (void)close(snmp_client.fd);
1132 snmp_client.fd = -1;
1133 if (snmp_client.local_path[0] != '\0')
1134 (void)remove(snmp_client.local_path);
1136 while(!LIST_EMPTY(&sent_pdus)){
1137 p1 = LIST_FIRST(&sent_pdus);
1138 if (p1->timeout_id != NULL)
1139 snmp_client.timeout_stop(p1->timeout_id);
1140 LIST_REMOVE(p1, entries);
1143 free(snmp_client.chost);
1144 free(snmp_client.cport);
1148 * initialize a snmp_pdu structure
1151 snmp_pdu_create(struct snmp_pdu *pdu, u_int op)
1153 memset(pdu, 0, sizeof(struct snmp_pdu));
1155 if (op == SNMP_PDU_SET)
1156 strlcpy(pdu->community, snmp_client.write_community,
1157 sizeof(pdu->community));
1159 strlcpy(pdu->community, snmp_client.read_community,
1160 sizeof(pdu->community));
1163 pdu->version = snmp_client.version;
1164 pdu->error_status = 0;
1165 pdu->error_index = 0;
1168 if (snmp_client.version != SNMP_V3)
1171 pdu->identifier = ++snmp_client.identifier;
1172 pdu->engine.max_msg_size = snmp_client.engine.max_msg_size;
1174 pdu->security_model = snmp_client.security_model;
1176 if (snmp_client.security_model == SNMP_SECMODEL_USM) {
1177 memcpy(&pdu->engine, &snmp_client.engine, sizeof(pdu->engine));
1178 memcpy(&pdu->user, &snmp_client.user, sizeof(pdu->user));
1179 snmp_pdu_init_secparams(pdu);
1181 seterr(&snmp_client, "unknown security model");
1183 if (snmp_client.clen > 0) {
1184 memcpy(pdu->context_engine, snmp_client.cengine,
1186 pdu->context_engine_len = snmp_client.clen;
1188 memcpy(pdu->context_engine, snmp_client.engine.engine_id,
1189 snmp_client.engine.engine_len);
1190 pdu->context_engine_len = snmp_client.engine.engine_len;
1193 strlcpy(pdu->context_name, snmp_client.cname,
1194 sizeof(pdu->context_name));
1197 /* add pairs of (struct asn_oid, enum snmp_syntax) to an existing pdu */
1198 /* added 10/04/02 by kek: check for MAX_BINDINGS */
1200 snmp_add_binding(struct snmp_v1_pdu *pdu, ...)
1203 const struct asn_oid *oid;
1208 ret = pdu->nbindings;
1209 while ((oid = va_arg(ap, const struct asn_oid *)) != NULL) {
1210 if (pdu->nbindings >= SNMP_MAX_BINDINGS){
1214 pdu->bindings[pdu->nbindings].var = *oid;
1215 pdu->bindings[pdu->nbindings].syntax =
1216 va_arg(ap, enum snmp_syntax);
1225 snmp_next_reqid(struct snmp_client * c)
1230 if (c->next_reqid >= c->max_reqid)
1231 c->next_reqid = c->min_reqid;
1238 * Send request and return request id.
1241 snmp_send_packet(struct snmp_pdu * pdu)
1247 if ((buf = calloc(1, snmp_client.txbuflen)) == NULL) {
1248 seterr(&snmp_client, "%s", strerror(errno));
1252 pdu->request_id = snmp_next_reqid(&snmp_client);
1255 b.asn_len = snmp_client.txbuflen;
1256 if (snmp_pdu_encode(pdu, &b)) {
1257 seterr(&snmp_client, "%s", strerror(errno));
1262 if (snmp_client.dump_pdus)
1265 if ((ret = send(snmp_client.fd, buf, b.asn_ptr - buf, 0)) == -1) {
1266 seterr(&snmp_client, "%s", strerror(errno));
1272 return (pdu->request_id);
1276 * to be called when a snmp request timed out
1279 snmp_timeout(void * listentry_ptr)
1281 struct sent_pdu *listentry = listentry_ptr;
1284 warnx("snmp request %i timed out, attempt (%i/%i)",
1285 listentry->reqid, listentry->retrycount, snmp_client.retries);
1288 listentry->retrycount++;
1289 if (listentry->retrycount > snmp_client.retries) {
1290 /* there is no answer at all */
1291 LIST_REMOVE(listentry, entries);
1292 listentry->callback(listentry->pdu, NULL, listentry->arg);
1296 /* new request with new request ID */
1297 listentry->reqid = snmp_send_packet(listentry->pdu);
1298 listentry->timeout_id =
1299 snmp_client.timeout_start(&snmp_client.timeout,
1300 snmp_timeout, listentry);
1305 snmp_pdu_send(struct snmp_pdu *pdu, snmp_send_cb_f func, void *arg)
1307 struct sent_pdu *listentry;
1310 if ((listentry = malloc(sizeof(struct sent_pdu))) == NULL) {
1311 seterr(&snmp_client, "%s", strerror(errno));
1315 /* here we really send */
1316 if ((id = snmp_send_packet(pdu)) == -1) {
1321 /* add entry to list of sent PDUs */
1322 listentry->pdu = pdu;
1323 if (gettimeofday(&listentry->time, NULL) == -1)
1324 warn("gettimeofday() failed");
1326 listentry->reqid = pdu->request_id;
1327 listentry->callback = func;
1328 listentry->arg = arg;
1329 listentry->retrycount=1;
1330 listentry->timeout_id =
1331 snmp_client.timeout_start(&snmp_client.timeout, snmp_timeout,
1334 LIST_INSERT_HEAD(&sent_pdus, listentry, entries);
1340 * Receive an SNMP packet.
1342 * tv controls how we wait for a packet: if tv is a NULL pointer,
1343 * the receive blocks forever, if tv points to a structure with all
1344 * members 0 the socket is polled, in all other cases tv specifies the
1345 * maximum time to wait for a packet.
1350 * +1 if packet received
1353 snmp_receive_packet(struct snmp_pdu *pdu, struct timeval *tv)
1355 int dopoll, setpoll;
1360 struct asn_buf abuf;
1368 if ((buf = calloc(1, snmp_client.rxbuflen)) == NULL) {
1369 seterr(&snmp_client, "%s", strerror(errno));
1372 dopoll = setpoll = 0;
1375 /* poll or timeout */
1376 if (tv->tv_sec != 0 || tv->tv_usec != 0) {
1377 /* wait with timeout */
1378 if (setsockopt(snmp_client.fd, SOL_SOCKET, SO_RCVTIMEO,
1379 tv, sizeof(*tv)) == -1) {
1380 seterr(&snmp_client, "setsockopt: %s",
1385 optlen = sizeof(*tv);
1386 if (getsockopt(snmp_client.fd, SOL_SOCKET, SO_RCVTIMEO,
1387 tv, &optlen) == -1) {
1388 seterr(&snmp_client, "getsockopt: %s",
1393 /* at this point tv_sec and tv_usec may appear
1394 * as 0. This happens for timeouts lesser than
1395 * the clock granularity. The kernel rounds these to
1396 * 0 and this would result in a blocking receive.
1397 * Instead of an else we check tv_sec and tv_usec
1398 * again below and if this rounding happens,
1399 * switch to a polling receive. */
1401 if (tv->tv_sec == 0 && tv->tv_usec == 0) {
1404 if ((flags = fcntl(snmp_client.fd, F_GETFL, 0)) == -1) {
1405 seterr(&snmp_client, "fcntl: %s",
1410 if (!(flags & O_NONBLOCK)) {
1412 flags |= O_NONBLOCK;
1413 if (fcntl(snmp_client.fd, F_SETFL, flags) == -1) {
1414 seterr(&snmp_client, "fcntl: %s",
1422 ret = recv(snmp_client.fd, buf, snmp_client.rxbuflen, 0);
1423 saved_errno = errno;
1427 flags &= ~O_NONBLOCK;
1428 (void)fcntl(snmp_client.fd, F_SETFL, flags);
1433 (void)setsockopt(snmp_client.fd, SOL_SOCKET, SO_RCVTIMEO,
1439 if (errno == EAGAIN || errno == EWOULDBLOCK)
1441 seterr(&snmp_client, "recv: %s", strerror(saved_errno));
1445 /* this happens when we have a streaming socket and the
1446 * remote side has closed it */
1448 seterr(&snmp_client, "recv: socket closed by peer");
1456 memset(pdu, 0, sizeof(*pdu));
1457 if (snmp_client.security_model == SNMP_SECMODEL_USM) {
1458 memcpy(&pdu->engine, &snmp_client.engine, sizeof(pdu->engine));
1459 memcpy(&pdu->user, &snmp_client.user, sizeof(pdu->user));
1460 snmp_pdu_init_secparams(pdu);
1463 if (SNMP_CODE_OK != (ret = snmp_pdu_decode(&abuf, pdu, &ip))) {
1464 seterr(&snmp_client, "snmp_decode_pdu: failed %d", ret);
1470 if (snmp_client.dump_pdus)
1473 snmp_client.engine.engine_time = pdu->engine.engine_time;
1474 snmp_client.engine.engine_boots = pdu->engine.engine_boots;
1480 snmp_deliver_packet(struct snmp_pdu * resp)
1482 struct sent_pdu *listentry;
1484 if (resp->type != SNMP_PDU_RESPONSE) {
1485 warn("ignoring snmp pdu %u", resp->type);
1489 LIST_FOREACH(listentry, &sent_pdus, entries)
1490 if (listentry->reqid == resp->request_id)
1492 if (listentry == NULL)
1495 LIST_REMOVE(listentry, entries);
1496 listentry->callback(listentry->pdu, resp, listentry->arg);
1498 snmp_client.timeout_stop(listentry->timeout_id);
1505 snmp_receive(int blocking)
1510 struct snmp_pdu * resp;
1512 memset(&tv, 0, sizeof(tv));
1514 resp = malloc(sizeof(struct snmp_pdu));
1516 seterr(&snmp_client, "no memory for returning PDU");
1520 if ((ret = snmp_receive_packet(resp, blocking ? NULL : &tv)) <= 0) {
1524 ret = snmp_deliver_packet(resp);
1525 snmp_pdu_free(resp);
1532 * Check a GETNEXT response. Here we have three possible outcomes: -1 an
1533 * unexpected error happened. +1 response is ok and is within the table 0
1534 * response is ok, but is behind the table or error is NOSUCHNAME. The req
1535 * should point to a template PDU which contains the base OIDs and the
1536 * syntaxes. This is really only useful to sweep non-sparse tables.
1539 ok_getnext(const struct snmp_pdu * req, const struct snmp_pdu * resp)
1543 if (resp->version != req->version) {
1544 warnx("SNMP GETNEXT: response has wrong version");
1548 if (resp->error_status == SNMP_ERR_NOSUCHNAME)
1551 if (resp->error_status != SNMP_ERR_NOERROR) {
1552 warnx("SNMP GETNEXT: error %d", resp->error_status);
1555 if (resp->nbindings != req->nbindings) {
1556 warnx("SNMP GETNEXT: bad number of bindings in response");
1559 for (i = 0; i < req->nbindings; i++) {
1560 if (!asn_is_suboid(&req->bindings[i].var,
1561 &resp->bindings[i].var)) {
1563 warnx("SNMP GETNEXT: inconsistent table "
1567 if (resp->version != SNMP_V1 &&
1568 resp->bindings[i].syntax == SNMP_SYNTAX_ENDOFMIBVIEW)
1571 if (resp->bindings[i].syntax != req->bindings[i].syntax) {
1572 warnx("SNMP GETNEXT: bad syntax in response");
1580 * Check a GET response. Here we have three possible outcomes: -1 an
1581 * unexpected error happened. +1 response is ok. 0 NOSUCHNAME The req should
1582 * point to a template PDU which contains the OIDs and the syntaxes. This
1583 * is only useful for SNMPv1 or single object GETS.
1586 ok_get(const struct snmp_pdu * req, const struct snmp_pdu * resp)
1590 if (resp->version != req->version) {
1591 warnx("SNMP GET: response has wrong version");
1595 if (resp->error_status == SNMP_ERR_NOSUCHNAME)
1598 if (resp->error_status != SNMP_ERR_NOERROR) {
1599 warnx("SNMP GET: error %d", resp->error_status);
1603 if (resp->nbindings != req->nbindings) {
1604 warnx("SNMP GET: bad number of bindings in response");
1607 for (i = 0; i < req->nbindings; i++) {
1608 if (asn_compare_oid(&req->bindings[i].var,
1609 &resp->bindings[i].var) != 0) {
1610 warnx("SNMP GET: bad OID in response");
1613 if (snmp_client.version != SNMP_V1 &&
1614 (resp->bindings[i].syntax == SNMP_SYNTAX_NOSUCHOBJECT ||
1615 resp->bindings[i].syntax == SNMP_SYNTAX_NOSUCHINSTANCE))
1617 if (resp->bindings[i].syntax != req->bindings[i].syntax) {
1618 warnx("SNMP GET: bad syntax in response");
1626 * Check the response to a SET PDU. We check: - the error status must be 0 -
1627 * the number of bindings must be equal in response and request - the
1628 * syntaxes must be the same in response and request - the OIDs must be the
1629 * same in response and request
1632 ok_set(const struct snmp_pdu * req, const struct snmp_pdu * resp)
1636 if (resp->version != req->version) {
1637 warnx("SNMP SET: response has wrong version");
1641 if (resp->error_status == SNMP_ERR_NOSUCHNAME) {
1642 warnx("SNMP SET: error %d", resp->error_status);
1645 if (resp->error_status != SNMP_ERR_NOERROR) {
1646 warnx("SNMP SET: error %d", resp->error_status);
1650 if (resp->nbindings != req->nbindings) {
1651 warnx("SNMP SET: bad number of bindings in response");
1654 for (i = 0; i < req->nbindings; i++) {
1655 if (asn_compare_oid(&req->bindings[i].var,
1656 &resp->bindings[i].var) != 0) {
1657 warnx("SNMP SET: wrong OID in response to SET");
1660 if (resp->bindings[i].syntax != req->bindings[i].syntax) {
1661 warnx("SNMP SET: bad syntax in response");
1669 * Simple checks for response PDUs against request PDUs. Return values: 1=ok,
1670 * 0=nosuchname or similar, -1=failure, -2=no response at all
1673 snmp_pdu_check(const struct snmp_pdu *req,
1674 const struct snmp_pdu *resp)
1679 switch (req->type) {
1682 return (ok_get(req, resp));
1685 return (ok_set(req, resp));
1687 case SNMP_PDU_GETNEXT:
1688 return (ok_getnext(req, resp));
1691 errx(1, "%s: bad pdu type %i", __func__, req->type);
1695 snmp_dialog(struct snmp_v1_pdu *req, struct snmp_v1_pdu *resp)
1697 struct timeval tv = snmp_client.timeout;
1699 struct snmp_pdu pdu;
1705 * Make a copy of the request and replace the syntaxes by NULL
1706 * if this is a GET,GETNEXT or GETBULK.
1709 if (pdu.type == SNMP_PDU_GET || pdu.type == SNMP_PDU_GETNEXT ||
1710 pdu.type == SNMP_PDU_GETBULK) {
1711 for (i = 0; i < pdu.nbindings; i++)
1712 pdu.bindings[i].syntax = SNMP_SYNTAX_NULL;
1715 for (i = 0; i <= snmp_client.retries; i++) {
1716 (void)gettimeofday(&end, NULL);
1717 timeradd(&end, &snmp_client.timeout, &end);
1718 if ((reqid = snmp_send_packet(&pdu)) == -1)
1721 (void)gettimeofday(&tv, NULL);
1722 if (timercmp(&end, &tv, <=))
1724 timersub(&end, &tv, &tv);
1725 if ((ret = snmp_receive_packet(resp, &tv)) == 0)
1730 if (reqid == resp->request_id)
1733 (void)snmp_deliver_packet(resp);
1735 if (ret < 0 && errno == EPIPE)
1741 seterr(&snmp_client, "retry count exceeded");
1746 snmp_discover_engine(char *passwd)
1748 char cname[SNMP_ADM_STR32_SIZ];
1749 enum snmp_authentication cap;
1750 enum snmp_privacy cpp;
1751 struct snmp_pdu req, resp;
1753 if (snmp_client.version != SNMP_V3)
1754 seterr(&snmp_client, "wrong version");
1756 strlcpy(cname, snmp_client.user.sec_name, sizeof(cname));
1757 cap = snmp_client.user.auth_proto;
1758 cpp = snmp_client.user.priv_proto;
1760 snmp_client.engine.engine_len = 0;
1761 snmp_client.engine.engine_boots = 0;
1762 snmp_client.engine.engine_time = 0;
1763 snmp_client.user.auth_proto = SNMP_AUTH_NOAUTH;
1764 snmp_client.user.priv_proto = SNMP_PRIV_NOPRIV;
1765 memset(snmp_client.user.sec_name, 0, sizeof(snmp_client.user.sec_name));
1767 snmp_pdu_create(&req, SNMP_PDU_GET);
1769 if (snmp_dialog(&req, &resp) == -1)
1772 if (resp.version != req.version) {
1773 seterr(&snmp_client, "wrong version");
1777 if (resp.error_status != SNMP_ERR_NOERROR) {
1778 seterr(&snmp_client, "Error %d in responce", resp.error_status);
1782 snmp_client.engine.engine_len = resp.engine.engine_len;
1783 snmp_client.engine.max_msg_size = resp.engine.max_msg_size;
1784 memcpy(snmp_client.engine.engine_id, resp.engine.engine_id,
1785 resp.engine.engine_len);
1787 strlcpy(snmp_client.user.sec_name, cname,
1788 sizeof(snmp_client.user.sec_name));
1789 snmp_client.user.auth_proto = cap;
1790 snmp_client.user.priv_proto = cpp;
1792 if (snmp_client.user.auth_proto == SNMP_AUTH_NOAUTH)
1795 if (passwd == NULL ||
1796 snmp_passwd_to_keys(&snmp_client.user, passwd) != SNMP_CODE_OK ||
1797 snmp_get_local_keys(&snmp_client.user, snmp_client.engine.engine_id,
1798 snmp_client.engine.engine_len) != SNMP_CODE_OK)
1801 if (resp.engine.engine_boots != 0)
1802 snmp_client.engine.engine_boots = resp.engine.engine_boots;
1804 if (resp.engine.engine_time != 0) {
1805 snmp_client.engine.engine_time = resp.engine.engine_time;
1809 snmp_pdu_free(&req);
1811 snmp_pdu_create(&req, SNMP_PDU_GET);
1812 req.engine.engine_boots = 0;
1813 req.engine.engine_time = 0;
1815 if (snmp_dialog(&req, &resp) == -1)
1818 if (resp.version != req.version) {
1819 seterr(&snmp_client, "wrong version");
1823 if (resp.error_status != SNMP_ERR_NOERROR) {
1824 seterr(&snmp_client, "Error %d in responce", resp.error_status);
1828 snmp_client.engine.engine_boots = resp.engine.engine_boots;
1829 snmp_client.engine.engine_time = resp.engine.engine_time;
1831 snmp_pdu_free(&req);
1832 snmp_pdu_free(&resp);
1838 snmp_client_set_host(struct snmp_client *cl, const char *h)
1843 if (cl->chost != NULL)
1847 if ((np = malloc(strlen(h) + 1)) == NULL)
1850 if (cl->chost != NULL)
1858 snmp_client_set_port(struct snmp_client *cl, const char *p)
1863 if (cl->cport != NULL)
1867 if ((np = malloc(strlen(p) + 1)) == NULL)
1870 if (cl->cport != NULL)
1877 static const char *const trans_list[] = {
1878 [SNMP_TRANS_UDP] = "udp::",
1879 [SNMP_TRANS_LOC_DGRAM] = "dgram::",
1880 [SNMP_TRANS_LOC_STREAM] = "stream::",
1881 [SNMP_TRANS_UDP6] = "udp6::",
1885 * Try to get a transport identifier which is a leading alphanumeric string
1886 * terminated by a double colon. The string may not be empty. The transport
1887 * identifier is optional.
1889 * \param sc client struct to set errors
1890 * \param strp possible start of transport; updated to point to
1891 * the next character to parse
1893 * \return transport identifier
1896 get_transp(struct snmp_client *sc, const char **strp)
1901 for (i = 0; i < nitems(trans_list); i++) {
1902 if (trans_list[i] == NULL || *trans_list[i] == '\0')
1904 p = strstr(*strp, trans_list[i]);
1906 *strp += strlen(trans_list[i]);
1912 if (p[0] == ':' && p[1] == ':') {
1913 seterr(sc, "empty transport specifier");
1916 /* by default assume UDP */
1917 return (SNMP_TRANS_UDP);
1921 * Try to get community string. Eat everything up to the last @ (if there is
1922 * any) but only if it is not longer than SNMP_COMMUNITY_MAXLEN. Empty
1923 * community strings are legal.
1925 * \param sc client struct to set errors
1926 * \param strp possible start of community; updated to the point to
1927 * the next character to parse
1929 * \return end of community; equals *strp if there is none; NULL if there
1932 static inline const char *
1933 get_comm(struct snmp_client *sc, const char **strp)
1935 const char *p = strrchr(*strp, '@');
1938 /* no community string */
1941 if (p - *strp > SNMP_COMMUNITY_MAXLEN) {
1942 seterr(sc, "community string too long '%.*s'",
1952 * Try to get an IPv6 address. This starts with an [ and should end with an ]
1953 * and everything between should be not longer than INET6_ADDRSTRLEN and
1954 * parseable by inet_pton().
1956 * \param sc client struct to set errors
1957 * \param strp possible start of IPv6 address (the '['); updated to point to
1958 * the next character to parse (the one after the closing ']')
1960 * \return end of address (equals *strp + 1 if there is none) or NULL
1963 static inline const char *
1964 get_ipv6(struct snmp_client *sc, const char **strp)
1966 char str[INET6_ADDRSTRLEN + IF_NAMESIZE];
1967 struct addrinfo hints, *res;
1973 const char *p = *strp + 1;
1974 while (*p != ']' ) {
1976 seterr(sc, "unterminated IPv6 address '%.*s'",
1983 if (p - *strp > INET6_ADDRSTRLEN + IF_NAMESIZE) {
1984 seterr(sc, "IPv6 address too long '%.*s'", p - *strp, *strp);
1988 strncpy(str, *strp + 1, p - (*strp + 1));
1989 str[p - (*strp + 1)] = '\0';
1991 memset(&hints, 0, sizeof(hints));
1992 hints.ai_flags = AI_CANONNAME | AI_NUMERICHOST;
1993 hints.ai_family = AF_INET6;
1994 hints.ai_socktype = SOCK_DGRAM;
1995 hints.ai_protocol = IPPROTO_UDP;
1996 error = getaddrinfo(str, NULL, &hints, &res);
1998 seterr(sc, "%s: %s", str, gai_strerror(error));
2007 * Try to get an IPv4 address. This starts with a digit and consists of digits
2008 * and dots, is not longer INET_ADDRSTRLEN and must be parseable by
2011 * \param sc client struct to set errors
2012 * \param strp possible start of IPv4 address; updated to point to the
2013 * next character to parse
2015 * \return end of address (equals *strp if there is none) or NULL
2018 static inline const char *
2019 get_ipv4(struct snmp_client *sc, const char **strp)
2021 const char *p = *strp;
2023 while (isascii(*p) && (isdigit(*p) || *p == '.'))
2026 if (p - *strp > INET_ADDRSTRLEN) {
2027 seterr(sc, "IPv4 address too long '%.*s'", p - *strp, *strp);
2033 char str[INET_ADDRSTRLEN + 1];
2034 strncpy(str, *strp, p - *strp);
2035 str[p - *strp] = '\0';
2037 struct in_addr addr;
2038 if (inet_aton(str, &addr) != 1) {
2039 seterr(sc, "illegal IPv4 address '%s'", str);
2048 * Try to get a hostname. This includes everything up to but not including
2049 * the last colon (if any). There is no length restriction.
2051 * \param sc client struct to set errors
2052 * \param strp possible start of hostname; updated to point to the next
2053 * character to parse (the trailing NUL character or the last
2056 * \return end of address (equals *strp if there is none)
2058 static inline const char *
2059 get_host(struct snmp_client *sc __unused, const char **strp)
2061 const char *p = strrchr(*strp, ':');
2064 *strp += strlen(*strp);
2073 * Try to get a port number. This start with a colon and extends to the end
2074 * of string. The port number must not be empty.
2076 * \param sc client struct to set errors
2077 * \param strp possible start of port specification; if this points to a
2078 * colon there is a port specification
2080 * \return end of port number (equals *strp if there is none); NULL
2081 * if there is no port number
2083 static inline const char *
2084 get_port(struct snmp_client *sc, const char **strp)
2089 if ((*strp)[1] == '\0') {
2090 seterr(sc, "empty port name");
2094 *strp += strlen(*strp);
2099 * Save the string in the range given by two pointers.
2101 * \param sc client struct to set errors
2102 * \param s begin and end pointers
2104 * \return freshly allocated copy of the string between s[0] and s[1]
2106 static inline char *
2107 save_str(struct snmp_client *sc, const char *const s[2])
2111 if ((m = malloc(s[1] - s[0] + 1)) == NULL) {
2112 seterr(sc, "%s: %s", __func__, strerror(errno));
2115 strncpy(m, s[0], s[1] - s[0]);
2116 m[s[1] - s[0]] = '\0';
2122 * Parse a server specification. All parts are optional:
2124 * [<trans>::][<comm>@][<host-or-ip>][:<port>]
2126 * The transport string consists of letters, digits or '_' and starts with
2127 * a letter or digit. It is terminated by two colons and may not be empty.
2129 * The community string is terminated by the last '@' and does not exceed
2130 * SNMP_COMMUNITY_MAXLEN. It may be empty.
2132 * The host or ip is either an IPv4 address (as parsed by inet_pton()), an
2133 * IPv6 address in '[' and ']' and parseable by inet_aton() or a hostname
2134 * terminated by the last colon or by the NUL character.
2136 * The port number may be specified numerically or symbolically and starts
2137 * with the last colon.
2139 * The functions sets the chost, cport, trans, read_community and
2140 * write_community fields on success and the error field on errors.
2141 * The chost and cport fields are allocated by malloc(3), their previous
2142 * content is deallocated by free(3).
2144 * The function explicitly allows mismatches between the transport and
2145 * the address type in order to support IPv4 in IPv6 addresses.
2147 * \param sc client struct to fill
2148 * \param str string to parse
2150 * \return 0 on success and -1 on errors
2153 snmp_parse_server(struct snmp_client *sc, const char *str)
2155 const char *const orig = str;
2157 int i, trans = get_transp(sc, &str);
2160 /* choose automatically */
2161 i = orig == str ? -1: trans;
2163 const char *const comm[2] = {
2167 if (comm[1] == NULL)
2170 const char *const ipv6[2] = {
2174 if (ipv6[1] == NULL)
2177 const char *ipv4[2] = {
2182 const char *host[2] = {
2187 if (ipv6[0] == ipv6[1]) {
2188 ipv4[1] = get_ipv4(sc, &str);
2190 if (ipv4[0] == ipv4[1])
2191 host[1] = get_host(sc, &str);
2194 const char *port[2] = {
2198 if (port[1] == NULL)
2202 seterr(sc, "junk at end of server specification '%s'", str);
2207 printf("transp: %u\n", trans);
2208 printf("comm: %zu %zu\n", comm[0] - orig, comm[1] - orig);
2209 printf("ipv6: %zu %zu\n", ipv6[0] - orig, ipv6[1] - orig);
2210 printf("ipv4: %zu %zu\n", ipv4[0] - orig, ipv4[1] - orig);
2211 printf("host: %zu %zu\n", host[0] - orig, host[1] - orig);
2212 printf("port: %zu %zu\n", port[0] - orig, port[1] - orig);
2215 /* analyse and allocate */
2218 if (ipv6[0] != ipv6[1]) {
2219 if ((chost = save_str(sc, ipv6)) == NULL)
2221 if (i == -1 || trans == SNMP_TRANS_UDP)
2222 trans = SNMP_TRANS_UDP6;
2223 } else if (ipv4[0] != ipv4[1]) {
2224 if ((chost = save_str(sc, ipv4)) == NULL)
2227 trans = SNMP_TRANS_UDP;
2229 if ((chost = save_str(sc, host)) == NULL)
2234 * Default transport is UDP unless the host contains
2235 * a slash in which case we default to DGRAM.
2237 for (const char *p = host[0]; p < host[1]; p++)
2239 trans = SNMP_TRANS_LOC_DGRAM;
2247 if (port[0] == port[1] && (
2248 trans == SNMP_TRANS_UDP || trans == SNMP_TRANS_UDP6)) {
2249 /* If port was not specified, use "snmp" name by default */
2250 cport = strdup("snmp");
2252 cport = save_str(sc, port);
2254 if (cport == NULL) {
2262 * If community string was specified and it is empty, overwrite it.
2263 * If it was not specified, use default.
2265 if (comm[0] != comm[1] || strrchr(comm[0], '@') != NULL) {
2266 strncpy(sc->read_community, comm[0], comm[1] - comm[0]);
2267 sc->read_community[comm[1] - comm[0]] = '\0';
2268 strncpy(sc->write_community, comm[0], comm[1] - comm[0]);
2269 sc->write_community[comm[1] - comm[0]] = '\0';
2278 printf("Committed values:\n");
2279 printf("trans: %u\n", sc->trans);
2280 printf("comm: '%s'/'%s'\n", sc->read_community, sc->write_community);
2281 printf("host: '%s'\n", sc->chost);
2282 printf("port: '%s'\n", sc->cport);