]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - contrib/bsnmp/snmpd/main.c
MFC r362623:
[FreeBSD/stable/8.git] / contrib / bsnmp / snmpd / main.c
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/snmpd/main.c,v 1.100 2006/02/14 09:04:20 brandt_h Exp $
30  *
31  * SNMPd main stuff.
32  */
33 #include <sys/param.h>
34 #include <sys/un.h>
35 #include <sys/ucred.h>
36 #include <sys/uio.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <stddef.h>
40 #include <string.h>
41 #include <stdarg.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <syslog.h>
45 #include <unistd.h>
46 #include <signal.h>
47 #include <dlfcn.h>
48 #include <inttypes.h>
49
50 #ifdef USE_TCPWRAPPERS
51 #include <arpa/inet.h>
52 #include <tcpd.h>
53 #endif
54
55 #include "support.h"
56 #include "snmpmod.h"
57 #include "snmpd.h"
58 #include "tree.h"
59 #include "oid.h"
60
61 #define PATH_PID        "/var/run/%s.pid"
62 #define PATH_CONFIG     "/etc/%s.config"
63
64 uint64_t this_tick;     /* start of processing of current packet (absolute) */
65 uint64_t start_tick;    /* start of processing */
66
67 struct systemg systemg = {
68         NULL,
69         { 8, { 1, 3, 6, 1, 4, 1, 1115, 7352 }},
70         NULL, NULL, NULL,
71         64 + 8 + 4,
72         0
73 };
74 struct debug debug = {
75         0,              /* dump_pdus */
76         LOG_DEBUG,      /* log_pri */
77         0,              /* evdebug */
78 };
79
80 struct snmpd snmpd = {
81         2048,           /* txbuf */
82         2048,           /* rxbuf */
83         0,              /* comm_dis */
84         0,              /* auth_traps */
85         {0, 0, 0, 0},   /* trap1addr */
86         VERS_ENABLE_ALL,/* version_enable */
87 };
88 struct snmpd_stats snmpd_stats;
89
90 /* snmpSerialNo */
91 int32_t snmp_serial_no;
92
93 /* search path for config files */
94 const char *syspath = PATH_SYSCONFIG;
95
96 /* list of all loaded modules */
97 struct lmodules lmodules = TAILQ_HEAD_INITIALIZER(lmodules);
98
99 /* list of loaded modules during start-up in the order they were loaded */
100 static struct lmodules modules_start = TAILQ_HEAD_INITIALIZER(modules_start);
101
102 /* list of all known communities */
103 struct community_list community_list = TAILQ_HEAD_INITIALIZER(community_list);
104
105 /* list of all installed object resources */
106 struct objres_list objres_list = TAILQ_HEAD_INITIALIZER(objres_list);
107
108 /* community value generator */
109 static u_int next_community_index = 1;
110
111 /* list of all known ranges */
112 struct idrange_list idrange_list = TAILQ_HEAD_INITIALIZER(idrange_list);
113
114 /* identifier generator */
115 u_int next_idrange = 1;
116
117 /* list of all current timers */
118 struct timer_list timer_list = LIST_HEAD_INITIALIZER(timer_list);
119
120 /* list of file descriptors */
121 struct fdesc_list fdesc_list = LIST_HEAD_INITIALIZER(fdesc_list);
122
123 /* program arguments */
124 static char **progargs;
125 static int nprogargs;
126
127 /* current community */
128 u_int   community;
129 static struct community *comm;
130
131 /* file names */
132 static char config_file[MAXPATHLEN + 1];
133 static char pid_file[MAXPATHLEN + 1];
134
135 #ifndef USE_LIBBEGEMOT
136 /* event context */
137 static evContext evctx;
138 #endif
139
140 /* signal mask */
141 static sigset_t blocked_sigs;
142
143 /* signal handling */
144 static int work;
145 #define WORK_DOINFO     0x0001
146 #define WORK_RECONFIG   0x0002
147
148 /* oids */
149 static const struct asn_oid
150         oid_snmpMIB = OIDX_snmpMIB,
151         oid_begemotSnmpd = OIDX_begemotSnmpd,
152         oid_coldStart = OIDX_coldStart,
153         oid_authenticationFailure = OIDX_authenticationFailure;
154
155 const struct asn_oid oid_zeroDotZero = { 2, { 0, 0 }};
156
157 /* request id generator for traps */
158 u_int trap_reqid;
159
160 /* help text */
161 static const char usgtxt[] = "\
162 Begemot simple SNMP daemon. Copyright (c) 2001-2002 Fraunhofer Institute for\n\
163 Open Communication Systems (FhG Fokus). All rights reserved.\n\
164 usage: snmpd [-dh] [-c file] [-D options] [-I path] [-l prefix]\n\
165              [-m variable=value] [-p file]\n\
166 options:\n\
167   -d            don't daemonize\n\
168   -h            print this info\n\
169   -c file       specify configuration file\n\
170   -D options    debugging options\n\
171   -I path       system include path\n\
172   -l prefix     default basename for pid and config file\n\
173   -m var=val    define variable\n\
174   -p file       specify pid file\n\
175 ";
176
177 /* hosts_access(3) request */
178 #ifdef USE_TCPWRAPPERS
179 static struct request_info req;
180 #endif
181
182 /* transports */
183 extern const struct transport_def udp_trans;
184 extern const struct transport_def lsock_trans;
185
186 struct transport_list transport_list = TAILQ_HEAD_INITIALIZER(transport_list);
187
188 /* forward declarations */
189 static void snmp_printf_func(const char *fmt, ...);
190 static void snmp_error_func(const char *err, ...);
191 static void snmp_debug_func(const char *err, ...);
192 static void asn_error_func(const struct asn_buf *b, const char *err, ...);
193
194 /*
195  * Allocate rx/tx buffer. We allocate one byte more for rx.
196  */
197 void *
198 buf_alloc(int tx)
199 {
200         void *buf;
201
202         if ((buf = malloc(tx ? snmpd.txbuf : snmpd.rxbuf)) == NULL) {
203                 syslog(LOG_CRIT, "cannot allocate buffer");
204                 if (tx)
205                         snmpd_stats.noTxbuf++;
206                 else
207                         snmpd_stats.noRxbuf++;
208                 return (NULL);
209         }
210         return (buf);
211 }
212
213 /*
214  * Return the buffer size.
215  */
216 size_t
217 buf_size(int tx)
218 {
219         return (tx ? snmpd.txbuf : snmpd.rxbuf);
220 }
221
222 /*
223  * Prepare a PDU for output
224  */
225 void
226 snmp_output(struct snmp_pdu *pdu, u_char *sndbuf, size_t *sndlen,
227     const char *dest)
228 {
229         struct asn_buf resp_b;
230
231         resp_b.asn_ptr = sndbuf;
232         resp_b.asn_len = snmpd.txbuf;
233
234         if (snmp_pdu_encode(pdu, &resp_b) != 0) {
235                 syslog(LOG_ERR, "cannot encode message");
236                 abort();
237         }
238         if (debug.dump_pdus) {
239                 snmp_printf("%s <- ", dest);
240                 snmp_pdu_dump(pdu);
241         }
242         *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
243 }
244
245 /*
246  * SNMP input. Start: decode the PDU, find the community.
247  */
248 enum snmpd_input_err
249 snmp_input_start(const u_char *buf, size_t len, const char *source,
250     struct snmp_pdu *pdu, int32_t *ip, size_t *pdulen)
251 {
252         struct asn_buf b;
253         enum snmp_code code;
254         enum snmpd_input_err ret;
255         int sret;
256
257         b.asn_cptr = buf;
258         b.asn_len = len;
259
260         /* look whether we have enough bytes for the entire PDU. */
261         switch (sret = snmp_pdu_snoop(&b)) {
262
263           case 0:
264                 return (SNMPD_INPUT_TRUNC);
265
266           case -1:
267                 snmpd_stats.inASNParseErrs++;
268                 return (SNMPD_INPUT_FAILED);
269         }
270         b.asn_len = *pdulen = (size_t)sret;
271
272         code = snmp_pdu_decode(&b, pdu, ip);
273
274         snmpd_stats.inPkts++;
275
276         ret = SNMPD_INPUT_OK;
277         switch (code) {
278
279           case SNMP_CODE_FAILED:
280                 snmpd_stats.inASNParseErrs++;
281                 return (SNMPD_INPUT_FAILED);
282
283           case SNMP_CODE_BADVERS:
284           bad_vers:
285                 snmpd_stats.inBadVersions++;
286                 return (SNMPD_INPUT_FAILED);
287
288           case SNMP_CODE_BADLEN:
289                 if (pdu->type == SNMP_OP_SET)
290                         ret = SNMPD_INPUT_VALBADLEN;
291                 break;
292
293           case SNMP_CODE_OORANGE:
294                 if (pdu->type == SNMP_OP_SET)
295                         ret = SNMPD_INPUT_VALRANGE;
296                 break;
297
298           case SNMP_CODE_BADENC:
299                 if (pdu->type == SNMP_OP_SET)
300                         ret = SNMPD_INPUT_VALBADENC;
301                 break;
302
303           case SNMP_CODE_OK:
304                 switch (pdu->version) {
305
306                   case SNMP_V1:
307                         if (!(snmpd.version_enable & VERS_ENABLE_V1))
308                                 goto bad_vers;
309                         break;
310
311                   case SNMP_V2c:
312                         if (!(snmpd.version_enable & VERS_ENABLE_V2C))
313                                 goto bad_vers;
314                         break;
315
316                   case SNMP_Verr:
317                         goto bad_vers;
318                 }
319                 break;
320         }
321
322         if (debug.dump_pdus) {
323                 snmp_printf("%s -> ", source);
324                 snmp_pdu_dump(pdu);
325         }
326
327         /*
328          * Look, whether we know the community
329          */
330         TAILQ_FOREACH(comm, &community_list, link)
331                 if (comm->string != NULL &&
332                     strcmp(comm->string, pdu->community) == 0)
333                         break;
334
335         if (comm == NULL) {
336                 snmpd_stats.inBadCommunityNames++;
337                 snmp_pdu_free(pdu);
338                 if (snmpd.auth_traps)
339                         snmp_send_trap(&oid_authenticationFailure,
340                             (struct snmp_value *)NULL);
341                 ret = SNMPD_INPUT_BAD_COMM;
342         } else
343                 community = comm->value;
344
345         /* update uptime */
346         this_tick = get_ticks();
347
348         return (ret);
349 }
350
351 /*
352  * Will return only _OK or _FAILED
353  */
354 enum snmpd_input_err
355 snmp_input_finish(struct snmp_pdu *pdu, const u_char *rcvbuf, size_t rcvlen,
356     u_char *sndbuf, size_t *sndlen, const char *source,
357     enum snmpd_input_err ierr, int32_t ivar, void *data)
358 {
359         struct snmp_pdu resp;
360         struct asn_buf resp_b, pdu_b;
361         enum snmp_ret ret;
362
363         resp_b.asn_ptr = sndbuf;
364         resp_b.asn_len = snmpd.txbuf;
365
366         pdu_b.asn_cptr = rcvbuf;
367         pdu_b.asn_len = rcvlen;
368
369         if (ierr != SNMPD_INPUT_OK) {
370                 /* error decoding the input of a SET */
371                 if (pdu->version == SNMP_V1)
372                         pdu->error_status = SNMP_ERR_BADVALUE;
373                 else if (ierr == SNMPD_INPUT_VALBADLEN)
374                         pdu->error_status = SNMP_ERR_WRONG_LENGTH;
375                 else if (ierr == SNMPD_INPUT_VALRANGE)
376                         pdu->error_status = SNMP_ERR_WRONG_VALUE;
377                 else
378                         pdu->error_status = SNMP_ERR_WRONG_ENCODING;
379
380                 pdu->error_index = ivar;
381
382                 if (snmp_make_errresp(pdu, &pdu_b, &resp_b) == SNMP_RET_IGN) {
383                         syslog(LOG_WARNING, "could not encode error response");
384                         snmpd_stats.silentDrops++;
385                         return (SNMPD_INPUT_FAILED);
386                 }
387
388                 if (debug.dump_pdus) {
389                         snmp_printf("%s <- ", source);
390                         snmp_pdu_dump(pdu);
391                 }
392                 *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
393                 return (SNMPD_INPUT_OK);
394         }
395
396         switch (pdu->type) {
397
398           case SNMP_PDU_GET:
399                 ret = snmp_get(pdu, &resp_b, &resp, data);
400                 break;
401
402           case SNMP_PDU_GETNEXT:
403                 ret = snmp_getnext(pdu, &resp_b, &resp, data);
404                 break;
405
406           case SNMP_PDU_SET:
407                 ret = snmp_set(pdu, &resp_b, &resp, data);
408                 break;
409
410           case SNMP_PDU_GETBULK:
411                 ret = snmp_getbulk(pdu, &resp_b, &resp, data);
412                 break;
413
414           default:
415                 ret = SNMP_RET_IGN;
416                 break;
417         }
418
419         switch (ret) {
420
421           case SNMP_RET_OK:
422                 /* normal return - send a response */
423                 if (debug.dump_pdus) {
424                         snmp_printf("%s <- ", source);
425                         snmp_pdu_dump(&resp);
426                 }
427                 *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
428                 snmp_pdu_free(&resp);
429                 return (SNMPD_INPUT_OK);
430
431           case SNMP_RET_IGN:
432                 /* error - send nothing */
433                 snmpd_stats.silentDrops++;
434                 return (SNMPD_INPUT_FAILED);
435
436           case SNMP_RET_ERR:
437                 /* error - send error response. The snmp routine has
438                  * changed the error fields in the original message. */
439                 resp_b.asn_ptr = sndbuf;
440                 resp_b.asn_len = snmpd.txbuf;
441                 if (snmp_make_errresp(pdu, &pdu_b, &resp_b) == SNMP_RET_IGN) {
442                         syslog(LOG_WARNING, "could not encode error response");
443                         snmpd_stats.silentDrops++;
444                         return (SNMPD_INPUT_FAILED);
445                 } else {
446                         if (debug.dump_pdus) {
447                                 snmp_printf("%s <- ", source);
448                                 snmp_pdu_dump(pdu);
449                         }
450                         *sndlen = (size_t)(resp_b.asn_ptr - sndbuf);
451                         return (SNMPD_INPUT_OK);
452                 }
453         }
454         abort();
455 }
456
457 /*
458  * Insert a port into the right place in the transport's table of ports
459  */
460 void
461 trans_insert_port(struct transport *t, struct tport *port)
462 {
463         struct tport *p;
464
465         TAILQ_FOREACH(p, &t->table, link) {
466                 if (asn_compare_oid(&p->index, &port->index) > 0) {
467                         TAILQ_INSERT_BEFORE(p, port, link);
468                         return;
469                 }
470         }
471         port->transport = t;
472         TAILQ_INSERT_TAIL(&t->table, port, link);
473 }
474
475 /*
476  * Remove a port from a transport's list
477  */
478 void
479 trans_remove_port(struct tport *port)
480 {
481
482         TAILQ_REMOVE(&port->transport->table, port, link);
483 }
484
485 /*
486  * Find a port on a transport's list
487  */
488 struct tport *
489 trans_find_port(struct transport *t, const struct asn_oid *idx, u_int sub)
490 {
491
492         return (FIND_OBJECT_OID(&t->table, idx, sub));
493 }
494
495 /*
496  * Find next port on a transport's list
497  */
498 struct tport *
499 trans_next_port(struct transport *t, const struct asn_oid *idx, u_int sub)
500 {
501
502         return (NEXT_OBJECT_OID(&t->table, idx, sub));
503 }
504
505 /*
506  * Return first port
507  */
508 struct tport *
509 trans_first_port(struct transport *t)
510 {
511
512         return (TAILQ_FIRST(&t->table));
513 }
514
515 /*
516  * Iterate through all ports until a function returns a 0.
517  */
518 struct tport *
519 trans_iter_port(struct transport *t, int (*func)(struct tport *, intptr_t),
520     intptr_t arg)
521 {
522         struct tport *p;
523
524         TAILQ_FOREACH(p, &t->table, link)
525                 if (func(p, arg) == 0)
526                         return (p);
527         return (NULL);
528 }
529
530 /*
531  * Register a transport
532  */
533 int
534 trans_register(const struct transport_def *def, struct transport **pp)
535 {
536         u_int i;
537         char or_descr[256];
538
539         if ((*pp = malloc(sizeof(**pp))) == NULL)
540                 return (SNMP_ERR_GENERR);
541
542         /* construct index */
543         (*pp)->index.len = strlen(def->name) + 1;
544         (*pp)->index.subs[0] = strlen(def->name);
545         for (i = 0; i < (*pp)->index.subs[0]; i++)
546                 (*pp)->index.subs[i + 1] = def->name[i];
547
548         (*pp)->vtab = def;
549
550         if (FIND_OBJECT_OID(&transport_list, &(*pp)->index, 0) != NULL) {
551                 free(*pp);
552                 return (SNMP_ERR_INCONS_VALUE);
553         }
554
555         /* register module */
556         snprintf(or_descr, sizeof(or_descr), "%s transport mapping", def->name);
557         if (((*pp)->or_index = or_register(&def->id, or_descr, NULL)) == 0) {
558                 free(*pp);
559                 return (SNMP_ERR_GENERR);
560         }
561
562         INSERT_OBJECT_OID((*pp), &transport_list);
563
564         TAILQ_INIT(&(*pp)->table);
565
566         return (SNMP_ERR_NOERROR);
567 }
568
569 /*
570  * Unregister transport
571  */
572 int
573 trans_unregister(struct transport *t)
574 {
575         if (!TAILQ_EMPTY(&t->table))
576                 return (SNMP_ERR_INCONS_VALUE);
577
578         or_unregister(t->or_index);
579         TAILQ_REMOVE(&transport_list, t, link);
580
581         return (SNMP_ERR_NOERROR);
582 }
583
584 /*
585  * File descriptor support
586  */
587 #ifdef USE_LIBBEGEMOT
588 static void
589 input(int fd, int mask __unused, void *uap)
590 #else
591 static void
592 input(evContext ctx __unused, void *uap, int fd, int mask __unused)
593 #endif
594 {
595         struct fdesc *f = uap;
596
597         (*f->func)(fd, f->udata);
598 }
599
600 void
601 fd_suspend(void *p)
602 {
603         struct fdesc *f = p;
604
605 #ifdef USE_LIBBEGEMOT
606         if (f->id >= 0) {
607                 poll_unregister(f->id);
608                 f->id = -1;
609         }
610 #else
611         if (evTestID(f->id)) {
612                 (void)evDeselectFD(evctx, f->id);
613                 evInitID(&f->id);
614         }
615 #endif
616 }
617
618 int
619 fd_resume(void *p)
620 {
621         struct fdesc *f = p;
622         int err;
623
624 #ifdef USE_LIBBEGEMOT
625         if (f->id >= 0)
626                 return (0);
627         if ((f->id = poll_register(f->fd, input, f, POLL_IN)) < 0) {
628                 err = errno;
629                 syslog(LOG_ERR, "select fd %d: %m", f->fd);
630                 errno = err;
631                 return (-1);
632         }
633 #else
634         if (evTestID(f->id))
635                 return (0);
636         if (evSelectFD(evctx, f->fd, EV_READ, input, f, &f->id)) {
637                 err = errno;
638                 syslog(LOG_ERR, "select fd %d: %m", f->fd);
639                 errno = err;
640                 return (-1);
641         }
642 #endif
643         return (0);
644 }
645
646 void *
647 fd_select(int fd, void (*func)(int, void *), void *udata, struct lmodule *mod)
648 {
649         struct fdesc *f;
650         int err;
651
652         if ((f = malloc(sizeof(struct fdesc))) == NULL) {
653                 err = errno;
654                 syslog(LOG_ERR, "fd_select: %m");
655                 errno = err;
656                 return (NULL);
657         }
658         f->fd = fd;
659         f->func = func;
660         f->udata = udata;
661         f->owner = mod;
662 #ifdef USE_LIBBEGEMOT
663         f->id = -1;
664 #else
665         evInitID(&f->id);
666 #endif
667
668         if (fd_resume(f)) {
669                 err = errno;
670                 free(f);
671                 errno = err;
672                 return (NULL);
673         }
674
675         LIST_INSERT_HEAD(&fdesc_list, f, link);
676
677         return (f);
678 }
679
680 void
681 fd_deselect(void *p)
682 {
683         struct fdesc *f = p;
684
685         LIST_REMOVE(f, link);
686         fd_suspend(f);
687         free(f);
688 }
689
690 static void
691 fd_flush(struct lmodule *mod)
692 {
693         struct fdesc *t, *t1;
694
695         t = LIST_FIRST(&fdesc_list);
696         while (t != NULL) {
697                 t1 = LIST_NEXT(t, link);
698                 if (t->owner == mod)
699                         fd_deselect(t);
700                 t = t1;
701         }
702 }
703
704 /*
705  * Consume a message from the input buffer
706  */
707 static void
708 snmp_input_consume(struct port_input *pi)
709 {
710         if (!pi->stream) {
711                 /* always consume everything */
712                 pi->length = 0;
713                 return;
714         }
715         if (pi->consumed >= pi->length) {
716                 /* all bytes consumed */
717                 pi->length = 0;
718                 return;
719         }
720         memmove(pi->buf, pi->buf + pi->consumed, pi->length - pi->consumed);
721         pi->length -= pi->consumed;
722 }
723
724 struct credmsg {
725         struct cmsghdr hdr;
726         struct cmsgcred cred;
727 };
728
729 static void
730 check_priv(struct port_input *pi, struct msghdr *msg)
731 {
732         struct credmsg *cmsg;
733         struct xucred ucred;
734         socklen_t ucredlen;
735
736         pi->priv = 0;
737
738         if (msg->msg_controllen == sizeof(*cmsg)) {
739                 /* process explicitly sends credentials */
740
741                 cmsg = (struct credmsg *)msg->msg_control;
742                 pi->priv = (cmsg->cred.cmcred_euid == 0);
743                 return;
744         }
745
746         /* ok, obtain the accept time credentials */
747         ucredlen = sizeof(ucred);
748
749         if (getsockopt(pi->fd, 0, LOCAL_PEERCRED, &ucred, &ucredlen) == 0 &&
750             ucredlen >= sizeof(ucred) && ucred.cr_version == XUCRED_VERSION)
751                 pi->priv = (ucred.cr_uid == 0);
752 }
753
754 /*
755  * Input from a stream socket.
756  */
757 static int
758 recv_stream(struct port_input *pi)
759 {
760         struct msghdr msg;
761         struct iovec iov[1];
762         ssize_t len;
763         struct credmsg cmsg;
764
765         if (pi->buf == NULL) {
766                 /* no buffer yet - allocate one */
767                 if ((pi->buf = buf_alloc(0)) == NULL) {
768                         /* ups - could not get buffer. Return an error
769                          * the caller must close the transport. */
770                         return (-1);
771                 }
772                 pi->buflen = buf_size(0);
773                 pi->consumed = 0;
774                 pi->length = 0;
775         }
776
777         /* try to get a message */
778         msg.msg_name = pi->peer;
779         msg.msg_namelen = pi->peerlen;
780         msg.msg_iov = iov;
781         msg.msg_iovlen = 1;
782         if (pi->cred) {
783                 msg.msg_control = &cmsg;
784                 msg.msg_controllen = sizeof(cmsg);
785
786                 cmsg.hdr.cmsg_len = sizeof(cmsg);
787                 cmsg.hdr.cmsg_level = SOL_SOCKET;
788                 cmsg.hdr.cmsg_type = SCM_CREDS;
789         } else {
790                 msg.msg_control = NULL;
791                 msg.msg_controllen = 0;
792         }
793         msg.msg_flags = 0;
794
795         iov[0].iov_base = pi->buf + pi->length;
796         iov[0].iov_len = pi->buflen - pi->length;
797
798         len = recvmsg(pi->fd, &msg, 0);
799
800         if (len == -1 || len == 0)
801                 /* receive error */
802                 return (-1);
803
804         pi->length += len;
805
806         if (pi->cred)
807                 check_priv(pi, &msg);
808
809         return (0);
810 }
811
812 /*
813  * Input from a datagram socket.
814  * Each receive should return one datagram.
815  */
816 static int
817 recv_dgram(struct port_input *pi)
818 {
819         u_char embuf[1000];
820         struct msghdr msg;
821         struct iovec iov[1];
822         ssize_t len;
823         struct credmsg cmsg;
824
825         if (pi->buf == NULL) {
826                 /* no buffer yet - allocate one */
827                 if ((pi->buf = buf_alloc(0)) == NULL) {
828                         /* ups - could not get buffer. Read away input
829                          * and drop it */
830                         (void)recvfrom(pi->fd, embuf, sizeof(embuf),
831                             0, NULL, NULL);
832                         /* return error */
833                         return (-1);
834                 }
835                 pi->buflen = buf_size(0);
836         }
837
838         /* try to get a message */
839         msg.msg_name = pi->peer;
840         msg.msg_namelen = pi->peerlen;
841         msg.msg_iov = iov;
842         msg.msg_iovlen = 1;
843         if (pi->cred) {
844                 msg.msg_control = &cmsg;
845                 msg.msg_controllen = sizeof(cmsg);
846
847                 cmsg.hdr.cmsg_len = sizeof(cmsg);
848                 cmsg.hdr.cmsg_level = SOL_SOCKET;
849                 cmsg.hdr.cmsg_type = SCM_CREDS;
850         } else {
851                 msg.msg_control = NULL;
852                 msg.msg_controllen = 0;
853         }
854         msg.msg_flags = 0;
855
856         iov[0].iov_base = pi->buf;
857         iov[0].iov_len = pi->buflen;
858
859         len = recvmsg(pi->fd, &msg, 0);
860
861         if (len == -1 || len == 0)
862                 /* receive error */
863                 return (-1);
864
865         if (msg.msg_flags & MSG_TRUNC) {
866                 /* truncated - drop */
867                 snmpd_stats.silentDrops++;
868                 snmpd_stats.inTooLong++;
869                 return (-1);
870         }
871
872         pi->length = (size_t)len;
873
874         if (pi->cred)
875                 check_priv(pi, &msg);
876
877         return (0);
878 }
879
880 /*
881  * Input from a socket
882  */
883 int
884 snmpd_input(struct port_input *pi, struct tport *tport)
885 {
886         u_char *sndbuf;
887         size_t sndlen;
888         struct snmp_pdu pdu;
889         enum snmpd_input_err ierr, ferr;
890         enum snmpd_proxy_err perr;
891         int32_t vi;
892         int ret;
893         ssize_t slen;
894 #ifdef USE_TCPWRAPPERS
895         char client[16];
896 #endif
897
898         /* get input depending on the transport */
899         if (pi->stream) {
900                 ret = recv_stream(pi);
901         } else {
902                 ret = recv_dgram(pi);
903         }
904
905         if (ret == -1)
906                 return (-1);
907
908 #ifdef USE_TCPWRAPPERS
909         /*
910          * In case of AF_INET{6} peer, do hosts_access(5) check.
911          */
912         if (pi->peer->sa_family != AF_LOCAL &&
913             inet_ntop(pi->peer->sa_family,
914             &((const struct sockaddr_in *)(const void *)pi->peer)->sin_addr,
915             client, sizeof(client)) != NULL) {
916                 request_set(&req, RQ_CLIENT_ADDR, client, 0);
917                 if (hosts_access(&req) == 0) {
918                         syslog(LOG_ERR, "refused connection from %.500s",
919                             eval_client(&req));
920                         return (-1);
921                 }
922         } else if (pi->peer->sa_family != AF_LOCAL)
923                 syslog(LOG_ERR, "inet_ntop(): %m");
924 #endif
925
926         /*
927          * Handle input
928          */
929         ierr = snmp_input_start(pi->buf, pi->length, "SNMP", &pdu, &vi,
930             &pi->consumed);
931         if (ierr == SNMPD_INPUT_TRUNC) {
932                 /* need more bytes. This is ok only for streaming transports.
933                  * but only if we have not reached bufsiz yet. */
934                 if (pi->stream) {
935                         if (pi->length == buf_size(0)) {
936                                 snmpd_stats.silentDrops++;
937                                 return (-1);
938                         }
939                         return (0);
940                 }
941                 snmpd_stats.silentDrops++;
942                 return (-1);
943         }
944
945         /* can't check for bad SET pdus here, because a proxy may have to
946          * check the access first. We don't want to return an error response
947          * to a proxy PDU with a wrong community */
948         if (ierr == SNMPD_INPUT_FAILED) {
949                 /* for streaming transports this is fatal */
950                 if (pi->stream)
951                         return (-1);
952                 snmp_input_consume(pi);
953                 return (0);
954         }
955         if (ierr == SNMPD_INPUT_BAD_COMM) {
956                 snmp_input_consume(pi);
957                 return (0);
958         }
959
960         /*
961          * If that is a module community and the module has a proxy function,
962          * the hand it over to the module.
963          */
964         if (comm->owner != NULL && comm->owner->config->proxy != NULL) {
965                 perr = (*comm->owner->config->proxy)(&pdu, tport->transport,
966                     &tport->index, pi->peer, pi->peerlen, ierr, vi,
967                     !pi->cred || pi->priv);
968
969                 switch (perr) {
970
971                   case SNMPD_PROXY_OK:
972                         snmp_input_consume(pi);
973                         return (0);
974
975                   case SNMPD_PROXY_REJ:
976                         break;
977
978                   case SNMPD_PROXY_DROP:
979                         snmp_input_consume(pi);
980                         snmp_pdu_free(&pdu);
981                         snmpd_stats.proxyDrops++;
982                         return (0);
983
984                   case SNMPD_PROXY_BADCOMM:
985                         snmp_input_consume(pi);
986                         snmp_pdu_free(&pdu);
987                         snmpd_stats.inBadCommunityNames++;
988                         if (snmpd.auth_traps)
989                                 snmp_send_trap(&oid_authenticationFailure,
990                                     (struct snmp_value *)NULL);
991                         return (0);
992
993                   case SNMPD_PROXY_BADCOMMUSE:
994                         snmp_input_consume(pi);
995                         snmp_pdu_free(&pdu);
996                         snmpd_stats.inBadCommunityUses++;
997                         if (snmpd.auth_traps)
998                                 snmp_send_trap(&oid_authenticationFailure,
999                                     (struct snmp_value *)NULL);
1000                         return (0);
1001                 }
1002         }
1003
1004         /*
1005          * Check type
1006          */
1007         if (pdu.type == SNMP_PDU_RESPONSE ||
1008             pdu.type == SNMP_PDU_TRAP ||
1009             pdu.type == SNMP_PDU_TRAP2) {
1010                 snmpd_stats.silentDrops++;
1011                 snmpd_stats.inBadPduTypes++;
1012                 snmp_pdu_free(&pdu);
1013                 snmp_input_consume(pi);
1014                 return (0);
1015         }
1016
1017         /*
1018          * Check community
1019          */
1020         if ((pi->cred && !pi->priv && pdu.type == SNMP_PDU_SET) ||
1021             (community != COMM_WRITE &&
1022             (pdu.type == SNMP_PDU_SET || community != COMM_READ))) {
1023                 snmpd_stats.inBadCommunityUses++;
1024                 snmp_pdu_free(&pdu);
1025                 snmp_input_consume(pi);
1026                 if (snmpd.auth_traps)
1027                         snmp_send_trap(&oid_authenticationFailure,
1028                             (struct snmp_value *)NULL);
1029                 return (0);
1030         }
1031
1032         /*
1033          * Execute it.
1034          */
1035         if ((sndbuf = buf_alloc(1)) == NULL) {
1036                 snmpd_stats.silentDrops++;
1037                 snmp_pdu_free(&pdu);
1038                 snmp_input_consume(pi);
1039                 return (0);
1040         }
1041         ferr = snmp_input_finish(&pdu, pi->buf, pi->length,
1042             sndbuf, &sndlen, "SNMP", ierr, vi, NULL);
1043
1044         if (ferr == SNMPD_INPUT_OK) {
1045                 slen = sendto(pi->fd, sndbuf, sndlen, 0, pi->peer, pi->peerlen);
1046                 if (slen == -1)
1047                         syslog(LOG_ERR, "sendto: %m");
1048                 else if ((size_t)slen != sndlen)
1049                         syslog(LOG_ERR, "sendto: short write %zu/%zu",
1050                             sndlen, (size_t)slen);
1051         }
1052         snmp_pdu_free(&pdu);
1053         free(sndbuf);
1054         snmp_input_consume(pi);
1055
1056         return (0);
1057 }
1058
1059 /*
1060  * Send a PDU to a given port
1061  */
1062 void
1063 snmp_send_port(void *targ, const struct asn_oid *port, struct snmp_pdu *pdu,
1064     const struct sockaddr *addr, socklen_t addrlen)
1065 {
1066         struct transport *trans = targ;
1067         struct tport *tp;
1068         u_char *sndbuf;
1069         size_t sndlen;
1070         ssize_t len;
1071
1072         TAILQ_FOREACH(tp, &trans->table, link)
1073                 if (asn_compare_oid(port, &tp->index) == 0)
1074                         break;
1075         if (tp == 0)
1076                 return;
1077
1078         if ((sndbuf = buf_alloc(1)) == NULL)
1079                 return;
1080
1081         snmp_output(pdu, sndbuf, &sndlen, "SNMP PROXY");
1082
1083         len = trans->vtab->send(tp, sndbuf, sndlen, addr, addrlen);
1084
1085         if (len == -1)
1086                 syslog(LOG_ERR, "sendto: %m");
1087         else if ((size_t)len != sndlen)
1088                 syslog(LOG_ERR, "sendto: short write %zu/%zu",
1089                     sndlen, (size_t)len);
1090
1091         free(sndbuf);
1092 }
1093
1094
1095 /*
1096  * Close an input source
1097  */
1098 void
1099 snmpd_input_close(struct port_input *pi)
1100 {
1101         if (pi->id != NULL)
1102                 fd_deselect(pi->id);
1103         if (pi->fd >= 0)
1104                 (void)close(pi->fd);
1105         if (pi->buf != NULL)
1106                 free(pi->buf);
1107 }
1108
1109 /*
1110  * Dump internal state.
1111  */
1112 #ifdef USE_LIBBEGEMOT
1113 static void
1114 info_func(void)
1115 #else
1116 static void
1117 info_func(evContext ctx __unused, void *uap __unused, const void *tag __unused)
1118 #endif
1119 {
1120         struct lmodule *m;
1121         u_int i;
1122         char buf[10000];
1123
1124         syslog(LOG_DEBUG, "Dump of SNMPd %lu\n", (u_long)getpid());
1125         for (i = 0; i < tree_size; i++) {
1126                 switch (tree[i].type) {
1127
1128                   case SNMP_NODE_LEAF:
1129                         sprintf(buf, "LEAF: %s %s", tree[i].name,
1130                             asn_oid2str(&tree[i].oid));
1131                         break;
1132
1133                   case SNMP_NODE_COLUMN:
1134                         sprintf(buf, "COL: %s %s", tree[i].name,
1135                             asn_oid2str(&tree[i].oid));
1136                         break;
1137                 }
1138                 syslog(LOG_DEBUG, "%s", buf);
1139         }
1140
1141         TAILQ_FOREACH(m, &lmodules, link)
1142                 if (m->config->dump)
1143                         (*m->config->dump)();
1144 }
1145
1146 /*
1147  * Re-read configuration
1148  */
1149 #ifdef USE_LIBBEGEMOT
1150 static void
1151 config_func(void)
1152 #else
1153 static void
1154 config_func(evContext ctx __unused, void *uap __unused,
1155     const void *tag __unused)
1156 #endif
1157 {
1158         struct lmodule *m;
1159
1160         if (read_config(config_file, NULL)) {
1161                 syslog(LOG_ERR, "error reading config file '%s'", config_file);
1162                 return;
1163         }
1164         TAILQ_FOREACH(m, &lmodules, link)
1165                 if (m->config->config)
1166                         (*m->config->config)();
1167 }
1168
1169 /*
1170  * On USR1 dump actual configuration.
1171  */
1172 static void
1173 onusr1(int s __unused)
1174 {
1175
1176         work |= WORK_DOINFO;
1177 }
1178 static void
1179 onhup(int s __unused)
1180 {
1181
1182         work |= WORK_RECONFIG;
1183 }
1184
1185 static void
1186 onterm(int s __unused)
1187 {
1188
1189         /* allow clean-up */
1190         exit(0);
1191 }
1192
1193 static void
1194 init_sigs(void)
1195 {
1196         struct sigaction sa;
1197
1198         sa.sa_handler = onusr1;
1199         sa.sa_flags = SA_RESTART;
1200         sigemptyset(&sa.sa_mask);
1201         if (sigaction(SIGUSR1, &sa, NULL)) {
1202                 syslog(LOG_ERR, "sigaction: %m");
1203                 exit(1);
1204         }
1205
1206         sa.sa_handler = onhup;
1207         if (sigaction(SIGHUP, &sa, NULL)) {
1208                 syslog(LOG_ERR, "sigaction: %m");
1209                 exit(1);
1210         }
1211
1212         sa.sa_handler = onterm;
1213         sa.sa_flags = 0;
1214         sigemptyset(&sa.sa_mask);
1215         if (sigaction(SIGTERM, &sa, NULL)) {
1216                 syslog(LOG_ERR, "sigaction: %m");
1217                 exit(1);
1218         }
1219         if (sigaction(SIGINT, &sa, NULL)) {
1220                 syslog(LOG_ERR, "sigaction: %m");
1221                 exit(1);
1222         }
1223 }
1224
1225 static void
1226 block_sigs(void)
1227 {
1228         sigset_t set;
1229
1230         sigfillset(&set);
1231         if (sigprocmask(SIG_BLOCK, &set, &blocked_sigs) == -1) {
1232                 syslog(LOG_ERR, "SIG_BLOCK: %m");
1233                 exit(1);
1234         }
1235 }
1236 static void
1237 unblock_sigs(void)
1238 {
1239         if (sigprocmask(SIG_SETMASK, &blocked_sigs, NULL) == -1) {
1240                 syslog(LOG_ERR, "SIG_SETMASK: %m");
1241                 exit(1);
1242         }
1243 }
1244
1245 /*
1246  * Shut down
1247  */
1248 static void
1249 term(void)
1250 {
1251         (void)unlink(pid_file);
1252 }
1253
1254 static void
1255 trans_stop(void)
1256 {
1257         struct transport *t;
1258
1259         TAILQ_FOREACH(t, &transport_list, link)
1260                 (void)t->vtab->stop(1);
1261 }
1262
1263 /*
1264  * Define a macro from the command line
1265  */
1266 static void
1267 do_macro(char *arg)
1268 {
1269         char *eq;
1270         int err;
1271
1272         if ((eq = strchr(arg, '=')) == NULL)
1273                 err = define_macro(arg, "");
1274         else {
1275                 *eq++ = '\0';
1276                 err = define_macro(arg, eq);
1277         }
1278         if (err == -1) {
1279                 syslog(LOG_ERR, "cannot save macro: %m");
1280                 exit(1);
1281         }
1282 }
1283
1284 /*
1285  * Re-implement getsubopt from scratch, because the second argument is broken
1286  * and will not compile with WARNS=5.
1287  */
1288 static int
1289 getsubopt1(char **arg, const char *const *options, char **valp, char **optp)
1290 {
1291         static const char *const delim = ",\t ";
1292         u_int i;
1293         char *ptr;
1294
1295         *optp = NULL;
1296
1297         /* skip leading junk */
1298         for (ptr = *arg; *ptr != '\0'; ptr++)
1299                 if (strchr(delim, *ptr) == NULL)
1300                         break;
1301         if (*ptr == '\0') {
1302                 *arg = ptr;
1303                 return (-1);
1304         }
1305         *optp = ptr;
1306
1307         /* find the end of the option */
1308         while (*++ptr != '\0')
1309                 if (strchr(delim, *ptr) != NULL || *ptr == '=')
1310                         break;
1311
1312         if (*ptr != '\0') {
1313                 if (*ptr == '=') {
1314                         *ptr++ = '\0';
1315                         *valp = ptr;
1316                         while (*ptr != '\0' && strchr(delim, *ptr) == NULL)
1317                                 ptr++;
1318                         if (*ptr != '\0')
1319                                 *ptr++ = '\0';
1320                 } else
1321                         *ptr++ = '\0';
1322         }
1323
1324         *arg = ptr;
1325
1326         for (i = 0; *options != NULL; options++, i++)
1327                 if (strcmp(*optp, *options) == 0)
1328                         return (i);
1329         return (-1);
1330 }
1331
1332 int
1333 main(int argc, char *argv[])
1334 {
1335         int opt;
1336         FILE *fp;
1337         int background = 1;
1338         struct tport *p;
1339         const char *prefix = "snmpd";
1340         struct lmodule *m;
1341         char *value, *option;
1342         struct transport *t;
1343
1344 #define DBG_DUMP        0
1345 #define DBG_EVENTS      1
1346 #define DBG_TRACE       2
1347         static const char *const debug_opts[] = {
1348                 "dump",
1349                 "events",
1350                 "trace",
1351                 NULL
1352         };
1353
1354         snmp_printf = snmp_printf_func;
1355         snmp_error = snmp_error_func;
1356         snmp_debug = snmp_debug_func;
1357         asn_error = asn_error_func;
1358
1359         while ((opt = getopt(argc, argv, "c:dD:hI:l:m:p:")) != EOF)
1360                 switch (opt) {
1361
1362                   case 'c':
1363                         strlcpy(config_file, optarg, sizeof(config_file));
1364                         break;
1365
1366                   case 'd':
1367                         background = 0;
1368                         break;
1369
1370                   case 'D':
1371                         while (*optarg) {
1372                                 switch (getsubopt1(&optarg, debug_opts,
1373                                     &value, &option)) {
1374
1375                                   case DBG_DUMP:
1376                                         debug.dump_pdus = 1;
1377                                         break;
1378
1379                                   case DBG_EVENTS:
1380                                         debug.evdebug++;
1381                                         break;
1382
1383                                   case DBG_TRACE:
1384                                         if (value == NULL)
1385                                                 syslog(LOG_ERR,
1386                                                     "no value for 'trace'");
1387                                         else
1388                                                 snmp_trace = strtoul(value,
1389                                                     NULL, 0);
1390                                         break;
1391
1392                                   case -1:
1393                                         if (suboptarg)
1394                                                 syslog(LOG_ERR,
1395                                                     "unknown debug flag '%s'",
1396                                                     option);
1397                                         else
1398                                                 syslog(LOG_ERR,
1399                                                     "missing debug flag");
1400                                         break;
1401                                 }
1402                         }
1403                         break;
1404
1405                   case 'h':
1406                         fprintf(stderr, "%s", usgtxt);
1407                         exit(0);
1408
1409                   case 'I':
1410                         syspath = optarg;
1411                         break;
1412
1413                   case 'l':
1414                         prefix = optarg;
1415                         break;
1416
1417                   case 'm':
1418                         do_macro(optarg);
1419                         break;
1420
1421                   case 'p':
1422                         strlcpy(pid_file, optarg, sizeof(pid_file));
1423                         break;
1424                 }
1425
1426         openlog(prefix, LOG_PID | (background ? 0 : LOG_PERROR), LOG_USER);
1427         setlogmask(LOG_UPTO(debug.logpri - 1));
1428
1429         if (background && daemon(0, 0) < 0) {
1430                 syslog(LOG_ERR, "daemon: %m");
1431                 exit(1);
1432         }
1433
1434         argc -= optind;
1435         argv += optind;
1436
1437         progargs = argv;
1438         nprogargs = argc;
1439
1440         srandomdev();
1441
1442         snmp_serial_no = random();
1443
1444 #ifdef USE_TCPWRAPPERS
1445         /*
1446          * Initialize hosts_access(3) handler.
1447          */
1448         request_init(&req, RQ_DAEMON, "snmpd", 0);
1449         sock_methods(&req);
1450 #endif
1451
1452         /*
1453          * Initialize the tree.
1454          */
1455         if ((tree = malloc(sizeof(struct snmp_node) * CTREE_SIZE)) == NULL) {
1456                 syslog(LOG_ERR, "%m");
1457                 exit(1);
1458         }
1459         memcpy(tree, ctree, sizeof(struct snmp_node) * CTREE_SIZE);
1460         tree_size = CTREE_SIZE;
1461
1462         /*
1463          * Get standard communities
1464          */
1465         (void)comm_define(1, "SNMP read", NULL, NULL);
1466         (void)comm_define(2, "SNMP write", NULL, NULL);
1467         community = COMM_INITIALIZE;
1468
1469         trap_reqid = reqid_allocate(512, NULL);
1470
1471         if (config_file[0] == '\0')
1472                 snprintf(config_file, sizeof(config_file), PATH_CONFIG, prefix);
1473
1474         init_actvals();
1475
1476         this_tick = get_ticks();
1477         start_tick = this_tick;
1478
1479         /* start transports */
1480         if (atexit(trans_stop) == -1) {
1481                 syslog(LOG_ERR, "atexit failed: %m");
1482                 exit(1);
1483         }
1484         if (udp_trans.start() != SNMP_ERR_NOERROR)
1485                 syslog(LOG_WARNING, "cannot start UDP transport");
1486         if (lsock_trans.start() != SNMP_ERR_NOERROR)
1487                 syslog(LOG_WARNING, "cannot start LSOCK transport");
1488
1489 #ifdef USE_LIBBEGEMOT
1490         if (debug.evdebug > 0)
1491                 rpoll_trace = 1;
1492 #else
1493         if (evCreate(&evctx)) {
1494                 syslog(LOG_ERR, "evCreate: %m");
1495                 exit(1);
1496         }
1497         if (debug.evdebug > 0)
1498                 evSetDebug(evctx, 10, stderr);
1499 #endif
1500
1501         if (read_config(config_file, NULL)) {
1502                 syslog(LOG_ERR, "error in config file");
1503                 exit(1);
1504         }
1505
1506         TAILQ_FOREACH(t, &transport_list, link)
1507                 TAILQ_FOREACH(p, &t->table, link)
1508                         t->vtab->init_port(p);
1509
1510         init_sigs();
1511
1512         if (pid_file[0] == '\0')
1513                 snprintf(pid_file, sizeof(pid_file), PATH_PID, prefix);
1514
1515         if ((fp = fopen(pid_file, "w")) != NULL) {
1516                 fprintf(fp, "%u", getpid());
1517                 fclose(fp);
1518                 if (atexit(term) == -1) {
1519                         syslog(LOG_ERR, "atexit failed: %m");
1520                         (void)remove(pid_file);
1521                         exit(0);
1522                 }
1523         }
1524
1525         if (or_register(&oid_snmpMIB, "The MIB module for SNMPv2 entities.",
1526             NULL) == 0) {
1527                 syslog(LOG_ERR, "cannot register SNMPv2 MIB");
1528                 exit(1);
1529         }
1530         if (or_register(&oid_begemotSnmpd, "The MIB module for the Begemot SNMPd.",
1531             NULL) == 0) {
1532                 syslog(LOG_ERR, "cannot register begemotSnmpd MIB");
1533                 exit(1);
1534         }
1535
1536         snmp_send_trap(&oid_coldStart, (struct snmp_value *)NULL);
1537
1538         while ((m = TAILQ_FIRST(&modules_start)) != NULL) {
1539                 m->flags &= ~LM_ONSTARTLIST;
1540                 TAILQ_REMOVE(&modules_start, m, start);
1541                 lm_start(m);
1542         }
1543
1544         for (;;) {
1545 #ifndef USE_LIBBEGEMOT
1546                 evEvent event;
1547 #endif
1548                 struct lmodule *mod;
1549
1550                 TAILQ_FOREACH(mod, &lmodules, link)
1551                         if (mod->config->idle != NULL)
1552                                 (*mod->config->idle)();
1553
1554 #ifndef USE_LIBBEGEMOT
1555                 if (evGetNext(evctx, &event, EV_WAIT) == 0) {
1556                         if (evDispatch(evctx, event))
1557                                 syslog(LOG_ERR, "evDispatch: %m");
1558                 } else if (errno != EINTR) {
1559                         syslog(LOG_ERR, "evGetNext: %m");
1560                         exit(1);
1561                 }
1562 #else
1563                 poll_dispatch(1);
1564 #endif
1565
1566                 if (work != 0) {
1567                         block_sigs();
1568                         if (work & WORK_DOINFO) {
1569 #ifdef USE_LIBBEGEMOT
1570                                 info_func();
1571 #else
1572                                 if (evWaitFor(evctx, &work, info_func,
1573                                     NULL, NULL) == -1) {
1574                                         syslog(LOG_ERR, "evWaitFor: %m");
1575                                         exit(1);
1576                                 }
1577 #endif
1578                         }
1579                         if (work & WORK_RECONFIG) {
1580 #ifdef USE_LIBBEGEMOT
1581                                 config_func();
1582 #else
1583                                 if (evWaitFor(evctx, &work, config_func,
1584                                     NULL, NULL) == -1) {
1585                                         syslog(LOG_ERR, "evWaitFor: %m");
1586                                         exit(1);
1587                                 }
1588 #endif
1589                         }
1590                         work = 0;
1591                         unblock_sigs();
1592 #ifndef USE_LIBBEGEMOT
1593                         if (evDo(evctx, &work) == -1) {
1594                                 syslog(LOG_ERR, "evDo: %m");
1595                                 exit(1);
1596                         }
1597 #endif
1598                 }
1599         }
1600
1601         return (0);
1602 }
1603
1604 uint64_t
1605 get_ticks()
1606 {
1607         struct timeval tv;
1608         uint64_t ret;
1609
1610         if (gettimeofday(&tv, NULL))
1611                 abort();
1612         ret = tv.tv_sec * 100ULL + tv.tv_usec / 10000ULL;
1613         return (ret);
1614 }
1615
1616 /*
1617  * Timer support
1618  */
1619
1620 /*
1621  * Trampoline for the non-repeatable timers.
1622  */
1623 #ifdef USE_LIBBEGEMOT
1624 static void
1625 tfunc(int tid __unused, void *uap)
1626 #else
1627 static void
1628 tfunc(evContext ctx __unused, void *uap, struct timespec due __unused,
1629         struct timespec inter __unused)
1630 #endif
1631 {
1632         struct timer *tp = uap;
1633
1634         LIST_REMOVE(tp, link);
1635         tp->func(tp->udata);
1636         free(tp);
1637 }
1638
1639 /*
1640  * Trampoline for the repeatable timers.
1641  */
1642 #ifdef USE_LIBBEGEMOT
1643 static void
1644 trfunc(int tid __unused, void *uap)
1645 #else
1646 static void
1647 trfunc(evContext ctx __unused, void *uap, struct timespec due __unused,
1648         struct timespec inter __unused)
1649 #endif
1650 {
1651         struct timer *tp = uap;
1652
1653         tp->func(tp->udata);
1654 }
1655
1656 /*
1657  * Start a one-shot timer
1658  */
1659 void *
1660 timer_start(u_int ticks, void (*func)(void *), void *udata, struct lmodule *mod)
1661 {
1662         struct timer *tp;
1663 #ifndef USE_LIBBEGEMOT
1664         struct timespec due;
1665 #endif
1666
1667         if ((tp = malloc(sizeof(struct timer))) == NULL) {
1668                 syslog(LOG_CRIT, "out of memory for timer");
1669                 exit(1);
1670         }
1671
1672 #ifndef USE_LIBBEGEMOT
1673         due = evAddTime(evNowTime(),
1674             evConsTime(ticks / 100, (ticks % 100) * 10000));
1675 #endif
1676
1677         tp->udata = udata;
1678         tp->owner = mod;
1679         tp->func = func;
1680
1681         LIST_INSERT_HEAD(&timer_list, tp, link);
1682
1683 #ifdef USE_LIBBEGEMOT
1684         if ((tp->id = poll_start_timer(ticks * 10, 0, tfunc, tp)) < 0) {
1685                 syslog(LOG_ERR, "cannot set timer: %m");
1686                 exit(1);
1687         }
1688 #else
1689         if (evSetTimer(evctx, tfunc, tp, due, evConsTime(0, 0), &tp->id)
1690             == -1) {
1691                 syslog(LOG_ERR, "cannot set timer: %m");
1692                 exit(1);
1693         }
1694 #endif
1695         return (tp);
1696 }
1697
1698 /*
1699  * Start a repeatable timer. When used with USE_LIBBEGEMOT the first argument
1700  * is currently ignored and the initial number of ticks is set to the
1701  * repeat number of ticks.
1702  */
1703 void *
1704 timer_start_repeat(u_int ticks __unused, u_int repeat_ticks,
1705     void (*func)(void *), void *udata, struct lmodule *mod)
1706 {
1707         struct timer *tp;
1708 #ifndef USE_LIBBEGEMOT
1709         struct timespec due;
1710         struct timespec inter;
1711 #endif
1712
1713         if ((tp = malloc(sizeof(struct timer))) == NULL) {
1714                 syslog(LOG_CRIT, "out of memory for timer");
1715                 exit(1);
1716         }
1717
1718 #ifndef USE_LIBBEGEMOT
1719         due = evAddTime(evNowTime(),
1720             evConsTime(ticks / 100, (ticks % 100) * 10000));
1721         inter = evConsTime(repeat_ticks / 100, (repeat_ticks % 100) * 10000);
1722 #endif
1723
1724         tp->udata = udata;
1725         tp->owner = mod;
1726         tp->func = func;
1727
1728         LIST_INSERT_HEAD(&timer_list, tp, link);
1729
1730 #ifdef USE_LIBBEGEMOT
1731         if ((tp->id = poll_start_timer(repeat_ticks * 10, 1, trfunc, tp)) < 0) {
1732                 syslog(LOG_ERR, "cannot set timer: %m");
1733                 exit(1);
1734         }
1735 #else
1736         if (evSetTimer(evctx, trfunc, tp, due, inter, &tp->id) == -1) {
1737                 syslog(LOG_ERR, "cannot set timer: %m");
1738                 exit(1);
1739         }
1740 #endif
1741         return (tp);
1742 }
1743
1744 /*
1745  * Stop a timer.
1746  */
1747 void
1748 timer_stop(void *p)
1749 {
1750         struct timer *tp = p;
1751
1752         LIST_REMOVE(tp, link);
1753 #ifdef USE_LIBBEGEMOT
1754         poll_stop_timer(tp->id);
1755 #else
1756         if (evClearTimer(evctx, tp->id) == -1) {
1757                 syslog(LOG_ERR, "cannot stop timer: %m");
1758                 exit(1);
1759         }
1760 #endif
1761         free(p);
1762 }
1763
1764 static void
1765 timer_flush(struct lmodule *mod)
1766 {
1767         struct timer *t, *t1;
1768
1769         t = LIST_FIRST(&timer_list);
1770         while (t != NULL) {
1771                 t1 = LIST_NEXT(t, link);
1772                 if (t->owner == mod)
1773                         timer_stop(t);
1774                 t = t1;
1775         }
1776 }
1777
1778 static void
1779 snmp_printf_func(const char *fmt, ...)
1780 {
1781         va_list ap;
1782         static char *pend = NULL;
1783         char *ret, *new;
1784
1785         va_start(ap, fmt);
1786         vasprintf(&ret, fmt, ap);
1787         va_end(ap);
1788
1789         if (ret == NULL)
1790                 return;
1791         if (pend != NULL) {
1792                 if ((new = realloc(pend, strlen(pend) + strlen(ret) + 1))
1793                     == NULL) {
1794                         free(ret);
1795                         return;
1796                 }
1797                 pend = new;
1798                 strcat(pend, ret);
1799                 free(ret);
1800         } else
1801                 pend = ret;
1802
1803         while ((ret = strchr(pend, '\n')) != NULL) {
1804                 *ret = '\0';
1805                 syslog(LOG_DEBUG, "%s", pend);
1806                 if (strlen(ret + 1) == 0) {
1807                         free(pend);
1808                         pend = NULL;
1809                         break;
1810                 }
1811                 strcpy(pend, ret + 1);
1812         }
1813 }
1814
1815 static void
1816 snmp_error_func(const char *err, ...)
1817 {
1818         char errbuf[1000];
1819         va_list ap;
1820
1821         if (!(snmp_trace & LOG_SNMP_ERRORS))
1822                 return;
1823
1824         va_start(ap, err);
1825         snprintf(errbuf, sizeof(errbuf), "SNMP: ");
1826         vsnprintf(errbuf + strlen(errbuf),
1827             sizeof(errbuf) - strlen(errbuf), err, ap);
1828         va_end(ap);
1829
1830         syslog(LOG_ERR, "%s", errbuf);
1831 }
1832
1833 static void
1834 snmp_debug_func(const char *err, ...)
1835 {
1836         char errbuf[1000];
1837         va_list ap;
1838
1839         va_start(ap, err);
1840         snprintf(errbuf, sizeof(errbuf), "SNMP: ");
1841         vsnprintf(errbuf+strlen(errbuf), sizeof(errbuf)-strlen(errbuf),
1842             err, ap);
1843         va_end(ap);
1844
1845         syslog(LOG_DEBUG, "%s", errbuf);
1846 }
1847
1848 static void
1849 asn_error_func(const struct asn_buf *b, const char *err, ...)
1850 {
1851         char errbuf[1000];
1852         va_list ap;
1853         u_int i;
1854
1855         if (!(snmp_trace & LOG_ASN1_ERRORS))
1856                 return;
1857
1858         va_start(ap, err);
1859         snprintf(errbuf, sizeof(errbuf), "ASN.1: ");
1860         vsnprintf(errbuf + strlen(errbuf),
1861             sizeof(errbuf) - strlen(errbuf), err, ap);
1862         va_end(ap);
1863
1864         if (b != NULL) {
1865                 snprintf(errbuf + strlen(errbuf),
1866                     sizeof(errbuf) - strlen(errbuf), " at");
1867                 for (i = 0; b->asn_len > i; i++)
1868                         snprintf(errbuf + strlen(errbuf),
1869                             sizeof(errbuf) - strlen(errbuf),
1870                             " %02x", b->asn_cptr[i]);
1871         }
1872
1873         syslog(LOG_ERR, "%s", errbuf);
1874 }
1875
1876 /*
1877  * Create a new community
1878  */
1879 u_int
1880 comm_define(u_int priv, const char *descr, struct lmodule *owner,
1881     const char *str)
1882 {
1883         struct community *c, *p;
1884         u_int ncomm;
1885
1886         /* generate an identifier */
1887         do {
1888                 if ((ncomm = next_community_index++) == UINT_MAX)
1889                         next_community_index = 1;
1890                 TAILQ_FOREACH(c, &community_list, link)
1891                         if (c->value == ncomm)
1892                                 break;
1893         } while (c != NULL);
1894
1895         if ((c = malloc(sizeof(struct community))) == NULL) {
1896                 syslog(LOG_ERR, "comm_define: %m");
1897                 return (0);
1898         }
1899         c->owner = owner;
1900         c->value = ncomm;
1901         c->descr = descr;
1902         c->string = NULL;
1903         c->private = priv;
1904
1905         if (str != NULL) {
1906                 if((c->string = malloc(strlen(str)+1)) == NULL) {
1907                         free(c);
1908                         return (0);
1909                 }
1910                 strcpy(c->string, str);
1911         }
1912
1913         /* make index */
1914         if (c->owner == NULL) {
1915                 c->index.len = 1;
1916                 c->index.subs[0] = 0;
1917         } else {
1918                 c->index = c->owner->index;
1919         }
1920         c->index.subs[c->index.len++] = c->private;
1921
1922         /*
1923          * Insert ordered
1924          */
1925         TAILQ_FOREACH(p, &community_list, link) {
1926                 if (asn_compare_oid(&p->index, &c->index) > 0) {
1927                         TAILQ_INSERT_BEFORE(p, c, link);
1928                         break;
1929                 }
1930         }
1931         if (p == NULL)
1932                 TAILQ_INSERT_TAIL(&community_list, c, link);
1933         return (c->value);
1934 }
1935
1936 const char *
1937 comm_string(u_int ncomm)
1938 {
1939         struct community *p;
1940
1941         TAILQ_FOREACH(p, &community_list, link)
1942                 if (p->value == ncomm)
1943                         return (p->string);
1944         return (NULL);
1945 }
1946
1947 /*
1948  * Delete all communities allocated by a module
1949  */
1950 static void
1951 comm_flush(struct lmodule *mod)
1952 {
1953         struct community *p, *p1;
1954
1955         p = TAILQ_FIRST(&community_list);
1956         while (p != NULL) {
1957                 p1 = TAILQ_NEXT(p, link);
1958                 if (p->owner == mod) {
1959                         free(p->string);
1960                         TAILQ_REMOVE(&community_list, p, link);
1961                         free(p);
1962                 }
1963                 p = p1;
1964         }
1965 }
1966
1967 /*
1968  * Request ID handling.
1969  *
1970  * Allocate a new range of request ids. Use a first fit algorithm.
1971  */
1972 u_int
1973 reqid_allocate(int size, struct lmodule *mod)
1974 {
1975         u_int type;
1976         struct idrange *r, *r1;
1977
1978         if (size <= 0 || size > INT32_MAX) {
1979                 syslog(LOG_CRIT, "%s: size out of range: %d", __func__, size);
1980                 return (0);
1981         }
1982         /* allocate a type id */
1983         do {
1984                 if ((type = next_idrange++) == UINT_MAX)
1985                         next_idrange = 1;
1986                 TAILQ_FOREACH(r, &idrange_list, link)
1987                         if (r->type == type)
1988                                 break;
1989         } while(r != NULL);
1990
1991         /* find a range */
1992         if (TAILQ_EMPTY(&idrange_list))
1993                 r = NULL;
1994         else {
1995                 r = TAILQ_FIRST(&idrange_list);
1996                 if (r->base < size) {
1997                         while((r1 = TAILQ_NEXT(r, link)) != NULL) {
1998                                 if (r1->base - (r->base + r->size) >= size)
1999                                         break;
2000                                 r = r1;
2001                         }
2002                         r = r1;
2003                 }
2004                 if (r == NULL) {
2005                         r1 = TAILQ_LAST(&idrange_list, idrange_list);
2006                         if (INT32_MAX - size + 1 < r1->base + r1->size) {
2007                                 syslog(LOG_ERR, "out of id ranges (%u)", size);
2008                                 return (0);
2009                         }
2010                 }
2011         }
2012
2013         /* allocate structure */
2014         if ((r1 = malloc(sizeof(struct idrange))) == NULL) {
2015                 syslog(LOG_ERR, "%s: %m", __FUNCTION__);
2016                 return (0);
2017         }
2018
2019         r1->type = type;
2020         r1->size = size;
2021         r1->owner = mod;
2022         if (TAILQ_EMPTY(&idrange_list) || r == TAILQ_FIRST(&idrange_list)) {
2023                 r1->base = 0;
2024                 TAILQ_INSERT_HEAD(&idrange_list, r1, link);
2025         } else if (r == NULL) {
2026                 r = TAILQ_LAST(&idrange_list, idrange_list);
2027                 r1->base = r->base + r->size;
2028                 TAILQ_INSERT_TAIL(&idrange_list, r1, link);
2029         } else {
2030                 r = TAILQ_PREV(r, idrange_list, link);
2031                 r1->base = r->base + r->size;
2032                 TAILQ_INSERT_AFTER(&idrange_list, r, r1, link);
2033         }
2034         r1->next = r1->base;
2035
2036         return (type);
2037 }
2038
2039 int32_t
2040 reqid_next(u_int type)
2041 {
2042         struct idrange *r;
2043         int32_t id;
2044
2045         TAILQ_FOREACH(r, &idrange_list, link)
2046                 if (r->type == type)
2047                         break;
2048         if (r == NULL) {
2049                 syslog(LOG_CRIT, "wrong idrange type");
2050                 abort();
2051         }
2052         if ((id = r->next++) == r->base + (r->size - 1))
2053                 r->next = r->base;
2054         return (id);
2055 }
2056
2057 int32_t
2058 reqid_base(u_int type)
2059 {
2060         struct idrange *r;
2061
2062         TAILQ_FOREACH(r, &idrange_list, link)
2063                 if (r->type == type)
2064                         return (r->base);
2065         syslog(LOG_CRIT, "wrong idrange type");
2066         abort();
2067 }
2068
2069 u_int
2070 reqid_type(int32_t reqid)
2071 {
2072         struct idrange *r;
2073
2074         TAILQ_FOREACH(r, &idrange_list, link)
2075                 if (reqid >= r->base && reqid <= r->base + (r->size - 1))
2076                         return (r->type);
2077         return (0);
2078 }
2079
2080 int
2081 reqid_istype(int32_t reqid, u_int type)
2082 {
2083         return (reqid_type(reqid) == type);
2084 }
2085
2086 /*
2087  * Delete all communities allocated by a module
2088  */
2089 static void
2090 reqid_flush(struct lmodule *mod)
2091 {
2092         struct idrange *p, *p1;
2093
2094         p = TAILQ_FIRST(&idrange_list);
2095         while (p != NULL) {
2096                 p1 = TAILQ_NEXT(p, link);
2097                 if (p->owner == mod) {
2098                         TAILQ_REMOVE(&idrange_list, p, link);
2099                         free(p);
2100                 }
2101                 p = p1;
2102         }
2103 }
2104
2105 /*
2106  * Merge the given tree for the given module into the main tree.
2107  */
2108 static int
2109 compare_node(const void *v1, const void *v2)
2110 {
2111         const struct snmp_node *n1 = v1;
2112         const struct snmp_node *n2 = v2;
2113
2114         return (asn_compare_oid(&n1->oid, &n2->oid));
2115 }
2116 static int
2117 tree_merge(const struct snmp_node *ntree, u_int nsize, struct lmodule *mod)
2118 {
2119         struct snmp_node *xtree;
2120         u_int i;
2121
2122         xtree = realloc(tree, sizeof(*tree) * (tree_size + nsize));
2123         if (xtree == NULL) {
2124                 syslog(LOG_ERR, "tree_merge: %m");
2125                 return (-1);
2126         }
2127         tree = xtree;
2128         memcpy(&tree[tree_size], ntree, sizeof(*tree) * nsize);
2129
2130         for (i = 0; i < nsize; i++)
2131                 tree[tree_size + i].tree_data = mod;
2132
2133         tree_size += nsize;
2134
2135         qsort(tree, tree_size, sizeof(tree[0]), compare_node);
2136
2137         return (0);
2138 }
2139
2140 /*
2141  * Remove all nodes belonging to the loadable module
2142  */
2143 static void
2144 tree_unmerge(struct lmodule *mod)
2145 {
2146         u_int s, d;
2147
2148         for(s = d = 0; s < tree_size; s++)
2149                 if (tree[s].tree_data != mod) {
2150                         if (s != d)
2151                                 tree[d] = tree[s];
2152                         d++;
2153                 }
2154         tree_size = d;
2155 }
2156
2157 /*
2158  * Loadable modules
2159  */
2160 struct lmodule *
2161 lm_load(const char *path, const char *section)
2162 {
2163         struct lmodule *m;
2164         int err;
2165         int i;
2166         char *av[MAX_MOD_ARGS + 1];
2167         int ac;
2168         u_int u;
2169
2170         if ((m = malloc(sizeof(*m))) == NULL) {
2171                 syslog(LOG_ERR, "lm_load: %m");
2172                 return (NULL);
2173         }
2174         m->handle = NULL;
2175         m->flags = 0;
2176         strcpy(m->section, section);
2177
2178         if ((m->path = malloc(strlen(path) + 1)) == NULL) {
2179                 syslog(LOG_ERR, "lm_load: %m");
2180                 goto err;
2181         }
2182         strcpy(m->path, path);
2183
2184         /*
2185          * Make index
2186          */
2187         m->index.subs[0] = strlen(section);
2188         m->index.len = m->index.subs[0] + 1;
2189         for (u = 0; u < m->index.subs[0]; u++)
2190                 m->index.subs[u + 1] = section[u];
2191
2192         /*
2193          * Load the object file and locate the config structure
2194          */
2195         if ((m->handle = dlopen(m->path, RTLD_NOW|RTLD_GLOBAL)) == NULL) {
2196                 syslog(LOG_ERR, "lm_load: open %s", dlerror());
2197                 goto err;
2198         }
2199
2200         if ((m->config = dlsym(m->handle, "config")) == NULL) {
2201                 syslog(LOG_ERR, "lm_load: no 'config' symbol %s", dlerror());
2202                 goto err;
2203         }
2204
2205         /*
2206          * Insert it into the right place
2207          */
2208         INSERT_OBJECT_OID(m, &lmodules);
2209
2210         /* preserve order */
2211         if (community == COMM_INITIALIZE) {
2212                 m->flags |= LM_ONSTARTLIST;
2213                 TAILQ_INSERT_TAIL(&modules_start, m, start);
2214         }
2215
2216         /*
2217          * make the argument vector.
2218          */
2219         ac = 0;
2220         for (i = 0; i < nprogargs; i++) {
2221                 if (strlen(progargs[i]) >= strlen(section) + 1 &&
2222                     strncmp(progargs[i], section, strlen(section)) == 0 &&
2223                     progargs[i][strlen(section)] == ':') {
2224                         if (ac == MAX_MOD_ARGS) {
2225                                 syslog(LOG_WARNING, "too many arguments for "
2226                                     "module '%s", section);
2227                                 break;
2228                         }
2229                         av[ac++] = &progargs[i][strlen(section)+1];
2230                 }
2231         }
2232         av[ac] = NULL;
2233
2234         /*
2235          * Run the initialization function
2236          */
2237         if ((err = (*m->config->init)(m, ac, av)) != 0) {
2238                 syslog(LOG_ERR, "lm_load: init failed: %d", err);
2239                 TAILQ_REMOVE(&lmodules, m, link);
2240                 goto err;
2241         }
2242
2243         return (m);
2244
2245   err:
2246         if ((m->flags & LM_ONSTARTLIST) != 0)
2247                 TAILQ_REMOVE(&modules_start, m, start);
2248         if (m->handle)
2249                 dlclose(m->handle);
2250         free(m->path);
2251         free(m);
2252         return (NULL);
2253 }
2254
2255 /*
2256  * Start a module
2257  */
2258 void
2259 lm_start(struct lmodule *mod)
2260 {
2261         const struct lmodule *m;
2262
2263         /*
2264          * Merge tree. If this fails, unload the module.
2265          */
2266         if (tree_merge(mod->config->tree, mod->config->tree_size, mod)) {
2267                 lm_unload(mod);
2268                 return;
2269         }
2270
2271         /*
2272          * Read configuration
2273          */
2274         if (read_config(config_file, mod)) {
2275                 syslog(LOG_ERR, "error in config file");
2276                 lm_unload(mod);
2277                 return;
2278         }
2279         if (mod->config->start)
2280                 (*mod->config->start)();
2281
2282         mod->flags |= LM_STARTED;
2283
2284         /*
2285          * Inform other modules
2286          */
2287         TAILQ_FOREACH(m, &lmodules, link)
2288                 if (m->config->loading)
2289                         (*m->config->loading)(mod, 1);
2290 }
2291
2292
2293 /*
2294  * Unload a module.
2295  */
2296 void
2297 lm_unload(struct lmodule *m)
2298 {
2299         int err;
2300         const struct lmodule *mod;
2301
2302         TAILQ_REMOVE(&lmodules, m, link);
2303         if (m->flags & LM_ONSTARTLIST)
2304                 TAILQ_REMOVE(&modules_start, m, start);
2305         tree_unmerge(m);
2306
2307         if ((m->flags & LM_STARTED) && m->config->fini &&
2308             (err = (*m->config->fini)()) != 0)
2309                 syslog(LOG_WARNING, "lm_unload(%s): fini %d", m->section, err);
2310
2311         comm_flush(m);
2312         reqid_flush(m);
2313         timer_flush(m);
2314         fd_flush(m);
2315
2316         dlclose(m->handle);
2317         free(m->path);
2318
2319         /*
2320          * Inform other modules
2321          */
2322         TAILQ_FOREACH(mod, &lmodules, link)
2323                 if (mod->config->loading)
2324                         (*mod->config->loading)(m, 0);
2325
2326         free(m);
2327 }
2328
2329 /*
2330  * Register an object resource and return the index (or 0 on failures)
2331  */
2332 u_int
2333 or_register(const struct asn_oid *or, const char *descr, struct lmodule *mod)
2334 {
2335         struct objres *objres, *or1;
2336         u_int idx;
2337
2338         /* find a free index */
2339         idx = 1;
2340         for (objres = TAILQ_FIRST(&objres_list);
2341              objres != NULL;
2342              objres = TAILQ_NEXT(objres, link)) {
2343                 if ((or1 = TAILQ_NEXT(objres, link)) == NULL ||
2344                     or1->index > objres->index + 1) {
2345                         idx = objres->index + 1;
2346                         break;
2347                 }
2348         }
2349
2350         if ((objres = malloc(sizeof(*objres))) == NULL)
2351                 return (0);
2352
2353         objres->index = idx;
2354         objres->oid = *or;
2355         strlcpy(objres->descr, descr, sizeof(objres->descr));
2356         objres->uptime = (uint32_t)(get_ticks() - start_tick);
2357         objres->module = mod;
2358
2359         INSERT_OBJECT_INT(objres, &objres_list);
2360
2361         systemg.or_last_change = objres->uptime;
2362
2363         return (idx);
2364 }
2365
2366 void
2367 or_unregister(u_int idx)
2368 {
2369         struct objres *objres;
2370
2371         TAILQ_FOREACH(objres, &objres_list, link)
2372                 if (objres->index == idx) {
2373                         TAILQ_REMOVE(&objres_list, objres, link);
2374                         free(objres);
2375                         return;
2376                 }
2377 }