2 * Copyright (c) 2004-2005
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/types.h>
39 #include <sys/queue.h>
40 #include <sys/socket.h>
53 #elif defined(HAVE_INTTYPES_H)
64 #include "snmpclient.h"
68 struct snmp_client snmp_client;
70 /* List of all outstanding requests */
76 snmp_send_cb_f callback;
79 LIST_ENTRY(sent_pdu) entries;
81 LIST_HEAD(sent_pdu_list, sent_pdu);
83 static struct sent_pdu_list sent_pdus;
86 * Prototype table entry. All C-structure produced by the table function must
87 * start with these two fields. This relies on the fact, that all TAILQ_ENTRY
88 * are compatible with each other in the sense implied by ANSI-C.
91 TAILQ_ENTRY(entry) link;
94 TAILQ_HEAD(table, entry);
97 * working list entry. This list is used to hold the Index part of the
98 * table row's. The entry list and the work list parallel each other.
101 TAILQ_ENTRY(work) link;
102 struct asn_oid index;
104 TAILQ_HEAD(worklist, work);
110 const struct snmp_table *descr;
112 struct worklist worklist;
113 uint32_t last_change;
116 snmp_table_cb_f callback;
122 * Set the error string
125 seterr(struct snmp_client *sc, const char *fmt, ...)
130 vsnprintf(sc->error, sizeof(sc->error), fmt, ap);
135 * Free the entire table and work list. If table is NULL only the worklist
139 table_free(struct tabwork *work, int all)
143 const struct snmp_table_entry *d;
146 while ((w = TAILQ_FIRST(&work->worklist)) != NULL) {
147 TAILQ_REMOVE(&work->worklist, w, link);
154 while ((e = TAILQ_FIRST(work->table)) != NULL) {
155 for (i = 0; work->descr->entries[i].syntax != SNMP_SYNTAX_NULL;
157 d = &work->descr->entries[i];
158 if (d->syntax == SNMP_SYNTAX_OCTETSTRING &&
159 (e->found & ((uint64_t)1 << i)))
160 free(*(void **)(void *)
161 ((u_char *)e + d->offset));
163 TAILQ_REMOVE(work->table, e, link);
169 * Find the correct table entry for the given variable. If non exists,
172 static struct entry *
173 table_find(struct tabwork *work, const struct asn_oid *var)
175 struct entry *e, *e1;
183 asn_slice_oid(&oid, var, work->descr->table.len + 2, var->len);
185 e = TAILQ_FIRST(work->table);
186 w = TAILQ_FIRST(&work->worklist);
188 if (asn_compare_oid(&w->index, &oid) == 0)
190 e = TAILQ_NEXT(e, link);
191 w = TAILQ_NEXT(w, link);
194 /* Not found create new one */
195 if ((e = malloc(work->descr->entry_size)) == NULL) {
196 seterr(&snmp_client, "no memory for table entry");
199 if ((w = malloc(sizeof(*w))) == NULL) {
200 seterr(&snmp_client, "no memory for table entry");
205 memset(e, 0, work->descr->entry_size);
208 p = work->descr->table.len + 2;
209 for (i = 0; i < work->descr->index_size; i++) {
210 switch (work->descr->entries[i].syntax) {
212 case SNMP_SYNTAX_INTEGER:
213 if (var->len < p + 1) {
214 seterr(&snmp_client, "bad index: need integer");
217 if (var->subs[p] > INT32_MAX) {
219 "bad index: integer too large");
222 *(int32_t *)(void *)((u_char *)e +
223 work->descr->entries[i].offset) = var->subs[p++];
226 case SNMP_SYNTAX_OCTETSTRING:
227 if (var->len < p + 1) {
229 "bad index: need string length");
232 len = var->subs[p++];
233 if (var->len < p + len) {
235 "bad index: string too short");
238 if ((ptr = malloc(len + 1)) == NULL) {
240 "no memory for index string");
243 for (j = 0; j < len; j++) {
244 if (var->subs[p] > UCHAR_MAX) {
246 "bad index: char too large");
250 ptr[j] = var->subs[p++];
253 *(u_char **)(void *)((u_char *)e +
254 work->descr->entries[i].offset) = ptr;
255 *(size_t *)(void *)((u_char *)e +
256 work->descr->entries[i].offset + sizeof(u_char *))
260 case SNMP_SYNTAX_OID:
261 if (var->len < p + 1) {
263 "bad index: need oid length");
266 oid.len = var->subs[p++];
267 if (var->len < p + oid.len) {
269 "bad index: oid too short");
272 for (j = 0; j < oid.len; j++)
273 oid.subs[j] = var->subs[p++];
274 *(struct asn_oid *)(void *)((u_char *)e +
275 work->descr->entries[i].offset) = oid;
278 case SNMP_SYNTAX_IPADDRESS:
279 if (var->len < p + 4) {
281 "bad index: need ip-address");
284 for (j = 0; j < 4; j++) {
285 if (var->subs[p] > 0xff) {
287 "bad index: ipaddress too large");
291 work->descr->entries[i].offset)[j] =
296 case SNMP_SYNTAX_GAUGE:
297 if (var->len < p + 1) {
299 "bad index: need unsigned");
302 if (var->subs[p] > UINT32_MAX) {
304 "bad index: unsigned too large");
307 *(uint32_t *)(void *)((u_char *)e +
308 work->descr->entries[i].offset) = var->subs[p++];
311 case SNMP_SYNTAX_COUNTER:
312 case SNMP_SYNTAX_TIMETICKS:
313 case SNMP_SYNTAX_COUNTER64:
314 case SNMP_SYNTAX_NULL:
315 case SNMP_SYNTAX_NOSUCHOBJECT:
316 case SNMP_SYNTAX_NOSUCHINSTANCE:
317 case SNMP_SYNTAX_ENDOFMIBVIEW:
320 e->found |= (uint64_t)1 << i;
323 /* link into the correct place */
324 e1 = TAILQ_FIRST(work->table);
325 w1 = TAILQ_FIRST(&work->worklist);
327 if (asn_compare_oid(&w1->index, &w->index) > 0)
329 e1 = TAILQ_NEXT(e1, link);
330 w1 = TAILQ_NEXT(w1, link);
333 TAILQ_INSERT_TAIL(work->table, e, link);
334 TAILQ_INSERT_TAIL(&work->worklist, w, link);
336 TAILQ_INSERT_BEFORE(e1, e, link);
337 TAILQ_INSERT_BEFORE(w1, w, link);
344 * Error happend. Free all octet string index parts and the entry
347 for (i = 0; i < work->descr->index_size; i++) {
348 if (work->descr->entries[i].syntax == SNMP_SYNTAX_OCTETSTRING &&
349 (e->found & ((uint64_t)1 << i)))
350 free(*(void **)(void *)((u_char *)e +
351 work->descr->entries[i].offset));
362 table_value(const struct snmp_table *descr, struct entry *e,
363 const struct snmp_value *b)
368 for (i = descr->index_size;
369 descr->entries[i].syntax != SNMP_SYNTAX_NULL; i++)
370 if (descr->entries[i].subid ==
371 b->var.subs[descr->table.len + 1])
373 if (descr->entries[i].syntax == SNMP_SYNTAX_NULL)
377 if (b->syntax != descr->entries[i].syntax) {
378 seterr(&snmp_client, "bad syntax (%u instead of %u)", b->syntax,
379 descr->entries[i].syntax);
385 case SNMP_SYNTAX_INTEGER:
386 *(int32_t *)(void *)((u_char *)e + descr->entries[i].offset) =
390 case SNMP_SYNTAX_OCTETSTRING:
391 if ((ptr = malloc(b->v.octetstring.len + 1)) == NULL) {
392 seterr(&snmp_client, "no memory for string");
395 memcpy(ptr, b->v.octetstring.octets, b->v.octetstring.len);
396 ptr[b->v.octetstring.len] = '\0';
397 *(u_char **)(void *)((u_char *)e + descr->entries[i].offset) =
399 *(size_t *)(void *)((u_char *)e + descr->entries[i].offset +
400 sizeof(u_char *)) = b->v.octetstring.len;
403 case SNMP_SYNTAX_OID:
404 *(struct asn_oid *)(void *)((u_char *)e + descr->entries[i].offset) =
408 case SNMP_SYNTAX_IPADDRESS:
409 memcpy((u_char *)e + descr->entries[i].offset,
413 case SNMP_SYNTAX_COUNTER:
414 case SNMP_SYNTAX_GAUGE:
415 case SNMP_SYNTAX_TIMETICKS:
416 *(uint32_t *)(void *)((u_char *)e + descr->entries[i].offset) =
420 case SNMP_SYNTAX_COUNTER64:
421 *(uint64_t *)(void *)((u_char *)e + descr->entries[i].offset) =
425 case SNMP_SYNTAX_NULL:
426 case SNMP_SYNTAX_NOSUCHOBJECT:
427 case SNMP_SYNTAX_NOSUCHINSTANCE:
428 case SNMP_SYNTAX_ENDOFMIBVIEW:
431 e->found |= (uint64_t)1 << i;
437 * Initialize the first PDU to send
440 table_init_pdu(const struct snmp_table *descr, struct snmp_pdu *pdu)
442 if (snmp_client.version == SNMP_V1)
443 snmp_pdu_create(pdu, SNMP_PDU_GETNEXT);
445 snmp_pdu_create(pdu, SNMP_PDU_GETBULK);
446 pdu->error_index = 10;
448 if (descr->last_change.len != 0) {
449 pdu->bindings[pdu->nbindings].syntax = SNMP_SYNTAX_NULL;
450 pdu->bindings[pdu->nbindings].var = descr->last_change;
452 if (pdu->version != SNMP_V1)
455 pdu->bindings[pdu->nbindings].var = descr->table;
456 pdu->bindings[pdu->nbindings].syntax = SNMP_SYNTAX_NULL;
464 * -2 - Last change changed - again
468 table_check_response(struct tabwork *work, const struct snmp_pdu *resp)
470 const struct snmp_value *b;
473 if (resp->error_status != SNMP_ERR_NOERROR) {
474 if (snmp_client.version == SNMP_V1 &&
475 resp->error_status == SNMP_ERR_NOSUCHNAME &&
477 (work->descr->last_change.len == 0) ? 1 : 2)
481 seterr(&snmp_client, "error fetching table: status=%d index=%d",
482 resp->error_status, resp->error_index);
486 for (b = resp->bindings; b < resp->bindings + resp->nbindings; b++) {
487 if (work->descr->last_change.len != 0 && b == resp->bindings) {
488 if (!asn_is_suboid(&work->descr->last_change, &b->var) ||
489 b->var.len != work->descr->last_change.len + 1 ||
490 b->var.subs[work->descr->last_change.len] != 0) {
492 "last_change: bad response");
495 if (b->syntax != SNMP_SYNTAX_TIMETICKS) {
497 "last_change: bad syntax %u", b->syntax);
501 work->last_change = b->v.uint32;
504 } else if (work->last_change != b->v.uint32) {
505 if (++work->iter >= work->descr->max_iter) {
507 "max iteration count exceeded");
516 if (!asn_is_suboid(&work->descr->table, &b->var) ||
517 b->syntax == SNMP_SYNTAX_ENDOFMIBVIEW)
520 if ((e = table_find(work, &b->var)) == NULL)
522 if (table_value(work->descr, e, b))
529 * Check table consistency
532 table_check_cons(struct tabwork *work)
536 TAILQ_FOREACH(e, work->table, link)
537 if ((e->found & work->descr->req_mask) !=
538 work->descr->req_mask) {
539 if (work->descr->last_change.len == 0) {
540 if (++work->iter >= work->descr->max_iter) {
542 "max iteration count exceeded");
547 seterr(&snmp_client, "inconsistency detected %llx %llx",
548 e->found, work->descr->req_mask);
555 * Fetch a table. Returns 0 if ok, -1 on errors.
556 * This is the synchronous variant.
559 snmp_table_fetch(const struct snmp_table *descr, void *list)
561 struct snmp_pdu resp;
566 work.table = (struct table *)list;
568 TAILQ_INIT(work.table);
569 TAILQ_INIT(&work.worklist);
570 work.callback = NULL;
575 * We come to this label when the code detects that the table
576 * has changed while fetching it.
579 work.last_change = 0;
580 table_init_pdu(descr, &work.pdu);
583 if (snmp_dialog(&work.pdu, &resp)) {
584 table_free(&work, 1);
587 if ((ret = table_check_response(&work, &resp)) == 0) {
588 snmp_pdu_free(&resp);
592 snmp_pdu_free(&resp);
593 table_free(&work, 1);
597 snmp_pdu_free(&resp);
601 work.pdu.bindings[work.pdu.nbindings - 1].var =
602 resp.bindings[resp.nbindings - 1].var;
604 snmp_pdu_free(&resp);
607 if ((ret = table_check_cons(&work)) == -1) {
608 table_free(&work, 1);
612 table_free(&work, 1);
618 table_free(&work, 0);
626 table_cb(struct snmp_pdu *req __unused, struct snmp_pdu *resp, void *arg)
628 struct tabwork *work = arg;
633 seterr(&snmp_client, "no response to fetch table request");
635 work->callback(work->table, work->arg, -1);
640 if ((ret = table_check_response(work, resp)) == 0) {
644 if ((ret = table_check_cons(work)) == -1) {
647 work->callback(work->table, work->arg, -1);
656 work->last_change = 0;
657 table_init_pdu(work->descr, &work->pdu);
658 if (snmp_pdu_send(&work->pdu, table_cb, work) == -1) {
659 work->callback(work->table, work->arg, -1);
669 work->callback(work->table, work->arg, 0);
678 work->callback(work->table, work->arg, -1);
691 work->pdu.bindings[work->pdu.nbindings - 1].var =
692 resp->bindings[resp->nbindings - 1].var;
696 if (snmp_pdu_send(&work->pdu, table_cb, work) == -1) {
698 work->callback(work->table, work->arg, -1);
705 snmp_table_fetch_async(const struct snmp_table *descr, void *list,
706 snmp_table_cb_f func, void *arg)
708 struct tabwork *work;
710 if ((work = malloc(sizeof(*work))) == NULL) {
711 seterr(&snmp_client, "%s", strerror(errno));
716 work->table = (struct table *)list;
718 TAILQ_INIT(work->table);
719 TAILQ_INIT(&work->worklist);
721 work->callback = func;
725 * Start by sending the first PDU
728 work->last_change = 0;
729 table_init_pdu(descr, &work->pdu);
731 if (snmp_pdu_send(&work->pdu, table_cb, work) == -1)
737 * Append an index to an oid
740 snmp_oid_append(struct asn_oid *oid, const char *fmt, ...)
755 while (*fmt != '\0') {
758 /* just an integer more */
759 if (oid->len + 1 > ASN_MAXOIDLEN) {
760 warnx("%s: OID too long for integer", __func__);
764 oid->subs[oid->len++] = va_arg(va, asn_subid_t);
768 /* append an IP address */
769 if (oid->len + 4 > ASN_MAXOIDLEN) {
770 warnx("%s: OID too long for ip-addr", __func__);
774 ina = va_arg(va, struct in_addr);
775 ina.s_addr = ntohl(ina.s_addr);
776 oid->subs[oid->len++] = (ina.s_addr >> 24) & 0xff;
777 oid->subs[oid->len++] = (ina.s_addr >> 16) & 0xff;
778 oid->subs[oid->len++] = (ina.s_addr >> 8) & 0xff;
779 oid->subs[oid->len++] = (ina.s_addr >> 0) & 0xff;
783 /* append a null-terminated string,
784 * length is computed */
785 str = (const u_char *)va_arg(va, const char *);
786 len = strlen((const char *)str);
787 if (oid->len + len + 1 > ASN_MAXOIDLEN) {
788 warnx("%s: OID too long for string", __func__);
792 oid->subs[oid->len++] = len;
794 oid->subs[oid->len++] = *str++;
798 /* the integer value between ( and ) is stored
800 size = strtol(fmt, &nextptr, 10);
807 /* append `size` characters */
808 str = (const u_char *)va_arg(va, const char *);
809 if (oid->len + size > ASN_MAXOIDLEN) {
810 warnx("%s: OID too long for string", __func__);
815 oid->subs[oid->len++] = *str++;
819 /* get size and the octets from the arguments */
820 size = va_arg(va, size_t);
821 str = va_arg(va, const u_char *);
822 if (oid->len + size + 1 > ASN_MAXOIDLEN) {
823 warnx("%s: OID too long for string", __func__);
827 oid->subs[oid->len++] = size;
829 oid->subs[oid->len++] = *str++;
841 * Initialize a client structure
844 snmp_client_init(struct snmp_client *c)
846 memset(c, 0, sizeof(*c));
848 c->version = SNMP_V2c;
849 c->trans = SNMP_TRANS_UDP;
853 strcpy(c->read_community, "public");
854 strcpy(c->write_community, "private");
856 c->security_model = SNMP_SECMODEL_USM;
857 strcpy(c->cname, "");
859 c->timeout.tv_sec = 3;
860 c->timeout.tv_usec = 0;
863 c->txbuflen = c->rxbuflen = 10000;
867 c->max_reqid = INT32_MAX;
871 c->engine.max_msg_size = 1500; /* XXX */
876 * Open UDP client socket
879 open_client_udp(const char *host, const char *port)
883 struct addrinfo hints, *res0, *res;
885 /* copy host- and portname */
886 if (snmp_client.chost == NULL) {
887 if ((snmp_client.chost = malloc(1 + sizeof(DEFAULT_HOST)))
889 seterr(&snmp_client, "%s", strerror(errno));
892 strcpy(snmp_client.chost, DEFAULT_HOST);
895 if ((ptr = malloc(1 + strlen(host))) == NULL) {
896 seterr(&snmp_client, "%s", strerror(errno));
899 free(snmp_client.chost);
900 snmp_client.chost = ptr;
901 strcpy(snmp_client.chost, host);
903 if (snmp_client.cport == NULL) {
904 if ((snmp_client.cport = malloc(1 + sizeof(DEFAULT_PORT)))
906 seterr(&snmp_client, "%s", strerror(errno));
909 strcpy(snmp_client.cport, DEFAULT_PORT);
912 if ((ptr = malloc(1 + strlen(port))) == NULL) {
913 seterr(&snmp_client, "%s", strerror(errno));
916 free(snmp_client.cport);
917 snmp_client.cport = ptr;
918 strcpy(snmp_client.cport, port);
921 /* open connection */
922 memset(&hints, 0, sizeof(hints));
923 hints.ai_flags = AI_CANONNAME;
924 hints.ai_family = AF_INET;
925 hints.ai_socktype = SOCK_DGRAM;
926 hints.ai_protocol = 0;
927 error = getaddrinfo(snmp_client.chost, snmp_client.cport, &hints, &res0);
929 seterr(&snmp_client, "%s: %s", snmp_client.chost,
930 gai_strerror(error));
935 if ((snmp_client.fd = socket(res->ai_family, res->ai_socktype,
936 res->ai_protocol)) == -1) {
937 if ((res = res->ai_next) == NULL) {
938 seterr(&snmp_client, "%s", strerror(errno));
942 } else if (connect(snmp_client.fd, res->ai_addr,
943 res->ai_addrlen) == -1) {
944 if ((res = res->ai_next) == NULL) {
945 seterr(&snmp_client, "%s", strerror(errno));
959 (void)remove(snmp_client.local_path);
966 open_client_local(const char *path)
968 struct sockaddr_un sa;
972 if (snmp_client.chost == NULL) {
973 if ((snmp_client.chost = malloc(1 + sizeof(DEFAULT_LOCAL)))
975 seterr(&snmp_client, "%s", strerror(errno));
978 strcpy(snmp_client.chost, DEFAULT_LOCAL);
981 if ((ptr = malloc(1 + strlen(path))) == NULL) {
982 seterr(&snmp_client, "%s", strerror(errno));
985 free(snmp_client.chost);
986 snmp_client.chost = ptr;
987 strcpy(snmp_client.chost, path);
990 if (snmp_client.trans == SNMP_TRANS_LOC_DGRAM)
995 if ((snmp_client.fd = socket(PF_LOCAL, stype, 0)) == -1) {
996 seterr(&snmp_client, "%s", strerror(errno));
1000 snprintf(snmp_client.local_path, sizeof(snmp_client.local_path),
1001 "%s", SNMP_LOCAL_PATH);
1003 if (mktemp(snmp_client.local_path) == NULL) {
1004 seterr(&snmp_client, "%s", strerror(errno));
1005 (void)close(snmp_client.fd);
1006 snmp_client.fd = -1;
1010 sa.sun_family = AF_LOCAL;
1011 sa.sun_len = sizeof(sa);
1012 strcpy(sa.sun_path, snmp_client.local_path);
1014 if (bind(snmp_client.fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
1015 seterr(&snmp_client, "%s", strerror(errno));
1016 (void)close(snmp_client.fd);
1017 snmp_client.fd = -1;
1018 (void)remove(snmp_client.local_path);
1021 atexit(remove_local);
1023 sa.sun_family = AF_LOCAL;
1024 sa.sun_len = offsetof(struct sockaddr_un, sun_path) +
1025 strlen(snmp_client.chost);
1026 strncpy(sa.sun_path, snmp_client.chost, sizeof(sa.sun_path) - 1);
1027 sa.sun_path[sizeof(sa.sun_path) - 1] = '\0';
1029 if (connect(snmp_client.fd, (struct sockaddr *)&sa, sa.sun_len) == -1) {
1030 seterr(&snmp_client, "%s", strerror(errno));
1031 (void)close(snmp_client.fd);
1032 snmp_client.fd = -1;
1033 (void)remove(snmp_client.local_path);
1043 snmp_open(const char *host, const char *port, const char *readcomm,
1044 const char *writecomm)
1046 struct timeval tout;
1049 if (snmp_client.fd != -1) {
1051 seterr(&snmp_client, "%s", strerror(errno));
1055 /* copy community strings */
1056 if (readcomm != NULL)
1057 strlcpy(snmp_client.read_community, readcomm,
1058 sizeof(snmp_client.read_community));
1059 if (writecomm != NULL)
1060 strlcpy(snmp_client.write_community, writecomm,
1061 sizeof(snmp_client.write_community));
1063 switch (snmp_client.trans) {
1065 case SNMP_TRANS_UDP:
1066 if (open_client_udp(host, port))
1070 case SNMP_TRANS_LOC_DGRAM:
1071 case SNMP_TRANS_LOC_STREAM:
1072 if (open_client_local(host))
1077 seterr(&snmp_client, "bad transport mapping");
1082 if (setsockopt(snmp_client.fd, SOL_SOCKET, SO_SNDTIMEO,
1083 &tout, sizeof(struct timeval)) == -1) {
1084 seterr(&snmp_client, "%s", strerror(errno));
1085 (void)close(snmp_client.fd);
1086 snmp_client.fd = -1;
1087 if (snmp_client.local_path[0] != '\0')
1088 (void)remove(snmp_client.local_path);
1092 /* initialize list */
1093 LIST_INIT(&sent_pdus);
1102 * closes connection to snmp server
1103 * - function cannot fail
1104 * - clears connection
1105 * - clears list of sent pdus
1115 struct sent_pdu *p1;
1117 if (snmp_client.fd != -1) {
1118 (void)close(snmp_client.fd);
1119 snmp_client.fd = -1;
1120 if (snmp_client.local_path[0] != '\0')
1121 (void)remove(snmp_client.local_path);
1123 while(!LIST_EMPTY(&sent_pdus)){
1124 p1 = LIST_FIRST(&sent_pdus);
1125 if (p1->timeout_id != NULL)
1126 snmp_client.timeout_stop(p1->timeout_id);
1127 LIST_REMOVE(p1, entries);
1130 free(snmp_client.chost);
1131 free(snmp_client.cport);
1135 * initialize a snmp_pdu structure
1138 snmp_pdu_create(struct snmp_pdu *pdu, u_int op)
1140 memset(pdu, 0, sizeof(struct snmp_pdu));
1142 if (op == SNMP_PDU_SET)
1143 strlcpy(pdu->community, snmp_client.write_community,
1144 sizeof(pdu->community));
1146 strlcpy(pdu->community, snmp_client.read_community,
1147 sizeof(pdu->community));
1150 pdu->version = snmp_client.version;
1151 pdu->error_status = 0;
1152 pdu->error_index = 0;
1155 if (snmp_client.version != SNMP_V3)
1158 pdu->identifier = ++snmp_client.identifier;
1159 pdu->engine.max_msg_size = snmp_client.engine.max_msg_size;
1161 pdu->security_model = snmp_client.security_model;
1163 if (snmp_client.security_model == SNMP_SECMODEL_USM) {
1164 memcpy(&pdu->engine, &snmp_client.engine, sizeof(pdu->engine));
1165 memcpy(&pdu->user, &snmp_client.user, sizeof(pdu->user));
1166 snmp_pdu_init_secparams(pdu);
1168 seterr(&snmp_client, "unknown security model");
1170 if (snmp_client.clen > 0) {
1171 memcpy(pdu->context_engine, snmp_client.cengine,
1173 pdu->context_engine_len = snmp_client.clen;
1175 memcpy(pdu->context_engine, snmp_client.engine.engine_id,
1176 snmp_client.engine.engine_len);
1177 pdu->context_engine_len = snmp_client.engine.engine_len;
1180 strlcpy(pdu->context_name, snmp_client.cname,
1181 sizeof(pdu->context_name));
1184 /* add pairs of (struct asn_oid, enum snmp_syntax) to an existing pdu */
1185 /* added 10/04/02 by kek: check for MAX_BINDINGS */
1187 snmp_add_binding(struct snmp_v1_pdu *pdu, ...)
1190 const struct asn_oid *oid;
1195 ret = pdu->nbindings;
1196 while ((oid = va_arg(ap, const struct asn_oid *)) != NULL) {
1197 if (pdu->nbindings >= SNMP_MAX_BINDINGS){
1201 pdu->bindings[pdu->nbindings].var = *oid;
1202 pdu->bindings[pdu->nbindings].syntax =
1203 va_arg(ap, enum snmp_syntax);
1212 snmp_next_reqid(struct snmp_client * c)
1217 if (c->next_reqid >= c->max_reqid)
1218 c->next_reqid = c->min_reqid;
1225 * Send request and return request id.
1228 snmp_send_packet(struct snmp_pdu * pdu)
1234 if ((buf = malloc(snmp_client.txbuflen)) == NULL) {
1235 seterr(&snmp_client, "%s", strerror(errno));
1239 pdu->request_id = snmp_next_reqid(&snmp_client);
1242 b.asn_len = snmp_client.txbuflen;
1243 if (snmp_pdu_encode(pdu, &b)) {
1244 seterr(&snmp_client, "%s", strerror(errno));
1249 if (snmp_client.dump_pdus)
1252 if ((ret = send(snmp_client.fd, buf, b.asn_ptr - buf, 0)) == -1) {
1253 seterr(&snmp_client, "%s", strerror(errno));
1259 return pdu->request_id;
1263 * to be called when a snmp request timed out
1266 snmp_timeout(void * listentry_ptr)
1268 struct sent_pdu *listentry = listentry_ptr;
1271 warnx("snmp request %i timed out, attempt (%i/%i)",
1272 listentry->reqid, listentry->retrycount, snmp_client.retries);
1275 listentry->retrycount++;
1276 if (listentry->retrycount > snmp_client.retries) {
1277 /* there is no answer at all */
1278 LIST_REMOVE(listentry, entries);
1279 listentry->callback(listentry->pdu, NULL, listentry->arg);
1283 /* new request with new request ID */
1284 listentry->reqid = snmp_send_packet(listentry->pdu);
1285 listentry->timeout_id =
1286 snmp_client.timeout_start(&snmp_client.timeout,
1287 snmp_timeout, listentry);
1292 snmp_pdu_send(struct snmp_pdu *pdu, snmp_send_cb_f func, void *arg)
1294 struct sent_pdu *listentry;
1297 if ((listentry = malloc(sizeof(struct sent_pdu))) == NULL) {
1298 seterr(&snmp_client, "%s", strerror(errno));
1302 /* here we really send */
1303 if ((id = snmp_send_packet(pdu)) == -1) {
1308 /* add entry to list of sent PDUs */
1309 listentry->pdu = pdu;
1310 if (gettimeofday(&listentry->time, NULL) == -1)
1311 warn("gettimeofday() failed");
1313 listentry->reqid = pdu->request_id;
1314 listentry->callback = func;
1315 listentry->arg = arg;
1316 listentry->retrycount=1;
1317 listentry->timeout_id =
1318 snmp_client.timeout_start(&snmp_client.timeout, snmp_timeout,
1321 LIST_INSERT_HEAD(&sent_pdus, listentry, entries);
1327 * Receive an SNMP packet.
1329 * tv controls how we wait for a packet: if tv is a NULL pointer,
1330 * the receive blocks forever, if tv points to a structure with all
1331 * members 0 the socket is polled, in all other cases tv specifies the
1332 * maximum time to wait for a packet.
1337 * +1 if packet received
1340 snmp_receive_packet(struct snmp_pdu *pdu, struct timeval *tv)
1342 int dopoll, setpoll;
1347 struct asn_buf abuf;
1355 if ((buf = malloc(snmp_client.rxbuflen)) == NULL) {
1356 seterr(&snmp_client, "%s", strerror(errno));
1359 dopoll = setpoll = 0;
1362 /* poll or timeout */
1363 if (tv->tv_sec != 0 || tv->tv_usec != 0) {
1364 /* wait with timeout */
1365 if (setsockopt(snmp_client.fd, SOL_SOCKET, SO_RCVTIMEO,
1366 tv, sizeof(*tv)) == -1) {
1367 seterr(&snmp_client, "setsockopt: %s",
1372 optlen = sizeof(*tv);
1373 if (getsockopt(snmp_client.fd, SOL_SOCKET, SO_RCVTIMEO,
1374 tv, &optlen) == -1) {
1375 seterr(&snmp_client, "getsockopt: %s",
1380 /* at this point tv_sec and tv_usec may appear
1381 * as 0. This happens for timeouts lesser than
1382 * the clock granularity. The kernel rounds these to
1383 * 0 and this would result in a blocking receive.
1384 * Instead of an else we check tv_sec and tv_usec
1385 * again below and if this rounding happens,
1386 * switch to a polling receive. */
1388 if (tv->tv_sec == 0 && tv->tv_usec == 0) {
1391 if ((flags = fcntl(snmp_client.fd, F_GETFL, 0)) == -1) {
1392 seterr(&snmp_client, "fcntl: %s",
1397 if (!(flags & O_NONBLOCK)) {
1399 flags |= O_NONBLOCK;
1400 if (fcntl(snmp_client.fd, F_SETFL, flags) == -1) {
1401 seterr(&snmp_client, "fcntl: %s",
1409 ret = recv(snmp_client.fd, buf, snmp_client.rxbuflen, 0);
1410 saved_errno = errno;
1414 flags &= ~O_NONBLOCK;
1415 (void)fcntl(snmp_client.fd, F_SETFL, flags);
1420 (void)setsockopt(snmp_client.fd, SOL_SOCKET, SO_RCVTIMEO,
1426 if (errno == EAGAIN || errno == EWOULDBLOCK)
1428 seterr(&snmp_client, "recv: %s", strerror(saved_errno));
1432 /* this happens when we have a streaming socket and the
1433 * remote side has closed it */
1435 seterr(&snmp_client, "recv: socket closed by peer");
1443 memset(pdu, 0, sizeof(*pdu));
1444 if (snmp_client.security_model == SNMP_SECMODEL_USM) {
1445 memcpy(&pdu->engine, &snmp_client.engine, sizeof(pdu->engine));
1446 memcpy(&pdu->user, &snmp_client.user, sizeof(pdu->user));
1447 snmp_pdu_init_secparams(pdu);
1450 if (SNMP_CODE_OK != (ret = snmp_pdu_decode(&abuf, pdu, &ip))) {
1451 seterr(&snmp_client, "snmp_decode_pdu: failed %d", ret);
1457 if (snmp_client.dump_pdus)
1460 snmp_client.engine.engine_time = pdu->engine.engine_time;
1461 snmp_client.engine.engine_boots = pdu->engine.engine_boots;
1467 snmp_deliver_packet(struct snmp_pdu * resp)
1469 struct sent_pdu *listentry;
1471 if (resp->type != SNMP_PDU_RESPONSE) {
1472 warn("ignoring snmp pdu %u", resp->type);
1476 LIST_FOREACH(listentry, &sent_pdus, entries)
1477 if (listentry->reqid == resp->request_id)
1479 if (listentry == NULL)
1482 LIST_REMOVE(listentry, entries);
1483 listentry->callback(listentry->pdu, resp, listentry->arg);
1485 snmp_client.timeout_stop(listentry->timeout_id);
1492 snmp_receive(int blocking)
1497 struct snmp_pdu * resp;
1499 memset(&tv, 0, sizeof(tv));
1501 resp = malloc(sizeof(struct snmp_pdu));
1503 seterr(&snmp_client, "no memory for returning PDU");
1507 if ((ret = snmp_receive_packet(resp, blocking ? NULL : &tv)) <= 0) {
1511 ret = snmp_deliver_packet(resp);
1512 snmp_pdu_free(resp);
1519 * Check a GETNEXT response. Here we have three possible outcomes: -1 an
1520 * unexpected error happened. +1 response is ok and is within the table 0
1521 * response is ok, but is behind the table or error is NOSUCHNAME. The req
1522 * should point to a template PDU which contains the base OIDs and the
1523 * syntaxes. This is really only useful to sweep non-sparse tables.
1526 ok_getnext(const struct snmp_pdu * req, const struct snmp_pdu * resp)
1530 if (resp->version != req->version) {
1531 warnx("SNMP GETNEXT: response has wrong version");
1535 if (resp->error_status == SNMP_ERR_NOSUCHNAME)
1538 if (resp->error_status != SNMP_ERR_NOERROR) {
1539 warnx("SNMP GETNEXT: error %d", resp->error_status);
1542 if (resp->nbindings != req->nbindings) {
1543 warnx("SNMP GETNEXT: bad number of bindings in response");
1546 for (i = 0; i < req->nbindings; i++) {
1547 if (!asn_is_suboid(&req->bindings[i].var,
1548 &resp->bindings[i].var)) {
1550 warnx("SNMP GETNEXT: inconsistent table "
1554 if (resp->version != SNMP_V1 &&
1555 resp->bindings[i].syntax == SNMP_SYNTAX_ENDOFMIBVIEW)
1558 if (resp->bindings[i].syntax != req->bindings[i].syntax) {
1559 warnx("SNMP GETNEXT: bad syntax in response");
1567 * Check a GET response. Here we have three possible outcomes: -1 an
1568 * unexpected error happened. +1 response is ok. 0 NOSUCHNAME The req should
1569 * point to a template PDU which contains the OIDs and the syntaxes. This
1570 * is only useful for SNMPv1 or single object GETS.
1573 ok_get(const struct snmp_pdu * req, const struct snmp_pdu * resp)
1577 if (resp->version != req->version) {
1578 warnx("SNMP GET: response has wrong version");
1582 if (resp->error_status == SNMP_ERR_NOSUCHNAME)
1585 if (resp->error_status != SNMP_ERR_NOERROR) {
1586 warnx("SNMP GET: error %d", resp->error_status);
1590 if (resp->nbindings != req->nbindings) {
1591 warnx("SNMP GET: bad number of bindings in response");
1594 for (i = 0; i < req->nbindings; i++) {
1595 if (asn_compare_oid(&req->bindings[i].var,
1596 &resp->bindings[i].var) != 0) {
1597 warnx("SNMP GET: bad OID in response");
1600 if (snmp_client.version != SNMP_V1 &&
1601 (resp->bindings[i].syntax == SNMP_SYNTAX_NOSUCHOBJECT ||
1602 resp->bindings[i].syntax == SNMP_SYNTAX_NOSUCHINSTANCE))
1604 if (resp->bindings[i].syntax != req->bindings[i].syntax) {
1605 warnx("SNMP GET: bad syntax in response");
1613 * Check the response to a SET PDU. We check: - the error status must be 0 -
1614 * the number of bindings must be equal in response and request - the
1615 * syntaxes must be the same in response and request - the OIDs must be the
1616 * same in response and request
1619 ok_set(const struct snmp_pdu * req, const struct snmp_pdu * resp)
1623 if (resp->version != req->version) {
1624 warnx("SNMP SET: response has wrong version");
1628 if (resp->error_status == SNMP_ERR_NOSUCHNAME) {
1629 warnx("SNMP SET: error %d", resp->error_status);
1632 if (resp->error_status != SNMP_ERR_NOERROR) {
1633 warnx("SNMP SET: error %d", resp->error_status);
1637 if (resp->nbindings != req->nbindings) {
1638 warnx("SNMP SET: bad number of bindings in response");
1641 for (i = 0; i < req->nbindings; i++) {
1642 if (asn_compare_oid(&req->bindings[i].var,
1643 &resp->bindings[i].var) != 0) {
1644 warnx("SNMP SET: wrong OID in response to SET");
1647 if (resp->bindings[i].syntax != req->bindings[i].syntax) {
1648 warnx("SNMP SET: bad syntax in response");
1656 * Simple checks for response PDUs against request PDUs. Return values: 1=ok,
1657 * 0=nosuchname or similar, -1=failure, -2=no response at all
1660 snmp_pdu_check(const struct snmp_pdu *req,
1661 const struct snmp_pdu *resp)
1666 switch (req->type) {
1669 return (ok_get(req, resp));
1672 return (ok_set(req, resp));
1674 case SNMP_PDU_GETNEXT:
1675 return (ok_getnext(req, resp));
1678 errx(1, "%s: bad pdu type %i", __func__, req->type);
1682 snmp_dialog(struct snmp_v1_pdu *req, struct snmp_v1_pdu *resp)
1687 struct timeval tv = snmp_client.timeout;
1689 struct snmp_pdu pdu;
1692 * Make a copy of the request and replace the syntaxes by NULL
1693 * if this is a GET,GETNEXT or GETBULK.
1696 if (pdu.type == SNMP_PDU_GET || pdu.type == SNMP_PDU_GETNEXT ||
1697 pdu.type == SNMP_PDU_GETBULK) {
1698 for (i = 0; i < pdu.nbindings; i++)
1699 pdu.bindings[i].syntax = SNMP_SYNTAX_NULL;
1702 for (i = 0; i <= snmp_client.retries; i++) {
1703 (void)gettimeofday(&end, NULL);
1704 timeradd(&end, &snmp_client.timeout, &end);
1705 if ((reqid = snmp_send_packet(&pdu)) == -1)
1708 (void)gettimeofday(&tv, NULL);
1709 if (timercmp(&end, &tv, <=))
1711 timersub(&end, &tv, &tv);
1712 if ((ret = snmp_receive_packet(resp, &tv)) == 0)
1717 if (reqid == resp->request_id)
1720 (void)snmp_deliver_packet(resp);
1722 if (ret < 0 && errno == EPIPE)
1728 seterr(&snmp_client, "retry count exceeded");
1733 snmp_discover_engine(char *passwd)
1735 char cname[SNMP_ADM_STR32_SIZ];
1736 enum snmp_authentication cap;
1737 enum snmp_privacy cpp;
1738 struct snmp_pdu req, resp;
1740 if (snmp_client.version != SNMP_V3)
1741 seterr(&snmp_client, "wrong version");
1743 strlcpy(cname, snmp_client.user.sec_name, sizeof(cname));
1744 cap = snmp_client.user.auth_proto;
1745 cpp = snmp_client.user.priv_proto;
1747 snmp_client.engine.engine_len = 0;
1748 snmp_client.engine.engine_boots = 0;
1749 snmp_client.engine.engine_time = 0;
1750 snmp_client.user.auth_proto = SNMP_AUTH_NOAUTH;
1751 snmp_client.user.priv_proto = SNMP_PRIV_NOPRIV;
1752 memset(snmp_client.user.sec_name, 0, sizeof(snmp_client.user.sec_name));
1754 snmp_pdu_create(&req, SNMP_PDU_GET);
1756 if (snmp_dialog(&req, &resp) == -1)
1759 if (resp.version != req.version) {
1760 seterr(&snmp_client, "wrong version");
1764 if (resp.error_status != SNMP_ERR_NOERROR) {
1765 seterr(&snmp_client, "Error %d in responce", resp.error_status);
1769 snmp_client.engine.engine_len = resp.engine.engine_len;
1770 snmp_client.engine.max_msg_size = resp.engine.max_msg_size;
1771 memcpy(snmp_client.engine.engine_id, resp.engine.engine_id,
1772 resp.engine.engine_len);
1774 strlcpy(snmp_client.user.sec_name, cname,
1775 sizeof(snmp_client.user.sec_name));
1776 snmp_client.user.auth_proto = cap;
1777 snmp_client.user.priv_proto = cpp;
1779 if (snmp_client.user.auth_proto == SNMP_AUTH_NOAUTH)
1782 if (passwd == NULL ||
1783 snmp_passwd_to_keys(&snmp_client.user, passwd) != SNMP_CODE_OK ||
1784 snmp_get_local_keys(&snmp_client.user, snmp_client.engine.engine_id,
1785 snmp_client.engine.engine_len) != SNMP_CODE_OK)
1788 if (resp.engine.engine_boots != 0)
1789 snmp_client.engine.engine_boots = resp.engine.engine_boots;
1791 if (resp.engine.engine_time != 0) {
1792 snmp_client.engine.engine_time = resp.engine.engine_time;
1796 snmp_pdu_create(&req, SNMP_PDU_GET);
1797 req.engine.engine_boots = 0;
1798 req.engine.engine_time = 0;
1800 if (snmp_dialog(&req, &resp) == -1)
1803 if (resp.version != req.version) {
1804 seterr(&snmp_client, "wrong version");
1808 if (resp.error_status != SNMP_ERR_NOERROR) {
1809 seterr(&snmp_client, "Error %d in responce", resp.error_status);
1813 snmp_client.engine.engine_boots = resp.engine.engine_boots;
1814 snmp_client.engine.engine_time = resp.engine.engine_time;
1820 snmp_client_set_host(struct snmp_client *cl, const char *h)
1825 if (cl->chost != NULL)
1829 if ((np = malloc(strlen(h) + 1)) == NULL)
1832 if (cl->chost != NULL)
1840 snmp_client_set_port(struct snmp_client *cl, const char *p)
1845 if (cl->cport != NULL)
1849 if ((np = malloc(strlen(p) + 1)) == NULL)
1852 if (cl->cport != NULL)
1860 * parse a server specification
1862 * [trans::][community@][server][:port]
1865 snmp_parse_server(struct snmp_client *sc, const char *str)
1867 const char *p, *s = str;
1869 /* look for a double colon */
1870 for (p = s; *p != '\0'; p++) {
1871 if (*p == '\\' && p[1] != '\0') {
1875 if (*p == ':' && p[1] == ':')
1880 if (p - s == 3 && strncmp(s, "udp", 3) == 0)
1881 sc->trans = SNMP_TRANS_UDP;
1882 else if (p - s == 6 && strncmp(s, "stream", 6) == 0)
1883 sc->trans = SNMP_TRANS_LOC_STREAM;
1884 else if (p - s == 5 && strncmp(s, "dgram", 5) == 0)
1885 sc->trans = SNMP_TRANS_LOC_DGRAM;
1887 seterr(sc, "unknown SNMP transport '%.*s'",
1896 for (p = s; *p != '\0'; p++) {
1897 if (*p == '\\' && p[1] != '\0') {
1906 if (p - s > SNMP_COMMUNITY_MAXLEN) {
1907 seterr(sc, "community string too long");
1910 strncpy(sc->read_community, s, p - s);
1911 sc->read_community[p - s] = '\0';
1912 strncpy(sc->write_community, s, p - s);
1913 sc->write_community[p - s] = '\0';
1917 /* look for a colon */
1918 for (p = s; *p != '\0'; p++) {
1919 if (*p == '\\' && p[1] != '\0') {
1931 if ((sc->chost = malloc(p - s + 1)) == NULL) {
1932 seterr(sc, "%s", strerror(errno));
1935 strncpy(sc->chost, s, p - s);
1936 sc->chost[p - s] = '\0';
1940 if ((sc->cport = malloc(strlen(p + 1) + 1)) == NULL) {
1941 seterr(sc, "%s", strerror(errno));
1944 strcpy(sc->cport, p + 1);
1949 if ((sc->chost = malloc(strlen(s) + 1)) == NULL) {
1950 seterr(sc, "%s", strerror(errno));
1953 strcpy(sc->chost, s);