2 * Copyright (c) 2001-2003
3 * Fraunhofer Institute for Open Communication Systems (FhG Fokus).
6 * Author: Harti Brandt <harti@freebsd.org>
8 * Copyright (c) 2010 The FreeBSD Foundation
11 * Portions of this software were developed by Shteryana Sotirova Shopova
12 * under sponsorship from the FreeBSD Foundation.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * $Begemot: bsnmp/snmpd/main.c,v 1.100 2006/02/14 09:04:20 brandt_h Exp $
40 #include <sys/queue.h>
41 #include <sys/param.h>
43 #include <sys/ucred.h>
57 #ifdef USE_TCPWRAPPERS
58 #include <arpa/inet.h>
68 #define PATH_PID "/var/run/%s.pid"
69 #define PATH_CONFIG "/etc/%s.config"
70 #define PATH_ENGINE "/var/%s.engine"
72 uint64_t this_tick; /* start of processing of current packet (absolute) */
73 uint64_t start_tick; /* start of processing */
75 struct systemg systemg = {
77 { 8, { 1, 3, 6, 1, 4, 1, 1115, 7352 }},
82 struct debug debug = {
84 LOG_DEBUG, /* log_pri */
88 struct snmpd snmpd = {
93 {0, 0, 0, 0}, /* trap1addr */
94 VERS_ENABLE_ALL,/* version_enable */
96 struct snmpd_stats snmpd_stats;
98 struct snmpd_usmstat snmpd_usmstats;
101 struct snmp_engine snmpd_engine;
104 int32_t snmp_serial_no;
106 struct snmpd_target_stats snmpd_target_stats;
108 /* search path for config files */
109 const char *syspath = PATH_SYSCONFIG;
111 /* list of all loaded modules */
112 struct lmodules lmodules = TAILQ_HEAD_INITIALIZER(lmodules);
114 /* list of loaded modules during start-up in the order they were loaded */
115 static struct lmodules modules_start = TAILQ_HEAD_INITIALIZER(modules_start);
117 /* list of all known communities */
118 struct community_list community_list = TAILQ_HEAD_INITIALIZER(community_list);
120 /* list of all known USM users */
121 static struct usm_userlist usm_userlist = SLIST_HEAD_INITIALIZER(usm_userlist);
123 /* A list of all VACM users configured, including v1, v2c and v3 */
124 static struct vacm_userlist vacm_userlist =
125 SLIST_HEAD_INITIALIZER(vacm_userlist);
127 /* A list of all VACM groups */
128 static struct vacm_grouplist vacm_grouplist =
129 SLIST_HEAD_INITIALIZER(vacm_grouplist);
131 static struct vacm_group vacm_default_group = {
135 /* The list of configured access entries */
136 static struct vacm_accesslist vacm_accesslist =
137 TAILQ_HEAD_INITIALIZER(vacm_accesslist);
139 /* The list of configured views */
140 static struct vacm_viewlist vacm_viewlist =
141 SLIST_HEAD_INITIALIZER(vacm_viewlist);
143 /* The list of configured contexts */
144 static struct vacm_contextlist vacm_contextlist =
145 SLIST_HEAD_INITIALIZER(vacm_contextlist);
147 /* list of all installed object resources */
148 struct objres_list objres_list = TAILQ_HEAD_INITIALIZER(objres_list);
150 /* community value generator */
151 static u_int next_community_index = 1;
153 /* list of all known ranges */
154 struct idrange_list idrange_list = TAILQ_HEAD_INITIALIZER(idrange_list);
156 /* identifier generator */
157 u_int next_idrange = 1;
159 /* list of all current timers */
160 struct timer_list timer_list = LIST_HEAD_INITIALIZER(timer_list);
162 /* list of file descriptors */
163 struct fdesc_list fdesc_list = LIST_HEAD_INITIALIZER(fdesc_list);
165 /* program arguments */
166 static char **progargs;
167 static int nprogargs;
169 /* current community */
171 static struct community *comm;
173 /* current USM user */
174 struct usm_user *usm_user;
177 static char config_file[MAXPATHLEN + 1];
178 static char pid_file[MAXPATHLEN + 1];
179 char engine_file[MAXPATHLEN + 1];
181 #ifndef USE_LIBBEGEMOT
183 static evContext evctx;
187 static sigset_t blocked_sigs;
189 /* signal handling */
191 #define WORK_DOINFO 0x0001
192 #define WORK_RECONFIG 0x0002
195 static const struct asn_oid
196 oid_snmpMIB = OIDX_snmpMIB,
197 oid_begemotSnmpd = OIDX_begemotSnmpd,
198 oid_coldStart = OIDX_coldStart,
199 oid_authenticationFailure = OIDX_authenticationFailure;
201 const struct asn_oid oid_zeroDotZero = { 2, { 0, 0 }};
203 const struct asn_oid oid_usmUnknownEngineIDs =
204 { 11, { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0}};
206 const struct asn_oid oid_usmNotInTimeWindows =
207 { 11, { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0}};
209 /* request id generator for traps */
213 static const char usgtxt[] = "\
214 Begemot simple SNMP daemon. Copyright (c) 2001-2002 Fraunhofer Institute for\n\
215 Open Communication Systems (FhG Fokus). All rights reserved.\n\
216 Copyright (c) 2010 The FreeBSD Foundation. All rights reserved.\n\
217 usage: snmpd [-dh] [-c file] [-D options] [-e file] [-I path]\n\
218 [-l prefix] [-m variable=value] [-p file]\n\
220 -d don't daemonize\n\
221 -h print this info\n\
222 -c file specify configuration file\n\
223 -D options debugging options\n\
224 -e file specify engine id file\n\
225 -I path system include path\n\
226 -l prefix default basename for pid and config file\n\
227 -m var=val define variable\n\
228 -p file specify pid file\n\
231 /* hosts_access(3) request */
232 #ifdef USE_TCPWRAPPERS
233 static struct request_info req;
237 extern const struct transport_def udp_trans;
238 extern const struct transport_def lsock_trans;
240 struct transport_list transport_list = TAILQ_HEAD_INITIALIZER(transport_list);
242 /* forward declarations */
243 static void snmp_printf_func(const char *fmt, ...);
244 static void snmp_error_func(const char *err, ...);
245 static void snmp_debug_func(const char *err, ...);
246 static void asn_error_func(const struct asn_buf *b, const char *err, ...);
249 * Allocate rx/tx buffer. We allocate one byte more for rx.
256 if ((buf = malloc(tx ? snmpd.txbuf : snmpd.rxbuf)) == NULL) {
257 syslog(LOG_CRIT, "cannot allocate buffer");
259 snmpd_stats.noTxbuf++;
261 snmpd_stats.noRxbuf++;
268 * Return the buffer size.
273 return (tx ? snmpd.txbuf : snmpd.rxbuf);
277 * Prepare a PDU for output
280 snmp_output(struct snmp_pdu *pdu, u_char *sndbuf, size_t *sndlen,
283 struct asn_buf resp_b;
286 resp_b.asn_ptr = sndbuf;
287 resp_b.asn_len = snmpd.txbuf;
289 if ((code = snmp_pdu_encode(pdu, &resp_b)) != SNMP_CODE_OK) {
290 syslog(LOG_ERR, "cannot encode message (code=%d)", code);
293 if (debug.dump_pdus) {
294 snmp_printf("%s <- ", dest);
297 *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
301 * Check USM PDU header credentials against local SNMP Engine & users.
303 static enum snmp_code
304 snmp_pdu_auth_user(struct snmp_pdu *pdu)
308 /* un-authenticated snmpEngineId discovery */
309 if (pdu->engine.engine_len == 0 && strlen(pdu->user.sec_name) == 0) {
310 pdu->engine.engine_len = snmpd_engine.engine_len;
311 memcpy(pdu->engine.engine_id, snmpd_engine.engine_id,
312 snmpd_engine.engine_len);
313 update_snmpd_engine_time();
314 pdu->engine.engine_boots = snmpd_engine.engine_boots;
315 pdu->engine.engine_time = snmpd_engine.engine_time;
316 pdu->flags |= SNMP_MSG_AUTODISCOVER;
317 return (SNMP_CODE_OK);
320 if ((usm_user = usm_find_user(pdu->engine.engine_id,
321 pdu->engine.engine_len, pdu->user.sec_name)) == NULL ||
322 usm_user->status != 1 /* active */)
323 return (SNMP_CODE_BADUSER);
325 if (usm_user->user_engine_len != snmpd_engine.engine_len ||
326 memcmp(usm_user->user_engine_id, snmpd_engine.engine_id,
327 snmpd_engine.engine_len) != 0)
328 return (SNMP_CODE_BADENGINE);
330 pdu->user.priv_proto = usm_user->suser.priv_proto;
331 memcpy(pdu->user.priv_key, usm_user->suser.priv_key,
332 sizeof(pdu->user.priv_key));
334 /* authenticated snmpEngineId discovery */
335 if ((pdu->flags & SNMP_MSG_AUTH_FLAG) != 0) {
336 update_snmpd_engine_time();
337 pdu->user.auth_proto = usm_user->suser.auth_proto;
338 memcpy(pdu->user.auth_key, usm_user->suser.auth_key,
339 sizeof(pdu->user.auth_key));
341 if (pdu->engine.engine_boots == 0 &&
342 pdu->engine.engine_time == 0) {
343 update_snmpd_engine_time();
344 pdu->flags |= SNMP_MSG_AUTODISCOVER;
345 return (SNMP_CODE_OK);
348 if (pdu->engine.engine_boots != snmpd_engine.engine_boots ||
349 abs(pdu->engine.engine_time - snmpd_engine.engine_time) >
351 return (SNMP_CODE_NOTINTIME);
354 if (((pdu->flags & SNMP_MSG_PRIV_FLAG) != 0 &&
355 (pdu->flags & SNMP_MSG_AUTH_FLAG) == 0) ||
356 ((pdu->flags & SNMP_MSG_AUTH_FLAG) == 0 &&
357 usm_user->suser.auth_proto != SNMP_AUTH_NOAUTH) ||
358 ((pdu->flags & SNMP_MSG_PRIV_FLAG) == 0 &&
359 usm_user->suser.priv_proto != SNMP_PRIV_NOPRIV))
360 return (SNMP_CODE_BADSECLEVEL);
362 return (SNMP_CODE_OK);
366 * Check whether access to each of var bindings in the PDU is allowed based
367 * on the user credentials against the configured User groups & VACM views.
370 snmp_pdu_auth_access(struct snmp_pdu *pdu, int32_t *ip)
373 int32_t suboid, smodel;
375 struct vacm_user *vuser;
376 struct vacm_access *acl;
377 struct vacm_context *vacmctx;
378 struct vacm_view *view;
381 * At least a default context exists if the snmpd_vacm(3) module is
384 if (SLIST_EMPTY(&vacm_contextlist) ||
385 (pdu->flags & SNMP_MSG_AUTODISCOVER) != 0)
386 return (SNMP_CODE_OK);
388 switch (pdu->version) {
390 if ((uname = comm_string(community)) == NULL)
391 return (SNMP_CODE_FAILED);
392 smodel = SNMP_SECMODEL_SNMPv1;
396 if ((uname = comm_string(community)) == NULL)
397 return (SNMP_CODE_FAILED);
398 smodel = SNMP_SECMODEL_SNMPv2c;
402 uname = pdu->user.sec_name;
403 if ((smodel = pdu->security_model) != SNMP_SECMODEL_USM)
404 return (SNMP_CODE_FAILED);
405 /* Compare the PDU context engine id against the agent's */
406 if (pdu->context_engine_len != snmpd_engine.engine_len ||
407 memcmp(pdu->context_engine, snmpd_engine.engine_id,
408 snmpd_engine.engine_len) != 0)
409 return (SNMP_CODE_FAILED);
416 SLIST_FOREACH(vuser, &vacm_userlist, vvu)
417 if (strcmp(uname, vuser->secname) == 0 &&
418 vuser->sec_model == smodel)
421 if (vuser == NULL || vuser->group == NULL)
422 return (SNMP_CODE_FAILED);
424 /* XXX: shteryana - recheck */
425 TAILQ_FOREACH_REVERSE(acl, &vacm_accesslist, vacm_accesslist, vva) {
426 if (acl->group != vuser->group)
428 SLIST_FOREACH(vacmctx, &vacm_contextlist, vcl)
429 if (memcmp(vacmctx->ctxname, acl->ctx_prefix,
430 acl->ctx_match) == 0)
434 return (SNMP_CODE_FAILED);
440 case SNMP_PDU_GETNEXT:
441 case SNMP_PDU_GETBULK:
442 if ((view = acl->read_view) == NULL)
443 return (SNMP_CODE_FAILED);
447 if ((view = acl->write_view) == NULL)
448 return (SNMP_CODE_FAILED);
452 case SNMP_PDU_INFORM:
454 case SNMP_PDU_REPORT:
455 if ((view = acl->notify_view) == NULL)
456 return (SNMP_CODE_FAILED);
458 case SNMP_PDU_RESPONSE:
460 return (SNMP_CODE_FAILED);
465 for (i = 0; i < pdu->nbindings; i++) {
466 /* XXX - view->mask*/
467 suboid = asn_is_suboid(&view->subtree, &pdu->bindings[i].var);
468 if ((!suboid && !view->exclude) || (suboid && view->exclude)) {
470 return (SNMP_CODE_FAILED);
474 return (SNMP_CODE_OK);
478 * SNMP input. Start: decode the PDU, find the user or community.
481 snmp_input_start(const u_char *buf, size_t len, const char *source,
482 struct snmp_pdu *pdu, int32_t *ip, size_t *pdulen)
486 enum snmpd_input_err ret;
490 this_tick = get_ticks();
495 ret = SNMPD_INPUT_OK;
497 /* look whether we have enough bytes for the entire PDU. */
498 switch (sret = snmp_pdu_snoop(&b)) {
501 return (SNMPD_INPUT_TRUNC);
504 snmpd_stats.inASNParseErrs++;
505 return (SNMPD_INPUT_FAILED);
507 b.asn_len = *pdulen = (size_t)sret;
509 memset(pdu, 0, sizeof(*pdu));
510 if ((code = snmp_pdu_decode_header(&b, pdu)) != SNMP_CODE_OK)
513 if (pdu->version == SNMP_V3) {
514 if (pdu->security_model != SNMP_SECMODEL_USM) {
515 code = SNMP_CODE_FAILED;
518 if ((code = snmp_pdu_auth_user(pdu)) != SNMP_CODE_OK)
520 if ((code = snmp_pdu_decode_secmode(&b, pdu)) != SNMP_CODE_OK)
523 code = snmp_pdu_decode_scoped(&b, pdu, ip);
526 snmpd_stats.inPkts++;
530 case SNMP_CODE_FAILED:
531 snmpd_stats.inASNParseErrs++;
532 return (SNMPD_INPUT_FAILED);
534 case SNMP_CODE_BADVERS:
536 snmpd_stats.inBadVersions++;
537 return (SNMPD_INPUT_FAILED);
539 case SNMP_CODE_BADLEN:
540 if (pdu->type == SNMP_OP_SET)
541 ret = SNMPD_INPUT_VALBADLEN;
544 case SNMP_CODE_OORANGE:
545 if (pdu->type == SNMP_OP_SET)
546 ret = SNMPD_INPUT_VALRANGE;
549 case SNMP_CODE_BADENC:
550 if (pdu->type == SNMP_OP_SET)
551 ret = SNMPD_INPUT_VALBADENC;
554 case SNMP_CODE_BADSECLEVEL:
555 snmpd_usmstats.unsupported_seclevels++;
556 return (SNMPD_INPUT_FAILED);
558 case SNMP_CODE_NOTINTIME:
559 snmpd_usmstats.not_in_time_windows++;
560 return (SNMPD_INPUT_FAILED);
562 case SNMP_CODE_BADUSER:
563 snmpd_usmstats.unknown_users++;
564 return (SNMPD_INPUT_FAILED);
566 case SNMP_CODE_BADENGINE:
567 snmpd_usmstats.unknown_engine_ids++;
568 return (SNMPD_INPUT_FAILED);
570 case SNMP_CODE_BADDIGEST:
571 snmpd_usmstats.wrong_digests++;
572 return (SNMPD_INPUT_FAILED);
574 case SNMP_CODE_EDECRYPT:
575 snmpd_usmstats.decrypt_errors++;
576 return (SNMPD_INPUT_FAILED);
579 switch (pdu->version) {
582 if (!(snmpd.version_enable & VERS_ENABLE_V1))
587 if (!(snmpd.version_enable & VERS_ENABLE_V2C))
592 if (!(snmpd.version_enable & VERS_ENABLE_V3))
602 if (debug.dump_pdus) {
603 snmp_printf("%s -> ", source);
608 * Look, whether we know the community or user
611 if (pdu->version != SNMP_V3) {
612 TAILQ_FOREACH(comm, &community_list, link)
613 if (comm->string != NULL &&
614 strcmp(comm->string, pdu->community) == 0)
618 snmpd_stats.inBadCommunityNames++;
620 if (snmpd.auth_traps)
621 snmp_send_trap(&oid_authenticationFailure,
622 (struct snmp_value *)NULL);
623 ret = SNMPD_INPUT_BAD_COMM;
625 community = comm->value;
626 } else if (pdu->nbindings == 0) {
627 /* RFC 3414 - snmpEngineID Discovery */
628 if (strlen(pdu->user.sec_name) == 0) {
629 asn_append_oid(&(pdu->bindings[pdu->nbindings++].var),
630 &oid_usmUnknownEngineIDs);
631 pdu->context_engine_len = snmpd_engine.engine_len;
632 memcpy(pdu->context_engine, snmpd_engine.engine_id,
633 snmpd_engine.engine_len);
634 } else if (pdu->engine.engine_boots == 0 &&
635 pdu->engine.engine_time == 0) {
636 asn_append_oid(&(pdu->bindings[pdu->nbindings++].var),
637 &oid_usmNotInTimeWindows);
638 update_snmpd_engine_time();
639 pdu->engine.engine_boots = snmpd_engine.engine_boots;
640 pdu->engine.engine_time = snmpd_engine.engine_time;
642 } else if (usm_user->suser.auth_proto != SNMP_AUTH_NOAUTH &&
643 (pdu->engine.engine_boots == 0 || pdu->engine.engine_time == 0)) {
644 snmpd_usmstats.not_in_time_windows++;
645 ret = SNMPD_INPUT_FAILED;
648 if ((code = snmp_pdu_auth_access(pdu, ip)) != SNMP_CODE_OK)
649 ret = SNMPD_INPUT_FAILED;
655 * Will return only _OK or _FAILED
658 snmp_input_finish(struct snmp_pdu *pdu, const u_char *rcvbuf, size_t rcvlen,
659 u_char *sndbuf, size_t *sndlen, const char *source,
660 enum snmpd_input_err ierr, int32_t ivar, void *data)
662 struct snmp_pdu resp;
663 struct asn_buf resp_b, pdu_b;
666 resp_b.asn_ptr = sndbuf;
667 resp_b.asn_len = snmpd.txbuf;
669 pdu_b.asn_cptr = rcvbuf;
670 pdu_b.asn_len = rcvlen;
672 if (ierr != SNMPD_INPUT_OK) {
673 /* error decoding the input of a SET */
674 if (pdu->version == SNMP_V1)
675 pdu->error_status = SNMP_ERR_BADVALUE;
676 else if (ierr == SNMPD_INPUT_VALBADLEN)
677 pdu->error_status = SNMP_ERR_WRONG_LENGTH;
678 else if (ierr == SNMPD_INPUT_VALRANGE)
679 pdu->error_status = SNMP_ERR_WRONG_VALUE;
681 pdu->error_status = SNMP_ERR_WRONG_ENCODING;
683 pdu->error_index = ivar;
685 if (snmp_make_errresp(pdu, &pdu_b, &resp_b) == SNMP_RET_IGN) {
686 syslog(LOG_WARNING, "could not encode error response");
687 snmpd_stats.silentDrops++;
688 return (SNMPD_INPUT_FAILED);
691 if (debug.dump_pdus) {
692 snmp_printf("%s <- ", source);
695 *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
696 return (SNMPD_INPUT_OK);
702 ret = snmp_get(pdu, &resp_b, &resp, data);
705 case SNMP_PDU_GETNEXT:
706 ret = snmp_getnext(pdu, &resp_b, &resp, data);
710 ret = snmp_set(pdu, &resp_b, &resp, data);
713 case SNMP_PDU_GETBULK:
714 ret = snmp_getbulk(pdu, &resp_b, &resp, data);
725 /* normal return - send a response */
726 if (debug.dump_pdus) {
727 snmp_printf("%s <- ", source);
728 snmp_pdu_dump(&resp);
730 *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
731 snmp_pdu_free(&resp);
732 return (SNMPD_INPUT_OK);
735 /* error - send nothing */
736 snmpd_stats.silentDrops++;
737 return (SNMPD_INPUT_FAILED);
740 /* error - send error response. The snmp routine has
741 * changed the error fields in the original message. */
742 resp_b.asn_ptr = sndbuf;
743 resp_b.asn_len = snmpd.txbuf;
744 if (snmp_make_errresp(pdu, &pdu_b, &resp_b) == SNMP_RET_IGN) {
745 syslog(LOG_WARNING, "could not encode error response");
746 snmpd_stats.silentDrops++;
747 return (SNMPD_INPUT_FAILED);
749 if (debug.dump_pdus) {
750 snmp_printf("%s <- ", source);
753 *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
754 return (SNMPD_INPUT_OK);
761 * Insert a port into the right place in the transport's table of ports
764 trans_insert_port(struct transport *t, struct tport *port)
769 TAILQ_FOREACH(p, &t->table, link) {
770 if (asn_compare_oid(&p->index, &port->index) > 0) {
771 TAILQ_INSERT_BEFORE(p, port, link);
775 TAILQ_INSERT_TAIL(&t->table, port, link);
779 * Remove a port from a transport's list
782 trans_remove_port(struct tport *port)
785 TAILQ_REMOVE(&port->transport->table, port, link);
789 * Find a port on a transport's list
792 trans_find_port(struct transport *t, const struct asn_oid *idx, u_int sub)
795 return (FIND_OBJECT_OID(&t->table, idx, sub));
799 * Find next port on a transport's list
802 trans_next_port(struct transport *t, const struct asn_oid *idx, u_int sub)
805 return (NEXT_OBJECT_OID(&t->table, idx, sub));
812 trans_first_port(struct transport *t)
815 return (TAILQ_FIRST(&t->table));
819 * Iterate through all ports until a function returns a 0.
822 trans_iter_port(struct transport *t, int (*func)(struct tport *, intptr_t),
827 TAILQ_FOREACH(p, &t->table, link)
828 if (func(p, arg) == 0)
834 * Register a transport
837 trans_register(const struct transport_def *def, struct transport **pp)
842 if ((*pp = malloc(sizeof(**pp))) == NULL)
843 return (SNMP_ERR_GENERR);
845 /* construct index */
846 (*pp)->index.len = strlen(def->name) + 1;
847 (*pp)->index.subs[0] = strlen(def->name);
848 for (i = 0; i < (*pp)->index.subs[0]; i++)
849 (*pp)->index.subs[i + 1] = def->name[i];
853 if (FIND_OBJECT_OID(&transport_list, &(*pp)->index, 0) != NULL) {
855 return (SNMP_ERR_INCONS_VALUE);
858 /* register module */
859 snprintf(or_descr, sizeof(or_descr), "%s transport mapping", def->name);
860 if (((*pp)->or_index = or_register(&def->id, or_descr, NULL)) == 0) {
862 return (SNMP_ERR_GENERR);
865 INSERT_OBJECT_OID((*pp), &transport_list);
867 TAILQ_INIT(&(*pp)->table);
869 return (SNMP_ERR_NOERROR);
873 * Unregister transport
876 trans_unregister(struct transport *t)
878 if (!TAILQ_EMPTY(&t->table))
879 return (SNMP_ERR_INCONS_VALUE);
881 or_unregister(t->or_index);
882 TAILQ_REMOVE(&transport_list, t, link);
884 return (SNMP_ERR_NOERROR);
888 * File descriptor support
890 #ifdef USE_LIBBEGEMOT
892 input(int fd, int mask __unused, void *uap)
895 input(evContext ctx __unused, void *uap, int fd, int mask __unused)
898 struct fdesc *f = uap;
900 (*f->func)(fd, f->udata);
908 #ifdef USE_LIBBEGEMOT
910 poll_unregister(f->id);
914 if (evTestID(f->id)) {
915 (void)evDeselectFD(evctx, f->id);
927 #ifdef USE_LIBBEGEMOT
930 if ((f->id = poll_register(f->fd, input, f, RPOLL_IN)) < 0) {
932 syslog(LOG_ERR, "select fd %d: %m", f->fd);
939 if (evSelectFD(evctx, f->fd, EV_READ, input, f, &f->id)) {
941 syslog(LOG_ERR, "select fd %d: %m", f->fd);
950 fd_select(int fd, void (*func)(int, void *), void *udata, struct lmodule *mod)
955 if ((f = malloc(sizeof(struct fdesc))) == NULL) {
957 syslog(LOG_ERR, "fd_select: %m");
965 #ifdef USE_LIBBEGEMOT
978 LIST_INSERT_HEAD(&fdesc_list, f, link);
988 LIST_REMOVE(f, link);
994 fd_flush(struct lmodule *mod)
996 struct fdesc *t, *t1;
998 t = LIST_FIRST(&fdesc_list);
1000 t1 = LIST_NEXT(t, link);
1001 if (t->owner == mod)
1008 * Consume a message from the input buffer
1011 snmp_input_consume(struct port_input *pi)
1014 /* always consume everything */
1018 if (pi->consumed >= pi->length) {
1019 /* all bytes consumed */
1023 memmove(pi->buf, pi->buf + pi->consumed, pi->length - pi->consumed);
1024 pi->length -= pi->consumed;
1028 * Input from a socket
1031 snmpd_input(struct port_input *pi, struct tport *tport)
1035 struct snmp_pdu pdu;
1036 enum snmpd_input_err ierr, ferr;
1037 enum snmpd_proxy_err perr;
1040 #ifdef USE_TCPWRAPPERS
1044 ret = tport->transport->vtab->recv(tport, pi);
1048 #ifdef USE_TCPWRAPPERS
1050 * In case of AF_INET{6} peer, do hosts_access(5) check.
1052 if (pi->peer->sa_family != AF_LOCAL &&
1053 inet_ntop(pi->peer->sa_family,
1054 &((const struct sockaddr_in *)(const void *)pi->peer)->sin_addr,
1055 client, sizeof(client)) != NULL) {
1056 request_set(&req, RQ_CLIENT_ADDR, client, 0);
1057 if (hosts_access(&req) == 0) {
1058 syslog(LOG_ERR, "refused connection from %.500s",
1062 } else if (pi->peer->sa_family != AF_LOCAL)
1063 syslog(LOG_ERR, "inet_ntop(): %m");
1069 ierr = snmp_input_start(pi->buf, pi->length, "SNMP", &pdu, &vi,
1071 if (ierr == SNMPD_INPUT_TRUNC) {
1072 /* need more bytes. This is ok only for streaming transports.
1073 * but only if we have not reached bufsiz yet. */
1075 if (pi->length == buf_size(0)) {
1076 snmpd_stats.silentDrops++;
1081 snmpd_stats.silentDrops++;
1085 /* can't check for bad SET pdus here, because a proxy may have to
1086 * check the access first. We don't want to return an error response
1087 * to a proxy PDU with a wrong community */
1088 if (ierr == SNMPD_INPUT_FAILED) {
1089 /* for streaming transports this is fatal */
1092 snmp_input_consume(pi);
1095 if (ierr == SNMPD_INPUT_BAD_COMM) {
1096 snmp_input_consume(pi);
1101 * If that is a module community and the module has a proxy function,
1102 * the hand it over to the module.
1104 if (comm != NULL && comm->owner != NULL &&
1105 comm->owner->config->proxy != NULL) {
1106 perr = (*comm->owner->config->proxy)(&pdu, tport->transport,
1107 &tport->index, pi->peer, pi->peerlen, ierr, vi,
1108 !pi->cred || pi->priv);
1112 case SNMPD_PROXY_OK:
1113 snmp_input_consume(pi);
1116 case SNMPD_PROXY_REJ:
1119 case SNMPD_PROXY_DROP:
1120 snmp_input_consume(pi);
1121 snmp_pdu_free(&pdu);
1122 snmpd_stats.proxyDrops++;
1125 case SNMPD_PROXY_BADCOMM:
1126 snmp_input_consume(pi);
1127 snmp_pdu_free(&pdu);
1128 snmpd_stats.inBadCommunityNames++;
1129 if (snmpd.auth_traps)
1130 snmp_send_trap(&oid_authenticationFailure,
1131 (struct snmp_value *)NULL);
1134 case SNMPD_PROXY_BADCOMMUSE:
1135 snmp_input_consume(pi);
1136 snmp_pdu_free(&pdu);
1137 snmpd_stats.inBadCommunityUses++;
1138 if (snmpd.auth_traps)
1139 snmp_send_trap(&oid_authenticationFailure,
1140 (struct snmp_value *)NULL);
1148 if (pdu.type == SNMP_PDU_RESPONSE ||
1149 pdu.type == SNMP_PDU_TRAP ||
1150 pdu.type == SNMP_PDU_TRAP2) {
1151 snmpd_stats.silentDrops++;
1152 snmpd_stats.inBadPduTypes++;
1153 snmp_pdu_free(&pdu);
1154 snmp_input_consume(pi);
1161 if (pdu.version < SNMP_V3 &&
1162 ((pi->cred && !pi->priv && pdu.type == SNMP_PDU_SET) ||
1163 (comm != NULL && comm->private != COMM_WRITE &&
1164 (pdu.type == SNMP_PDU_SET || comm->private != COMM_READ)))) {
1165 snmpd_stats.inBadCommunityUses++;
1166 snmp_pdu_free(&pdu);
1167 snmp_input_consume(pi);
1168 if (snmpd.auth_traps)
1169 snmp_send_trap(&oid_authenticationFailure,
1170 (struct snmp_value *)NULL);
1177 if ((sndbuf = buf_alloc(1)) == NULL) {
1178 snmpd_stats.silentDrops++;
1179 snmp_pdu_free(&pdu);
1180 snmp_input_consume(pi);
1183 ferr = snmp_input_finish(&pdu, pi->buf, pi->length,
1184 sndbuf, &sndlen, "SNMP", ierr, vi, NULL);
1186 if (ferr == SNMPD_INPUT_OK) {
1187 slen = tport->transport->vtab->send(tport, sndbuf, sndlen,
1188 pi->peer, pi->peerlen);
1190 syslog(LOG_ERR, "send*: %m");
1191 else if ((size_t)slen != sndlen)
1192 syslog(LOG_ERR, "send*: short write %zu/%zu", sndlen,
1196 snmp_pdu_free(&pdu);
1198 snmp_input_consume(pi);
1204 * Send a PDU to a given port
1207 snmp_send_port(void *targ, const struct asn_oid *port, struct snmp_pdu *pdu,
1208 const struct sockaddr *addr, socklen_t addrlen)
1210 struct transport *trans = targ;
1216 TAILQ_FOREACH(tp, &trans->table, link)
1217 if (asn_compare_oid(port, &tp->index) == 0)
1222 if ((sndbuf = buf_alloc(1)) == NULL)
1225 snmp_output(pdu, sndbuf, &sndlen, "SNMP PROXY");
1227 len = trans->vtab->send(tp, sndbuf, sndlen, addr, addrlen);
1230 syslog(LOG_ERR, "sendto: %m");
1231 else if ((size_t)len != sndlen)
1232 syslog(LOG_ERR, "sendto: short write %zu/%zu",
1233 sndlen, (size_t)len);
1240 * Close an input source
1243 snmpd_input_close(struct port_input *pi)
1246 fd_deselect(pi->id);
1248 (void)close(pi->fd);
1249 if (pi->buf != NULL)
1254 * Dump internal state.
1256 #ifdef USE_LIBBEGEMOT
1261 info_func(evContext ctx __unused, void *uap __unused, const void *tag __unused)
1268 syslog(LOG_DEBUG, "Dump of SNMPd %lu\n", (u_long)getpid());
1269 for (i = 0; i < tree_size; i++) {
1270 switch (tree[i].type) {
1272 case SNMP_NODE_LEAF:
1273 sprintf(buf, "LEAF: %s %s", tree[i].name,
1274 asn_oid2str(&tree[i].oid));
1277 case SNMP_NODE_COLUMN:
1278 sprintf(buf, "COL: %s %s", tree[i].name,
1279 asn_oid2str(&tree[i].oid));
1282 syslog(LOG_DEBUG, "%s", buf);
1285 TAILQ_FOREACH(m, &lmodules, link)
1286 if (m->config->dump)
1287 (*m->config->dump)();
1291 * Re-read configuration
1293 #ifdef USE_LIBBEGEMOT
1298 config_func(evContext ctx __unused, void *uap __unused,
1299 const void *tag __unused)
1304 if (read_config(config_file, NULL)) {
1305 syslog(LOG_ERR, "error reading config file '%s'", config_file);
1308 TAILQ_FOREACH(m, &lmodules, link)
1309 if (m->config->config)
1310 (*m->config->config)();
1314 * On USR1 dump actual configuration.
1317 onusr1(int s __unused)
1320 work |= WORK_DOINFO;
1323 onhup(int s __unused)
1326 work |= WORK_RECONFIG;
1330 onterm(int s __unused)
1333 /* allow clean-up */
1340 struct sigaction sa;
1342 sa.sa_handler = onusr1;
1343 sa.sa_flags = SA_RESTART;
1344 sigemptyset(&sa.sa_mask);
1345 if (sigaction(SIGUSR1, &sa, NULL)) {
1346 syslog(LOG_ERR, "sigaction: %m");
1350 sa.sa_handler = onhup;
1351 if (sigaction(SIGHUP, &sa, NULL)) {
1352 syslog(LOG_ERR, "sigaction: %m");
1356 sa.sa_handler = onterm;
1358 sigemptyset(&sa.sa_mask);
1359 if (sigaction(SIGTERM, &sa, NULL)) {
1360 syslog(LOG_ERR, "sigaction: %m");
1363 if (sigaction(SIGINT, &sa, NULL)) {
1364 syslog(LOG_ERR, "sigaction: %m");
1375 if (sigprocmask(SIG_BLOCK, &set, &blocked_sigs) == -1) {
1376 syslog(LOG_ERR, "SIG_BLOCK: %m");
1383 if (sigprocmask(SIG_SETMASK, &blocked_sigs, NULL) == -1) {
1384 syslog(LOG_ERR, "SIG_SETMASK: %m");
1395 (void)unlink(pid_file);
1401 struct transport *t;
1403 TAILQ_FOREACH(t, &transport_list, link)
1404 (void)t->vtab->stop(1);
1408 * Define a macro from the command line
1416 if ((eq = strchr(arg, '=')) == NULL)
1417 err = define_macro(arg, "");
1420 err = define_macro(arg, eq);
1423 syslog(LOG_ERR, "cannot save macro: %m");
1429 * Re-implement getsubopt from scratch, because the second argument is broken
1430 * and will not compile with WARNS=5.
1433 getsubopt1(char **arg, const char *const *options, char **valp, char **optp)
1435 static const char *const delim = ",\t ";
1441 /* skip leading junk */
1442 for (ptr = *arg; *ptr != '\0'; ptr++)
1443 if (strchr(delim, *ptr) == NULL)
1451 /* find the end of the option */
1452 while (*++ptr != '\0')
1453 if (strchr(delim, *ptr) != NULL || *ptr == '=')
1460 while (*ptr != '\0' && strchr(delim, *ptr) == NULL)
1470 for (i = 0; *options != NULL; options++, i++)
1471 if (strcmp(*optp, *options) == 0)
1477 main(int argc, char *argv[])
1483 const char *prefix = "snmpd";
1485 char *value = NULL, *option; /* XXX */
1486 struct transport *t;
1489 #define DBG_EVENTS 1
1491 static const char *const debug_opts[] = {
1498 snmp_printf = snmp_printf_func;
1499 snmp_error = snmp_error_func;
1500 snmp_debug = snmp_debug_func;
1501 asn_error = asn_error_func;
1503 while ((opt = getopt(argc, argv, "c:dD:e:hI:l:m:p:")) != EOF)
1507 strlcpy(config_file, optarg, sizeof(config_file));
1516 switch (getsubopt1(&optarg, debug_opts,
1520 debug.dump_pdus = 1;
1530 "no value for 'trace'");
1532 snmp_trace = strtoul(value,
1539 "unknown debug flag '%s'",
1543 "missing debug flag");
1550 strlcpy(engine_file, optarg, sizeof(engine_file));
1553 fprintf(stderr, "%s", usgtxt);
1569 strlcpy(pid_file, optarg, sizeof(pid_file));
1573 openlog(prefix, LOG_PID | (background ? 0 : LOG_PERROR), LOG_USER);
1574 setlogmask(LOG_UPTO(debug.logpri - 1));
1576 if (background && daemon(0, 0) < 0) {
1577 syslog(LOG_ERR, "daemon: %m");
1589 snmp_serial_no = random();
1591 #ifdef USE_TCPWRAPPERS
1593 * Initialize hosts_access(3) handler.
1595 request_init(&req, RQ_DAEMON, "snmpd", 0);
1600 * Initialize the tree.
1602 if ((tree = malloc(sizeof(struct snmp_node) * CTREE_SIZE)) == NULL) {
1603 syslog(LOG_ERR, "%m");
1606 memcpy(tree, ctree, sizeof(struct snmp_node) * CTREE_SIZE);
1607 tree_size = CTREE_SIZE;
1610 * Get standard communities
1612 comm_define(COMM_READ, "SNMP read", NULL, NULL);
1613 comm_define(COMM_WRITE, "SNMP write", NULL, NULL);
1614 community = COMM_INITIALIZE;
1616 trap_reqid = reqid_allocate(512, NULL);
1618 if (config_file[0] == '\0')
1619 snprintf(config_file, sizeof(config_file), PATH_CONFIG, prefix);
1622 init_snmpd_engine();
1624 this_tick = get_ticks();
1625 start_tick = this_tick;
1627 /* start transports */
1628 if (atexit(trans_stop) == -1) {
1629 syslog(LOG_ERR, "atexit failed: %m");
1632 if (udp_trans.start() != SNMP_ERR_NOERROR)
1633 syslog(LOG_WARNING, "cannot start UDP transport");
1634 if (lsock_trans.start() != SNMP_ERR_NOERROR)
1635 syslog(LOG_WARNING, "cannot start LSOCK transport");
1637 #ifdef USE_LIBBEGEMOT
1638 if (debug.evdebug > 0)
1641 if (evCreate(&evctx)) {
1642 syslog(LOG_ERR, "evCreate: %m");
1645 if (debug.evdebug > 0)
1646 evSetDebug(evctx, 10, stderr);
1649 if (engine_file[0] == '\0')
1650 snprintf(engine_file, sizeof(engine_file), PATH_ENGINE, prefix);
1652 if (read_config(config_file, NULL)) {
1653 syslog(LOG_ERR, "error in config file");
1657 TAILQ_FOREACH(t, &transport_list, link)
1658 TAILQ_FOREACH(p, &t->table, link)
1659 t->vtab->init_port(p);
1663 if (pid_file[0] == '\0')
1664 snprintf(pid_file, sizeof(pid_file), PATH_PID, prefix);
1666 if ((fp = fopen(pid_file, "w")) != NULL) {
1667 fprintf(fp, "%u", getpid());
1669 if (atexit(term) == -1) {
1670 syslog(LOG_ERR, "atexit failed: %m");
1671 (void)remove(pid_file);
1676 if (or_register(&oid_snmpMIB, "The MIB module for SNMPv2 entities.",
1678 syslog(LOG_ERR, "cannot register SNMPv2 MIB");
1681 if (or_register(&oid_begemotSnmpd, "The MIB module for the Begemot SNMPd.",
1683 syslog(LOG_ERR, "cannot register begemotSnmpd MIB");
1687 while ((m = TAILQ_FIRST(&modules_start)) != NULL) {
1688 m->flags &= ~LM_ONSTARTLIST;
1689 TAILQ_REMOVE(&modules_start, m, start);
1693 snmp_send_trap(&oid_coldStart, (struct snmp_value *)NULL);
1696 #ifndef USE_LIBBEGEMOT
1699 struct lmodule *mod;
1701 TAILQ_FOREACH(mod, &lmodules, link)
1702 if (mod->config->idle != NULL)
1703 (*mod->config->idle)();
1705 #ifndef USE_LIBBEGEMOT
1706 if (evGetNext(evctx, &event, EV_WAIT) == 0) {
1707 if (evDispatch(evctx, event))
1708 syslog(LOG_ERR, "evDispatch: %m");
1709 } else if (errno != EINTR) {
1710 syslog(LOG_ERR, "evGetNext: %m");
1719 if (work & WORK_DOINFO) {
1720 #ifdef USE_LIBBEGEMOT
1723 if (evWaitFor(evctx, &work, info_func,
1724 NULL, NULL) == -1) {
1725 syslog(LOG_ERR, "evWaitFor: %m");
1730 if (work & WORK_RECONFIG) {
1731 #ifdef USE_LIBBEGEMOT
1734 if (evWaitFor(evctx, &work, config_func,
1735 NULL, NULL) == -1) {
1736 syslog(LOG_ERR, "evWaitFor: %m");
1743 #ifndef USE_LIBBEGEMOT
1744 if (evDo(evctx, &work) == -1) {
1745 syslog(LOG_ERR, "evDo: %m");
1761 if (gettimeofday(&tv, NULL))
1763 ret = tv.tv_sec * 100ULL + tv.tv_usec / 10000ULL;
1772 * Trampoline for the non-repeatable timers.
1774 #ifdef USE_LIBBEGEMOT
1776 tfunc(int tid __unused, void *uap)
1779 tfunc(evContext ctx __unused, void *uap, struct timespec due __unused,
1780 struct timespec inter __unused)
1783 struct timer *tp = uap;
1785 LIST_REMOVE(tp, link);
1786 tp->func(tp->udata);
1791 * Trampoline for the repeatable timers.
1793 #ifdef USE_LIBBEGEMOT
1795 trfunc(int tid __unused, void *uap)
1798 trfunc(evContext ctx __unused, void *uap, struct timespec due __unused,
1799 struct timespec inter __unused)
1802 struct timer *tp = uap;
1804 tp->func(tp->udata);
1808 * Start a one-shot timer
1811 timer_start(u_int ticks, void (*func)(void *), void *udata, struct lmodule *mod)
1814 #ifndef USE_LIBBEGEMOT
1815 struct timespec due;
1818 if ((tp = malloc(sizeof(struct timer))) == NULL) {
1819 syslog(LOG_CRIT, "out of memory for timer");
1823 #ifndef USE_LIBBEGEMOT
1824 due = evAddTime(evNowTime(),
1825 evConsTime(ticks / 100, (ticks % 100) * 10000));
1832 LIST_INSERT_HEAD(&timer_list, tp, link);
1834 #ifdef USE_LIBBEGEMOT
1835 if ((tp->id = poll_start_timer(ticks * 10, 0, tfunc, tp)) < 0) {
1836 syslog(LOG_ERR, "cannot set timer: %m");
1840 if (evSetTimer(evctx, tfunc, tp, due, evConsTime(0, 0), &tp->id)
1842 syslog(LOG_ERR, "cannot set timer: %m");
1850 * Start a repeatable timer. When used with USE_LIBBEGEMOT the first argument
1851 * is currently ignored and the initial number of ticks is set to the
1852 * repeat number of ticks.
1855 timer_start_repeat(u_int ticks __unused, u_int repeat_ticks,
1856 void (*func)(void *), void *udata, struct lmodule *mod)
1859 #ifndef USE_LIBBEGEMOT
1860 struct timespec due;
1861 struct timespec inter;
1864 if ((tp = malloc(sizeof(struct timer))) == NULL) {
1865 syslog(LOG_CRIT, "out of memory for timer");
1869 #ifndef USE_LIBBEGEMOT
1870 due = evAddTime(evNowTime(),
1871 evConsTime(ticks / 100, (ticks % 100) * 10000));
1872 inter = evConsTime(repeat_ticks / 100, (repeat_ticks % 100) * 10000);
1879 LIST_INSERT_HEAD(&timer_list, tp, link);
1881 #ifdef USE_LIBBEGEMOT
1882 if ((tp->id = poll_start_timer(repeat_ticks * 10, 1, trfunc, tp)) < 0) {
1883 syslog(LOG_ERR, "cannot set timer: %m");
1887 if (evSetTimer(evctx, trfunc, tp, due, inter, &tp->id) == -1) {
1888 syslog(LOG_ERR, "cannot set timer: %m");
1901 struct timer *tp = p;
1903 LIST_REMOVE(tp, link);
1904 #ifdef USE_LIBBEGEMOT
1905 poll_stop_timer(tp->id);
1907 if (evClearTimer(evctx, tp->id) == -1) {
1908 syslog(LOG_ERR, "cannot stop timer: %m");
1916 timer_flush(struct lmodule *mod)
1918 struct timer *t, *t1;
1920 t = LIST_FIRST(&timer_list);
1922 t1 = LIST_NEXT(t, link);
1923 if (t->owner == mod)
1930 snmp_printf_func(const char *fmt, ...)
1933 static char *pend = NULL;
1937 vasprintf(&ret, fmt, ap);
1943 if ((new = realloc(pend, strlen(pend) + strlen(ret) + 1))
1954 while ((ret = strchr(pend, '\n')) != NULL) {
1956 syslog(LOG_DEBUG, "%s", pend);
1957 if (strlen(ret + 1) == 0) {
1962 strcpy(pend, ret + 1);
1967 snmp_error_func(const char *err, ...)
1972 if (!(snmp_trace & LOG_SNMP_ERRORS))
1976 snprintf(errbuf, sizeof(errbuf), "SNMP: ");
1977 vsnprintf(errbuf + strlen(errbuf),
1978 sizeof(errbuf) - strlen(errbuf), err, ap);
1981 syslog(LOG_ERR, "%s", errbuf);
1985 snmp_debug_func(const char *err, ...)
1991 snprintf(errbuf, sizeof(errbuf), "SNMP: ");
1992 vsnprintf(errbuf+strlen(errbuf), sizeof(errbuf)-strlen(errbuf),
1996 syslog(LOG_DEBUG, "%s", errbuf);
2000 asn_error_func(const struct asn_buf *b, const char *err, ...)
2006 if (!(snmp_trace & LOG_ASN1_ERRORS))
2010 snprintf(errbuf, sizeof(errbuf), "ASN.1: ");
2011 vsnprintf(errbuf + strlen(errbuf),
2012 sizeof(errbuf) - strlen(errbuf), err, ap);
2016 snprintf(errbuf + strlen(errbuf),
2017 sizeof(errbuf) - strlen(errbuf), " at");
2018 for (i = 0; b->asn_len > i; i++)
2019 snprintf(errbuf + strlen(errbuf),
2020 sizeof(errbuf) - strlen(errbuf),
2021 " %02x", b->asn_cptr[i]);
2024 syslog(LOG_ERR, "%s", errbuf);
2028 * Create a new community
2031 comm_define_ordered(u_int priv, const char *descr, struct asn_oid *idx,
2032 struct lmodule *owner, const char *str)
2034 struct community *c, *p;
2037 ncomm = idx->subs[idx->len - 1];
2039 /* check that community doesn't already exist */
2040 TAILQ_FOREACH(c, &community_list, link)
2041 if (c->value == ncomm)
2044 if ((c = malloc(sizeof(struct community))) == NULL) {
2045 syslog(LOG_ERR, "%s: %m", __func__);
2055 if((c->string = malloc(strlen(str)+1)) == NULL) {
2059 strcpy(c->string, str);
2065 TAILQ_FOREACH(p, &community_list, link) {
2066 if (asn_compare_oid(&p->index, &c->index) > 0) {
2067 TAILQ_INSERT_BEFORE(p, c, link);
2072 TAILQ_INSERT_TAIL(&community_list, c, link);
2077 comm_define(u_int priv, const char *descr, struct lmodule *owner,
2080 struct asn_oid idx, *p;
2081 struct community *c;
2084 /* generate an identifier */
2086 if ((ncomm = next_community_index++) == UINT_MAX)
2087 next_community_index = 1;
2088 TAILQ_FOREACH(c, &community_list, link)
2089 if (c->value == ncomm)
2091 } while (c != NULL);
2101 p->subs[p->len++] = ncomm;
2102 c = comm_define_ordered(priv, descr, p, owner, str);
2109 comm_string(u_int ncomm)
2111 struct community *p;
2113 TAILQ_FOREACH(p, &community_list, link)
2114 if (p->value == ncomm)
2120 * Delete all communities allocated by a module
2123 comm_flush(struct lmodule *mod)
2125 struct community *p, *p1;
2127 p = TAILQ_FIRST(&community_list);
2129 p1 = TAILQ_NEXT(p, link);
2130 if (p->owner == mod) {
2132 TAILQ_REMOVE(&community_list, p, link);
2140 * Request ID handling.
2142 * Allocate a new range of request ids. Use a first fit algorithm.
2145 reqid_allocate(int size, struct lmodule *mod)
2148 struct idrange *r, *r1;
2150 if (size <= 0 || size > INT32_MAX) {
2151 syslog(LOG_CRIT, "%s: size out of range: %d", __func__, size);
2154 /* allocate a type id */
2156 if ((type = next_idrange++) == UINT_MAX)
2158 TAILQ_FOREACH(r, &idrange_list, link)
2159 if (r->type == type)
2164 if (TAILQ_EMPTY(&idrange_list))
2167 r = TAILQ_FIRST(&idrange_list);
2168 if (r->base < size) {
2169 while((r1 = TAILQ_NEXT(r, link)) != NULL) {
2170 if (r1->base - (r->base + r->size) >= size)
2177 r1 = TAILQ_LAST(&idrange_list, idrange_list);
2178 if (INT32_MAX - size + 1 < r1->base + r1->size) {
2179 syslog(LOG_ERR, "out of id ranges (%u)", size);
2185 /* allocate structure */
2186 if ((r1 = malloc(sizeof(struct idrange))) == NULL) {
2187 syslog(LOG_ERR, "%s: %m", __FUNCTION__);
2194 if (TAILQ_EMPTY(&idrange_list) || r == TAILQ_FIRST(&idrange_list)) {
2196 TAILQ_INSERT_HEAD(&idrange_list, r1, link);
2197 } else if (r == NULL) {
2198 r = TAILQ_LAST(&idrange_list, idrange_list);
2199 r1->base = r->base + r->size;
2200 TAILQ_INSERT_TAIL(&idrange_list, r1, link);
2202 r = TAILQ_PREV(r, idrange_list, link);
2203 r1->base = r->base + r->size;
2204 TAILQ_INSERT_AFTER(&idrange_list, r, r1, link);
2206 r1->next = r1->base;
2212 reqid_next(u_int type)
2217 TAILQ_FOREACH(r, &idrange_list, link)
2218 if (r->type == type)
2221 syslog(LOG_CRIT, "wrong idrange type");
2224 if ((id = r->next++) == r->base + (r->size - 1))
2230 reqid_base(u_int type)
2234 TAILQ_FOREACH(r, &idrange_list, link)
2235 if (r->type == type)
2237 syslog(LOG_CRIT, "wrong idrange type");
2242 reqid_type(int32_t reqid)
2246 TAILQ_FOREACH(r, &idrange_list, link)
2247 if (reqid >= r->base && reqid <= r->base + (r->size - 1))
2253 reqid_istype(int32_t reqid, u_int type)
2255 return (reqid_type(reqid) == type);
2259 * Delete all communities allocated by a module
2262 reqid_flush(struct lmodule *mod)
2264 struct idrange *p, *p1;
2266 p = TAILQ_FIRST(&idrange_list);
2268 p1 = TAILQ_NEXT(p, link);
2269 if (p->owner == mod) {
2270 TAILQ_REMOVE(&idrange_list, p, link);
2278 * Merge the given tree for the given module into the main tree.
2281 compare_node(const void *v1, const void *v2)
2283 const struct snmp_node *n1 = v1;
2284 const struct snmp_node *n2 = v2;
2286 return (asn_compare_oid(&n1->oid, &n2->oid));
2289 tree_merge(const struct snmp_node *ntree, u_int nsize, struct lmodule *mod)
2291 struct snmp_node *xtree;
2294 xtree = realloc(tree, sizeof(*tree) * (tree_size + nsize));
2295 if (xtree == NULL) {
2296 syslog(LOG_ERR, "tree_merge: %m");
2300 memcpy(&tree[tree_size], ntree, sizeof(*tree) * nsize);
2302 for (i = 0; i < nsize; i++)
2303 tree[tree_size + i].tree_data = mod;
2307 qsort(tree, tree_size, sizeof(tree[0]), compare_node);
2313 * Remove all nodes belonging to the loadable module
2316 tree_unmerge(struct lmodule *mod)
2320 for(s = d = 0; s < tree_size; s++)
2321 if (tree[s].tree_data != mod) {
2333 lm_load(const char *path, const char *section)
2338 char *av[MAX_MOD_ARGS + 1];
2342 if ((m = malloc(sizeof(*m))) == NULL) {
2343 syslog(LOG_ERR, "lm_load: %m");
2348 strlcpy(m->section, section, sizeof(m->section));
2350 if ((m->path = strdup(path)) == NULL) {
2351 syslog(LOG_ERR, "lm_load: %m");
2358 m->index.subs[0] = strlen(section);
2359 m->index.len = m->index.subs[0] + 1;
2360 for (u = 0; u < m->index.subs[0]; u++)
2361 m->index.subs[u + 1] = section[u];
2364 * Load the object file and locate the config structure
2366 if ((m->handle = dlopen(m->path, RTLD_NOW|RTLD_GLOBAL)) == NULL) {
2367 syslog(LOG_ERR, "lm_load: open %s", dlerror());
2371 if ((m->config = dlsym(m->handle, "config")) == NULL) {
2372 syslog(LOG_ERR, "lm_load: no 'config' symbol %s", dlerror());
2377 * Insert it into the right place
2379 INSERT_OBJECT_OID(m, &lmodules);
2381 /* preserve order */
2382 if (community == COMM_INITIALIZE) {
2383 m->flags |= LM_ONSTARTLIST;
2384 TAILQ_INSERT_TAIL(&modules_start, m, start);
2388 * make the argument vector.
2391 for (i = 0; i < nprogargs; i++) {
2392 if (strlen(progargs[i]) >= strlen(section) + 1 &&
2393 strncmp(progargs[i], section, strlen(section)) == 0 &&
2394 progargs[i][strlen(section)] == ':') {
2395 if (ac == MAX_MOD_ARGS) {
2396 syslog(LOG_WARNING, "too many arguments for "
2397 "module '%s", section);
2400 av[ac++] = &progargs[i][strlen(section)+1];
2406 * Run the initialization function
2408 if ((err = (*m->config->init)(m, ac, av)) != 0) {
2409 syslog(LOG_ERR, "lm_load: init failed: %d", err);
2410 TAILQ_REMOVE(&lmodules, m, link);
2417 if ((m->flags & LM_ONSTARTLIST) != 0)
2418 TAILQ_REMOVE(&modules_start, m, start);
2430 lm_start(struct lmodule *mod)
2432 const struct lmodule *m;
2435 * Merge tree. If this fails, unload the module.
2437 if (tree_merge(mod->config->tree, mod->config->tree_size, mod)) {
2443 * Read configuration
2445 if (read_config(config_file, mod)) {
2446 syslog(LOG_ERR, "error in config file");
2450 if (mod->config->start)
2451 (*mod->config->start)();
2453 mod->flags |= LM_STARTED;
2456 * Inform other modules
2458 TAILQ_FOREACH(m, &lmodules, link)
2459 if (m->config->loading)
2460 (*m->config->loading)(mod, 1);
2468 lm_unload(struct lmodule *m)
2471 const struct lmodule *mod;
2473 TAILQ_REMOVE(&lmodules, m, link);
2474 if (m->flags & LM_ONSTARTLIST)
2475 TAILQ_REMOVE(&modules_start, m, start);
2478 if ((m->flags & LM_STARTED) && m->config->fini &&
2479 (err = (*m->config->fini)()) != 0)
2480 syslog(LOG_WARNING, "lm_unload(%s): fini %d", m->section, err);
2491 * Inform other modules
2493 TAILQ_FOREACH(mod, &lmodules, link)
2494 if (mod->config->loading)
2495 (*mod->config->loading)(m, 0);
2501 * Register an object resource and return the index (or 0 on failures)
2504 or_register(const struct asn_oid *or, const char *descr, struct lmodule *mod)
2506 struct objres *objres, *or1;
2509 /* find a free index */
2511 for (objres = TAILQ_FIRST(&objres_list);
2513 objres = TAILQ_NEXT(objres, link)) {
2514 if ((or1 = TAILQ_NEXT(objres, link)) == NULL ||
2515 or1->index > objres->index + 1) {
2516 idx = objres->index + 1;
2521 if ((objres = malloc(sizeof(*objres))) == NULL)
2524 objres->index = idx;
2526 strlcpy(objres->descr, descr, sizeof(objres->descr));
2527 objres->uptime = (uint32_t)(get_ticks() - start_tick);
2528 objres->module = mod;
2530 INSERT_OBJECT_INT(objres, &objres_list);
2532 systemg.or_last_change = objres->uptime;
2538 or_unregister(u_int idx)
2540 struct objres *objres;
2542 TAILQ_FOREACH(objres, &objres_list, link)
2543 if (objres->index == idx) {
2544 TAILQ_REMOVE(&objres_list, objres, link);
2551 * RFC 3414 User-based Security Model support
2554 struct snmpd_usmstat *
2555 bsnmpd_get_usm_stats(void)
2557 return (&snmpd_usmstats);
2561 bsnmpd_reset_usm_stats(void)
2563 memset(&snmpd_usmstats, 0, sizeof(snmpd_usmstats));
2567 usm_first_user(void)
2569 return (SLIST_FIRST(&usm_userlist));
2573 usm_next_user(struct usm_user *uuser)
2578 return (SLIST_NEXT(uuser, up));
2582 usm_find_user(uint8_t *engine, uint32_t elen, char *uname)
2584 struct usm_user *uuser;
2586 SLIST_FOREACH(uuser, &usm_userlist, up)
2587 if (uuser->user_engine_len == elen &&
2588 memcmp(uuser->user_engine_id, engine, elen) == 0 &&
2589 strlen(uuser->suser.sec_name) == strlen(uname) &&
2590 strcmp(uuser->suser.sec_name, uname) == 0)
2597 usm_compare_user(struct usm_user *u1, struct usm_user *u2)
2601 if (u1->user_engine_len < u2->user_engine_len)
2603 if (u1->user_engine_len > u2->user_engine_len)
2606 for (i = 0; i < u1->user_engine_len; i++) {
2607 if (u1->user_engine_id[i] < u2->user_engine_id[i])
2609 if (u1->user_engine_id[i] > u2->user_engine_id[i])
2613 if (strlen(u1->suser.sec_name) < strlen(u2->suser.sec_name))
2615 if (strlen(u1->suser.sec_name) > strlen(u2->suser.sec_name))
2618 for (i = 0; i < strlen(u1->suser.sec_name); i++) {
2619 if (u1->suser.sec_name[i] < u2->suser.sec_name[i])
2621 if (u1->suser.sec_name[i] > u2->suser.sec_name[i])
2629 usm_new_user(uint8_t *eid, uint32_t elen, char *uname)
2632 struct usm_user *uuser, *temp, *prev;
2634 for (uuser = usm_first_user(); uuser != NULL;
2635 (uuser = usm_next_user(uuser))) {
2636 if (uuser->user_engine_len == elen &&
2637 strlen(uname) == strlen(uuser->suser.sec_name) &&
2638 strcmp(uname, uuser->suser.sec_name) == 0 &&
2639 memcmp(eid, uuser->user_engine_id, elen) == 0)
2643 if ((uuser = (struct usm_user *)malloc(sizeof(*uuser))) == NULL)
2646 memset(uuser, 0, sizeof(*uuser));
2647 strlcpy(uuser->suser.sec_name, uname, SNMP_ADM_STR32_SIZ);
2648 memcpy(uuser->user_engine_id, eid, elen);
2649 uuser->user_engine_len = elen;
2651 if ((prev = SLIST_FIRST(&usm_userlist)) == NULL ||
2652 usm_compare_user(uuser, prev) < 0) {
2653 SLIST_INSERT_HEAD(&usm_userlist, uuser, up);
2657 SLIST_FOREACH(temp, &usm_userlist, up) {
2658 if ((cmp = usm_compare_user(uuser, temp)) <= 0)
2663 if (temp == NULL || cmp < 0)
2664 SLIST_INSERT_AFTER(prev, uuser, up);
2666 SLIST_INSERT_AFTER(temp, uuser, up);
2668 syslog(LOG_ERR, "User %s exists", uuser->suser.sec_name);
2677 usm_delete_user(struct usm_user *uuser)
2679 SLIST_REMOVE(&usm_userlist, uuser, usm_user, up);
2684 usm_flush_users(void)
2686 struct usm_user *uuser;
2688 while ((uuser = SLIST_FIRST(&usm_userlist)) != NULL) {
2689 SLIST_REMOVE_HEAD(&usm_userlist, up);
2693 SLIST_INIT(&usm_userlist);
2697 * RFC 3415 View-based Access Control Model support
2700 vacm_first_user(void)
2702 return (SLIST_FIRST(&vacm_userlist));
2706 vacm_next_user(struct vacm_user *vuser)
2711 return (SLIST_NEXT(vuser, vvu));
2715 vacm_compare_user(struct vacm_user *v1, struct vacm_user *v2)
2719 if (v1->sec_model < v2->sec_model)
2721 if (v1->sec_model > v2->sec_model)
2724 if (strlen(v1->secname) < strlen(v2->secname))
2726 if (strlen(v1->secname) > strlen(v2->secname))
2729 for (i = 0; i < strlen(v1->secname); i++) {
2730 if (v1->secname[i] < v2->secname[i])
2732 if (v1->secname[i] > v2->secname[i])
2740 vacm_new_user(int32_t smodel, char *uname)
2743 struct vacm_user *user, *temp, *prev;
2745 SLIST_FOREACH(user, &vacm_userlist, vvu)
2746 if (strcmp(uname, user->secname) == 0 &&
2747 smodel == user->sec_model)
2750 if ((user = (struct vacm_user *)malloc(sizeof(*user))) == NULL)
2753 memset(user, 0, sizeof(*user));
2754 user->group = &vacm_default_group;
2755 SLIST_INSERT_HEAD(&vacm_default_group.group_users, user, vvg);
2756 user->sec_model = smodel;
2757 strlcpy(user->secname, uname, sizeof(user->secname));
2759 if ((prev = SLIST_FIRST(&vacm_userlist)) == NULL ||
2760 vacm_compare_user(user, prev) < 0) {
2761 SLIST_INSERT_HEAD(&vacm_userlist, user, vvu);
2765 SLIST_FOREACH(temp, &vacm_userlist, vvu) {
2766 if ((cmp = vacm_compare_user(user, temp)) <= 0)
2771 if (temp == NULL || cmp < 0)
2772 SLIST_INSERT_AFTER(prev, user, vvu);
2774 SLIST_INSERT_AFTER(temp, user, vvu);
2776 syslog(LOG_ERR, "User %s exists", user->secname);
2785 vacm_delete_user(struct vacm_user *user)
2787 if (user->group != NULL && user->group != &vacm_default_group) {
2788 SLIST_REMOVE(&user->group->group_users, user, vacm_user, vvg);
2789 if (SLIST_EMPTY(&user->group->group_users)) {
2790 SLIST_REMOVE(&vacm_grouplist, user->group,
2796 SLIST_REMOVE(&vacm_userlist, user, vacm_user, vvu);
2803 vacm_user_set_group(struct vacm_user *user, u_char *octets, u_int len)
2805 struct vacm_group *group;
2807 if (len >= SNMP_ADM_STR32_SIZ)
2810 SLIST_FOREACH(group, &vacm_grouplist, vge)
2811 if (strlen(group->groupname) == len &&
2812 memcmp(octets, group->groupname, len) == 0)
2815 if (group == NULL) {
2816 if ((group = (struct vacm_group *)malloc(sizeof(*group))) == NULL)
2818 memset(group, 0, sizeof(*group));
2819 memcpy(group->groupname, octets, len);
2820 group->groupname[len] = '\0';
2821 SLIST_INSERT_HEAD(&vacm_grouplist, group, vge);
2824 SLIST_REMOVE(&user->group->group_users, user, vacm_user, vvg);
2825 SLIST_INSERT_HEAD(&group->group_users, user, vvg);
2826 user->group = group;
2832 vacm_groups_init(void)
2834 SLIST_INSERT_HEAD(&vacm_grouplist, &vacm_default_group, vge);
2837 struct vacm_access *
2838 vacm_first_access_rule(void)
2840 return (TAILQ_FIRST(&vacm_accesslist));
2843 struct vacm_access *
2844 vacm_next_access_rule(struct vacm_access *acl)
2849 return (TAILQ_NEXT(acl, vva));
2853 vacm_compare_access_rule(struct vacm_access *v1, struct vacm_access *v2)
2857 if (strlen(v1->group->groupname) < strlen(v2->group->groupname))
2859 if (strlen(v1->group->groupname) > strlen(v2->group->groupname))
2862 for (i = 0; i < strlen(v1->group->groupname); i++) {
2863 if (v1->group->groupname[i] < v2->group->groupname[i])
2865 if (v1->group->groupname[i] > v2->group->groupname[i])
2869 if (strlen(v1->ctx_prefix) < strlen(v2->ctx_prefix))
2871 if (strlen(v1->ctx_prefix) > strlen(v2->ctx_prefix))
2874 for (i = 0; i < strlen(v1->ctx_prefix); i++) {
2875 if (v1->ctx_prefix[i] < v2->ctx_prefix[i])
2877 if (v1->ctx_prefix[i] > v2->ctx_prefix[i])
2881 if (v1->sec_model < v2->sec_model)
2883 if (v1->sec_model > v2->sec_model)
2886 if (v1->sec_level < v2->sec_level)
2888 if (v1->sec_level > v2->sec_level)
2894 struct vacm_access *
2895 vacm_new_access_rule(char *gname, char *cprefix, int32_t smodel, int32_t slevel)
2897 struct vacm_group *group;
2898 struct vacm_access *acl, *temp;
2900 TAILQ_FOREACH(acl, &vacm_accesslist, vva) {
2901 if (acl->group == NULL)
2903 if (strcmp(gname, acl->group->groupname) == 0 &&
2904 strcmp(cprefix, acl->ctx_prefix) == 0 &&
2905 acl->sec_model == smodel && acl->sec_level == slevel)
2909 /* Make sure the group exists */
2910 SLIST_FOREACH(group, &vacm_grouplist, vge)
2911 if (strcmp(gname, group->groupname) == 0)
2917 if ((acl = (struct vacm_access *)malloc(sizeof(*acl))) == NULL)
2920 memset(acl, 0, sizeof(*acl));
2922 strlcpy(acl->ctx_prefix, cprefix, sizeof(acl->ctx_prefix));
2923 acl->sec_model = smodel;
2924 acl->sec_level = slevel;
2926 if ((temp = TAILQ_FIRST(&vacm_accesslist)) == NULL ||
2927 vacm_compare_access_rule(acl, temp) < 0) {
2928 TAILQ_INSERT_HEAD(&vacm_accesslist, acl, vva);
2932 TAILQ_FOREACH(temp, &vacm_accesslist, vva)
2933 if (vacm_compare_access_rule(acl, temp) < 0) {
2934 TAILQ_INSERT_BEFORE(temp, acl, vva);
2938 TAILQ_INSERT_TAIL(&vacm_accesslist, acl, vva);
2944 vacm_delete_access_rule(struct vacm_access *acl)
2946 TAILQ_REMOVE(&vacm_accesslist, acl, vva);
2953 vacm_first_view(void)
2955 return (SLIST_FIRST(&vacm_viewlist));
2959 vacm_next_view(struct vacm_view *view)
2964 return (SLIST_NEXT(view, vvl));
2968 vacm_compare_view(struct vacm_view *v1, struct vacm_view *v2)
2972 if (strlen(v1->viewname) < strlen(v2->viewname))
2974 if (strlen(v1->viewname) > strlen(v2->viewname))
2977 for (i = 0; i < strlen(v1->viewname); i++) {
2978 if (v1->viewname[i] < v2->viewname[i])
2980 if (v1->viewname[i] > v2->viewname[i])
2984 return (asn_compare_oid(&v1->subtree, &v2->subtree));
2988 vacm_new_view(char *vname, struct asn_oid *oid)
2991 struct vacm_view *view, *temp, *prev;
2993 SLIST_FOREACH(view, &vacm_viewlist, vvl)
2994 if (strcmp(vname, view->viewname) == 0)
2997 if ((view = (struct vacm_view *)malloc(sizeof(*view))) == NULL)
3000 memset(view, 0, sizeof(*view));
3001 strlcpy(view->viewname, vname, sizeof(view->viewname));
3002 asn_append_oid(&view->subtree, oid);
3004 if ((prev = SLIST_FIRST(&vacm_viewlist)) == NULL ||
3005 vacm_compare_view(view, prev) < 0) {
3006 SLIST_INSERT_HEAD(&vacm_viewlist, view, vvl);
3010 SLIST_FOREACH(temp, &vacm_viewlist, vvl) {
3011 if ((cmp = vacm_compare_view(view, temp)) <= 0)
3016 if (temp == NULL || cmp < 0)
3017 SLIST_INSERT_AFTER(prev, view, vvl);
3019 SLIST_INSERT_AFTER(temp, view, vvl);
3021 syslog(LOG_ERR, "View %s exists", view->viewname);
3030 vacm_delete_view(struct vacm_view *view)
3032 SLIST_REMOVE(&vacm_viewlist, view, vacm_view, vvl);
3038 struct vacm_context *
3039 vacm_first_context(void)
3041 return (SLIST_FIRST(&vacm_contextlist));
3044 struct vacm_context *
3045 vacm_next_context(struct vacm_context *vacmctx)
3047 if (vacmctx == NULL)
3050 return (SLIST_NEXT(vacmctx, vcl));
3053 struct vacm_context *
3054 vacm_add_context(char *ctxname, int regid)
3057 struct vacm_context *ctx, *temp, *prev;
3059 SLIST_FOREACH(ctx, &vacm_contextlist, vcl)
3060 if (strcmp(ctxname, ctx->ctxname) == 0) {
3061 syslog(LOG_ERR, "Context %s exists", ctx->ctxname);
3065 if ((ctx = (struct vacm_context *)malloc(sizeof(*ctx))) == NULL)
3068 memset(ctx, 0, sizeof(*ctx));
3069 strlcpy(ctx->ctxname, ctxname, sizeof(ctx->ctxname));
3072 if ((prev = SLIST_FIRST(&vacm_contextlist)) == NULL ||
3073 strlen(ctx->ctxname) < strlen(prev->ctxname) ||
3074 strcmp(ctx->ctxname, prev->ctxname) < 0) {
3075 SLIST_INSERT_HEAD(&vacm_contextlist, ctx, vcl);
3079 SLIST_FOREACH(temp, &vacm_contextlist, vcl) {
3080 if (strlen(ctx->ctxname) < strlen(temp->ctxname) ||
3081 strcmp(ctx->ctxname, temp->ctxname) < 0) {
3088 if (temp == NULL || cmp < 0)
3089 SLIST_INSERT_AFTER(prev, ctx, vcl);
3091 SLIST_INSERT_AFTER(temp, ctx, vcl);
3093 syslog(LOG_ERR, "Context %s exists", ctx->ctxname);
3102 vacm_flush_contexts(int regid)
3104 struct vacm_context *ctx, *temp;
3106 SLIST_FOREACH_SAFE(ctx, &vacm_contextlist, vcl, temp)
3107 if (ctx->regid == regid) {
3108 SLIST_REMOVE(&vacm_contextlist, ctx, vacm_context, vcl);