xref: /freebsd/contrib/bsnmp/lib/snmpagent.c (revision 546401ce5417bd3d20056f3f6ba42a5c7cdd4e95)
1 /*
2  * Copyright (c) 2001-2003
3  *	Fraunhofer Institute for Open Communication Systems (FhG Fokus).
4  *	All rights reserved.
5  *
6  * Author: Harti Brandt <harti@freebsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $Begemot: bsnmp/lib/snmpagent.c,v 1.20 2005/10/04 11:21:33 brandt_h Exp $
30  *
31  * SNMP Agent functions
32  */
33 #include <sys/types.h>
34 #include <sys/queue.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <stddef.h>
38 #include <stdarg.h>
39 #ifdef HAVE_STDINT_H
40 #include <stdint.h>
41 #elif defined(HAVE_INTTYPES_H)
42 #include <inttypes.h>
43 #endif
44 #include <string.h>
45 
46 #include "asn1.h"
47 #include "snmp.h"
48 #include "snmppriv.h"
49 #include "snmpagent.h"
50 
51 static void snmp_debug_func(const char *fmt, ...);
52 
53 void (*snmp_debug)(const char *fmt, ...) = snmp_debug_func;
54 
55 struct snmp_node *tree;
56 u_int  tree_size;
57 
58 /*
59  * Structure to hold dependencies during SET processing
60  * The last two members of this structure must be the
61  * dependency visible by the user and the user data.
62  */
63 struct depend {
64 	TAILQ_ENTRY(depend) link;
65 	size_t	len;		/* size of data part */
66 	snmp_depop_t	func;
67 	struct snmp_dependency dep;
68 #if defined(__GNUC__) && __GNUC__ < 3
69 	u_char	data[0];
70 #else
71 	u_char	data[];
72 #endif
73 };
74 TAILQ_HEAD(depend_list, depend);
75 
76 /*
77  * Set context
78  */
79 struct context {
80 	struct snmp_context	ctx;
81 	struct depend_list	dlist;
82 	const struct snmp_node	*node[SNMP_MAX_BINDINGS];
83 	struct snmp_scratch	scratch[SNMP_MAX_BINDINGS];
84 	struct depend		*depend;
85 };
86 
87 #define	TR(W)	(snmp_trace & SNMP_TRACE_##W)
88 u_int snmp_trace = 0;
89 
90 static char oidbuf[ASN_OIDSTRLEN];
91 
92 /*
93  * Allocate a context
94  */
95 struct snmp_context *
96 snmp_init_context(void)
97 {
98 	struct context *context;
99 
100 	if ((context = malloc(sizeof(*context))) == NULL)
101 		return (NULL);
102 
103 	memset(context, 0, sizeof(*context));
104 	TAILQ_INIT(&context->dlist);
105 
106 	return (&context->ctx);
107 }
108 
109 /*
110  * Find a variable for SET/GET and the first GETBULK pass.
111  * Return the node pointer. If the search fails, set the errp to
112  * the correct SNMPv2 GET exception code.
113  */
114 static struct snmp_node *
115 find_node(const struct snmp_value *value, enum snmp_syntax *errp)
116 {
117 	struct snmp_node *tp;
118 
119 	if (TR(FIND))
120 		snmp_debug("find: searching %s",
121 		    asn_oid2str_r(&value->var, oidbuf));
122 
123 	/*
124 	 * If we have an exact match (the entry in the table is a
125 	 * sub-oid from the variable) we have found what we are for.
126 	 * If the table oid is higher than the variable, there is no match.
127 	 */
128 	for (tp = tree; tp < tree + tree_size; tp++) {
129 		if (asn_is_suboid(&tp->oid, &value->var))
130 			goto found;
131 		if (asn_compare_oid(&tp->oid, &value->var) >= 0)
132 			break;
133 	}
134 
135 	if (TR(FIND))
136 		snmp_debug("find: no match");
137 	*errp = SNMP_SYNTAX_NOSUCHOBJECT;
138 	return (NULL);
139 
140   found:
141 	/* leafs must have a 0 instance identifier */
142 	if (tp->type == SNMP_NODE_LEAF &&
143 	    (value->var.len != tp->oid.len + 1 ||
144 	     value->var.subs[tp->oid.len] != 0)) {
145 		if (TR(FIND))
146 			snmp_debug("find: bad leaf index");
147 		*errp = SNMP_SYNTAX_NOSUCHINSTANCE;
148 		return (NULL);
149 	}
150 	if (TR(FIND))
151 		snmp_debug("find: found %s",
152 		    asn_oid2str_r(&value->var, oidbuf));
153 	return (tp);
154 }
155 
156 static struct snmp_node *
157 find_subnode(const struct snmp_value *value)
158 {
159 	struct snmp_node *tp;
160 
161 	for (tp = tree; tp < tree + tree_size; tp++) {
162 		if (asn_is_suboid(&value->var, &tp->oid))
163 			return (tp);
164 	}
165 	return (NULL);
166 }
167 
168 static void
169 snmp_pdu_create_response(const struct snmp_pdu *pdu, struct snmp_pdu *resp)
170 {
171 	memset(resp, 0, sizeof(*resp));
172 	strcpy(resp->community, pdu->community);
173 	resp->version = pdu->version;
174 	resp->type = SNMP_PDU_RESPONSE;
175 	resp->request_id = pdu->request_id;
176 	resp->version = pdu->version;
177 
178 	if (resp->version != SNMP_V3)
179 		return;
180 
181 	memcpy(&resp->engine, &pdu->engine, sizeof(pdu->engine));
182 	memcpy(&resp->user, &pdu->user, sizeof(pdu->user));
183 	snmp_pdu_init_secparams(resp);
184 	resp->identifier = pdu->identifier;
185 	resp->security_model = pdu->security_model;
186 	resp->context_engine_len = pdu->context_engine_len;
187 	memcpy(resp->context_engine, pdu->context_engine,
188 	    resp->context_engine_len);
189 	strlcpy(resp->context_name, pdu->context_name,
190 	    sizeof(resp->context_name));
191 }
192 
193 /*
194  * Execute a GET operation. The tree is rooted at the global 'root'.
195  * Build the response PDU on the fly. If the return code is SNMP_RET_ERR
196  * the pdu error status and index will be set.
197  */
198 enum snmp_ret
199 snmp_get(struct snmp_pdu *pdu, struct asn_buf *resp_b,
200     struct snmp_pdu *resp, void *data)
201 {
202 	int ret;
203 	u_int i;
204 	struct snmp_node *tp;
205 	enum snmp_syntax except;
206 	struct context context;
207 	enum asn_err err;
208 
209 	memset(&context, 0, sizeof(context));
210 	context.ctx.data = data;
211 
212 	snmp_pdu_create_response(pdu, resp);
213 
214 	if (snmp_pdu_encode_header(resp_b, resp) != SNMP_CODE_OK)
215 		/* cannot even encode header - very bad */
216 		return (SNMP_RET_IGN);
217 
218 	for (i = 0; i < pdu->nbindings; i++) {
219 		resp->bindings[i].var = pdu->bindings[i].var;
220 		if ((tp = find_node(&pdu->bindings[i], &except)) == NULL) {
221 			if (pdu->version == SNMP_V1) {
222 				if (TR(GET))
223 					snmp_debug("get: nosuchname");
224 				pdu->error_status = SNMP_ERR_NOSUCHNAME;
225 				pdu->error_index = i + 1;
226 				snmp_pdu_free(resp);
227 				return (SNMP_RET_ERR);
228 			}
229 			if (TR(GET))
230 				snmp_debug("get: exception %u", except);
231 			resp->bindings[i].syntax = except;
232 
233 		} else {
234 			/* call the action to fetch the value. */
235 			resp->bindings[i].syntax = tp->syntax;
236 			ret = (*tp->op)(&context.ctx, &resp->bindings[i],
237 			    tp->oid.len, tp->index, SNMP_OP_GET);
238 			if (TR(GET))
239 				snmp_debug("get: action returns %d", ret);
240 
241 			if (ret == SNMP_ERR_NOSUCHNAME) {
242 				if (pdu->version == SNMP_V1) {
243 					pdu->error_status = SNMP_ERR_NOSUCHNAME;
244 					pdu->error_index = i + 1;
245 					snmp_pdu_free(resp);
246 					return (SNMP_RET_ERR);
247 				}
248 				if (TR(GET))
249 					snmp_debug("get: exception noSuchInstance");
250 				resp->bindings[i].syntax = SNMP_SYNTAX_NOSUCHINSTANCE;
251 
252 			} else if (ret != SNMP_ERR_NOERROR) {
253 				pdu->error_status = SNMP_ERR_GENERR;
254 				pdu->error_index = i + 1;
255 				snmp_pdu_free(resp);
256 				return (SNMP_RET_ERR);
257 			}
258 		}
259 		resp->nbindings++;
260 
261 		err = snmp_binding_encode(resp_b, &resp->bindings[i]);
262 
263 		if (err == ASN_ERR_EOBUF) {
264 			pdu->error_status = SNMP_ERR_TOOBIG;
265 			pdu->error_index = 0;
266 			snmp_pdu_free(resp);
267 			return (SNMP_RET_ERR);
268 		}
269 		if (err != ASN_ERR_OK) {
270 			if (TR(GET))
271 				snmp_debug("get: binding encoding: %u", err);
272 			pdu->error_status = SNMP_ERR_GENERR;
273 			pdu->error_index = i + 1;
274 			snmp_pdu_free(resp);
275 			return (SNMP_RET_ERR);
276 		}
277 	}
278 
279 	if (snmp_fix_encoding(resp_b, resp) != SNMP_CODE_OK) {
280 		snmp_debug("get: failed to encode PDU");
281 		return (SNMP_RET_ERR);
282 	}
283 
284 	return (SNMP_RET_OK);
285 }
286 
287 static struct snmp_node *
288 next_node(const struct snmp_value *value, int *pnext)
289 {
290 	struct snmp_node *tp;
291 
292 	if (TR(FIND))
293 		snmp_debug("next: searching %s",
294 		    asn_oid2str_r(&value->var, oidbuf));
295 
296 	*pnext = 0;
297 	for (tp = tree; tp < tree + tree_size; tp++) {
298 		if (asn_is_suboid(&tp->oid, &value->var)) {
299 			/* the tree OID is a sub-oid of the requested OID. */
300 			if (tp->type == SNMP_NODE_LEAF) {
301 				if (tp->oid.len == value->var.len) {
302 					/* request for scalar type */
303 					if (TR(FIND))
304 						snmp_debug("next: found scalar %s",
305 						    asn_oid2str_r(&tp->oid, oidbuf));
306 					return (tp);
307 				}
308 				/* try next */
309 			} else {
310 				if (TR(FIND))
311 					snmp_debug("next: found column %s",
312 					    asn_oid2str_r(&tp->oid, oidbuf));
313 				return (tp);
314 			}
315 		} else if (asn_is_suboid(&value->var, &tp->oid) ||
316 		    asn_compare_oid(&tp->oid, &value->var) >= 0) {
317 			if (TR(FIND))
318 				snmp_debug("next: found %s",
319 				    asn_oid2str_r(&tp->oid, oidbuf));
320 			*pnext = 1;
321 			return (tp);
322 		}
323 	}
324 
325 	if (TR(FIND))
326 		snmp_debug("next: failed");
327 
328 	return (NULL);
329 }
330 
331 static enum snmp_ret
332 do_getnext(struct context *context, const struct snmp_value *inb,
333     struct snmp_value *outb, struct snmp_pdu *pdu)
334 {
335 	const struct snmp_node *tp;
336 	int ret, next;
337 
338 	if ((tp = next_node(inb, &next)) == NULL)
339 		goto eofMib;
340 
341 	/* retain old variable if we are doing a GETNEXT on an exact
342 	 * matched leaf only */
343 	if (tp->type == SNMP_NODE_LEAF || next)
344 		outb->var = tp->oid;
345 	else
346 		outb->var = inb->var;
347 
348 	for (;;) {
349 		outb->syntax = tp->syntax;
350 		if (tp->type == SNMP_NODE_LEAF) {
351 			/* make a GET operation */
352 			outb->var.subs[outb->var.len++] = 0;
353 			ret = (*tp->op)(&context->ctx, outb, tp->oid.len,
354 			    tp->index, SNMP_OP_GET);
355 		} else {
356 			/* make a GETNEXT */
357 			ret = (*tp->op)(&context->ctx, outb, tp->oid.len,
358 			     tp->index, SNMP_OP_GETNEXT);
359 		}
360 		if (ret != SNMP_ERR_NOSUCHNAME) {
361 			/* got something */
362 			if (ret != SNMP_ERR_NOERROR && TR(GETNEXT))
363 				snmp_debug("getnext: %s returns %u",
364 				    asn_oid2str(&outb->var), ret);
365 			break;
366 		}
367 
368 		/* object has no data - try next */
369 		if (++tp == tree + tree_size)
370 			break;
371 
372 		if (TR(GETNEXT))
373 			snmp_debug("getnext: no data - avancing to %s",
374 			    asn_oid2str(&tp->oid));
375 
376 		outb->var = tp->oid;
377 	}
378 
379 	if (ret == SNMP_ERR_NOSUCHNAME) {
380   eofMib:
381 		outb->var = inb->var;
382 		if (pdu->version == SNMP_V1) {
383 			pdu->error_status = SNMP_ERR_NOSUCHNAME;
384 			return (SNMP_RET_ERR);
385 		}
386 		outb->syntax = SNMP_SYNTAX_ENDOFMIBVIEW;
387 
388 	} else if (ret != SNMP_ERR_NOERROR) {
389 		pdu->error_status = SNMP_ERR_GENERR;
390 		return (SNMP_RET_ERR);
391 	}
392 	return (SNMP_RET_OK);
393 }
394 
395 
396 /*
397  * Execute a GETNEXT operation. The tree is rooted at the global 'root'.
398  * Build the response PDU on the fly. The return is:
399  */
400 enum snmp_ret
401 snmp_getnext(struct snmp_pdu *pdu, struct asn_buf *resp_b,
402     struct snmp_pdu *resp, void *data)
403 {
404 	struct context context;
405 	u_int i;
406 	enum asn_err err;
407 	enum snmp_ret result;
408 
409 	memset(&context, 0, sizeof(context));
410 	context.ctx.data = data;
411 
412 	snmp_pdu_create_response(pdu, resp);
413 
414 	if (snmp_pdu_encode_header(resp_b, resp))
415 		return (SNMP_RET_IGN);
416 
417 	for (i = 0; i < pdu->nbindings; i++) {
418 		result = do_getnext(&context, &pdu->bindings[i],
419 		    &resp->bindings[i], pdu);
420 
421 		if (result != SNMP_RET_OK) {
422 			pdu->error_index = i + 1;
423 			snmp_pdu_free(resp);
424 			return (result);
425 		}
426 
427 		resp->nbindings++;
428 
429 		err = snmp_binding_encode(resp_b, &resp->bindings[i]);
430 
431 		if (err == ASN_ERR_EOBUF) {
432 			pdu->error_status = SNMP_ERR_TOOBIG;
433 			pdu->error_index = 0;
434 			snmp_pdu_free(resp);
435 			return (SNMP_RET_ERR);
436 		}
437 		if (err != ASN_ERR_OK) {
438 			if (TR(GET))
439 				snmp_debug("getnext: binding encoding: %u", err);
440 			pdu->error_status = SNMP_ERR_GENERR;
441 			pdu->error_index = i + 1;
442 			snmp_pdu_free(resp);
443 			return (SNMP_RET_ERR);
444 		}
445 	}
446 
447 	if (snmp_fix_encoding(resp_b, resp) != SNMP_CODE_OK) {
448 		snmp_debug("getnext: failed to encode PDU");
449 		return (SNMP_RET_ERR);
450 	}
451 
452 	return (SNMP_RET_OK);
453 }
454 
455 enum snmp_ret
456 snmp_getbulk(struct snmp_pdu *pdu, struct asn_buf *resp_b,
457     struct snmp_pdu *resp, void *data)
458 {
459 	struct context context;
460 	u_int i;
461 	int cnt;
462 	u_int non_rep;
463 	int eomib;
464 	enum snmp_ret result;
465 	enum asn_err err;
466 
467 	memset(&context, 0, sizeof(context));
468 	context.ctx.data = data;
469 
470 	snmp_pdu_create_response(pdu, resp);
471 
472 	if (snmp_pdu_encode_header(resp_b, resp) != SNMP_CODE_OK)
473 		/* cannot even encode header - very bad */
474 		return (SNMP_RET_IGN);
475 
476 	if ((non_rep = pdu->error_status) > pdu->nbindings)
477 		non_rep = pdu->nbindings;
478 
479 	/* non-repeaters */
480 	for (i = 0; i < non_rep; i++) {
481 		result = do_getnext(&context, &pdu->bindings[i],
482 		    &resp->bindings[resp->nbindings], pdu);
483 
484 		if (result != SNMP_RET_OK) {
485 			pdu->error_index = i + 1;
486 			snmp_pdu_free(resp);
487 			return (result);
488 		}
489 
490 		err = snmp_binding_encode(resp_b,
491 		    &resp->bindings[resp->nbindings++]);
492 
493 		if (err == ASN_ERR_EOBUF)
494 			goto done;
495 
496 		if (err != ASN_ERR_OK) {
497 			if (TR(GET))
498 				snmp_debug("getnext: binding encoding: %u", err);
499 			pdu->error_status = SNMP_ERR_GENERR;
500 			pdu->error_index = i + 1;
501 			snmp_pdu_free(resp);
502 			return (SNMP_RET_ERR);
503 		}
504 	}
505 
506 	if (non_rep == pdu->nbindings)
507 		goto done;
508 
509 	/* repeates */
510 	for (cnt = 0; cnt < pdu->error_index; cnt++) {
511 		eomib = 1;
512 		for (i = non_rep; i < pdu->nbindings; i++) {
513 			if (cnt == 0)
514 				result = do_getnext(&context, &pdu->bindings[i],
515 				    &resp->bindings[resp->nbindings], pdu);
516 			else
517 				result = do_getnext(&context,
518 				    &resp->bindings[resp->nbindings -
519 				    (pdu->nbindings - non_rep)],
520 				    &resp->bindings[resp->nbindings], pdu);
521 
522 			if (result != SNMP_RET_OK) {
523 				pdu->error_index = i + 1;
524 				snmp_pdu_free(resp);
525 				return (result);
526 			}
527 			if (resp->bindings[resp->nbindings].syntax !=
528 			    SNMP_SYNTAX_ENDOFMIBVIEW)
529 				eomib = 0;
530 
531 			err = snmp_binding_encode(resp_b,
532 			    &resp->bindings[resp->nbindings++]);
533 
534 			if (err == ASN_ERR_EOBUF)
535 				goto done;
536 
537 			if (err != ASN_ERR_OK) {
538 				if (TR(GET))
539 					snmp_debug("getnext: binding encoding: %u", err);
540 				pdu->error_status = SNMP_ERR_GENERR;
541 				pdu->error_index = i + 1;
542 				snmp_pdu_free(resp);
543 				return (SNMP_RET_ERR);
544 			}
545 		}
546 		if (eomib)
547 			break;
548 	}
549 
550   done:
551 	if (snmp_fix_encoding(resp_b, resp) != SNMP_CODE_OK) {
552 		snmp_debug("getnext: failed to encode PDU");
553 		return (SNMP_RET_ERR);
554 	}
555 
556 	return (SNMP_RET_OK);
557 }
558 
559 /*
560  * Rollback a SET operation. Failed index is 'i'.
561  */
562 static void
563 rollback(struct context *context, struct snmp_pdu *pdu, u_int i)
564 {
565 	struct snmp_value *b;
566 	const struct snmp_node *np;
567 	int ret;
568 
569 	while (i-- > 0) {
570 		b = &pdu->bindings[i];
571 		np = context->node[i];
572 
573 		context->ctx.scratch = &context->scratch[i];
574 
575 		ret = (*np->op)(&context->ctx, b, np->oid.len, np->index,
576 		    SNMP_OP_ROLLBACK);
577 
578 		if (ret != SNMP_ERR_NOERROR) {
579 			snmp_error("set: rollback failed (%d) on variable %s "
580 			    "index %u", ret, asn_oid2str(&b->var), i);
581 			if (pdu->version != SNMP_V1) {
582 				pdu->error_status = SNMP_ERR_UNDO_FAILED;
583 				pdu->error_index = 0;
584 			}
585 		}
586 	}
587 }
588 
589 /*
590  * Commit dependencies.
591  */
592 int
593 snmp_dep_commit(struct snmp_context *ctx)
594 {
595 	struct context *context = (struct context *)ctx;
596 	int ret;
597 
598 	TAILQ_FOREACH(context->depend, &context->dlist, link) {
599 		ctx->dep = &context->depend->dep;
600 
601 		if (TR(SET))
602 			snmp_debug("set: dependency commit %s",
603 			    asn_oid2str(&ctx->dep->obj));
604 
605 		ret = context->depend->func(ctx, ctx->dep, SNMP_DEPOP_COMMIT);
606 
607 		if (ret != SNMP_ERR_NOERROR) {
608 			if (TR(SET))
609 				snmp_debug("set: dependency failed %d", ret);
610 			return (ret);
611 		}
612 	}
613 	return (SNMP_ERR_NOERROR);
614 }
615 
616 /*
617  * Rollback dependencies
618  */
619 int
620 snmp_dep_rollback(struct snmp_context *ctx)
621 {
622 	struct context *context = (struct context *)ctx;
623 	int ret, ret1;
624 	char objbuf[ASN_OIDSTRLEN];
625 	char idxbuf[ASN_OIDSTRLEN];
626 
627 	ret1 = SNMP_ERR_NOERROR;
628 	while ((context->depend =
629 	    TAILQ_PREV(context->depend, depend_list, link)) != NULL) {
630 		ctx->dep = &context->depend->dep;
631 
632 		if (TR(SET))
633 			snmp_debug("set: dependency rollback %s",
634 			    asn_oid2str(&ctx->dep->obj));
635 
636 		ret = context->depend->func(ctx, ctx->dep, SNMP_DEPOP_ROLLBACK);
637 
638 		if (ret != SNMP_ERR_NOERROR) {
639 			snmp_debug("set: dep rollback returns %u: %s %s", ret,
640 			    asn_oid2str_r(&ctx->dep->obj, objbuf),
641 			    asn_oid2str_r(&ctx->dep->idx, idxbuf));
642 			if (ret1 == SNMP_ERR_NOERROR)
643 				ret1 = ret;
644 		}
645 	}
646 	return (ret1);
647 }
648 
649 void
650 snmp_dep_finish(struct snmp_context *ctx)
651 {
652 	struct context *context = (struct context *)ctx;
653 	struct depend *d;
654 
655 	while ((d = TAILQ_FIRST(&context->dlist)) != NULL) {
656 		ctx->dep = &d->dep;
657 		(void)d->func(ctx, ctx->dep, SNMP_DEPOP_FINISH);
658 		TAILQ_REMOVE(&context->dlist, d, link);
659 		free(d);
660 	}
661 }
662 
663 /*
664  * Do a SET operation.
665  */
666 enum snmp_ret
667 snmp_set(struct snmp_pdu *pdu, struct asn_buf *resp_b,
668     struct snmp_pdu *resp, void *data)
669 {
670 	int ret;
671 	u_int i;
672 	enum asn_err asnerr;
673 	struct context context;
674 	const struct snmp_node *np;
675 	struct snmp_value *b;
676 	enum snmp_syntax except;
677 
678 	memset(&context, 0, sizeof(context));
679 	TAILQ_INIT(&context.dlist);
680 	context.ctx.data = data;
681 
682 	snmp_pdu_create_response(pdu, resp);
683 
684 	if (snmp_pdu_encode_header(resp_b, resp))
685 		return (SNMP_RET_IGN);
686 
687 	/*
688 	 * 1. Find all nodes, check that they are writeable and
689 	 *    that the syntax is ok, copy over the binding to the response.
690 	 */
691 	for (i = 0; i < pdu->nbindings; i++) {
692 		b = &pdu->bindings[i];
693 
694 		if ((np = context.node[i] = find_node(b, &except)) == NULL) {
695 			/* not found altogether or LEAF with wrong index */
696 			if (TR(SET))
697 				snmp_debug("set: node not found %s",
698 				    asn_oid2str_r(&b->var, oidbuf));
699 			if (pdu->version == SNMP_V1) {
700 				pdu->error_index = i + 1;
701 				pdu->error_status = SNMP_ERR_NOSUCHNAME;
702 			} else if ((np = find_subnode(b)) != NULL) {
703 				/* 2. intermediate object */
704 				pdu->error_index = i + 1;
705 				pdu->error_status = SNMP_ERR_NOT_WRITEABLE;
706 			} else if (except == SNMP_SYNTAX_NOSUCHOBJECT) {
707 				pdu->error_index = i + 1;
708 				pdu->error_status = SNMP_ERR_NO_ACCESS;
709 			} else {
710 				pdu->error_index = i + 1;
711 				pdu->error_status = SNMP_ERR_NO_CREATION;
712 			}
713 			snmp_pdu_free(resp);
714 			return (SNMP_RET_ERR);
715 		}
716 		/*
717 		 * 2. write/createable?
718 		 * Can check this for leafs only, because in v2 we have
719 		 * to differentiate between NOT_WRITEABLE and NO_CREATION
720 		 * and only the action routine for COLUMNS knows, whether
721 		 * a column exists.
722 		 */
723 		if (np->type == SNMP_NODE_LEAF &&
724 		    !(np->flags & SNMP_NODE_CANSET)) {
725 			if (pdu->version == SNMP_V1) {
726 				pdu->error_index = i + 1;
727 				pdu->error_status = SNMP_ERR_NOSUCHNAME;
728 			} else {
729 				pdu->error_index = i + 1;
730 				pdu->error_status = SNMP_ERR_NOT_WRITEABLE;
731 			}
732 			snmp_pdu_free(resp);
733 			return (SNMP_RET_ERR);
734 		}
735 		/*
736 		 * 3. Ensure the right syntax
737 		 */
738 		if (np->syntax != b->syntax) {
739 			if (pdu->version == SNMP_V1) {
740 				pdu->error_index = i + 1;
741 				pdu->error_status = SNMP_ERR_BADVALUE; /* v2: wrongType */
742 			} else {
743 				pdu->error_index = i + 1;
744 				pdu->error_status = SNMP_ERR_WRONG_TYPE;
745 			}
746 			snmp_pdu_free(resp);
747 			return (SNMP_RET_ERR);
748 		}
749 		/*
750 		 * 4. Copy binding
751 		 */
752 		if (snmp_value_copy(&resp->bindings[i], b)) {
753 			pdu->error_index = i + 1;
754 			pdu->error_status = SNMP_ERR_GENERR;
755 			snmp_pdu_free(resp);
756 			return (SNMP_RET_ERR);
757 		}
758 		asnerr = snmp_binding_encode(resp_b, &resp->bindings[i]);
759 		if (asnerr == ASN_ERR_EOBUF) {
760 			pdu->error_index = i + 1;
761 			pdu->error_status = SNMP_ERR_TOOBIG;
762 			snmp_pdu_free(resp);
763 			return (SNMP_RET_ERR);
764 		} else if (asnerr != ASN_ERR_OK) {
765 			pdu->error_index = i + 1;
766 			pdu->error_status = SNMP_ERR_GENERR;
767 			snmp_pdu_free(resp);
768 			return (SNMP_RET_ERR);
769 		}
770 		resp->nbindings++;
771 	}
772 
773 	context.ctx.code = SNMP_RET_OK;
774 
775 	/*
776 	 * 2. Call the SET method for each node. If a SET fails, rollback
777 	 *    everything. Map error codes depending on the version.
778 	 */
779 	for (i = 0; i < pdu->nbindings; i++) {
780 		b = &pdu->bindings[i];
781 		np = context.node[i];
782 
783 		context.ctx.var_index = i + 1;
784 		context.ctx.scratch = &context.scratch[i];
785 
786 		ret = (*np->op)(&context.ctx, b, np->oid.len, np->index,
787 		    SNMP_OP_SET);
788 
789 		if (TR(SET))
790 			snmp_debug("set: action %s returns %d", np->name, ret);
791 
792 		if (pdu->version == SNMP_V1) {
793 			switch (ret) {
794 			  case SNMP_ERR_NO_ACCESS:
795 				ret = SNMP_ERR_NOSUCHNAME;
796 				break;
797 			  case SNMP_ERR_WRONG_TYPE:
798 				/* should no happen */
799 				ret = SNMP_ERR_BADVALUE;
800 				break;
801 			  case SNMP_ERR_WRONG_LENGTH:
802 				ret = SNMP_ERR_BADVALUE;
803 				break;
804 			  case SNMP_ERR_WRONG_ENCODING:
805 				/* should not happen */
806 				ret = SNMP_ERR_BADVALUE;
807 				break;
808 			  case SNMP_ERR_WRONG_VALUE:
809 				ret = SNMP_ERR_BADVALUE;
810 				break;
811 			  case SNMP_ERR_NO_CREATION:
812 				ret = SNMP_ERR_NOSUCHNAME;
813 				break;
814 			  case SNMP_ERR_INCONS_VALUE:
815 				ret = SNMP_ERR_BADVALUE;
816 				break;
817 			  case SNMP_ERR_RES_UNAVAIL:
818 				ret = SNMP_ERR_GENERR;
819 				break;
820 			  case SNMP_ERR_COMMIT_FAILED:
821 				ret = SNMP_ERR_GENERR;
822 				break;
823 			  case SNMP_ERR_UNDO_FAILED:
824 				ret = SNMP_ERR_GENERR;
825 				break;
826 			  case SNMP_ERR_AUTH_ERR:
827 				/* should not happen */
828 				ret = SNMP_ERR_GENERR;
829 				break;
830 			  case SNMP_ERR_NOT_WRITEABLE:
831 				ret = SNMP_ERR_NOSUCHNAME;
832 				break;
833 			  case SNMP_ERR_INCONS_NAME:
834 				ret = SNMP_ERR_BADVALUE;
835 				break;
836 			}
837 		}
838 		if (ret != SNMP_ERR_NOERROR) {
839 			pdu->error_index = i + 1;
840 			pdu->error_status = ret;
841 
842 			rollback(&context, pdu, i);
843 			snmp_pdu_free(resp);
844 
845 			context.ctx.code = SNMP_RET_ERR;
846 
847 			goto errout;
848 		}
849 	}
850 
851 	/*
852 	 * 3. Call dependencies
853 	 */
854 	if (TR(SET))
855 		snmp_debug("set: set operations ok");
856 
857 	if ((ret = snmp_dep_commit(&context.ctx)) != SNMP_ERR_NOERROR) {
858 		pdu->error_status = ret;
859 		pdu->error_index = context.ctx.var_index;
860 
861 		if ((ret = snmp_dep_rollback(&context.ctx)) != SNMP_ERR_NOERROR) {
862 			if (pdu->version != SNMP_V1) {
863 				pdu->error_status = SNMP_ERR_UNDO_FAILED;
864 				pdu->error_index = 0;
865 			}
866 		}
867 		rollback(&context, pdu, i);
868 		snmp_pdu_free(resp);
869 
870 		context.ctx.code = SNMP_RET_ERR;
871 
872 		goto errout;
873 	}
874 
875 	/*
876 	 * 4. Commit and copy values from the original packet to the response.
877 	 *    This is not the commit operation from RFC 1905 but rather an
878 	 *    'FREE RESOURCES' operation. It shouldn't fail.
879 	 */
880 	if (TR(SET))
881 		snmp_debug("set: commiting");
882 
883 	for (i = 0; i < pdu->nbindings; i++) {
884 		b = &resp->bindings[i];
885 		np = context.node[i];
886 
887 		context.ctx.var_index = i + 1;
888 		context.ctx.scratch = &context.scratch[i];
889 
890 		ret = (*np->op)(&context.ctx, b, np->oid.len, np->index,
891 		    SNMP_OP_COMMIT);
892 
893 		if (ret != SNMP_ERR_NOERROR)
894 			snmp_error("set: commit failed (%d) on"
895 			    " variable %s index %u", ret,
896 			    asn_oid2str_r(&b->var, oidbuf), i);
897 	}
898 
899 	if (snmp_fix_encoding(resp_b, resp) != SNMP_CODE_OK) {
900 		snmp_error("set: fix_encoding failed");
901 		snmp_pdu_free(resp);
902 		context.ctx.code = SNMP_RET_IGN;
903 	}
904 
905 	/*
906 	 * Done
907 	 */
908   errout:
909 	snmp_dep_finish(&context.ctx);
910 
911 	if (TR(SET))
912 		snmp_debug("set: returning %d", context.ctx.code);
913 
914 	return (context.ctx.code);
915 }
916 /*
917  * Lookup a dependency. If it doesn't exist, create one
918  */
919 struct snmp_dependency *
920 snmp_dep_lookup(struct snmp_context *ctx, const struct asn_oid *obj,
921     const struct asn_oid *idx, size_t len, snmp_depop_t func)
922 {
923 	struct context *context;
924 	struct depend *d;
925 
926 	context = (struct context *)(void *)
927 	    ((char *)ctx - offsetof(struct context, ctx));
928 	if (TR(DEPEND)) {
929 		snmp_debug("depend: looking for %s", asn_oid2str(obj));
930 		if (idx)
931 			snmp_debug("depend: index is %s", asn_oid2str(idx));
932 	}
933 	TAILQ_FOREACH(d, &context->dlist, link)
934 		if (asn_compare_oid(obj, &d->dep.obj) == 0 &&
935 		    ((idx == NULL && d->dep.idx.len == 0) ||
936 		     (idx != NULL && asn_compare_oid(idx, &d->dep.idx) == 0))) {
937 			if(TR(DEPEND))
938 				snmp_debug("depend: found");
939 			return (&d->dep);
940 		}
941 
942 	if(TR(DEPEND))
943 		snmp_debug("depend: creating");
944 
945 	if ((d = malloc(offsetof(struct depend, dep) + len)) == NULL)
946 		return (NULL);
947 	memset(&d->dep, 0, len);
948 
949 	d->dep.obj = *obj;
950 	if (idx == NULL)
951 		d->dep.idx.len = 0;
952 	else
953 		d->dep.idx = *idx;
954 	d->len = len;
955 	d->func = func;
956 
957 	TAILQ_INSERT_TAIL(&context->dlist, d, link);
958 
959 	return (&d->dep);
960 }
961 
962 /*
963  * Make an error response from a PDU. We do this without decoding the
964  * variable bindings. This means we can sent the junk back to a caller
965  * that has sent us junk in the first place.
966  */
967 enum snmp_ret
968 snmp_make_errresp(const struct snmp_pdu *pdu, struct asn_buf *pdu_b,
969     struct asn_buf *resp_b)
970 {
971 	u_char type;
972 	asn_len_t len;
973 	struct snmp_pdu resp;
974 	enum asn_err err;
975 	enum snmp_code code;
976 
977 	snmp_pdu_create_response(pdu, &resp);
978 
979 	if ((code = snmp_pdu_decode_header(pdu_b, &resp)) != SNMP_CODE_OK)
980 		return (SNMP_RET_IGN);
981 
982 	if (pdu->version == SNMP_V3) {
983 		if (resp.user.priv_proto != SNMP_PRIV_NOPRIV &&
984 		   (asn_get_header(pdu_b, &type, &resp.scoped_len) != ASN_ERR_OK
985 		   || type != ASN_TYPE_OCTETSTRING)) {
986 			snmp_error("cannot decode encrypted pdu");
987 			return (SNMP_RET_IGN);
988 		}
989 
990 		if (asn_get_sequence(pdu_b, &len) != ASN_ERR_OK) {
991 			snmp_error("cannot decode scoped pdu header");
992 			return (SNMP_RET_IGN);
993 		}
994 
995 		len = SNMP_ENGINE_ID_SIZ;
996 		if (asn_get_octetstring(pdu_b, (u_char *)resp.context_engine,
997 		    &len) != ASN_ERR_OK) {
998 			snmp_error("cannot decode msg context engine");
999 			return (SNMP_RET_IGN);
1000 		}
1001 		resp.context_engine_len = len;
1002 		len = SNMP_CONTEXT_NAME_SIZ;
1003 		if (asn_get_octetstring(pdu_b, (u_char *)resp.context_name,
1004 		    &len) != ASN_ERR_OK) {
1005 			snmp_error("cannot decode msg context name");
1006 			return (SNMP_RET_IGN);
1007 		}
1008 		resp.context_name[len] = '\0';
1009 	}
1010 
1011 
1012 	if (asn_get_header(pdu_b, &type, &len) != ASN_ERR_OK) {
1013 		snmp_error("cannot get pdu header");
1014 		return (SNMP_RET_IGN);
1015 	}
1016 
1017 	if ((type & ~ASN_TYPE_MASK) !=
1018 	    (ASN_TYPE_CONSTRUCTED | ASN_CLASS_CONTEXT)) {
1019 		snmp_error("bad pdu header tag");
1020 		return (SNMP_RET_IGN);
1021 	}
1022 
1023 	err = snmp_parse_pdus_hdr(pdu_b, &resp, &len);
1024 	if (ASN_ERR_STOPPED(err))
1025 		return (SNMP_RET_IGN);
1026 	if (pdu_b->asn_len < len)
1027 		return (SNMP_RET_IGN);
1028 	pdu_b->asn_len = len;
1029 
1030 	/* now we have the bindings left - construct new message */
1031 	resp.error_status = pdu->error_status;
1032 	resp.error_index = pdu->error_index;
1033 	resp.type = SNMP_PDU_RESPONSE;
1034 
1035 	code = snmp_pdu_encode_header(resp_b, &resp);
1036 	if (code != SNMP_CODE_OK)
1037 		return (SNMP_RET_IGN);
1038 
1039 	if (pdu_b->asn_len > resp_b->asn_len)
1040 		/* too short */
1041 		return (SNMP_RET_IGN);
1042 	(void)memcpy(resp_b->asn_ptr, pdu_b->asn_cptr, pdu_b->asn_len);
1043 	resp_b->asn_len -= pdu_b->asn_len;
1044 	resp_b->asn_ptr += pdu_b->asn_len;
1045 
1046 	code = snmp_fix_encoding(resp_b, &resp);
1047 	if (code != SNMP_CODE_OK)
1048 		return (SNMP_RET_IGN);
1049 
1050 	return (SNMP_RET_OK);
1051 }
1052 
1053 static void
1054 snmp_debug_func(const char *fmt, ...)
1055 {
1056 	va_list ap;
1057 
1058 	va_start(ap, fmt);
1059 	vfprintf(stderr, fmt, ap);
1060 	va_end(ap);
1061 	fprintf(stderr, "\n");
1062 }
1063