Coverage Report

Created: 2026-12-01 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/net-snmp/snmplib/snmp_api.c
Line
Count
Source
1
2
/* Portions of this file are subject to the following copyright(s).  See
3
 * the Net-SNMP's COPYING file for more details and other copyrights
4
 * that may apply:
5
 */
6
/******************************************************************
7
  Copyright 1989, 1991, 1992 by Carnegie Mellon University
8
9
                      All Rights Reserved
10
11
Permission to use, copy, modify, and distribute this software and its
12
documentation for any purpose and without fee is hereby granted,
13
provided that the above copyright notice appear in all copies and that
14
both that copyright notice and this permission notice appear in
15
supporting documentation, and that the name of CMU not be
16
used in advertising or publicity pertaining to distribution of the
17
software without specific, written prior permission.
18
19
CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
20
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
21
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
22
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
23
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
24
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
25
SOFTWARE.
26
******************************************************************/
27
/*
28
 * Portions of this file are copyrighted by:
29
 * Copyright Copyright 2003 Sun Microsystems, Inc. All rights reserved.
30
 * Use is subject to license terms specified in the COPYING file
31
 * distributed with the Net-SNMP package.
32
 *
33
 * Portions of this file are copyrighted by:
34
 * Copyright (c) 2016 VMware, Inc. All rights reserved.
35
 * Use is subject to license terms specified in the COPYING file
36
 * distributed with the Net-SNMP package.
37
 */
38
39
/** @defgroup library The Net-SNMP library
40
 *  @{
41
 */
42
/*
43
 * snmp_api.c - API for access to snmp.
44
 */
45
#include <net-snmp/net-snmp-config.h>
46
#include <net-snmp/net-snmp-features.h>
47
48
#include <stdio.h>
49
#include <ctype.h>
50
#ifdef HAVE_STDLIB_H
51
#include <stdlib.h>
52
#endif
53
#ifdef HAVE_STRING_H
54
#include <string.h>
55
#else
56
#include <strings.h>
57
#endif
58
#ifdef HAVE_UNISTD_H
59
#include <unistd.h>
60
#endif
61
#include <sys/types.h>
62
#ifdef HAVE_SYS_PARAM_H
63
#include <sys/param.h>
64
#endif
65
#ifdef TIME_WITH_SYS_TIME
66
# include <sys/time.h>
67
# include <time.h>
68
#else
69
# ifdef HAVE_SYS_TIME_H
70
#  include <sys/time.h>
71
# else
72
#  include <time.h>
73
# endif
74
#endif
75
#ifdef HAVE_NETINET_IN_H
76
#include <netinet/in.h>
77
#endif
78
#ifdef HAVE_ARPA_INET_H
79
#include <arpa/inet.h>
80
#endif
81
#ifdef HAVE_SYS_SELECT_H
82
#include <sys/select.h>
83
#endif
84
#ifdef HAVE_IO_H
85
#include <io.h>
86
#endif
87
#ifdef HAVE_SYS_SOCKET_H
88
#include <sys/socket.h>
89
#endif
90
#ifdef HAVE_SYS_UN_H
91
#include <sys/un.h>
92
#endif
93
#ifdef HAVE_NETDB_H
94
#include <netdb.h>
95
#endif
96
#ifdef HAVE_NET_IF_DL_H
97
#ifndef dynix
98
#include <net/if_dl.h>
99
#else
100
#include <sys/net/if_dl.h>
101
#endif
102
#endif
103
#include <errno.h>
104
105
#ifdef HAVE_LOCALE_H
106
#include <locale.h>
107
#endif
108
109
#include <net-snmp/types.h>
110
#include <net-snmp/output_api.h>
111
#include <net-snmp/config_api.h>
112
#include <net-snmp/utilities.h>
113
#include <net-snmp/agent/agent_callbacks.h>
114
115
#include <net-snmp/library/asn1.h>
116
#include <net-snmp/library/snmp.h>      /* for xdump & {build,parse}_var_op */
117
#include <net-snmp/library/snmp_api.h>
118
#include <net-snmp/library/snmp_client.h>
119
#include <net-snmp/library/parse.h>
120
#include <net-snmp/library/mib.h>
121
#include <net-snmp/library/int64.h>
122
#include <net-snmp/library/snmpv3.h>
123
#include <net-snmp/library/callback.h>
124
#include <net-snmp/library/container.h>
125
#include <net-snmp/library/snmp_secmod.h>
126
#include <net-snmp/library/large_fd_set.h>
127
#ifdef NETSNMP_SECMOD_USM
128
#include <net-snmp/library/snmpusm.h>
129
#endif
130
#ifdef NETSNMP_SECMOD_KSM
131
#include <net-snmp/library/snmpksm.h>
132
#endif
133
#include <net-snmp/library/keytools.h>
134
#include <net-snmp/library/lcd_time.h>
135
#include <net-snmp/library/snmp_alarm.h>
136
#include <net-snmp/library/snmp_transport.h>
137
#include <net-snmp/library/snmp_service.h>
138
#include <net-snmp/library/vacm.h>
139
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL)
140
#include <openssl/ssl.h>
141
#include <net-snmp/library/cert_util.h>
142
#endif
143
144
netsnmp_feature_child_of(statistics, libnetsnmp);
145
netsnmp_feature_child_of(snmp_api, libnetsnmp);
146
netsnmp_feature_child_of(oid_is_subtree, snmp_api);
147
netsnmp_feature_child_of(snmpv3_probe_contextEngineID_rfc5343, snmp_api);
148
149
static int      _snmp_store_needed = 0;
150
151
#include "../agent/mibgroup/agentx/protocol.h"
152
#include <net-snmp/library/transform_oids.h>
153
#ifndef timercmp
154
#define timercmp(tvp, uvp, cmp) \
155
  /* CSTYLED */ \
156
  ((tvp)->tv_sec cmp (uvp)->tv_sec || \
157
  ((tvp)->tv_sec == (uvp)->tv_sec && \
158
  /* CSTYLED */ \
159
  (tvp)->tv_usec cmp (uvp)->tv_usec))
160
#endif
161
#ifndef timerclear
162
#define timerclear(tvp)   (tvp)->tv_sec = (tvp)->tv_usec = 0
163
#endif
164
165
/*
166
 * Globals.
167
 */
168
#ifndef NETSNMP_STREAM_QUEUE_LEN
169
#define NETSNMP_STREAM_QUEUE_LEN  5
170
#endif
171
#ifndef NETSNMP_STREAM_FRAME_TIMEOUT
172
0
#define NETSNMP_STREAM_FRAME_TIMEOUT 30
173
#endif
174
#ifndef NETSNMP_STREAM_MAX_SESSIONS
175
0
#define NETSNMP_STREAM_MAX_SESSIONS 32
176
#endif
177
#ifndef NETSNMP_STREAM_MAX_SESSIONS_PER_PEER
178
0
#define NETSNMP_STREAM_MAX_SESSIONS_PER_PEER 8
179
#endif
180
181
#ifndef BSD4_3
182
#define BSD4_2
183
#endif
184
185
static const oid default_enterprise[] = { 1, 3, 6, 1, 4, 1, 3, 1, 1 };
186
/*
187
 * enterprises.cmu.systems.cmuSNMP 
188
 */
189
190
#define DEFAULT_COMMUNITY   "public"
191
2
#define DEFAULT_RETRIES     5
192
2.80k
#define DEFAULT_TIMEOUT     (1000L * 1000L)
193
#define DEFAULT_REMPORT     SNMP_PORT
194
0
#define DEFAULT_ENTERPRISE  default_enterprise
195
0
#define DEFAULT_TIME      0
196
197
/*
198
 * A list of all the outstanding requests for a particular session.
199
 */
200
typedef struct request_list {
201
    struct request_list *next_request;
202
    long            request_id;     /* request id */
203
    long            message_id;     /* message id */
204
    netsnmp_callback callback;      /* user callback per request (NULL if unused) */
205
    void           *cb_data;        /* user callback data per request (NULL if unused) */
206
    char            cb_data_refcounted;
207
    int             retries;        /* Number of retries */
208
    u_long          timeout;        /* length to wait for timeout */
209
    struct timeval  timeM;   /* Time this request was made [monotonic clock] */
210
    struct timeval  expireM; /* Time this request is due to expire [monotonic clock]. */
211
    struct snmp_session *session;
212
    netsnmp_pdu    *pdu;    /* The pdu for this request
213
           * (saved so it can be retransmitted */
214
} netsnmp_request_list;
215
216
/*
217
 * Internal information about the state of the snmp session.
218
 */
219
struct snmp_internal_session {
220
    netsnmp_request_list *requests;     /* Info about outstanding requests */
221
    netsnmp_request_list *requestsEnd;  /* ptr to end of list */
222
    int             (*hook_pre) (netsnmp_session *, netsnmp_transport *,
223
                                 void *, int);
224
    int             (*hook_parse) (netsnmp_session *, netsnmp_pdu *,
225
                                   u_char *, size_t);
226
    int             (*hook_post) (netsnmp_session *, netsnmp_pdu *, int);
227
    int             (*hook_build) (netsnmp_session *, netsnmp_pdu *,
228
                                   u_char *, size_t *);
229
    int             (*hook_realloc_build) (netsnmp_session *,
230
                                           netsnmp_pdu *, u_char **,
231
                                           size_t *, size_t *);
232
    int             (*check_packet) (u_char *, size_t);
233
    netsnmp_pdu    *(*hook_create_pdu) (netsnmp_transport *,
234
                                        void *, size_t);
235
236
    u_char       *packet;      /* curr rcv packet data (may be incomplete) */
237
    size_t        packet_len;  /* length of data received so far */
238
    size_t        packet_size; /* size of buffer for packet data */
239
    struct timeval packet_deadline; /* incomplete stream frame deadline */
240
    int            accepted_stream;
241
    int            stream_peer_valid;
242
    netsnmp_sockaddr_storage stream_peer;
243
244
    u_char       *obuf;         /* send packet buffer */
245
    size_t        obuf_size;    /* size of buffer for packet data */
246
    u_char       *opacket;      /* send packet data (within obuf) */
247
    size_t        opacket_len;  /* length of data */
248
};
249
250
/*
251
 * information about received packet
252
 */
253
typedef struct snmp_rcv_packet_s {
254
    u_char   *packet;
255
    size_t    packet_len;
256
    void     *opaque;
257
    int       olength;
258
} snmp_rcv_packet;
259
260
static const char *api_errors[-SNMPERR_MAX + 1] = {
261
    "No error",                 /* SNMPERR_SUCCESS */
262
    "Generic error",            /* SNMPERR_GENERR */
263
    "Invalid local port",       /* SNMPERR_BAD_LOCPORT */
264
    "Unknown host",             /* SNMPERR_BAD_ADDRESS */
265
    "Unknown session",          /* SNMPERR_BAD_SESSION */
266
    "Too long",                 /* SNMPERR_TOO_LONG */
267
    "No socket",                /* SNMPERR_NO_SOCKET */
268
    "Cannot send V2 PDU on V1 session", /* SNMPERR_V2_IN_V1 */
269
    "Cannot send V1 PDU on V2 session", /* SNMPERR_V1_IN_V2 */
270
    "Bad value for non-repeaters",      /* SNMPERR_BAD_REPEATERS */
271
    "Bad value for max-repetitions",    /* SNMPERR_BAD_REPETITIONS */
272
    "Error building ASN.1 representation",      /* SNMPERR_BAD_ASN1_BUILD */
273
    "Failure in sendto",        /* SNMPERR_BAD_SENDTO */
274
    "Bad parse of ASN.1 type",  /* SNMPERR_BAD_PARSE */
275
    "Bad version specified",    /* SNMPERR_BAD_VERSION */
276
    "Bad source party specified",       /* SNMPERR_BAD_SRC_PARTY */
277
    "Bad destination party specified",  /* SNMPERR_BAD_DST_PARTY */
278
    "Bad context specified",    /* SNMPERR_BAD_CONTEXT */
279
    "Bad community specified",  /* SNMPERR_BAD_COMMUNITY */
280
    "Cannot send noAuth/Priv",       /* SNMPERR_NOAUTH_DESPRIV */
281
    "Bad ACL definition",       /* SNMPERR_BAD_ACL */
282
    "Bad Party definition",     /* SNMPERR_BAD_PARTY */
283
    "Session abort failure",    /* SNMPERR_ABORT */
284
    "Unknown PDU type",         /* SNMPERR_UNKNOWN_PDU */
285
    "Timeout",                  /* SNMPERR_TIMEOUT */
286
    "Failure in recvfrom",      /* SNMPERR_BAD_RECVFROM */
287
    "Unable to determine contextEngineID",      /* SNMPERR_BAD_ENG_ID */
288
    "No securityName specified",        /* SNMPERR_BAD_SEC_NAME */
289
    "Unable to determine securityLevel",        /* SNMPERR_BAD_SEC_LEVEL  */
290
    "ASN.1 parse error in message",     /* SNMPERR_ASN_PARSE_ERR */
291
    "Unknown security model in message",        /* SNMPERR_UNKNOWN_SEC_MODEL */
292
    "Invalid message (e.g. msgFlags)",  /* SNMPERR_INVALID_MSG */
293
    "Unknown engine ID",        /* SNMPERR_UNKNOWN_ENG_ID */
294
    "Unknown user name",        /* SNMPERR_UNKNOWN_USER_NAME */
295
    "Unsupported security level",       /* SNMPERR_UNSUPPORTED_SEC_LEVEL */
296
    "Authentication failure (incorrect password, community or key)",    /* SNMPERR_AUTHENTICATION_FAILURE */
297
    "Not in time window",       /* SNMPERR_NOT_IN_TIME_WINDOW */
298
    "Decryption error",         /* SNMPERR_DECRYPTION_ERR */
299
    "SCAPI general failure",    /* SNMPERR_SC_GENERAL_FAILURE */
300
    "SCAPI sub-system not configured",  /* SNMPERR_SC_NOT_CONFIGURED */
301
    "Key tools not available",  /* SNMPERR_KT_NOT_AVAILABLE */
302
    "Unknown Report message",   /* SNMPERR_UNKNOWN_REPORT */
303
    "USM generic error",        /* SNMPERR_USM_GENERICERROR */
304
    "USM unknown security name (no such user exists)",  /* SNMPERR_USM_UNKNOWNSECURITYNAME */
305
    "USM unsupported security level (this user has not been configured for that level of security)",    /* SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL */
306
    "USM encryption error",     /* SNMPERR_USM_ENCRYPTIONERROR */
307
    "USM authentication failure (incorrect password or key)",   /* SNMPERR_USM_AUTHENTICATIONFAILURE */
308
    "USM parse error",          /* SNMPERR_USM_PARSEERROR */
309
    "USM unknown engineID",     /* SNMPERR_USM_UNKNOWNENGINEID */
310
    "USM not in time window",   /* SNMPERR_USM_NOTINTIMEWINDOW */
311
    "USM decryption error",     /* SNMPERR_USM_DECRYPTIONERROR */
312
    "MIB not initialized",      /* SNMPERR_NOMIB */
313
    "Value out of range",       /* SNMPERR_RANGE */
314
    "Sub-id out of range",      /* SNMPERR_MAX_SUBID */
315
    "Bad sub-id in object identifier",  /* SNMPERR_BAD_SUBID */
316
    "Object identifier too long",       /* SNMPERR_LONG_OID */
317
    "Bad value name",           /* SNMPERR_BAD_NAME */
318
    "Bad value notation",       /* SNMPERR_VALUE */
319
    "Unknown Object Identifier",        /* SNMPERR_UNKNOWN_OBJID */
320
    "No PDU in snmp_send",      /* SNMPERR_NULL_PDU */
321
    "Missing variables in PDU", /* SNMPERR_NO_VARS */
322
    "Bad variable type",        /* SNMPERR_VAR_TYPE */
323
    "Out of memory (malloc failure)",   /* SNMPERR_MALLOC */
324
    "Kerberos related error",   /* SNMPERR_KRB5 */
325
    "Protocol error",   /* SNMPERR_PROTOCOL */
326
    "OID not increasing",       /* SNMPERR_OID_NONINCREASING */
327
    "Context probe",            /* SNMPERR_JUST_A_CONTEXT_PROBE */
328
    "Configuration data found but the transport can't be configured", /* SNMPERR_TRANSPORT_NO_CONFIG */
329
    "Transport configuration failed", /* SNMPERR_TRANSPORT_CONFIG_ERROR */
330
};
331
332
static const char *secLevelName[] = {
333
    "BAD_SEC_LEVEL",
334
    "noAuthNoPriv",
335
    "authNoPriv",
336
    "authPriv"
337
};
338
339
/*
340
 * Multiple threads may changes these variables.
341
 * Suggest using the Single API, which does not use Sessions.
342
 *
343
 * Reqid may need to be protected. Time will tell...
344
 *
345
 */
346
/*
347
 * MTCRITICAL_RESOURCE
348
 */
349
/*
350
 * use token in comments to individually protect these resources 
351
 */
352
struct session_list *Sessions = NULL;   /* MT_LIB_SESSION */
353
static long     Reqid = 0;      /* MT_LIB_REQUESTID */
354
static long     Msgid = 0;      /* MT_LIB_MESSAGEID */
355
static long     Sessid = 0;     /* MT_LIB_SESSIONID */
356
static long     Transid = 0;    /* MT_LIB_TRANSID */
357
int             snmp_errno = 0;
358
/*
359
 * END MTCRITICAL_RESOURCE
360
 */
361
362
/*
363
 * global error detail storage
364
 */
365
static char     snmp_detail[192];
366
static int      snmp_detail_f = 0;
367
368
/*
369
 * return configured max message size for outgoing packets
370
 */
371
int
372
netsnmp_max_send_msg_size(void)
373
45.9k
{
374
45.9k
    u_int max = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
375
45.9k
                                   NETSNMP_DS_LIB_MSG_SEND_MAX);
376
45.9k
    if (0 == max)
377
45.9k
        max = SNMP_MAX_PACKET_LEN;
378
0
    else if (max < SNMP_MIN_MAX_LEN)
379
0
        max = SNMP_MIN_MAX_LEN; /* minimum max size per SNMP specs */
380
0
    else if (max > SNMP_MAX_PACKET_LEN)
381
0
        max = SNMP_MAX_PACKET_LEN;
382
383
45.9k
    return max;
384
45.9k
}
385
386
#ifndef HAVE_STRERROR
387
const char     *
388
strerror(int err)
389
{
390
    extern const char *sys_errlist[];
391
    extern int      sys_nerr;
392
393
    if (err < 0 || err >= sys_nerr)
394
        return "Unknown error";
395
    return sys_errlist[err];
396
}
397
#endif
398
399
const char *
400
snmp_pdu_type(int type)
401
0
{
402
0
    static char unknown[20];
403
0
    switch(type) {
404
0
    case SNMP_MSG_GET:
405
0
        return "GET";
406
0
    case SNMP_MSG_GETNEXT:
407
0
        return "GETNEXT";
408
0
    case SNMP_MSG_GETBULK:
409
0
        return "GETBULK";
410
0
#ifndef NETSNMP_NO_WRITE_SUPPORT
411
0
    case SNMP_MSG_SET:
412
0
        return "SET";
413
0
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
414
0
    case SNMP_MSG_RESPONSE:
415
0
        return "RESPONSE";
416
0
    case SNMP_MSG_TRAP:
417
0
        return "TRAP";
418
0
    case SNMP_MSG_INFORM:
419
0
        return "INFORM";
420
0
    case SNMP_MSG_TRAP2:
421
0
        return "TRAP2";
422
0
    case SNMP_MSG_REPORT:
423
0
        return "REPORT";
424
0
    default:
425
0
        snprintf(unknown, sizeof(unknown), "?0x%2X?", type);
426
0
  return unknown;
427
0
    }
428
0
}
429
430
#define DEBUGPRINTPDUTYPE(token, type) \
431
0
    DEBUGDUMPSECTION(token, snmp_pdu_type(type))
432
433
long
434
snmp_get_next_reqid(void)
435
0
{
436
0
    long            retVal;
437
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_REQUESTID);
438
0
    retVal = 1 + Reqid;         /*MTCRITICAL_RESOURCE */
439
0
    if (!retVal)
440
0
        retVal = 2;
441
0
    Reqid = retVal;
442
0
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
443
0
        retVal &= 0x7fff; /* mask to 15 bits */
444
0
    else
445
0
        retVal &= 0x7fffffff; /* mask to 31 bits */
446
447
0
    if (!retVal) {
448
0
        Reqid = retVal = 2;
449
0
    }
450
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_REQUESTID);
451
0
    return retVal;
452
0
}
453
454
long
455
snmp_get_next_msgid(void)
456
0
{
457
0
    long            retVal;
458
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_MESSAGEID);
459
0
    retVal = 1 + Msgid;         /*MTCRITICAL_RESOURCE */
460
0
    if (!retVal)
461
0
        retVal = 2;
462
0
    Msgid = retVal;
463
0
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
464
0
        retVal &= 0x7fff; /* mask to 15 bits */
465
0
    else
466
0
        retVal &= 0x7fffffff; /* mask to 31 bits */
467
468
0
    if (!retVal) {
469
0
        Msgid = retVal = 2;
470
0
    }
471
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_MESSAGEID);
472
0
    return retVal;
473
0
}
474
475
long
476
snmp_get_next_sessid(void)
477
37.7k
{
478
37.7k
    long            retVal;
479
37.7k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSIONID);
480
37.7k
    retVal = 1 + Sessid;        /*MTCRITICAL_RESOURCE */
481
37.7k
    if (!retVal)
482
0
        retVal = 2;
483
37.7k
    Sessid = retVal;
484
37.7k
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
485
0
        retVal &= 0x7fff; /* mask to 15 bits */
486
37.7k
    else
487
37.7k
        retVal &= 0x7fffffff; /* mask to 31 bits */
488
489
37.7k
    if (!retVal) {
490
0
        Sessid = retVal = 2;
491
0
    }
492
37.7k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSIONID);
493
37.7k
    return retVal;
494
37.7k
}
495
496
long
497
snmp_get_next_transid(void)
498
0
{
499
0
    long            retVal;
500
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_TRANSID);
501
0
    retVal = 1 + Transid;       /*MTCRITICAL_RESOURCE */
502
0
    if (!retVal)
503
0
        retVal = 2;
504
0
    Transid = retVal;
505
0
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
506
0
        retVal &= 0x7fff; /* mask to 15 bits */
507
0
    else
508
0
        retVal &= 0x7fffffff; /* mask to 31 bits */
509
510
0
    if (!retVal) {
511
0
        Transid = retVal = 2;
512
0
    }
513
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_TRANSID);
514
0
    return retVal;
515
0
}
516
517
void
518
snmp_perror(const char *prog_string)
519
0
{
520
0
    const char     *str;
521
0
    int             xerr;
522
0
    xerr = snmp_errno;          /*MTCRITICAL_RESOURCE */
523
0
    str = snmp_api_errstring(xerr);
524
0
    snmp_log(LOG_ERR, "%s: %s\n", prog_string, str);
525
0
}
526
527
void
528
snmp_set_detail(const char *detail_string)
529
0
{
530
0
    if (detail_string != NULL) {
531
0
        strlcpy(snmp_detail, detail_string, sizeof(snmp_detail));
532
0
        snmp_detail_f = 1;
533
0
    }
534
0
}
535
536
/*
537
 * returns pointer to static data 
538
 */
539
/*
540
 * results not guaranteed in multi-threaded use 
541
 */
542
const char     *
543
snmp_api_errstring(int snmp_errnumber)
544
0
{
545
0
    const char     *msg = "";
546
0
    static char     msg_buf[SPRINT_MAX_LEN];
547
548
0
    if (snmp_errnumber >= SNMPERR_MAX && snmp_errnumber <= SNMPERR_GENERR) {
549
0
        msg = api_errors[-snmp_errnumber];
550
0
    } else if (snmp_errnumber != SNMPERR_SUCCESS) {
551
0
        msg = NULL;
552
0
    }
553
0
    if (!msg) {
554
0
  snprintf(msg_buf, sizeof(msg_buf), "Unknown error: %d", snmp_errnumber);
555
0
        msg_buf[sizeof(msg_buf)-1] = '\0';
556
0
    } else if (snmp_detail_f) {
557
0
        snprintf(msg_buf, sizeof(msg_buf), "%s (%s)", msg, snmp_detail);
558
0
        msg_buf[sizeof(msg_buf)-1] = '\0';
559
0
        snmp_detail_f = 0;
560
0
    } else {
561
0
        strlcpy(msg_buf, msg, sizeof(msg_buf));
562
0
    }
563
564
0
    return (msg_buf);
565
0
}
566
567
/*
568
 * snmp_error - return error data
569
 * Inputs :  address of errno, address of snmp_errno, address of string
570
 * Caller must free the string returned after use.
571
 */
572
void
573
snmp_error(netsnmp_session * psess,
574
           int *p_errno, int *p_snmp_errno, char **p_str)
575
35.4k
{
576
35.4k
    char            buf[SPRINT_MAX_LEN];
577
35.4k
    int             snmp_errnumber;
578
579
35.4k
    if (p_errno)
580
35.4k
        *p_errno = psess->s_errno;
581
35.4k
    if (p_snmp_errno)
582
35.4k
        *p_snmp_errno = psess->s_snmp_errno;
583
35.4k
    if (p_str == NULL)
584
0
        return;
585
586
35.4k
    strcpy(buf, "");
587
35.4k
    snmp_errnumber = psess->s_snmp_errno;
588
35.4k
    if (snmp_errnumber >= SNMPERR_MAX && snmp_errnumber <= SNMPERR_GENERR) {
589
35.4k
  if (snmp_detail_f) {
590
0
            snprintf(buf, sizeof(buf), "%s (%s)", api_errors[-snmp_errnumber],
591
0
        snmp_detail);
592
0
            buf[sizeof(buf)-1] = '\0';
593
0
      snmp_detail_f = 0;
594
0
  }
595
35.4k
  else
596
35.4k
      strlcpy(buf, api_errors[-snmp_errnumber], sizeof(buf));
597
35.4k
    } else {
598
0
        if (snmp_errnumber) {
599
0
            snprintf(buf, sizeof(buf), "Unknown Error %d", snmp_errnumber);
600
0
            buf[sizeof(buf)-1] = '\0';
601
0
        }
602
0
    }
603
604
    /*
605
     * append a useful system errno interpretation. 
606
     */
607
35.4k
    if (psess->s_errno) {
608
0
        const char* error = strerror(psess->s_errno);
609
0
        if(error == NULL)
610
0
            error = "Unknown Error";
611
0
        snprintf (&buf[strlen(buf)], sizeof(buf)-strlen(buf),
612
0
                 " (%s)", error);
613
0
    }
614
35.4k
    buf[sizeof(buf)-1] = '\0';
615
35.4k
    *p_str = strdup(buf);
616
35.4k
}
617
618
/*
619
 * snmp_sess_error - same as snmp_error for single session API use.
620
 */
621
void
622
snmp_sess_error(struct session_list *slp, int *p_errno, int *p_snmp_errno,
623
                char **p_str)
624
0
{
625
0
    if ((slp) && (slp->session))
626
0
        snmp_error(slp->session, p_errno, p_snmp_errno, p_str);
627
0
}
628
629
/*
630
 * netsnmp_sess_log_error(): print a error stored in a session pointer 
631
 */
632
void
633
netsnmp_sess_log_error(int priority,
634
                       const char *prog_string, netsnmp_session * ss)
635
0
{
636
0
    char           *err;
637
0
    snmp_error(ss, NULL, NULL, &err);
638
0
    snmp_log(priority, "%s: %s\n", prog_string, err);
639
0
    SNMP_FREE(err);
640
0
}
641
642
/*
643
 * snmp_sess_perror(): print a error stored in a session pointer 
644
 */
645
void
646
snmp_sess_perror(const char *prog_string, netsnmp_session * ss)
647
0
{
648
0
    netsnmp_sess_log_error(LOG_ERR, prog_string, ss);
649
0
}
650
651
long int netsnmp_random(void)
652
6
{
653
6
#if defined(HAVE_RANDOM)
654
    /*
655
     * The function random() is a more sophisticated random number generator
656
     * which uses nonlinear feedback and an internal table that is 124 bytes
657
     * (992 bits) long. The function returns random values that are 32 bits in
658
     * length. All of the bits generated by random() are usable. The random()
659
     * function is adequate for simulations and games, but should not be used
660
     * for security related applications such as picking cryptographic keys or
661
     * simulating one-time pads.
662
     */
663
6
    return random();
664
#elif defined(HAVE_LRAND48)
665
    /*
666
     * As with random(), lrand48() provides excellent random numbers for
667
     * simulations and games, but should not be used for security-related
668
     * applications such as picking cryptographic keys or simulating one-time
669
     * pads; linear congruential algorithms are too easy to break.
670
     */
671
    return lrand48();
672
#elif defined(HAVE_RAND)
673
    /*
674
     * The original UNIX random number generator, rand(), is not a very good
675
     * random number generator. It uses a 32-bit seed and maintains a 32-bit
676
     * internal state.
677
     */
678
    return rand();
679
#else
680
#error "Neither random(), nor lrand48() nor rand() are available"
681
#endif
682
6
}
683
684
void netsnmp_srandom(unsigned int seed)
685
2
{
686
2
#if defined(HAVE_SRANDOM)
687
2
    srandom(seed);
688
#elif defined(HAVE_SRAND48)
689
    srand48(seed);
690
#elif defined(HAVE_SRAND)
691
    srand(seed);
692
#else
693
#error "Neither srandom(), nor srand48() nor srand() are available"
694
#endif
695
2
}
696
697
/*
698
 * Primordial SNMP library initialization.
699
 * Initializes mutex locks.
700
 * Invokes minimum required initialization for displaying MIB objects.
701
 * Gets initial request ID for all transactions,
702
 * and finds which port SNMP over UDP uses.
703
 * SNMP over AppleTalk is not currently supported.
704
 *
705
 * Warning: no debug messages here.
706
 */
707
static char _init_snmp_init_done = 0;
708
static void
709
_init_snmp(void)
710
5.60k
{
711
712
5.60k
    struct timeval  tv;
713
5.60k
    long            tmpReqid, tmpMsgid;
714
715
5.60k
    if (_init_snmp_init_done)
716
5.60k
        return;
717
2
    _init_snmp_init_done = 1;
718
2
    Reqid = 1;
719
720
2
    snmp_res_init();            /* initialize the mt locking structures */
721
2
#ifndef NETSNMP_DISABLE_MIB_LOADING
722
2
    netsnmp_init_mib_internals();
723
2
#endif /* NETSNMP_DISABLE_MIB_LOADING */
724
2
    netsnmp_tdomain_init();
725
726
2
    gettimeofday(&tv, (struct timezone *) 0);
727
    /*
728
     * Now = tv;
729
     */
730
731
    /*
732
     * get pseudo-random values for request ID and message ID 
733
     */
734
2
    netsnmp_srandom((unsigned)(tv.tv_sec ^ tv.tv_usec));
735
2
    tmpReqid = netsnmp_random();
736
2
    tmpMsgid = netsnmp_random();
737
738
    /*
739
     * don't allow zero value to repeat init 
740
     */
741
2
    if (tmpReqid == 0)
742
0
        tmpReqid = 1;
743
2
    if (tmpMsgid == 0)
744
0
        tmpMsgid = 1;
745
2
    Reqid = tmpReqid;
746
2
    Msgid = tmpMsgid;
747
748
2
    netsnmp_register_default_domain("snmp", "udp udp6");
749
2
    netsnmp_register_default_domain("snmptrap", "udp udp6");
750
751
2
    netsnmp_register_default_target("snmp", "udp", ":161");
752
2
    netsnmp_register_default_target("snmp", "tcp", ":161");
753
2
    netsnmp_register_default_target("snmp", "udp6", ":161");
754
2
    netsnmp_register_default_target("snmp", "tcp6", ":161");
755
2
    netsnmp_register_default_target("snmp", "dtlsudp", ":10161");
756
2
    netsnmp_register_default_target("snmp", "tlstcp", ":10161");
757
2
    netsnmp_register_default_target("snmp", "ipx", "/36879");
758
759
2
    netsnmp_register_default_target("snmptrap", "udp", ":162");
760
2
    netsnmp_register_default_target("snmptrap", "tcp", ":162");
761
2
    netsnmp_register_default_target("snmptrap", "udp6", ":162");
762
2
    netsnmp_register_default_target("snmptrap", "tcp6", ":162");
763
2
    netsnmp_register_default_target("snmptrap", "dtlsudp", ":10162");
764
2
    netsnmp_register_default_target("snmptrap", "tlstcp", ":10162");
765
2
    netsnmp_register_default_target("snmptrap", "ipx", "/36880");
766
767
2
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, 
768
2
                       NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH, 16);
769
2
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES,
770
2
                       DEFAULT_RETRIES);
771
2
    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
772
2
         NETSNMP_DS_LIB_MIB_ERRORS, 1);
773
774
2
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
775
2
    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
776
2
         NETSNMP_DS_LIB_REVERSE_ENCODE,
777
2
         NETSNMP_DEFAULT_ASNENCODING_DIRECTION);
778
2
#endif
779
2
}
780
781
/*
782
 * Initializes the session structure.
783
 * May perform one time minimal library initialization.
784
 * No MIB file processing is done via this call.
785
 */
786
void
787
snmp_sess_init(netsnmp_session * session)
788
2.80k
{
789
2.80k
    _init_snmp();
790
791
    /*
792
     * initialize session to default values 
793
     */
794
795
2.80k
    memset(session, 0, sizeof(netsnmp_session));
796
2.80k
    session->timeout = SNMP_DEFAULT_TIMEOUT;
797
2.80k
    session->retries = SNMP_DEFAULT_RETRIES;
798
2.80k
    session->version = SNMP_DEFAULT_VERSION;
799
2.80k
    session->securityModel = SNMP_DEFAULT_SECMODEL;
800
2.80k
    session->rcvMsgMaxSize = netsnmp_max_send_msg_size();
801
2.80k
    session->sndMsgMaxSize = netsnmp_max_send_msg_size();
802
2.80k
    session->flags |= SNMP_FLAGS_DONT_PROBE;
803
2.80k
}
804
805
806
static void
807
register_default_handlers(void)
808
2
{
809
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "dumpPacket",
810
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DUMP_PACKET);
811
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "reverseEncodeBER",
812
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REVERSE_ENCODE);
813
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "defaultPort",
814
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DEFAULT_PORT);
815
2
#ifndef NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION
816
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv3",
817
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V3);
818
2
#endif /* NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION */
819
2
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
820
2
#ifndef NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION
821
2
#if !defined(NETSNMP_DISABLE_SNMPV1)
822
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv1",
823
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V1);
824
2
#endif
825
2
#if !defined(NETSNMP_DISABLE_SNMPV2C)
826
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv2c",
827
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V2c);
828
2
#endif
829
2
#endif /* NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION */
830
2
    netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "defCommunity",
831
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_COMMUNITY);
832
2
#endif /* !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C) */
833
2
    netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "noTokenWarnings",
834
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_TOKEN_WARNINGS);
835
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noRangeCheck",
836
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE);
837
2
    netsnmp_ds_register_premib(ASN_OCTET_STR, "snmp", "persistentDir",
838
2
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PERSISTENT_DIR);
839
2
    netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "tempFilePattern",
840
2
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TEMP_FILE_PATTERN);
841
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noDisplayHint",
842
2
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT);
843
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "16bitIDs",
844
2
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS);
845
2
    netsnmp_ds_register_premib(ASN_OCTET_STR, "snmp", "clientaddr",
846
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENT_ADDR);
847
2
    netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "clientaddrUsesPort",
848
2
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENT_ADDR_USES_PORT);
849
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "serverSendBuf",
850
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SERVERSENDBUF);
851
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "serverRecvBuf",
852
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SERVERRECVBUF);
853
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "clientSendBuf",
854
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENTSENDBUF);
855
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "clientRecvBuf",
856
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENTRECVBUF);
857
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "sendMessageMaxSize",
858
2
                               NETSNMP_DS_LIBRARY_ID,
859
2
                               NETSNMP_DS_LIB_MSG_SEND_MAX);
860
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noPersistentLoad",
861
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_PERSISTENT_LOAD);
862
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noPersistentSave",
863
2
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_PERSISTENT_SAVE);
864
2
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp",
865
2
                               "noContextEngineIDDiscovery",
866
2
                               NETSNMP_DS_LIBRARY_ID,
867
2
                               NETSNMP_DS_LIB_NO_DISCOVERY);
868
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "timeout",
869
2
                   NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TIMEOUT);
870
2
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "retries",
871
2
                   NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES);
872
2
    netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "outputPrecision",
873
2
                               NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION);
874
875
876
2
    netsnmp_register_service_handlers();
877
2
}
878
879
static int init_snmp_init_done = 0; /* To prevent double init's. */
880
/**
881
 * Calls the functions to do config file loading and  mib module parsing
882
 * in the correct order.
883
 *
884
 * @param type label for the config file "type"
885
 *
886
 * @return void
887
 *
888
 * @see init_agent
889
 */
890
void
891
init_snmp(const char *type)
892
2
{
893
2
    if (init_snmp_init_done) {
894
0
        return;
895
0
    }
896
897
2
    init_snmp_init_done = 1;
898
899
    /*
900
     * make the type available everywhere else 
901
     */
902
2
    if (type && !netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
903
2
               NETSNMP_DS_LIB_APPTYPE)) {
904
0
        netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, 
905
0
            NETSNMP_DS_LIB_APPTYPE, type);
906
0
    }
907
908
2
    _init_snmp();
909
910
    /*
911
     * set our current locale properly to initialize isprint() type functions 
912
     *
913
     * Do not use setlocale on qnx, it is buggy 
914
     * https://www.qnx.com/developers/docs/7.1/#com.qnx.doc.neutrino.lib_ref/topic/s/setlocale.html
915
     */
916
2
#if defined(HAVE_SETLOCALE) && !defined(__QNX__)
917
2
    setlocale(LC_CTYPE, "");
918
2
#endif
919
920
2
    snmp_debug_init();    /* should be done first, to turn on debugging ASAP */
921
2
    netsnmp_container_init_list();
922
2
    init_callbacks();
923
2
    init_snmp_logging();
924
2
    snmp_init_statistics();
925
2
    register_mib_handlers();
926
2
    register_default_handlers();
927
2
    init_snmp_transport();
928
2
    init_snmpv3(type);
929
2
    init_snmp_alarm();
930
2
    init_snmp_enum(type);
931
2
    init_vacm();
932
2
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL) && NETSNMP_TRANSPORT_TLSBASE_DOMAIN
933
2
    netsnmp_certs_init();
934
2
#endif
935
#ifdef DNSSEC_LOCAL_VALIDATION
936
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "dnssecWarnOnly",
937
                               NETSNMP_DS_LIBRARY_ID,
938
                               NETSNMP_DS_LIB_DNSSEC_WARN_ONLY);
939
#endif
940
941
2
    read_premib_configs();
942
2
#ifndef NETSNMP_DISABLE_MIB_LOADING
943
2
    netsnmp_init_mib();
944
2
#endif /* NETSNMP_DISABLE_MIB_LOADING */
945
946
2
    read_configs();
947
948
2
}                               /* end init_snmp() */
949
950
/**
951
 * set a flag indicating that the persistent store needs to be saved.
952
 */
953
void
954
snmp_store_needed(const char *type)
955
0
{
956
0
    DEBUGMSGTL(("snmp_store", "setting needed flag...\n"));
957
0
    _snmp_store_needed = 1;
958
0
}
959
960
void
961
snmp_store_if_needed(void)
962
0
{
963
0
    if (0 == _snmp_store_needed)
964
0
        return;
965
    
966
0
    DEBUGMSGTL(("snmp_store", "store needed...\n"));
967
0
    snmp_store(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
968
0
                                     NETSNMP_DS_LIB_APPTYPE));
969
0
    _snmp_store_needed = 0;
970
0
}
971
972
void
973
snmp_store(const char *type)
974
0
{
975
0
    DEBUGMSGTL(("snmp_store", "storing stuff...\n"));
976
0
    snmp_save_persistent(type);
977
0
    snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_STORE_DATA, NULL);
978
0
    snmp_clean_persistent(type);
979
0
}
980
981
982
/**
983
 * Shuts down the application, saving any needed persistent storage,
984
 * and appropriate clean up.
985
 * 
986
 * @param type Label for the config file "type" used
987
 *
988
 * @return void
989
 */
990
void
991
snmp_shutdown(const char *type)
992
0
{
993
0
    snmp_store(type);
994
0
    snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SHUTDOWN, NULL);
995
0
    shutdown_snmp_logging();
996
0
    snmp_alarm_unregister_all();
997
0
    netsnmp_query_shutdown();
998
0
    snmp_close_sessions();
999
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
1000
0
    shutdown_mib();
1001
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
1002
0
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL) && NETSNMP_TRANSPORT_TLSBASE_DOMAIN
1003
0
    netsnmp_certs_shutdown();
1004
0
#endif
1005
0
#if !defined(NETSNMP_FEATURE_REMOVE_FILTER_SOURCE)
1006
0
    netsnmp_transport_filter_cleanup();
1007
0
#endif
1008
0
    unregister_all_config_handlers();
1009
0
    netsnmp_container_free_list();
1010
0
    clear_sec_mod();
1011
0
    clear_snmp_enum();
1012
0
    netsnmp_clear_tdomain_list();
1013
0
    clear_callback();
1014
0
    netsnmp_ds_shutdown();
1015
0
    netsnmp_clear_default_target();
1016
0
    netsnmp_clear_default_domain();
1017
0
    shutdown_secmod();
1018
0
    shutdown_snmp_transport();
1019
0
    shutdown_data_list();
1020
0
    snmp_debug_shutdown();    /* should be done last */
1021
1022
0
    init_snmp_init_done  = 0;
1023
0
    _init_snmp_init_done = 0;
1024
0
}
1025
1026
/*
1027
 * inserts session into session list
1028
 */
1029
void  snmp_session_insert(struct session_list *slp)
1030
2.80k
{
1031
2.80k
    if (NULL == slp)
1032
0
        return;
1033
1034
2.80k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
1035
2.80k
    slp->next = Sessions;
1036
2.80k
    Sessions = slp;
1037
2.80k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
1038
2.80k
}
1039
1040
/*
1041
 * Sets up the session with the snmp_session information provided by the user.
1042
 * Then opens and binds the necessary low-level transport.  A handle to the
1043
 * created session is returned (this is NOT the same as the pointer passed to
1044
 * snmp_open()).  On any error, NULL is returned and snmp_errno is set to the
1045
 * appropriate error code.
1046
 */
1047
netsnmp_session *
1048
snmp_open(netsnmp_session *session)
1049
0
{
1050
0
    struct session_list *slp;
1051
1052
0
    slp = snmp_sess_open(session);
1053
0
    if (!slp) {
1054
0
        return NULL;
1055
0
    }
1056
1057
0
    slp->session->flags &= ~SNMP_FLAGS_SESSION_USER;
1058
1059
0
    snmp_session_insert(slp);
1060
1061
0
    return (slp->session);
1062
0
}
1063
1064
/*
1065
 * extended open 
1066
 */
1067
netsnmp_feature_child_of(snmp_open_ex, netsnmp_unused);
1068
#ifndef NETSNMP_FEATURE_REMOVE_SNMP_OPEN_EX
1069
netsnmp_session *
1070
snmp_open_ex(netsnmp_session *session,
1071
             int (*fpre_parse)  (netsnmp_session *, netsnmp_transport *,
1072
                                void *, int),
1073
             int (*fparse)  (netsnmp_session *, netsnmp_pdu *, u_char *,
1074
         size_t),
1075
       int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *, int),
1076
1077
             int (*fbuild)  (netsnmp_session *, netsnmp_pdu *, u_char *,
1078
         size_t *),
1079
       int (*frbuild) (netsnmp_session *, netsnmp_pdu *,
1080
         u_char **, size_t *, size_t *),
1081
             int (*fcheck)  (u_char *, size_t)
1082
       )
1083
0
{
1084
0
    struct session_list *slp;
1085
1086
0
    slp = snmp_sess_open(session);
1087
0
    if (!slp) {
1088
0
        return NULL;
1089
0
    }
1090
0
    slp->internal->hook_pre = fpre_parse;
1091
0
    slp->internal->hook_parse = fparse;
1092
0
    slp->internal->hook_post = fpost_parse;
1093
0
    slp->internal->hook_build = fbuild;
1094
0
    slp->internal->hook_realloc_build = frbuild;
1095
0
    slp->internal->check_packet = fcheck;
1096
1097
0
    slp->session->flags &= ~SNMP_FLAGS_SESSION_USER;
1098
1099
0
    snmp_session_insert(slp);
1100
1101
0
    return (slp->session);
1102
0
}
1103
#endif /* NETSNMP_FEATURE_REMOVE_SNMP_OPEN_EX */
1104
1105
static struct session_list *
1106
_sess_copy(netsnmp_session * in_session)
1107
2.80k
{
1108
2.80k
    struct session_list *slp;
1109
2.80k
    struct snmp_internal_session *isp;
1110
2.80k
    netsnmp_session *session;
1111
2.80k
    struct snmp_secmod_def *sptr;
1112
2.80k
    char           *cp;
1113
2.80k
    u_char         *ucp;
1114
1115
2.80k
    in_session->s_snmp_errno = 0;
1116
2.80k
    in_session->s_errno = 0;
1117
1118
    /*
1119
     * Copy session structure and link into list 
1120
     */
1121
2.80k
    slp = calloc(1, sizeof(struct session_list));
1122
2.80k
    if (slp == NULL) {
1123
0
        in_session->s_snmp_errno = SNMPERR_MALLOC;
1124
0
        return (NULL);
1125
0
    }
1126
1127
2.80k
    slp->transport = NULL;
1128
1129
2.80k
    isp = calloc(1, sizeof(struct snmp_internal_session));
1130
1131
2.80k
    if (isp == NULL) {
1132
0
        snmp_sess_close(slp);
1133
0
        in_session->s_snmp_errno = SNMPERR_MALLOC;
1134
0
        return (NULL);
1135
0
    }
1136
1137
2.80k
    slp->internal = isp;
1138
2.80k
    slp->session = netsnmp_memdup(in_session, sizeof(netsnmp_session));
1139
2.80k
    if (slp->session == NULL) {
1140
0
        snmp_sess_close(slp);
1141
0
        in_session->s_snmp_errno = SNMPERR_MALLOC;
1142
0
        return (NULL);
1143
0
    }
1144
2.80k
    session = slp->session;
1145
1146
    /*
1147
     * zero out pointers so if we have to free the session we wont free mem
1148
     * owned by in_session 
1149
     */
1150
2.80k
    session->localname = NULL;
1151
2.80k
    session->peername = NULL;
1152
2.80k
    session->community = NULL;
1153
2.80k
    session->contextEngineID = NULL;
1154
2.80k
    session->contextName = NULL;
1155
2.80k
    session->securityEngineID = NULL;
1156
2.80k
    session->securityName = NULL;
1157
2.80k
    session->securityAuthProto = NULL;
1158
2.80k
    session->securityAuthLocalKey = NULL;
1159
2.80k
    session->securityPrivProto = NULL;
1160
2.80k
    session->securityPrivLocalKey = NULL;
1161
2.80k
    session->sessUser = NULL;
1162
2.80k
    session->paramName = NULL;
1163
2.80k
#ifndef NETSNMP_NO_TRAP_STATS
1164
2.80k
    session->trap_stats = NULL;
1165
2.80k
#endif
1166
    /*
1167
     * session now points to the new structure that still contains pointers to
1168
     * data allocated elsewhere.  Some of this data is copied to space malloc'd
1169
     * here, and the pointer replaced with the new one.
1170
     */
1171
1172
2.80k
    if (in_session->peername != NULL) {
1173
0
        session->peername =
1174
0
            netsnmp_strdup_and_null((u_char*)in_session->peername,
1175
0
                                    strlen(in_session->peername));
1176
0
        if (session->peername == NULL) {
1177
0
            snmp_sess_close(slp);
1178
0
            in_session->s_snmp_errno = SNMPERR_MALLOC;
1179
0
            return (NULL);
1180
0
        }
1181
0
    }
1182
1183
    /*
1184
     * Fill in defaults if necessary 
1185
     */
1186
2.80k
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
1187
2.80k
    if (in_session->community_len != SNMP_DEFAULT_COMMUNITY_LEN) {
1188
0
        ucp = netsnmp_memdup(in_session->community, in_session->community_len);
1189
2.80k
    } else {
1190
2.80k
        if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
1191
2.80k
          NETSNMP_DS_LIB_COMMUNITY)) != NULL) {
1192
0
            session->community_len = strlen(cp);
1193
0
            ucp = (u_char *) strdup(cp);
1194
2.80k
        } else {
1195
#ifdef NETSNMP_NO_ZEROLENGTH_COMMUNITY
1196
            session->community_len = strlen(DEFAULT_COMMUNITY);
1197
            ucp = netsnmp_memdup(DEFAULT_COMMUNITY, session->community_len);
1198
#else
1199
2.80k
            ucp = (u_char *) strdup("");
1200
2.80k
#endif
1201
2.80k
        }
1202
2.80k
    }
1203
1204
2.80k
    if (ucp == NULL) {
1205
0
        snmp_sess_close(slp);
1206
0
        in_session->s_snmp_errno = SNMPERR_MALLOC;
1207
0
        return (NULL);
1208
0
    }
1209
2.80k
    session->community = ucp;   /* replace pointer with pointer to new data */
1210
2.80k
#endif
1211
1212
2.80k
    if (session->securityLevel <= 0) {
1213
2.80k
        session->securityLevel =
1214
2.80k
            netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECLEVEL);
1215
2.80k
    }
1216
1217
2.80k
    if (in_session->securityEngineIDLen > 0) {
1218
0
        ucp = netsnmp_memdup(in_session->securityEngineID,
1219
0
                             in_session->securityEngineIDLen);
1220
0
        if (ucp == NULL) {
1221
0
            snmp_sess_close(slp);
1222
0
            in_session->s_snmp_errno = SNMPERR_MALLOC;
1223
0
            return (NULL);
1224
0
        }
1225
0
        session->securityEngineID = ucp;
1226
0
        session->securityEngineIDLen = in_session->securityEngineIDLen;
1227
0
    }
1228
1229
2.80k
    if (in_session->contextEngineIDLen > 0) {
1230
0
        ucp = netsnmp_memdup(in_session->contextEngineID,
1231
0
                             in_session->contextEngineIDLen);
1232
0
        if (ucp == NULL) {
1233
0
            snmp_sess_close(slp);
1234
0
            in_session->s_snmp_errno = SNMPERR_MALLOC;
1235
0
            return (NULL);
1236
0
        }
1237
0
        session->contextEngineID = ucp;
1238
0
        session->contextEngineIDLen = in_session->contextEngineIDLen;
1239
2.80k
    } else if (in_session->securityEngineIDLen > 0) {
1240
        /*
1241
         * default contextEngineID to securityEngineIDLen if defined 
1242
         */
1243
0
        ucp = netsnmp_memdup(in_session->securityEngineID,
1244
0
                             in_session->securityEngineIDLen);
1245
0
        if (ucp == NULL) {
1246
0
            snmp_sess_close(slp);
1247
0
            in_session->s_snmp_errno = SNMPERR_MALLOC;
1248
0
            return (NULL);
1249
0
        }
1250
0
        session->contextEngineID = ucp;
1251
0
        session->contextEngineIDLen = in_session->securityEngineIDLen;
1252
0
    }
1253
1254
2.80k
    if (in_session->contextName) {
1255
0
        session->contextName = strdup(in_session->contextName);
1256
0
        if (session->contextName == NULL) {
1257
0
            snmp_sess_close(slp);
1258
0
            return (NULL);
1259
0
        }
1260
0
        session->contextNameLen = in_session->contextNameLen;
1261
2.80k
    } else {
1262
2.80k
        if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
1263
2.80k
                                        NETSNMP_DS_LIB_CONTEXT)) != NULL)
1264
0
            cp = strdup(cp);
1265
2.80k
        else
1266
2.80k
            cp = strdup(SNMP_DEFAULT_CONTEXT);
1267
2.80k
        if (cp == NULL) {
1268
0
            snmp_sess_close(slp);
1269
0
            return (NULL);
1270
0
        }
1271
2.80k
        session->contextName = cp;
1272
2.80k
        session->contextNameLen = strlen(cp);
1273
2.80k
    }
1274
1275
2.80k
    if (in_session->securityName) {
1276
0
        session->securityName = strdup(in_session->securityName);
1277
0
        if (session->securityName == NULL) {
1278
0
            snmp_sess_close(slp);
1279
0
            return (NULL);
1280
0
        }
1281
2.80k
    } else if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
1282
2.80k
             NETSNMP_DS_LIB_SECNAME)) != NULL) {
1283
0
        cp = strdup(cp);
1284
0
        if (cp == NULL) {
1285
0
            snmp_sess_close(slp);
1286
0
            return (NULL);
1287
0
        }
1288
0
        session->securityName = cp;
1289
0
        session->securityNameLen = strlen(cp);
1290
0
    }
1291
1292
2.80k
    if (in_session->securityAuthLocalKey) {
1293
0
            session->securityAuthLocalKey =
1294
0
                netsnmp_memdup(in_session->securityAuthLocalKey,
1295
0
                               in_session->securityAuthLocalKeyLen);
1296
0
            session->securityAuthLocalKeyLen =
1297
0
                in_session->securityAuthLocalKeyLen;
1298
0
    }
1299
1300
2.80k
    if (in_session->securityPrivLocalKey) {
1301
0
            session->securityPrivLocalKey =
1302
0
                netsnmp_memdup(in_session->securityPrivLocalKey,
1303
0
                               in_session->securityPrivLocalKeyLen);
1304
0
            session->securityPrivLocalKeyLen =
1305
0
                in_session->securityPrivLocalKeyLen;
1306
0
    }
1307
1308
2.80k
    if (session->transport_configuration) {
1309
0
        session->transport_configuration =
1310
0
            CONTAINER_DUP(session->transport_configuration, NULL, 0);
1311
0
        if (!session->transport_configuration) {
1312
0
            snmp_sess_close(slp);
1313
0
            return NULL;
1314
0
        }
1315
0
    }
1316
1317
2.80k
    if (session->retries == SNMP_DEFAULT_RETRIES) {
1318
2.80k
        int retry = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
1319
2.80k
                                       NETSNMP_DS_LIB_RETRIES);
1320
2.80k
        if (retry < 0)
1321
0
            session->retries = DEFAULT_RETRIES;
1322
2.80k
        else
1323
2.80k
            session->retries = retry;
1324
2.80k
    }
1325
2.80k
    if (session->timeout == SNMP_DEFAULT_TIMEOUT) {
1326
2.80k
        int timeout = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
1327
2.80k
                                         NETSNMP_DS_LIB_TIMEOUT);
1328
2.80k
        if (timeout <= 0)
1329
2.80k
            session->timeout = DEFAULT_TIMEOUT;
1330
0
        else
1331
0
            session->timeout = timeout * 1000L * 1000L;
1332
2.80k
    }
1333
2.80k
    session->sessid = snmp_get_next_sessid();
1334
1335
2.80k
    snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SESSION_INIT,
1336
2.80k
                        session);
1337
1338
2.80k
    if ((sptr = find_sec_mod(session->securityModel)) != NULL) {
1339
        /*
1340
         * security module specific copying 
1341
         */
1342
2.80k
        if (sptr->session_setup) {
1343
2.80k
            int ret = (*sptr->session_setup) (in_session, session);
1344
2.80k
            if (ret != SNMPERR_SUCCESS) {
1345
0
                snmp_sess_close(slp);
1346
0
                return NULL;
1347
0
            }
1348
2.80k
        }
1349
1350
        /*
1351
         * security module specific opening
1352
         */
1353
2.80k
        if (sptr->session_open) {
1354
0
            int ret = (*sptr->session_open) (session);
1355
0
            if (ret != SNMPERR_SUCCESS) {
1356
0
                snmp_sess_close(slp);
1357
0
                return NULL;
1358
0
            }
1359
0
        }
1360
2.80k
    }
1361
1362
2.80k
#ifndef NETSNMP_NO_WRITE_SUPPORT
1363
2.80k
    if (in_session->sessUser) {
1364
0
        struct usmUser *user;
1365
1366
0
        user = calloc(1, sizeof(struct usmUser));
1367
0
        if (user == NULL) {
1368
0
            snmp_sess_close(slp);
1369
0
            return NULL;
1370
0
        }
1371
0
        session->sessUser = usm_cloneFrom_user(in_session->sessUser, user);
1372
0
        if (session->sessUser == NULL) {
1373
0
            usm_free_user(user);
1374
0
            snmp_sess_close(slp);
1375
0
            return NULL;
1376
0
        }
1377
0
    }
1378
2.80k
#endif /* NETSNMP_NO_WRITE_SUPPORT */
1379
1380
2.80k
    if (in_session->paramName) {
1381
0
        session->paramName = strdup(in_session->paramName);
1382
0
        if (session->paramName == NULL) {
1383
0
            snmp_sess_close(slp);
1384
0
            return NULL;
1385
0
        }
1386
0
    }
1387
2.80k
#ifndef NETSNMP_NO_TRAP_STATS
1388
2.80k
    if (in_session->trap_stats) {
1389
0
        session->trap_stats = netsnmp_memdup(in_session->trap_stats,
1390
0
                                             sizeof(*in_session->trap_stats));
1391
0
        if (session->trap_stats == NULL) {
1392
0
            snmp_sess_close(slp);
1393
0
            return NULL;
1394
0
        }
1395
0
    }
1396
2.80k
#endif
1397
1398
2.80k
    return (slp);
1399
2.80k
}
1400
1401
static struct session_list *
1402
snmp_sess_copy(netsnmp_session * pss)
1403
2.80k
{
1404
2.80k
    struct session_list *psl;
1405
2.80k
    psl = _sess_copy(pss);
1406
2.80k
    if (!psl) {
1407
0
        if (!pss->s_snmp_errno) {
1408
0
            pss->s_snmp_errno = SNMPERR_GENERR;
1409
0
        }
1410
0
        SET_SNMP_ERROR(pss->s_snmp_errno);
1411
0
    }
1412
2.80k
    return psl;
1413
2.80k
}
1414
1415
/**
1416
 * Allocate a PDU for probing for the engineID
1417
 *
1418
 * The returned PDU can be used to probe synchronously or asynchronously.
1419
 * SNMP_FLAGS_DONT_PROBE must be set to disable internal synchronous probing,
1420
 * when response is received and all callbacks have executed the rest of PDUs
1421
 * can be sent as usual.
1422
 */
1423
netsnmp_pdu *snmpv3_probe_usm_pdu_create(void)
1424
0
{
1425
0
        netsnmp_pdu     *pdu;
1426
1427
0
        pdu = snmp_pdu_create(SNMP_MSG_GET);
1428
0
        if (!pdu)
1429
0
                return NULL;
1430
1431
0
        pdu->version = SNMP_VERSION_3;
1432
0
        pdu->securityName = strdup("");
1433
0
        if (!pdu->securityName) {
1434
0
                snmp_free_pdu(pdu);
1435
0
                return NULL;
1436
0
        }
1437
0
        pdu->securityNameLen = 0;
1438
0
        pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
1439
0
        pdu->securityModel = SNMP_SEC_MODEL_USM;
1440
1441
0
        return pdu;
1442
0
}
1443
1444
#ifndef NETSNMP_FEATURE_REMOVE_SNMPV3_PROBE_CONTEXTENGINEID_RFC5343
1445
/**
1446
 * probe for engineID using RFC 5343 probing mechanisms
1447
 *
1448
 * Designed to be a callback for within a security model's probe_engineid hook.
1449
 * Since it's likely multiple security models won't have engineIDs to
1450
 * probe for then this function is a callback likely to be used by
1451
 * multiple future security models.  E.G. both SSH and DTLS.
1452
 */
1453
int
1454
snmpv3_probe_contextEngineID_rfc5343(struct session_list *slp,
1455
                                     netsnmp_session *session)
1456
0
{
1457
0
    netsnmp_pdu    *pdu = NULL, *response = NULL;
1458
0
    static const oid snmpEngineIDoid[]   = { 1,3,6,1,6,3,10,2,1,1,0};
1459
0
    static size_t   snmpEngineIDoid_len = 11;
1460
1461
0
    static char     probeEngineID[] = { (char)0x80, 0, 0, 0, 6 };
1462
0
    static size_t   probeEngineID_len = sizeof(probeEngineID);
1463
    
1464
0
    int status;
1465
1466
0
    pdu = snmp_pdu_create(SNMP_MSG_GET);
1467
0
    if (!pdu)
1468
0
        return SNMP_ERR_GENERR;
1469
0
    pdu->version = SNMP_VERSION_3;
1470
    /* don't require a securityName */
1471
0
    if (session->securityName) {
1472
0
        pdu->securityName = strdup(session->securityName);
1473
0
        if (!pdu->securityName) {
1474
0
            snmp_free_pdu(pdu);
1475
0
            return SNMP_ERR_GENERR;
1476
0
        }
1477
0
        pdu->securityNameLen = strlen(pdu->securityName);
1478
0
    }
1479
0
    pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
1480
0
    pdu->securityModel = session->securityModel;
1481
0
    pdu->contextEngineID = netsnmp_memdup(probeEngineID, probeEngineID_len);
1482
0
    if (!pdu->contextEngineID) {
1483
0
        snmp_log(LOG_ERR, "failed to clone memory for rfc5343 probe\n");
1484
0
        snmp_free_pdu(pdu);
1485
0
        return SNMP_ERR_GENERR;
1486
0
    }
1487
0
    pdu->contextEngineIDLen = probeEngineID_len;
1488
    
1489
0
    snmp_add_null_var(pdu, snmpEngineIDoid, snmpEngineIDoid_len);
1490
1491
0
    DEBUGMSGTL(("snmp_api", "probing for engineID using rfc5343 methods...\n"));
1492
0
    session->flags |= SNMP_FLAGS_DONT_PROBE; /* prevent recursion */
1493
0
    status = snmp_sess_synch_response(slp, pdu, &response);
1494
1495
0
    if ((response == NULL) || (status != STAT_SUCCESS)) {
1496
0
        snmp_log(LOG_ERR, "failed rfc5343 contextEngineID probing\n");
1497
0
        if (response)
1498
0
            snmp_free_pdu(response);
1499
0
        return SNMP_ERR_GENERR;
1500
0
    }
1501
1502
    /* check that the response makes sense */
1503
0
    if (NULL != response->variables &&
1504
0
        NULL != response->variables->name &&
1505
0
        snmp_oid_compare(response->variables->name,
1506
0
                         response->variables->name_length,
1507
0
                         snmpEngineIDoid, snmpEngineIDoid_len) == 0 &&
1508
0
        ASN_OCTET_STR == response->variables->type  &&
1509
0
        NULL != response->variables->val.string &&
1510
0
        response->variables->val_len > 0) {
1511
0
        free(session->contextEngineID);
1512
0
        session->contextEngineID =
1513
0
            netsnmp_memdup(response->variables->val.string,
1514
0
                           response->variables->val_len);
1515
0
        if (!session->contextEngineID) {
1516
0
            snmp_log(LOG_ERR, "failed rfc5343 contextEngineID probing: memory allocation failed\n");
1517
0
            session->contextEngineIDLen = 0;
1518
0
            snmp_free_pdu(response);
1519
0
            return SNMP_ERR_GENERR;
1520
0
        }
1521
0
        session->contextEngineIDLen = response->variables->val_len;
1522
        
1523
        /* technically there likely isn't a securityEngineID but just
1524
           in case anyone goes looking we might as well have one */
1525
0
        free(session->securityEngineID);
1526
0
        session->securityEngineID =
1527
0
            netsnmp_memdup(response->variables->val.string,
1528
0
                           response->variables->val_len);
1529
0
        if (!session->securityEngineID) {
1530
0
            snmp_log(LOG_ERR, "failed rfc5343 securityEngineID probing: memory allocation failed\n");
1531
0
            session->securityEngineIDLen = 0;
1532
0
            snmp_free_pdu(response);
1533
0
            return SNMP_ERR_GENERR;
1534
0
        }
1535
        
1536
0
        session->securityEngineIDLen = response->variables->val_len;
1537
        
1538
0
        if (snmp_get_do_debugging()) {
1539
0
            size_t i;
1540
0
            DEBUGMSGTL(("snmp_sess_open",
1541
0
                        "  probe found engineID:  "));
1542
0
            for (i = 0; i < session->securityEngineIDLen; i++)
1543
0
                DEBUGMSG(("snmp_sess_open", "%02x",
1544
0
                          session->securityEngineID[i]));
1545
0
            DEBUGMSG(("snmp_sess_open", "\n"));
1546
0
        }
1547
0
    }
1548
0
    if (response)
1549
0
        snmp_free_pdu(response);
1550
0
    return SNMPERR_SUCCESS;
1551
0
}
1552
#endif /* NETSNMP_FEATURE_REMOVE_SNMPV3_PROBE_CONTEXTENGINEID_RFC5343 */
1553
1554
1555
/**
1556
 * probe for peer engineID
1557
 *
1558
 * @param slp         session list pointer.
1559
 * @param in_session  session for errors
1560
 *
1561
 * @note
1562
 *  - called by _sess_open(), snmp_sess_add_ex()
1563
 *  - in_session is the user supplied session provided to those functions.
1564
 *  - the first session in slp should the internal allocated copy of in_session
1565
 *
1566
 * @return 0 : error
1567
 * @return 1 : ok
1568
 *
1569
 */
1570
int
1571
snmpv3_engineID_probe(struct session_list *slp,
1572
                      netsnmp_session * in_session)
1573
0
{
1574
0
    netsnmp_session *session;
1575
0
    int             status;
1576
0
    struct snmp_secmod_def *sptr = NULL;
1577
1578
0
    if (slp == NULL || slp->session == NULL) {
1579
0
        return 0;
1580
0
    }
1581
1582
0
    session = slp->session;
1583
0
    netsnmp_assert_or_return(session != NULL, 0);
1584
0
    sptr = find_sec_mod(session->securityModel);
1585
1586
    /*
1587
     * If we are opening a V3 session and we don't know engineID we must probe
1588
     * it -- this must be done after the session is created and inserted in the
1589
     * list so that the response can handled correctly. 
1590
     */
1591
1592
0
    if (session->version == SNMP_VERSION_3 &&
1593
0
        (0 == (session->flags & SNMP_FLAGS_DONT_PROBE))) {
1594
0
        if (NULL != sptr && NULL != sptr->probe_engineid) {
1595
0
            DEBUGMSGTL(("snmp_api", "probing for engineID using security model callback...\n"));
1596
            /* security model specific mechanism of determining engineID */
1597
0
            status = (*sptr->probe_engineid) (slp, in_session);
1598
0
            if (status != SNMPERR_SUCCESS)
1599
0
                return 0;
1600
0
        } else {
1601
            /* XXX: default to the default RFC5343 contextEngineID Probe? */
1602
0
            return 0;
1603
0
        }
1604
0
    }
1605
1606
    /*
1607
     * see if there is a hook to call now that we're done probing for an
1608
     * engineID
1609
     */
1610
0
    if (sptr && sptr->post_probe_engineid) {
1611
0
        status = (*sptr->post_probe_engineid)(slp, in_session);
1612
0
        if (status != SNMPERR_SUCCESS)
1613
0
            return 0;
1614
0
    }
1615
1616
0
    return 1;
1617
0
}
1618
1619
/*******************************************************************-o-******
1620
 * netsnmp_sess_config_transport
1621
 *
1622
 * Parameters:
1623
 *  *in_session
1624
 *  *in_transport
1625
 *
1626
 * Returns:
1627
 *      SNMPERR_SUCCESS                     - Yay
1628
 *      SNMPERR_GENERR                      - Generic Error
1629
 *      SNMPERR_TRANSPORT_CONFIG_ERROR      - Transport rejected config
1630
 *      SNMPERR_TRANSPORT_NO_CONFIG         - Transport can't config
1631
 */
1632
int
1633
netsnmp_sess_config_transport(netsnmp_container *transport_configuration,
1634
                              netsnmp_transport *transport)
1635
2.80k
{
1636
    /* Optional supplemental transport configuration information and
1637
       final call to actually open the transport */
1638
2.80k
    if (transport_configuration) {
1639
0
        DEBUGMSGTL(("snmp_sess", "configuring transport\n"));
1640
0
        if (transport->f_config) {
1641
0
            netsnmp_iterator *iter;
1642
0
            netsnmp_transport_config *config_data;
1643
0
            int ret = 0;
1644
1645
0
            iter = CONTAINER_ITERATOR(transport_configuration);
1646
0
            if (NULL == iter) {
1647
0
                return SNMPERR_GENERR;
1648
0
            }
1649
1650
0
            for(config_data = (netsnmp_transport_config*)ITERATOR_FIRST(iter); config_data;
1651
0
                config_data = (netsnmp_transport_config*)ITERATOR_NEXT(iter)) {
1652
0
                ret = transport->f_config(transport, config_data->key,
1653
0
                                          config_data->value);
1654
0
                if (ret)
1655
0
                    break;
1656
0
            }
1657
0
            ITERATOR_RELEASE(iter);
1658
0
            if (ret)
1659
0
                return SNMPERR_TRANSPORT_CONFIG_ERROR;
1660
0
        } else {
1661
0
            return SNMPERR_TRANSPORT_NO_CONFIG;
1662
0
        }
1663
0
    }
1664
2.80k
    return SNMPERR_SUCCESS;
1665
2.80k
}
1666
1667
 
1668
/**
1669
 * Copies configuration from the session and calls f_open
1670
 * This function copies any configuration stored in the session
1671
 * pointer to the transport if it has a f_config pointer and then
1672
 * calls the transport's f_open function to actually open the
1673
 * connection.
1674
 *
1675
 * @param in_session A pointer to the session that config information is in.
1676
 * @param transport A pointer to the transport to config/open.
1677
 *
1678
 * @return SNMPERR_SUCCESS : on success
1679
 */
1680
1681
/*******************************************************************-o-******
1682
 * netsnmp_sess_config_transport
1683
 *
1684
 * Parameters:
1685
 *  *in_session
1686
 *  *in_transport
1687
 *
1688
 * Returns:
1689
 *      SNMPERR_SUCCESS                     - Yay
1690
 *      SNMPERR_GENERR                      - Generic Error
1691
 *      SNMPERR_TRANSPORT_CONFIG_ERROR      - Transport rejected config
1692
 *      SNMPERR_TRANSPORT_NO_CONFIG         - Transport can't config
1693
 */
1694
int
1695
netsnmp_sess_config_and_open_transport(netsnmp_session *in_session,
1696
                                       netsnmp_transport *transport)
1697
2.80k
{
1698
2.80k
    int rc;
1699
    
1700
2.80k
    DEBUGMSGTL(("snmp_sess", "opening transport: %x\n", transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED));
1701
1702
    /* don't double open */
1703
2.80k
    if (transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED)
1704
0
        return SNMPERR_SUCCESS;
1705
1706
2.80k
    if ((rc = netsnmp_sess_config_transport(in_session->transport_configuration,
1707
2.80k
                                            transport)) != SNMPERR_SUCCESS) {
1708
0
        in_session->s_snmp_errno = rc;
1709
0
        in_session->s_errno = 0;
1710
0
        return rc;
1711
0
    }
1712
        
1713
2.80k
    if (transport->f_open)
1714
0
        transport = transport->f_open(transport);
1715
1716
2.80k
    if (transport == NULL) {
1717
0
        DEBUGMSGTL(("snmp_sess", "couldn't open transport connection\n"));
1718
0
        in_session->s_snmp_errno = SNMPERR_BAD_ADDRESS;
1719
0
        in_session->s_errno = errno;
1720
0
        snmp_set_detail(in_session->peername);
1721
0
        return SNMPERR_BAD_ADDRESS;
1722
0
    }
1723
1724
    /** if transport has a max size, make sure session is the same (or less) */
1725
2.80k
    if (in_session->rcvMsgMaxSize > transport->msgMaxSize) {
1726
2.80k
        DEBUGMSGTL(("snmp_sess",
1727
2.80k
                    "limiting session rcv size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1728
2.80k
                    in_session->rcvMsgMaxSize, transport->msgMaxSize));
1729
2.80k
        in_session->rcvMsgMaxSize = transport->msgMaxSize;
1730
2.80k
    }
1731
1732
2.80k
    if (in_session->sndMsgMaxSize > transport->msgMaxSize) {
1733
2.80k
        DEBUGMSGTL(("snmp_sess",
1734
2.80k
                    "limiting session snd size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1735
2.80k
                    in_session->sndMsgMaxSize, transport->msgMaxSize));
1736
2.80k
        in_session->sndMsgMaxSize = transport->msgMaxSize;
1737
2.80k
    }
1738
1739
2.80k
    transport->flags |= NETSNMP_TRANSPORT_FLAG_OPENED;
1740
2.80k
    DEBUGMSGTL(("snmp_sess", "done opening transport: %x\n", transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED));
1741
2.80k
    return SNMPERR_SUCCESS;
1742
2.80k
}
1743
1744
/*******************************************************************-o-******
1745
 * snmp_sess_open
1746
 *
1747
 * Parameters:
1748
 *  *in_session
1749
 *
1750
 * Returns:
1751
 *      Pointer to a session in the session list   -OR-   FIX -- right?
1752
 *  NULL on failure.
1753
 *
1754
 * The "spin-free" version of snmp_open.
1755
 */
1756
static struct session_list *
1757
_sess_open(netsnmp_session * in_session)
1758
0
{
1759
0
    netsnmp_transport *transport = NULL;
1760
0
    int rc;
1761
1762
0
    in_session->s_snmp_errno = 0;
1763
0
    in_session->s_errno = 0;
1764
1765
0
    _init_snmp();
1766
1767
0
    {
1768
0
        char *clientaddr_save = NULL;
1769
1770
0
        if (NULL != in_session->localname) {
1771
0
            clientaddr_save =
1772
0
                netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
1773
0
                                      NETSNMP_DS_LIB_CLIENT_ADDR);
1774
0
            if (clientaddr_save)
1775
0
                clientaddr_save = strdup(clientaddr_save);
1776
1777
0
            netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
1778
0
                                  NETSNMP_DS_LIB_CLIENT_ADDR,
1779
0
                                  in_session->localname);
1780
0
        }
1781
1782
0
        if (in_session->flags & SNMP_FLAGS_STREAM_SOCKET) {
1783
0
            transport =
1784
0
                netsnmp_tdomain_transport_full("snmp", in_session->peername,
1785
0
                                               in_session->local_port, "tcp,tcp6",
1786
0
                                               NULL);
1787
0
        } else {
1788
0
            transport =
1789
0
                netsnmp_tdomain_transport_full("snmp", in_session->peername,
1790
0
                                               in_session->local_port, NULL,
1791
0
                                               NULL);
1792
0
        }
1793
1794
0
        if (NULL != in_session->localname)
1795
0
            netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
1796
0
                                  NETSNMP_DS_LIB_CLIENT_ADDR, clientaddr_save);
1797
0
        free(clientaddr_save);
1798
0
    }
1799
1800
0
    if (transport == NULL) {
1801
0
        DEBUGMSGTL(("_sess_open", "couldn't interpret peername\n"));
1802
0
        in_session->s_snmp_errno = SNMPERR_BAD_ADDRESS;
1803
0
        in_session->s_errno = errno;
1804
0
        snmp_set_detail(in_session->peername);
1805
0
        return NULL;
1806
0
    }
1807
1808
    /* Optional supplemental transport configuration information and
1809
       final call to actually open the transport */
1810
0
    if ((rc = netsnmp_sess_config_and_open_transport(in_session, transport))
1811
0
        != SNMPERR_SUCCESS) {
1812
0
        netsnmp_transport_free(transport);
1813
0
        transport = NULL;
1814
0
        return NULL;
1815
0
    }
1816
1817
0
#if defined(SO_BROADCAST) && defined(SOL_SOCKET)
1818
0
    if ( in_session->flags & SNMP_FLAGS_UDP_BROADCAST) {
1819
0
        int   b = 1;
1820
0
        int   rc;
1821
1822
0
        rc = setsockopt(transport->sock, SOL_SOCKET, SO_BROADCAST,
1823
0
                        (char *)&b, sizeof(b));
1824
1825
0
        if ( rc != 0 ) {
1826
0
            in_session->s_snmp_errno = SNMPERR_BAD_ADDRESS; /* good as any? */
1827
0
            in_session->s_errno = errno;
1828
1829
0
            DEBUGMSGTL(("_sess_open", "couldn't enable UDP_BROADCAST\n"));
1830
0
            transport->f_close(transport);
1831
0
            netsnmp_transport_free(transport);
1832
0
            return NULL;
1833
0
        }
1834
0
    }
1835
0
#endif
1836
1837
0
    return snmp_sess_add(in_session, transport, NULL, NULL);
1838
0
}
1839
1840
/*
1841
 * EXTENDED SESSION API ------------------------------------------ 
1842
 * 
1843
 * snmp_sess_add_ex, snmp_sess_add, snmp_add 
1844
 * 
1845
 * Analogous to snmp_open family of functions, but taking a netsnmp_transport
1846
 * pointer as an extra argument.  Unlike snmp_open et al. it doesn't attempt
1847
 * to interpret the in_session->peername as a transport endpoint specifier,
1848
 * but instead uses the supplied transport.  JBPN
1849
 * 
1850
 */
1851
1852
netsnmp_session *
1853
snmp_add(netsnmp_session * in_session,
1854
         netsnmp_transport *transport,
1855
         int (*fpre_parse) (netsnmp_session *, netsnmp_transport *, void *,
1856
                            int), int (*fpost_parse) (netsnmp_session *,
1857
                                                      netsnmp_pdu *, int))
1858
0
{
1859
0
    struct session_list *slp;
1860
1861
0
    slp = snmp_sess_add_ex(in_session, transport, fpre_parse, NULL,
1862
0
                           fpost_parse, NULL, NULL, NULL, NULL);
1863
0
    if (slp == NULL) {
1864
0
        return NULL;
1865
0
    }
1866
1867
0
    snmp_session_insert(slp);
1868
1869
0
    return (slp->session);
1870
0
}
1871
1872
netsnmp_session *
1873
snmp_add_full(netsnmp_session * in_session,
1874
              netsnmp_transport *transport,
1875
              int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
1876
                                 void *, int),
1877
              int (*fparse) (netsnmp_session *, netsnmp_pdu *, u_char *,
1878
                             size_t),
1879
              int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *, int),
1880
              int (*fbuild) (netsnmp_session *, netsnmp_pdu *, u_char *,
1881
                             size_t *), int (*frbuild) (netsnmp_session *,
1882
                                                        netsnmp_pdu *,
1883
                                                        u_char **,
1884
                                                        size_t *,
1885
                                                        size_t *),
1886
              int (*fcheck) (u_char *, size_t),
1887
              netsnmp_pdu *(*fcreate_pdu) (netsnmp_transport *, void *,
1888
                                           size_t))
1889
2.80k
{
1890
2.80k
    struct session_list *slp;
1891
1892
2.80k
    slp = snmp_sess_add_ex(in_session, transport, fpre_parse, fparse,
1893
2.80k
                           fpost_parse, fbuild, frbuild, fcheck, fcreate_pdu);
1894
2.80k
    if (slp == NULL) {
1895
0
        return NULL;
1896
0
    }
1897
1898
2.80k
    snmp_session_insert(slp);
1899
1900
2.80k
    return (slp->session);
1901
2.80k
}
1902
1903
struct session_list *
1904
snmp_sess_add_ex(netsnmp_session * in_session,
1905
                 netsnmp_transport *transport,
1906
                 int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
1907
                                    void *, int),
1908
                 int (*fparse) (netsnmp_session *, netsnmp_pdu *, u_char *,
1909
                                size_t),
1910
                 int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *,
1911
                                     int),
1912
                 int (*fbuild) (netsnmp_session *, netsnmp_pdu *, u_char *,
1913
                                size_t *),
1914
                 int (*frbuild) (netsnmp_session *, netsnmp_pdu *,
1915
                                 u_char **, size_t *, size_t *),
1916
                 int (*fcheck) (u_char *, size_t),
1917
                 netsnmp_pdu *(*fcreate_pdu) (netsnmp_transport *, void *,
1918
                                              size_t))
1919
2.80k
{
1920
2.80k
    struct session_list *slp;
1921
2.80k
    int rc;
1922
    
1923
2.80k
    _init_snmp();
1924
1925
2.80k
    if (transport == NULL)
1926
0
        return NULL;
1927
1928
2.80k
    if (NULL != in_session && (in_session->rcvMsgMaxSize < SNMP_MIN_MAX_LEN ||
1929
2.80k
                               in_session->sndMsgMaxSize < SNMP_MIN_MAX_LEN)) {
1930
0
        DEBUGMSGTL(("snmp_sess_add",
1931
0
                    "invalid session (msg sizes). need snmp_sess_init"));
1932
0
        in_session = NULL; /* force transport cleanup below */
1933
0
    }
1934
1935
2.80k
    if (in_session == NULL) {
1936
0
        transport->f_close(transport);
1937
0
        netsnmp_transport_free(transport);
1938
0
        return NULL;
1939
0
    }
1940
1941
    /* if the transport hasn't been fully opened yet, open it now */
1942
2.80k
    if ((rc = netsnmp_sess_config_and_open_transport(in_session, transport))
1943
2.80k
        != SNMPERR_SUCCESS) {
1944
0
        return NULL;
1945
0
    }
1946
1947
2.80k
    DEBUGMSGTL(("snmp_sess_add", "fd %" NETSNMP_FMT_SKT "\n",
1948
2.80k
                transport->sock));
1949
1950
2.80k
    if ((slp = snmp_sess_copy(in_session)) == NULL) {
1951
0
        transport->f_close(transport);
1952
0
        netsnmp_transport_free(transport);
1953
0
        return (NULL);
1954
0
    }
1955
1956
2.80k
    slp->transport = transport;
1957
2.80k
    slp->internal->hook_pre = fpre_parse;
1958
2.80k
    slp->internal->hook_parse = fparse;
1959
2.80k
    slp->internal->hook_post = fpost_parse;
1960
2.80k
    slp->internal->hook_build = fbuild;
1961
2.80k
    slp->internal->hook_realloc_build = frbuild;
1962
2.80k
    slp->internal->check_packet = fcheck;
1963
2.80k
    slp->internal->hook_create_pdu = fcreate_pdu;
1964
1965
    /** don't let session max exceed transport max */
1966
2.80k
    if (slp->session->rcvMsgMaxSize > transport->msgMaxSize) {
1967
0
        DEBUGMSGTL(("snmp_sess_add",
1968
0
                    "limiting session rcv size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1969
0
                    slp->session->rcvMsgMaxSize, transport->msgMaxSize));
1970
0
        slp->session->rcvMsgMaxSize = transport->msgMaxSize;
1971
0
    }
1972
2.80k
    if (slp->session->sndMsgMaxSize > transport->msgMaxSize) {
1973
0
        DEBUGMSGTL(("snmp_sess_add",
1974
0
                    "limiting session snd size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1975
0
                    slp->session->sndMsgMaxSize, transport->msgMaxSize));
1976
0
        slp->session->sndMsgMaxSize = transport->msgMaxSize;
1977
0
    }
1978
1979
2.80k
    if (transport->f_setup_session &&
1980
0
        transport->f_setup_session(transport, slp->session) != SNMPERR_SUCCESS)
1981
0
        goto close_session;
1982
1983
    /* Anything below this point should only be done if the transport
1984
       had no say in the matter */
1985
2.80k
    if (slp->session->securityLevel == 0)
1986
2.80k
        slp->session->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
1987
1988
2.80k
    if (slp->session->version == SNMP_VERSION_3) {
1989
0
        DEBUGMSGTL(("snmp_sess_add",
1990
0
                    "adding v3 session -- maybe engineID probe now\n"));
1991
0
        if (!snmpv3_engineID_probe(slp, slp->session)) {
1992
0
            DEBUGMSGTL(("snmp_sess_add", "engine ID probe failed\n"));
1993
0
            goto close_session;
1994
0
        }
1995
0
    }
1996
1997
2.80k
    slp->session->flags &= ~SNMP_FLAGS_DONT_PROBE;
1998
1999
2.80k
    return slp;
2000
2001
0
close_session:
2002
0
    snmp_sess_close(slp);
2003
0
    return NULL;
2004
2.80k
}                               /*  end snmp_sess_add_ex()  */
2005
2006
struct session_list *
2007
snmp_sess_add(netsnmp_session * in_session,
2008
              netsnmp_transport *transport,
2009
              int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
2010
                                 void *, int),
2011
              int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *, int))
2012
0
{
2013
0
    return snmp_sess_add_ex(in_session, transport, fpre_parse, NULL,
2014
0
                            fpost_parse, NULL, NULL, NULL, NULL);
2015
0
}
2016
2017
2018
2019
struct session_list *
2020
snmp_sess_open(netsnmp_session * pss)
2021
0
{
2022
0
    struct session_list *slp;
2023
2024
0
    pss->flags |= SNMP_FLAGS_SESSION_USER;
2025
2026
0
    slp = _sess_open(pss);
2027
0
    if (!slp) {
2028
0
        SET_SNMP_ERROR(pss->s_snmp_errno);
2029
0
    }
2030
0
    return slp;
2031
0
}
2032
2033
int
2034
0
create_user_from_session(netsnmp_session * session) {
2035
0
#ifdef NETSNMP_SECMOD_USM
2036
0
    return usm_create_user_from_session(session);
2037
#else
2038
    snmp_log(LOG_ERR, "create_user_from_session called when USM wasn't compiled in");
2039
    netsnmp_assert(0 == 1);
2040
    return SNMP_ERR_GENERR;
2041
#endif
2042
0
}
2043
2044
static void netsnmp_free_one_tr_cfg(void *data, void *context)
2045
0
{
2046
0
    netsnmp_transport_config *c = data;
2047
2048
0
    free(c->key);
2049
0
    free(c->value);
2050
0
    free(c);
2051
0
}
2052
2053
static void netsnmp_free_transport_config(netsnmp_container *tc)
2054
37.7k
{
2055
37.7k
    if (!tc)
2056
37.7k
        return;
2057
2058
0
    CONTAINER_CLEAR(tc, netsnmp_free_one_tr_cfg, NULL);
2059
0
    CONTAINER_FREE(tc);
2060
0
}
2061
2062
/* Free the memory owned by a session but not the session object itself. */
2063
void netsnmp_cleanup_session(netsnmp_session *s)
2064
37.7k
{
2065
37.7k
    free(s->localname);
2066
37.7k
    free(s->peername);
2067
37.7k
    free(s->community);
2068
37.7k
    free(s->contextEngineID);
2069
37.7k
    free(s->contextName);
2070
37.7k
    free(s->securityEngineID);
2071
37.7k
    free(s->securityName);
2072
37.7k
    free(s->securityAuthProto);
2073
37.7k
    free(s->securityAuthLocalKey);
2074
37.7k
    free(s->securityPrivProto);
2075
37.7k
    free(s->securityPrivLocalKey);
2076
37.7k
    free(s->paramName);
2077
37.7k
#ifndef NETSNMP_NO_TRAP_STATS
2078
37.7k
    free(s->trap_stats);
2079
37.7k
#endif /* NETSNMP_NO_TRAP_STATS */
2080
37.7k
    usm_free_user(s->sessUser);
2081
37.7k
    netsnmp_free_transport_config(s->transport_configuration);
2082
37.7k
    memset(s, 0, sizeof(*s));
2083
37.7k
}
2084
2085
/*
2086
 *  Do a "deep free()" of a netsnmp_session.
2087
 *
2088
 *  CAUTION:  SHOULD ONLY BE USED FROM snmp_sess_close() OR SIMILAR.
2089
 *                                                      (hence it is static)
2090
 */
2091
static void
2092
snmp_free_session(netsnmp_session * s)
2093
37.7k
{
2094
37.7k
    if (!s)
2095
0
        return;
2096
2097
37.7k
    netsnmp_cleanup_session(s);
2098
2099
    /*
2100
     * clear session from any callbacks
2101
     */
2102
37.7k
    netsnmp_callback_clear_client_arg(s, 0, 0);
2103
2104
37.7k
    free(s);
2105
37.7k
}
2106
2107
/* Remove request @rp from session @isp. @orp is the request before @rp. */
2108
static void
2109
remove_request(struct snmp_internal_session *isp,
2110
               netsnmp_request_list *orp, netsnmp_request_list *rp)
2111
0
{
2112
0
    if (orp)
2113
0
        orp->next_request = rp->next_request;
2114
0
    else
2115
0
        isp->requests = rp->next_request;
2116
0
    if (isp->requestsEnd == rp)
2117
0
        isp->requestsEnd = orp;
2118
0
    if (rp->cb_data_refcounted) {
2119
0
        netsnmp_refcnt_void *aux = (netsnmp_refcnt_void*) rp->cb_data;
2120
0
        if (aux) {
2121
0
            aux->refcnt--;
2122
0
            if (aux->refcnt <= 0) {
2123
0
                free(aux);
2124
0
            }
2125
0
        }
2126
0
    }
2127
0
    snmp_free_pdu(rp->pdu);
2128
0
}
2129
2130
/*
2131
 * Close the input session.  Frees all data allocated for the session,
2132
 * dequeues any pending requests, and closes any sockets allocated for
2133
 * the session.  Returns 0 on error, 1 otherwise.
2134
 */
2135
int
2136
snmp_sess_close(struct session_list *slp)
2137
2.80k
{
2138
2.80k
    netsnmp_transport *transport;
2139
2.80k
    struct snmp_internal_session *isp;
2140
2.80k
    netsnmp_session *sesp = NULL;
2141
2.80k
    struct snmp_secmod_def *sptr;
2142
2143
2.80k
    if (slp == NULL) {
2144
0
        return 0;
2145
0
    }
2146
2147
2.80k
    if (slp->session != NULL &&
2148
2.80k
        (sptr = find_sec_mod(slp->session->securityModel)) != NULL &&
2149
2.80k
        sptr->session_close != NULL) {
2150
0
        (*sptr->session_close) (slp->session);
2151
0
    }
2152
2153
2.80k
    isp = slp->internal;
2154
2.80k
    slp->internal = NULL;
2155
2156
2.80k
    if (isp) {
2157
2.80k
        netsnmp_request_list *rp, *orp;
2158
2159
2.80k
        SNMP_FREE(isp->packet);
2160
2161
        /*
2162
         * Free each element in the input request list.  
2163
         */
2164
2.80k
        rp = isp->requests;
2165
2.80k
        while (rp) {
2166
0
            orp = rp;
2167
0
            rp = rp->next_request;
2168
0
            if (orp->callback) {
2169
0
                orp->callback(NETSNMP_CALLBACK_OP_TIMED_OUT,
2170
0
                              slp->session, orp->pdu->reqid,
2171
0
                              orp->pdu, orp->cb_data);
2172
0
            }
2173
0
            remove_request(isp, NULL, orp);
2174
0
            free(orp);
2175
0
        }
2176
2177
2.80k
        free(isp);
2178
2.80k
    }
2179
2180
2.80k
    transport = slp->transport;
2181
2.80k
    slp->transport = NULL;
2182
2183
2.80k
    if (transport) {
2184
2.80k
        transport->f_close(transport);
2185
2.80k
        netsnmp_transport_free(transport);
2186
2.80k
    }
2187
2188
2.80k
    sesp = slp->session;
2189
2.80k
    slp->session = NULL;
2190
2191
    /*
2192
     * The following is necessary to avoid memory leakage when closing AgentX 
2193
     * sessions that may have multiple subsessions.  These hang off the main
2194
     * session at ->subsession, and chain through ->next.  
2195
     */
2196
2197
2.80k
    if (sesp != NULL && sesp->subsession != NULL) {
2198
786
        netsnmp_session *subsession = sesp->subsession, *tmpsub;
2199
2200
35.7k
        while (subsession != NULL) {
2201
34.9k
            DEBUGMSGTL(("snmp_sess_close",
2202
34.9k
                        "closing session %p, subsession %p\n", sesp,
2203
34.9k
                        subsession));
2204
34.9k
            tmpsub = subsession->next;
2205
34.9k
            snmp_free_session(subsession);
2206
34.9k
            subsession = tmpsub;
2207
34.9k
        }
2208
786
    }
2209
2210
2.80k
    snmp_free_session(sesp);
2211
2.80k
    free(slp);
2212
2.80k
    return 1;
2213
2.80k
}
2214
2215
int
2216
snmp_close(netsnmp_session * session)
2217
2.80k
{
2218
2.80k
    struct session_list *slp = NULL, *oslp = NULL;
2219
2220
2.80k
    {                           /*MTCRITICAL_RESOURCE */
2221
2.80k
        snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
2222
2.80k
        if (Sessions && Sessions->session == session) { /* If first entry */
2223
2.80k
            slp = Sessions;
2224
2.80k
            Sessions = slp->next;
2225
2.80k
        } else {
2226
0
            for (slp = Sessions; slp; slp = slp->next) {
2227
0
                if (slp->session == session) {
2228
0
                    if (oslp)   /* if we found entry that points here */
2229
0
                        oslp->next = slp->next; /* link around this entry */
2230
0
                    break;
2231
0
                }
2232
0
                oslp = slp;
2233
0
            }
2234
0
        }
2235
2.80k
        snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
2236
2.80k
    }                           /*END MTCRITICAL_RESOURCE */
2237
2.80k
    if (slp == NULL) {
2238
0
        return 0;
2239
0
    }
2240
2.80k
    return snmp_sess_close(slp);
2241
2.80k
}
2242
2243
int
2244
snmp_close_sessions(void)
2245
0
{
2246
0
    struct session_list *slp;
2247
2248
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
2249
0
    while (Sessions) {
2250
0
        slp = Sessions;
2251
0
        Sessions = Sessions->next;
2252
0
        snmp_sess_close(slp);
2253
0
    }
2254
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
2255
0
    return 1;
2256
0
}
2257
2258
static void
2259
snmpv3_calc_msg_flags(int sec_level, int msg_command, u_char * flags)
2260
0
{
2261
0
    *flags = 0;
2262
0
    if (sec_level == SNMP_SEC_LEVEL_AUTHNOPRIV)
2263
0
        *flags = SNMP_MSG_FLAG_AUTH_BIT;
2264
0
    else if (sec_level == SNMP_SEC_LEVEL_AUTHPRIV)
2265
0
        *flags = SNMP_MSG_FLAG_AUTH_BIT | SNMP_MSG_FLAG_PRIV_BIT;
2266
2267
0
    if (SNMP_CMD_CONFIRMED(msg_command))
2268
0
        *flags |= SNMP_MSG_FLAG_RPRT_BIT;
2269
2270
0
    return;
2271
0
}
2272
2273
static int
2274
snmpv3_verify_msg(netsnmp_request_list *rp, netsnmp_pdu *pdu)
2275
0
{
2276
0
    netsnmp_pdu    *rpdu;
2277
2278
    /* XX: This function silently rejects. Add error handling. */
2279
0
    if (!rp || !rp->pdu || !pdu)
2280
0
        return 0;
2281
    /*
2282
     * Reports don't have to match anything according to the spec 
2283
     */
2284
0
    if (pdu->command == SNMP_MSG_REPORT)
2285
0
        return 1;
2286
0
    rpdu = rp->pdu;
2287
0
    if (rp->request_id != pdu->reqid || rpdu->reqid != pdu->reqid)
2288
0
        return 0;
2289
0
    if (rpdu->version != pdu->version)
2290
0
        return 0;
2291
0
    if (rpdu->securityModel != pdu->securityModel)
2292
0
        return 0;
2293
0
    if (rpdu->securityLevel != pdu->securityLevel)
2294
0
        return 0;
2295
2296
0
    if (rpdu->contextEngineIDLen != pdu->contextEngineIDLen)
2297
0
        return 0;
2298
0
    if (pdu->contextEngineIDLen &&
2299
0
        memcmp(rpdu->contextEngineID, pdu->contextEngineID,
2300
0
               pdu->contextEngineIDLen))
2301
0
        return 0;
2302
0
    if (rpdu->contextNameLen != pdu->contextNameLen)
2303
0
        return 0;
2304
0
    if (pdu->contextNameLen &&
2305
0
        memcmp(rpdu->contextName, pdu->contextName, pdu->contextNameLen))
2306
0
        return 0;
2307
2308
    /* tunneled transports don't have a securityEngineID...  that's
2309
       USM specific (and maybe other future ones) */
2310
0
    if (pdu->securityModel == SNMP_SEC_MODEL_USM &&
2311
0
        (rpdu->securityEngineIDLen != pdu->securityEngineIDLen ||
2312
0
         (pdu->securityEngineIDLen &&
2313
0
          memcmp(rpdu->securityEngineID, pdu->securityEngineID,
2314
0
                 pdu->securityEngineIDLen))))
2315
0
        return 0;
2316
2317
    /* the securityName must match though regardless of secmodel */
2318
0
    if (rpdu->securityNameLen != pdu->securityNameLen ||
2319
0
        memcmp(rpdu->securityName, pdu->securityName,
2320
0
               pdu->securityNameLen))
2321
0
        return 0;
2322
0
    return 1;
2323
0
}
2324
2325
2326
/*
2327
 * SNMPv3
2328
 * * Takes a session and a pdu and serializes the ASN PDU into the area
2329
 * * pointed to by packet.  out_length is the size of the data area available.
2330
 * * Returns the length of the completed packet in out_length.  If any errors
2331
 * * occur, -1 is returned.  If all goes well, 0 is returned.
2332
 */
2333
static int
2334
snmpv3_build(u_char ** pkt, size_t * pkt_len, size_t * offset,
2335
             netsnmp_session * session, netsnmp_pdu *pdu)
2336
0
{
2337
0
    int             ret;
2338
2339
0
    session->s_snmp_errno = 0;
2340
0
    session->s_errno = 0;
2341
2342
    /*
2343
     * do validation for PDU types 
2344
     */
2345
0
    switch (pdu->command) {
2346
0
    case SNMP_MSG_RESPONSE:
2347
0
    case SNMP_MSG_TRAP2:
2348
0
    case SNMP_MSG_REPORT:
2349
0
        netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
2350
0
        NETSNMP_FALLTHROUGH;
2351
0
    case SNMP_MSG_INFORM:
2352
0
#ifndef NETSNMP_NOTIFY_ONLY
2353
0
    case SNMP_MSG_GET:
2354
0
    case SNMP_MSG_GETNEXT:
2355
0
#endif /* ! NETSNMP_NOTIFY_ONLY */
2356
0
#ifndef NETSNMP_NO_WRITE_SUPPORT
2357
0
    case SNMP_MSG_SET:
2358
0
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
2359
0
        if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
2360
0
            pdu->errstat = 0;
2361
0
        if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
2362
0
            pdu->errindex = 0;
2363
0
        break;
2364
2365
0
#ifndef NETSNMP_NOTIFY_ONLY
2366
0
    case SNMP_MSG_GETBULK:
2367
0
        if (pdu->max_repetitions < 0) {
2368
0
            session->s_snmp_errno = SNMPERR_BAD_REPETITIONS;
2369
0
            return -1;
2370
0
        }
2371
0
        if (pdu->non_repeaters < 0) {
2372
0
            session->s_snmp_errno = SNMPERR_BAD_REPEATERS;
2373
0
            return -1;
2374
0
        }
2375
0
        break;
2376
0
#endif /* ! NETSNMP_NOTIFY_ONLY */
2377
2378
0
    case SNMP_MSG_TRAP:
2379
0
        session->s_snmp_errno = SNMPERR_V1_IN_V2;
2380
0
        return -1;
2381
2382
0
    default:
2383
0
        session->s_snmp_errno = SNMPERR_UNKNOWN_PDU;
2384
0
        return -1;
2385
0
    }
2386
2387
    /* Do we need to set the session security engineid? */
2388
0
    if (pdu->securityEngineIDLen == 0) {
2389
0
        if (session->securityEngineIDLen) {
2390
0
            snmpv3_clone_engineID(&pdu->securityEngineID,
2391
0
                                  &pdu->securityEngineIDLen,
2392
0
                                  session->securityEngineID,
2393
0
                                  session->securityEngineIDLen);
2394
0
        }
2395
0
    }
2396
    
2397
    /* Do we need to set the session context engineid? */
2398
0
    if (pdu->contextEngineIDLen == 0) {
2399
0
        if (session->contextEngineIDLen) {
2400
0
            snmpv3_clone_engineID(&pdu->contextEngineID,
2401
0
                                  &pdu->contextEngineIDLen,
2402
0
                                  session->contextEngineID,
2403
0
                                  session->contextEngineIDLen);
2404
0
        } else if (pdu->securityEngineIDLen) {
2405
0
            snmpv3_clone_engineID(&pdu->contextEngineID,
2406
0
                                  &pdu->contextEngineIDLen,
2407
0
                                  pdu->securityEngineID,
2408
0
                                  pdu->securityEngineIDLen);
2409
0
        }
2410
0
    }
2411
2412
0
    if (pdu->contextName == NULL) {
2413
0
        if (!session->contextName) {
2414
0
            session->s_snmp_errno = SNMPERR_BAD_CONTEXT;
2415
0
            return -1;
2416
0
        }
2417
0
        pdu->contextName = strdup(session->contextName);
2418
0
        if (pdu->contextName == NULL) {
2419
0
            session->s_snmp_errno = SNMPERR_GENERR;
2420
0
            return -1;
2421
0
        }
2422
0
        pdu->contextNameLen = session->contextNameLen;
2423
0
    }
2424
0
    if (pdu->securityModel == SNMP_DEFAULT_SECMODEL) {
2425
0
        pdu->securityModel = session->securityModel;
2426
0
        if (pdu->securityModel == SNMP_DEFAULT_SECMODEL) {
2427
0
            pdu->securityModel = se_find_value_in_slist("snmp_secmods", netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECMODEL));
2428
            
2429
0
            if (pdu->securityModel <= 0) {
2430
0
                pdu->securityModel = SNMP_SEC_MODEL_USM;
2431
0
            }
2432
0
        }
2433
0
    }
2434
0
    if (pdu->securityNameLen == 0 && pdu->securityName == NULL) {
2435
0
        if (session->securityModel != SNMP_SEC_MODEL_TSM &&
2436
0
            session->securityNameLen == 0) {
2437
0
            session->s_snmp_errno = SNMPERR_BAD_SEC_NAME;
2438
0
            return -1;
2439
0
        }
2440
0
        if (session->securityName) {
2441
0
            pdu->securityName = strdup(session->securityName);
2442
0
            if (pdu->securityName == NULL) {
2443
0
                session->s_snmp_errno = SNMPERR_GENERR;
2444
0
                return -1;
2445
0
            }
2446
0
            pdu->securityNameLen = session->securityNameLen;
2447
0
        } else {
2448
0
            pdu->securityName = strdup("");
2449
0
            session->securityName = strdup("");
2450
0
            if (pdu->securityName == NULL || session->securityName == NULL) {
2451
0
                SNMP_FREE(pdu->securityName);
2452
0
                SNMP_FREE(session->securityName);
2453
0
                session->s_snmp_errno = SNMPERR_GENERR;
2454
0
                return -1;
2455
0
            }
2456
0
        }
2457
0
    }
2458
0
    if (pdu->securityLevel == 0) {
2459
0
        if (session->securityLevel == 0) {
2460
0
            session->s_snmp_errno = SNMPERR_BAD_SEC_LEVEL;
2461
0
            return -1;
2462
0
        }
2463
0
        pdu->securityLevel = session->securityLevel;
2464
0
    }
2465
0
    DEBUGMSGTL(("snmp_build",
2466
0
                "Building SNMPv3 message (secName:\"%s\", secLevel:%s)...\n",
2467
0
                ((session->securityName) ? (char *) session->securityName :
2468
0
                 ((pdu->securityName) ? (char *) pdu->securityName :
2469
0
                  "ERROR: undefined")),
2470
0
                (pdu->securityLevel >= 0 && pdu->securityLevel < 4) ?
2471
0
                secLevelName[pdu->securityLevel] : "ERROR: invalid"));
2472
2473
0
    DEBUGDUMPSECTION("send", "SNMPv3 Message");
2474
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
2475
0
    if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
2476
0
        ret = snmpv3_packet_realloc_rbuild(pkt, pkt_len, offset,
2477
0
                                           session, pdu, NULL, 0);
2478
0
    } else {
2479
0
#endif
2480
0
        ret = snmpv3_packet_build(session, pdu, *pkt, pkt_len, NULL, 0);
2481
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
2482
0
    }
2483
0
#endif
2484
0
    DEBUGINDENTLESS();
2485
0
    if (-1 != ret) {
2486
0
        session->s_snmp_errno = ret;
2487
0
    }
2488
2489
0
    return ret;
2490
2491
0
}                               /* end snmpv3_build() */
2492
2493
2494
2495
2496
static u_char  *
2497
snmpv3_header_build(netsnmp_session * session, const netsnmp_pdu *pdu,
2498
                    u_char * packet, size_t * out_length,
2499
                    size_t length, u_char ** msg_hdr_e)
2500
0
{
2501
0
    u_char         *global_hdr, *global_hdr_e;
2502
0
    u_char         *cp;
2503
0
    u_char          msg_flags;
2504
0
    long            max_size;
2505
0
    long            sec_model;
2506
0
    u_char         *pb, *pb0e;
2507
2508
    /*
2509
     * Save current location and build SEQUENCE tag and length placeholder
2510
     * * for SNMP message sequence (actual length inserted later)
2511
     */
2512
0
    cp = asn_build_sequence(packet, out_length,
2513
0
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
2514
0
                            length);
2515
0
    if (cp == NULL)
2516
0
        return NULL;
2517
0
    if (msg_hdr_e != NULL)
2518
0
        *msg_hdr_e = cp;
2519
0
    pb0e = cp;
2520
2521
2522
    /*
2523
     * store the version field - msgVersion
2524
     */
2525
0
    DEBUGDUMPHEADER("send", "SNMP Version Number");
2526
0
    cp = asn_build_int(cp, out_length,
2527
0
                       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2528
0
                                 ASN_INTEGER), (const long *) &pdu->version,
2529
0
                       sizeof(pdu->version));
2530
0
    DEBUGINDENTLESS();
2531
0
    if (cp == NULL)
2532
0
        return NULL;
2533
2534
0
    global_hdr = cp;
2535
    /*
2536
     * msgGlobalData HeaderData 
2537
     */
2538
0
    DEBUGDUMPSECTION("send", "msgGlobalData");
2539
0
    cp = asn_build_sequence(cp, out_length,
2540
0
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
2541
0
    if (cp == NULL)
2542
0
        return NULL;
2543
0
    global_hdr_e = cp;
2544
2545
2546
    /*
2547
     * msgID 
2548
     */
2549
0
    DEBUGDUMPHEADER("send", "msgID");
2550
0
    cp = asn_build_int(cp, out_length,
2551
0
                       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2552
0
                                 ASN_INTEGER), &pdu->msgid,
2553
0
                       sizeof(pdu->msgid));
2554
0
    DEBUGINDENTLESS();
2555
0
    if (cp == NULL)
2556
0
        return NULL;
2557
2558
    /*
2559
     * msgMaxSize 
2560
     */
2561
0
    max_size = netsnmp_max_send_msg_size();
2562
0
    if (session->rcvMsgMaxSize < max_size)
2563
0
        max_size = session->rcvMsgMaxSize;
2564
0
    DEBUGDUMPHEADER("send:msgMaxSize1", "msgMaxSize");
2565
0
    cp = asn_build_int(cp, out_length,
2566
0
                       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2567
0
                                 ASN_INTEGER), &max_size,
2568
0
                       sizeof(max_size));
2569
0
    DEBUGINDENTLESS();
2570
0
    if (cp == NULL)
2571
0
        return NULL;
2572
2573
    /*
2574
     * msgFlags 
2575
     */
2576
0
    snmpv3_calc_msg_flags(pdu->securityLevel, pdu->command, &msg_flags);
2577
0
    DEBUGDUMPHEADER("send", "msgFlags");
2578
0
    cp = asn_build_string(cp, out_length,
2579
0
                          (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2580
0
                                    ASN_OCTET_STR), &msg_flags,
2581
0
                          sizeof(msg_flags));
2582
0
    DEBUGINDENTLESS();
2583
0
    if (cp == NULL)
2584
0
        return NULL;
2585
2586
    /*
2587
     * msgSecurityModel 
2588
     */
2589
0
    sec_model = pdu->securityModel;
2590
0
    DEBUGDUMPHEADER("send", "msgSecurityModel");
2591
0
    cp = asn_build_int(cp, out_length,
2592
0
                       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2593
0
                                 ASN_INTEGER), &sec_model,
2594
0
                       sizeof(sec_model));
2595
0
    DEBUGINDENTADD(-4);         /* return from global data indent */
2596
0
    if (cp == NULL)
2597
0
        return NULL;
2598
2599
2600
    /*
2601
     * insert actual length of globalData
2602
     */
2603
0
    pb = asn_build_sequence(global_hdr, out_length,
2604
0
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
2605
0
                            cp - global_hdr_e);
2606
0
    if (pb == NULL)
2607
0
        return NULL;
2608
2609
2610
    /*
2611
     * insert the actual length of the entire packet
2612
     */
2613
0
    pb = asn_build_sequence(packet, out_length,
2614
0
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
2615
0
                            length + (cp - pb0e));
2616
0
    if (pb == NULL)
2617
0
        return NULL;
2618
2619
0
    return cp;
2620
2621
0
}                               /* end snmpv3_header_build() */
2622
2623
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
2624
2625
int
2626
snmpv3_header_realloc_rbuild(u_char ** pkt, size_t * pkt_len,
2627
                             size_t * offset, netsnmp_session * session,
2628
                             netsnmp_pdu *pdu)
2629
0
{
2630
0
    size_t          start_offset = *offset;
2631
0
    u_char          msg_flags;
2632
0
    long            max_size, sec_model;
2633
0
    int             rc = 0;
2634
2635
    /*
2636
     * msgSecurityModel.  
2637
     */
2638
0
    sec_model = pdu->securityModel;
2639
0
    DEBUGDUMPHEADER("send", "msgSecurityModel");
2640
0
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2641
0
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2642
0
                                          ASN_INTEGER), &sec_model,
2643
0
                                sizeof(sec_model));
2644
0
    DEBUGINDENTLESS();
2645
0
    if (rc == 0) {
2646
0
        return 0;
2647
0
    }
2648
2649
    /*
2650
     * msgFlags.  
2651
     */
2652
0
    snmpv3_calc_msg_flags(pdu->securityLevel, pdu->command, &msg_flags);
2653
0
    DEBUGDUMPHEADER("send", "msgFlags");
2654
0
    rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
2655
0
                                   (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
2656
0
                                             | ASN_OCTET_STR), &msg_flags,
2657
0
                                   sizeof(msg_flags));
2658
0
    DEBUGINDENTLESS();
2659
0
    if (rc == 0) {
2660
0
        return 0;
2661
0
    }
2662
2663
    /*
2664
     * msgMaxSize.  
2665
     */
2666
0
    max_size = netsnmp_max_send_msg_size();
2667
0
    if (session->rcvMsgMaxSize < max_size)
2668
0
        max_size = session->rcvMsgMaxSize;
2669
0
    DEBUGDUMPHEADER("send:msgMaxSize2", "msgMaxSize");
2670
0
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2671
0
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2672
0
                                          ASN_INTEGER), &max_size,
2673
0
                                sizeof(max_size));
2674
0
    DEBUGINDENTLESS();
2675
0
    if (rc == 0) {
2676
0
        return 0;
2677
0
    }
2678
2679
    /*
2680
     * msgID.  
2681
     */
2682
0
    DEBUGDUMPHEADER("send", "msgID");
2683
0
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2684
0
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2685
0
                                          ASN_INTEGER), &pdu->msgid,
2686
0
                                sizeof(pdu->msgid));
2687
0
    DEBUGINDENTLESS();
2688
0
    if (rc == 0) {
2689
0
        return 0;
2690
0
    }
2691
2692
    /*
2693
     * Global data sequence.  
2694
     */
2695
0
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
2696
0
                                     (u_char) (ASN_SEQUENCE |
2697
0
                                               ASN_CONSTRUCTOR),
2698
0
                                     *offset - start_offset);
2699
0
    if (rc == 0) {
2700
0
        return 0;
2701
0
    }
2702
2703
    /*
2704
     * Store the version field - msgVersion.  
2705
     */
2706
0
    DEBUGDUMPHEADER("send", "SNMP Version Number");
2707
0
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2708
0
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2709
0
                                          ASN_INTEGER),
2710
0
                                (long *) &pdu->version,
2711
0
                                sizeof(pdu->version));
2712
0
    DEBUGINDENTLESS();
2713
0
    return rc;
2714
0
}                               /* end snmpv3_header_realloc_rbuild() */
2715
#endif                          /* NETSNMP_USE_REVERSE_ASNENCODING */
2716
2717
static u_char  *
2718
snmpv3_scopedPDU_header_build(const netsnmp_pdu *pdu,
2719
                              u_char * packet, size_t * out_length,
2720
                              u_char ** spdu_e)
2721
0
{
2722
0
    u_char         *scopedPdu, *pb;
2723
2724
0
    pb = scopedPdu = packet;
2725
0
    pb = asn_build_sequence(pb, out_length,
2726
0
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
2727
0
    if (pb == NULL)
2728
0
        return NULL;
2729
0
    if (spdu_e)
2730
0
        *spdu_e = pb;
2731
2732
0
    DEBUGDUMPHEADER("send", "contextEngineID");
2733
0
    pb = asn_build_string(pb, out_length,
2734
0
                          (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OCTET_STR),
2735
0
                          pdu->contextEngineID, pdu->contextEngineIDLen);
2736
0
    DEBUGINDENTLESS();
2737
0
    if (pb == NULL)
2738
0
        return NULL;
2739
2740
0
    DEBUGDUMPHEADER("send", "contextName");
2741
0
    pb = asn_build_string(pb, out_length,
2742
0
                          (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OCTET_STR),
2743
0
                          (u_char *) pdu->contextName,
2744
0
                          pdu->contextNameLen);
2745
0
    DEBUGINDENTLESS();
2746
0
    if (pb == NULL)
2747
0
        return NULL;
2748
2749
0
    return pb;
2750
2751
0
}                               /* end snmpv3_scopedPDU_header_build() */
2752
2753
2754
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
2755
int
2756
snmpv3_scopedPDU_header_realloc_rbuild(u_char ** pkt, size_t * pkt_len,
2757
                                       size_t * offset, netsnmp_pdu *pdu,
2758
                                       size_t body_len)
2759
0
{
2760
0
    size_t          start_offset = *offset;
2761
0
    int             rc = 0;
2762
2763
    /*
2764
     * contextName.  
2765
     */
2766
0
    DEBUGDUMPHEADER("send", "contextName");
2767
0
    rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
2768
0
                                   (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
2769
0
                                             | ASN_OCTET_STR),
2770
0
                                   (u_char *) pdu->contextName,
2771
0
                                   pdu->contextNameLen);
2772
0
    DEBUGINDENTLESS();
2773
0
    if (rc == 0) {
2774
0
        return 0;
2775
0
    }
2776
2777
    /*
2778
     * contextEngineID.  
2779
     */
2780
0
    DEBUGDUMPHEADER("send", "contextEngineID");
2781
0
    rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
2782
0
                                   (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
2783
0
                                             | ASN_OCTET_STR),
2784
0
                                   pdu->contextEngineID,
2785
0
                                   pdu->contextEngineIDLen);
2786
0
    DEBUGINDENTLESS();
2787
0
    if (rc == 0) {
2788
0
        return 0;
2789
0
    }
2790
2791
0
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
2792
0
                                     (u_char) (ASN_SEQUENCE |
2793
0
                                               ASN_CONSTRUCTOR),
2794
0
                                     *offset - start_offset + body_len);
2795
2796
0
    return rc;
2797
0
}                               /* end snmpv3_scopedPDU_header_realloc_rbuild() */
2798
#endif                          /* NETSNMP_USE_REVERSE_ASNENCODING */
2799
2800
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
2801
/*
2802
 * returns 0 if success, -1 if fail, not 0 if SM build failure 
2803
 */
2804
int
2805
snmpv3_packet_realloc_rbuild(u_char ** pkt, size_t * pkt_len,
2806
                             size_t * offset, netsnmp_session * session,
2807
                             netsnmp_pdu *pdu, u_char * pdu_data,
2808
                             size_t pdu_data_len)
2809
0
{
2810
0
    u_char         *scoped_pdu, *hdrbuf = NULL, *hdr = NULL;
2811
0
    size_t          hdrbuf_len = SNMP_MAX_MSG_V3_HDRS, hdr_offset =
2812
0
        0, spdu_offset = 0;
2813
0
    size_t          body_end_offset = *offset, body_len = 0;
2814
0
    struct snmp_secmod_def *sptr = NULL;
2815
0
    int             rc = 0;
2816
2817
    /*
2818
     * Build a scopedPDU structure into the packet buffer.  
2819
     */
2820
0
    DEBUGPRINTPDUTYPE("send", pdu->command);
2821
0
    if (pdu_data) {
2822
0
        while ((*pkt_len - *offset) < pdu_data_len) {
2823
0
            if (!asn_realloc(pkt, pkt_len)) {
2824
0
                return -1;
2825
0
            }
2826
0
        }
2827
2828
0
        *offset += pdu_data_len;
2829
0
        memcpy(*pkt + *pkt_len - *offset, pdu_data, pdu_data_len);
2830
0
    } else {
2831
0
        rc = snmp_pdu_realloc_rbuild(pkt, pkt_len, offset, pdu);
2832
0
        if (rc == 0) {
2833
0
            return -1;
2834
0
        }
2835
0
    }
2836
0
    body_len = *offset - body_end_offset;
2837
2838
0
    DEBUGDUMPSECTION("send", "ScopedPdu");
2839
0
    rc = snmpv3_scopedPDU_header_realloc_rbuild(pkt, pkt_len, offset,
2840
0
                                                pdu, body_len);
2841
0
    if (rc == 0) {
2842
0
        return -1;
2843
0
    }
2844
0
    spdu_offset = *offset;
2845
0
    DEBUGINDENTADD(-4);         /*  Return from Scoped PDU.  */
2846
2847
0
    if ((hdrbuf = (u_char *) malloc(hdrbuf_len)) == NULL) {
2848
0
        return -1;
2849
0
    }
2850
2851
0
    rc = snmpv3_header_realloc_rbuild(&hdrbuf, &hdrbuf_len, &hdr_offset,
2852
0
                                      session, pdu);
2853
0
    if (rc == 0) {
2854
0
        SNMP_FREE(hdrbuf);
2855
0
        return -1;
2856
0
    }
2857
0
    hdr = hdrbuf + hdrbuf_len - hdr_offset;
2858
0
    scoped_pdu = *pkt + *pkt_len - spdu_offset;
2859
2860
    /*
2861
     * Call the security module to possibly encrypt and authenticate the
2862
     * message---the entire message to transmitted on the wire is returned.  
2863
     */
2864
2865
0
    sptr = find_sec_mod(pdu->securityModel);
2866
0
    DEBUGDUMPSECTION("send", "SM msgSecurityParameters");
2867
0
    if (sptr && sptr->encode_reverse) {
2868
0
        struct snmp_secmod_outgoing_params parms;
2869
2870
0
        parms.msgProcModel = pdu->msgParseModel;
2871
0
        parms.globalData = hdr;
2872
0
        parms.globalDataLen = hdr_offset;
2873
0
        parms.maxMsgSize = SNMP_MAX_MSG_SIZE;
2874
0
        parms.secModel = pdu->securityModel;
2875
0
        parms.secEngineID = pdu->securityEngineID;
2876
0
        parms.secEngineIDLen = pdu->securityEngineIDLen;
2877
0
        parms.secName = pdu->securityName;
2878
0
        parms.secNameLen = pdu->securityNameLen;
2879
0
        parms.secLevel = pdu->securityLevel;
2880
0
        parms.scopedPdu = scoped_pdu;
2881
0
        parms.scopedPduLen = spdu_offset;
2882
0
        parms.secStateRef = pdu->securityStateRef;
2883
0
        parms.wholeMsg = pkt;
2884
0
        parms.wholeMsgLen = pkt_len;
2885
0
        parms.wholeMsgOffset = offset;
2886
0
        parms.session = session;
2887
0
        parms.pdu = pdu;
2888
2889
0
        rc = (*sptr->encode_reverse) (&parms);
2890
0
    } else {
2891
0
        if (!sptr) {
2892
0
            snmp_log(LOG_ERR,
2893
0
                     "no such security service available: %d\n",
2894
0
                     pdu->securityModel);
2895
0
        } else if (!sptr->encode_reverse) {
2896
0
            snmp_log(LOG_ERR,
2897
0
                     "security service %d doesn't support reverse encoding.\n",
2898
0
                     pdu->securityModel);
2899
0
        }
2900
0
        rc = -1;
2901
0
    }
2902
2903
0
    DEBUGINDENTLESS();
2904
0
    SNMP_FREE(hdrbuf);
2905
0
    return rc;
2906
0
}                               /* end snmpv3_packet_realloc_rbuild() */
2907
#endif                          /* NETSNMP_USE_REVERSE_ASNENCODING */
2908
2909
/*
2910
 * returns 0 if success, -1 if fail, not 0 if SM build failure 
2911
 */
2912
int
2913
snmpv3_packet_build(netsnmp_session * session, netsnmp_pdu *pdu,
2914
                    u_char * packet, size_t * out_length,
2915
                    u_char * pdu_data, size_t pdu_data_len)
2916
0
{
2917
0
    u_char         *global_data, *sec_params, *spdu_hdr_e;
2918
0
    size_t          global_data_len, sec_params_len;
2919
0
    u_char          spdu_buf[SNMP_MAX_MSG_SIZE];
2920
0
    size_t          spdu_buf_len, spdu_len;
2921
0
    u_char         *cp;
2922
0
    int             result;
2923
0
    struct snmp_secmod_def *sptr;
2924
2925
0
    global_data = packet;
2926
2927
    /*
2928
     * build the headers for the packet, returned addr = start of secParams
2929
     */
2930
0
    sec_params = snmpv3_header_build(session, pdu, global_data,
2931
0
                                     out_length, 0, NULL);
2932
0
    if (sec_params == NULL)
2933
0
        return -1;
2934
0
    global_data_len = sec_params - global_data;
2935
0
    sec_params_len = *out_length;       /* length left in packet buf for sec_params */
2936
2937
2938
    /*
2939
     * build a scopedPDU structure into spdu_buf
2940
     */
2941
0
    spdu_buf_len = sizeof(spdu_buf);
2942
0
    DEBUGDUMPSECTION("send", "ScopedPdu");
2943
0
    cp = snmpv3_scopedPDU_header_build(pdu, spdu_buf, &spdu_buf_len,
2944
0
                                       &spdu_hdr_e);
2945
0
    if (cp == NULL)
2946
0
        return -1;
2947
2948
    /*
2949
     * build the PDU structure onto the end of spdu_buf 
2950
     */
2951
0
    DEBUGPRINTPDUTYPE("send", ((pdu_data) ? *pdu_data : 0x00));
2952
0
    if (pdu_data) {
2953
0
        if (cp + pdu_data_len > spdu_buf + sizeof(spdu_buf)) {
2954
0
            snmp_log(LOG_ERR, "%s: PDU too big (%" NETSNMP_PRIz "d > %" NETSNMP_PRIz "d)\n",
2955
0
                     NETSNMP_FUNCTION, pdu_data_len, sizeof(spdu_buf));
2956
0
            return -1;
2957
0
        }
2958
0
        memcpy(cp, pdu_data, pdu_data_len);
2959
0
        cp += pdu_data_len;
2960
0
    } else {
2961
0
        cp = snmp_pdu_build(pdu, cp, &spdu_buf_len);
2962
0
        if (cp == NULL)
2963
0
            return -1;
2964
0
    }
2965
0
    DEBUGINDENTADD(-4);         /* return from Scoped PDU */
2966
2967
    /*
2968
     * re-encode the actual ASN.1 length of the scopedPdu
2969
     */
2970
0
    spdu_len = cp - spdu_hdr_e; /* length of scopedPdu minus ASN.1 headers */
2971
0
    spdu_buf_len = sizeof(spdu_buf);
2972
0
    if (asn_build_sequence(spdu_buf, &spdu_buf_len,
2973
0
                           (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
2974
0
                           spdu_len) == NULL)
2975
0
        return -1;
2976
0
    spdu_len = cp - spdu_buf;   /* the length of the entire scopedPdu */
2977
2978
2979
    /*
2980
     * call the security module to possibly encrypt and authenticate the
2981
     * message - the entire message to transmitted on the wire is returned
2982
     */
2983
0
    cp = NULL;
2984
0
    *out_length = sizeof(spdu_buf);
2985
0
    DEBUGDUMPSECTION("send", "SM msgSecurityParameters");
2986
0
    sptr = find_sec_mod(pdu->securityModel);
2987
0
    if (sptr && sptr->encode_forward) {
2988
0
        struct snmp_secmod_outgoing_params parms;
2989
0
        parms.msgProcModel = pdu->msgParseModel;
2990
0
        parms.globalData = global_data;
2991
0
        parms.globalDataLen = global_data_len;
2992
0
        parms.maxMsgSize = SNMP_MAX_MSG_SIZE;
2993
0
        parms.secModel = pdu->securityModel;
2994
0
        parms.secEngineID = pdu->securityEngineID;
2995
0
        parms.secEngineIDLen = pdu->securityEngineIDLen;
2996
0
        parms.secName = pdu->securityName;
2997
0
        parms.secNameLen = pdu->securityNameLen;
2998
0
        parms.secLevel = pdu->securityLevel;
2999
0
        parms.scopedPdu = spdu_buf;
3000
0
        parms.scopedPduLen = spdu_len;
3001
0
        parms.secStateRef = pdu->securityStateRef;
3002
0
        parms.secParams = sec_params;
3003
0
        parms.secParamsLen = &sec_params_len;
3004
0
        parms.wholeMsg = &cp;
3005
0
        parms.wholeMsgLen = out_length;
3006
0
        parms.session = session;
3007
0
        parms.pdu = pdu;
3008
0
        result = (*sptr->encode_forward) (&parms);
3009
0
    } else {
3010
0
        if (!sptr) {
3011
0
            snmp_log(LOG_ERR, "no such security service available: %d\n",
3012
0
                     pdu->securityModel);
3013
0
        } else if (!sptr->encode_forward) {
3014
0
            snmp_log(LOG_ERR,
3015
0
                     "security service %d doesn't support forward out encoding.\n",
3016
0
                     pdu->securityModel);
3017
0
        }
3018
0
        result = -1;
3019
0
    }
3020
0
    DEBUGINDENTLESS();
3021
0
    return result;
3022
3023
0
}                               /* end snmpv3_packet_build() */
3024
3025
3026
/*
3027
 * Takes a session and a pdu and serializes the ASN PDU into the area
3028
 * pointed to by *pkt.  *pkt_len is the size of the data area available.
3029
 * Returns the length of the completed packet in *offset.  If any errors
3030
 * occur, -1 is returned.  If all goes well, 0 is returned.
3031
 */
3032
3033
static int
3034
_snmp_build(u_char ** pkt, size_t * pkt_len, size_t * offset,
3035
            netsnmp_session * session, netsnmp_pdu *pdu)
3036
0
{
3037
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3038
0
    u_char         *h0e = NULL;
3039
0
    size_t          start_offset = *offset;
3040
0
    long            version;
3041
0
    int             rc = 0;
3042
0
    size_t          length;
3043
0
#endif /* support for community based SNMP */
3044
3045
0
    u_char         *cp;
3046
3047
0
    if (NETSNMP_RUNTIME_PROTOCOL_SKIP(pdu->version)) {
3048
0
        DEBUGMSGTL(("snmp_send", "build packet (version 0x%02x disabled)\n",
3049
0
                    (u_int)pdu->version));
3050
0
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
3051
0
        return -1;
3052
0
    }
3053
3054
0
    session->s_snmp_errno = 0;
3055
0
    session->s_errno = 0;
3056
3057
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3058
0
    if ((pdu->flags & UCD_MSG_FLAG_BULK_TOOBIG) ||
3059
0
        (0 == netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
3060
0
                                     NETSNMP_DS_LIB_REVERSE_ENCODE))) {
3061
0
        pdu->flags |= UCD_MSG_FLAG_FORWARD_ENCODE;
3062
0
    }
3063
0
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
3064
3065
0
    if (pdu->version == SNMP_VERSION_3) {
3066
0
        return snmpv3_build(pkt, pkt_len, offset, session, pdu);
3067
0
    }
3068
3069
0
    switch (pdu->command) {
3070
0
    case SNMP_MSG_RESPONSE:
3071
0
        netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
3072
0
#ifndef NETSNMP_NOTIFY_ONLY
3073
0
        NETSNMP_FALLTHROUGH;
3074
0
    case SNMP_MSG_GET:
3075
0
    case SNMP_MSG_GETNEXT:
3076
0
#endif /* ! NETSNMP_NOTIFY_ONLY */
3077
0
#ifndef NETSNMP_NO_WRITE_SUPPORT
3078
0
    case SNMP_MSG_SET:
3079
0
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
3080
        /*
3081
         * all versions support these PDU types 
3082
         */
3083
        /*
3084
         * initialize defaulted PDU fields 
3085
         */
3086
3087
0
        if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
3088
0
            pdu->errstat = 0;
3089
0
        if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
3090
0
            pdu->errindex = 0;
3091
0
        break;
3092
3093
0
    case SNMP_MSG_TRAP2:
3094
0
        netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
3095
0
        NETSNMP_FALLTHROUGH;
3096
0
    case SNMP_MSG_INFORM:
3097
0
#ifndef NETSNMP_DISABLE_SNMPV1
3098
        /*
3099
         * not supported in SNMPv1 and SNMPsec 
3100
         */
3101
0
        if (pdu->version == SNMP_VERSION_1) {
3102
0
            session->s_snmp_errno = SNMPERR_V2_IN_V1;
3103
0
            return -1;
3104
0
        }
3105
0
#endif
3106
0
        if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
3107
0
            pdu->errstat = 0;
3108
0
        if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
3109
0
            pdu->errindex = 0;
3110
0
        break;
3111
3112
0
#ifndef NETSNMP_NOTIFY_ONLY
3113
0
    case SNMP_MSG_GETBULK:
3114
        /*
3115
         * not supported in SNMPv1 and SNMPsec 
3116
         */
3117
0
#ifndef NETSNMP_DISABLE_SNMPV1
3118
0
        if (pdu->version == SNMP_VERSION_1) {
3119
0
            session->s_snmp_errno = SNMPERR_V2_IN_V1;
3120
0
            return -1;
3121
0
        }
3122
0
#endif
3123
0
        if (pdu->max_repetitions < 0) {
3124
0
            session->s_snmp_errno = SNMPERR_BAD_REPETITIONS;
3125
0
            return -1;
3126
0
        }
3127
0
        if (pdu->non_repeaters < 0) {
3128
0
            session->s_snmp_errno = SNMPERR_BAD_REPEATERS;
3129
0
            return -1;
3130
0
        }
3131
0
        break;
3132
0
#endif /* ! NETSNMP_NOTIFY_ONLY */
3133
3134
0
    case SNMP_MSG_TRAP:
3135
        /*
3136
         * *only* supported in SNMPv1 and SNMPsec 
3137
         */
3138
0
#ifndef NETSNMP_DISABLE_SNMPV1
3139
0
        if (pdu->version != SNMP_VERSION_1) {
3140
0
            session->s_snmp_errno = SNMPERR_V1_IN_V2;
3141
0
            return -1;
3142
0
        }
3143
0
#endif
3144
        /*
3145
         * initialize defaulted Trap PDU fields 
3146
         */
3147
0
        pdu->reqid = 1;         /* give a bogus non-error reqid for traps */
3148
0
        if (pdu->enterprise_length == SNMP_DEFAULT_ENTERPRISE_LENGTH) {
3149
0
            pdu->enterprise = netsnmp_memdup(DEFAULT_ENTERPRISE,
3150
0
                                             sizeof(DEFAULT_ENTERPRISE));
3151
0
            if (pdu->enterprise == NULL) {
3152
0
                session->s_snmp_errno = SNMPERR_MALLOC;
3153
0
                return -1;
3154
0
            }
3155
0
            pdu->enterprise_length =
3156
0
                OID_LENGTH(DEFAULT_ENTERPRISE);
3157
0
        }
3158
0
        if (pdu->time == SNMP_DEFAULT_TIME)
3159
0
            pdu->time = DEFAULT_TIME;
3160
        /*
3161
         * don't expect a response 
3162
         */
3163
0
        pdu->flags &= (~UCD_MSG_FLAG_EXPECT_RESPONSE);
3164
0
        break;
3165
3166
0
    case SNMP_MSG_REPORT:      /* SNMPv3 only */
3167
0
    default:
3168
0
        session->s_snmp_errno = SNMPERR_UNKNOWN_PDU;
3169
0
        return -1;
3170
0
    }
3171
3172
    /*
3173
     * save length 
3174
     */
3175
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3176
0
    length = *pkt_len;
3177
0
#endif
3178
3179
    /*
3180
     * setup administrative fields based on version 
3181
     */
3182
    /*
3183
     * build the message wrapper and all the administrative fields
3184
     * upto the PDU sequence
3185
     * (note that actual length of message will be inserted later) 
3186
     */
3187
0
    switch (pdu->version) {
3188
0
#ifndef NETSNMP_DISABLE_SNMPV1
3189
0
    case SNMP_VERSION_1:
3190
0
#endif
3191
0
#ifndef NETSNMP_DISABLE_SNMPV2C
3192
0
    case SNMP_VERSION_2c:
3193
0
#endif
3194
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3195
#ifdef NETSNMP_NO_ZEROLENGTH_COMMUNITY
3196
        if (pdu->community_len == 0) {
3197
            if (session->community_len == 0) {
3198
                session->s_snmp_errno = SNMPERR_BAD_COMMUNITY;
3199
                return -1;
3200
            }
3201
            pdu->community = netsnmp_memdup(session->community,
3202
                                            session->community_len);
3203
            if (pdu->community == NULL) {
3204
                session->s_snmp_errno = SNMPERR_MALLOC;
3205
                return -1;
3206
            }
3207
            pdu->community_len = session->community_len;
3208
        }
3209
#else                           /* !NETSNMP_NO_ZEROLENGTH_COMMUNITY */
3210
0
        if (pdu->community_len == 0 && pdu->command != SNMP_MSG_RESPONSE) {
3211
            /*
3212
             * copy session community exactly to pdu community 
3213
             */
3214
0
            if (0 == session->community_len) {
3215
0
                SNMP_FREE(pdu->community);
3216
0
            } else if (pdu->community_len == session->community_len) {
3217
0
                memmove(pdu->community,
3218
0
                        session->community, session->community_len);
3219
0
            } else {
3220
0
                SNMP_FREE(pdu->community);
3221
0
                pdu->community = netsnmp_memdup(session->community,
3222
0
                                                session->community_len);
3223
0
                if (pdu->community == NULL) {
3224
0
                    session->s_snmp_errno = SNMPERR_MALLOC;
3225
0
                    return -1;
3226
0
                }
3227
0
            }
3228
0
            pdu->community_len = session->community_len;
3229
0
        }
3230
0
#endif                          /* !NETSNMP_NO_ZEROLENGTH_COMMUNITY */
3231
3232
0
        DEBUGMSGTL(("snmp_send", "Building SNMPv%ld message...\n",
3233
0
                    (1 + pdu->version)));
3234
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3235
0
        if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
3236
0
            DEBUGPRINTPDUTYPE("send", pdu->command);
3237
0
            rc = snmp_pdu_realloc_rbuild(pkt, pkt_len, offset, pdu);
3238
0
            if (rc == 0) {
3239
0
                return -1;
3240
0
            }
3241
3242
0
            DEBUGDUMPHEADER("send", "Community String");
3243
0
            rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
3244
0
                                           (u_char) (ASN_UNIVERSAL |
3245
0
                                                     ASN_PRIMITIVE |
3246
0
                                                     ASN_OCTET_STR),
3247
0
                                           pdu->community,
3248
0
                                           pdu->community_len);
3249
0
            DEBUGINDENTLESS();
3250
0
            if (rc == 0) {
3251
0
                return -1;
3252
0
            }
3253
3254
3255
            /*
3256
             * Store the version field.  
3257
             */
3258
0
            DEBUGDUMPHEADER("send", "SNMP Version Number");
3259
3260
0
            version = pdu->version;
3261
0
            rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3262
0
                                        (u_char) (ASN_UNIVERSAL |
3263
0
                                                  ASN_PRIMITIVE |
3264
0
                                                  ASN_INTEGER),
3265
0
                                        (long *) &version,
3266
0
                                        sizeof(version));
3267
0
            DEBUGINDENTLESS();
3268
0
            if (rc == 0) {
3269
0
                return -1;
3270
0
            }
3271
3272
            /*
3273
             * Build the final sequence.  
3274
             */
3275
0
#ifndef NETSNMP_DISABLE_SNMPV1
3276
0
            if (pdu->version == SNMP_VERSION_1) {
3277
0
                DEBUGDUMPSECTION("send", "SNMPv1 Message");
3278
0
            } else {
3279
0
#endif
3280
0
                DEBUGDUMPSECTION("send", "SNMPv2c Message");
3281
0
#ifndef NETSNMP_DISABLE_SNMPV1
3282
0
            }
3283
0
#endif
3284
0
            rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
3285
0
                                             (u_char) (ASN_SEQUENCE |
3286
0
                                                       ASN_CONSTRUCTOR),
3287
0
                                             *offset - start_offset);
3288
0
            DEBUGINDENTLESS();
3289
3290
0
            if (rc == 0) {
3291
0
                return -1;
3292
0
            }
3293
0
            return 0;
3294
0
        } else {
3295
3296
0
#endif                          /* NETSNMP_USE_REVERSE_ASNENCODING */
3297
            /*
3298
             * Save current location and build SEQUENCE tag and length
3299
             * placeholder for SNMP message sequence
3300
             * (actual length will be inserted later) 
3301
             */
3302
0
            cp = asn_build_sequence(*pkt, pkt_len,
3303
0
                                    (u_char) (ASN_SEQUENCE |
3304
0
                                              ASN_CONSTRUCTOR), 0);
3305
0
            if (cp == NULL) {
3306
0
                return -1;
3307
0
            }
3308
0
            h0e = cp;
3309
3310
0
#ifndef NETSNMP_DISABLE_SNMPV1
3311
0
            if (pdu->version == SNMP_VERSION_1) {
3312
0
                DEBUGDUMPSECTION("send", "SNMPv1 Message");
3313
0
            } else {
3314
0
#endif
3315
0
                DEBUGDUMPSECTION("send", "SNMPv2c Message");
3316
0
#ifndef NETSNMP_DISABLE_SNMPV1
3317
0
            }
3318
0
#endif
3319
3320
            /*
3321
             * store the version field 
3322
             */
3323
0
            DEBUGDUMPHEADER("send", "SNMP Version Number");
3324
3325
0
            version = pdu->version;
3326
0
            cp = asn_build_int(cp, pkt_len,
3327
0
                               (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3328
0
                                         ASN_INTEGER), (long *) &version,
3329
0
                               sizeof(version));
3330
0
            DEBUGINDENTLESS();
3331
0
            if (cp == NULL)
3332
0
                return -1;
3333
3334
            /*
3335
             * store the community string 
3336
             */
3337
0
            DEBUGDUMPHEADER("send", "Community String");
3338
0
            cp = asn_build_string(cp, pkt_len,
3339
0
                                  (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3340
0
                                            ASN_OCTET_STR), pdu->community,
3341
0
                                  pdu->community_len);
3342
0
            DEBUGINDENTLESS();
3343
0
            if (cp == NULL)
3344
0
                return -1;
3345
0
            break;
3346
3347
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3348
0
        }
3349
0
#endif                          /* NETSNMP_USE_REVERSE_ASNENCODING */
3350
0
        break;
3351
0
#endif /* support for community based SNMP */
3352
0
    case SNMP_VERSION_2p:
3353
0
    case SNMP_VERSION_sec:
3354
0
    case SNMP_VERSION_2u:
3355
0
    case SNMP_VERSION_2star:
3356
0
    default:
3357
0
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
3358
0
        return -1;
3359
0
    }
3360
3361
0
    DEBUGPRINTPDUTYPE("send", pdu->command);
3362
0
    cp = snmp_pdu_build(pdu, cp, pkt_len);
3363
0
    DEBUGINDENTADD(-4);         /* return from entire v1/v2c message */
3364
0
    if (cp == NULL)
3365
0
        return -1;
3366
3367
    /*
3368
     * insert the actual length of the message sequence 
3369
     */
3370
0
    switch (pdu->version) {
3371
0
#ifndef NETSNMP_DISABLE_SNMPV1
3372
0
    case SNMP_VERSION_1:
3373
0
#endif
3374
0
#ifndef NETSNMP_DISABLE_SNMPV2C
3375
0
    case SNMP_VERSION_2c:
3376
0
#endif
3377
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3378
0
        asn_build_sequence(*pkt, &length,
3379
0
                           (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
3380
0
                           cp - h0e);
3381
0
        break;
3382
0
#endif /* support for community based SNMP */
3383
3384
0
    case SNMP_VERSION_2p:
3385
0
    case SNMP_VERSION_sec:
3386
0
    case SNMP_VERSION_2u:
3387
0
    case SNMP_VERSION_2star:
3388
0
    default:
3389
0
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
3390
0
        return -1;
3391
0
    }
3392
0
    *pkt_len = cp - *pkt;
3393
0
    return 0;
3394
0
}
3395
3396
/**
3397
 * Serialize a PDU into ASN format.
3398
 * @param pkt     [out] Serialized PDU.
3399
 * @param pkt_len [out] Size of pkt.
3400
 * @param offset  [out] Number of bytes written into *pkt.
3401
 * @param pss     [in]  Session pointer.
3402
 * @param pdu     [in]  PDU to serialize.
3403
 *
3404
 * @returns 0 upon success; -1 upon failure.
3405
 */
3406
int
3407
snmp_build(u_char ** pkt, size_t * pkt_len, size_t * offset,
3408
           netsnmp_session * pss, netsnmp_pdu *pdu)
3409
0
{
3410
0
    int             rc;
3411
3412
0
    rc = _snmp_build(pkt, pkt_len, offset, pss, pdu);
3413
0
    if (rc) {
3414
0
        if (!pss->s_snmp_errno) {
3415
0
            snmp_log(LOG_ERR, "snmp_build: unknown failure\n");
3416
0
            pss->s_snmp_errno = SNMPERR_BAD_ASN1_BUILD;
3417
0
        }
3418
0
        SET_SNMP_ERROR(pss->s_snmp_errno);
3419
0
        rc = -1;
3420
0
    }
3421
0
    return rc;
3422
0
}
3423
3424
/*
3425
 * on error, returns NULL (likely an encoding problem). 
3426
 */
3427
u_char         *
3428
snmp_pdu_build(const netsnmp_pdu *pdu, u_char * cp, size_t * out_length)
3429
0
{
3430
0
    u_char         *h1, *h1e, *h2, *h2e, *save_ptr;
3431
0
    netsnmp_variable_list *vp, *save_vp = NULL;
3432
0
    size_t          length, save_length;
3433
3434
0
    length = *out_length;
3435
    /*
3436
     * Save current location and build PDU tag and length placeholder
3437
     * (actual length will be inserted later) 
3438
     */
3439
0
    h1 = cp;
3440
0
    cp = asn_build_sequence(cp, out_length, (u_char) pdu->command, 0);
3441
0
    if (cp == NULL)
3442
0
        return NULL;
3443
0
    h1e = cp;
3444
3445
    /*
3446
     * store fields in the PDU preceding the variable-bindings sequence
3447
     */
3448
0
    if (pdu->command != SNMP_MSG_TRAP) {
3449
        /*
3450
         * PDU is not an SNMPv1 trap 
3451
         */
3452
3453
0
        DEBUGDUMPHEADER("send", "request_id");
3454
        /*
3455
         * request id 
3456
         */
3457
0
        cp = asn_build_int(cp, out_length,
3458
0
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3459
0
                                     ASN_INTEGER), &pdu->reqid,
3460
0
                           sizeof(pdu->reqid));
3461
0
        DEBUGINDENTLESS();
3462
0
        if (cp == NULL)
3463
0
            return NULL;
3464
3465
        /*
3466
         * error status (getbulk non-repeaters) 
3467
         */
3468
0
        DEBUGDUMPHEADER("send", "error status");
3469
0
        cp = asn_build_int(cp, out_length,
3470
0
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3471
0
                                     ASN_INTEGER), &pdu->errstat,
3472
0
                           sizeof(pdu->errstat));
3473
0
        DEBUGINDENTLESS();
3474
0
        if (cp == NULL)
3475
0
            return NULL;
3476
3477
        /*
3478
         * error index (getbulk max-repetitions) 
3479
         */
3480
0
        DEBUGDUMPHEADER("send", "error index");
3481
0
        cp = asn_build_int(cp, out_length,
3482
0
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3483
0
                                     ASN_INTEGER), &pdu->errindex,
3484
0
                           sizeof(pdu->errindex));
3485
0
        DEBUGINDENTLESS();
3486
0
        if (cp == NULL)
3487
0
            return NULL;
3488
0
    } else {
3489
        /*
3490
         * an SNMPv1 trap PDU 
3491
         */
3492
3493
        /*
3494
         * enterprise 
3495
         */
3496
0
        DEBUGDUMPHEADER("send", "enterprise OBJID");
3497
0
        cp = asn_build_objid(cp, out_length,
3498
0
                             (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3499
0
                                       ASN_OBJECT_ID),
3500
0
                             pdu->enterprise, pdu->enterprise_length);
3501
0
        DEBUGINDENTLESS();
3502
0
        if (cp == NULL)
3503
0
            return NULL;
3504
3505
        /*
3506
         * agent-addr 
3507
         */
3508
0
        DEBUGDUMPHEADER("send", "agent Address");
3509
0
        cp = asn_build_string(cp, out_length,
3510
0
                              (u_char) (ASN_IPADDRESS | ASN_PRIMITIVE),
3511
0
                              (const u_char *) pdu->agent_addr, 4);
3512
0
        DEBUGINDENTLESS();
3513
0
        if (cp == NULL)
3514
0
            return NULL;
3515
3516
        /*
3517
         * generic trap 
3518
         */
3519
0
        DEBUGDUMPHEADER("send", "generic trap number");
3520
0
        cp = asn_build_int(cp, out_length,
3521
0
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3522
0
                                     ASN_INTEGER),
3523
0
                           (const long *) &pdu->trap_type,
3524
0
                           sizeof(pdu->trap_type));
3525
0
        DEBUGINDENTLESS();
3526
0
        if (cp == NULL)
3527
0
            return NULL;
3528
3529
        /*
3530
         * specific trap 
3531
         */
3532
0
        DEBUGDUMPHEADER("send", "specific trap number");
3533
0
        cp = asn_build_int(cp, out_length,
3534
0
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3535
0
                                     ASN_INTEGER),
3536
0
                           (const long *) &pdu->specific_type,
3537
0
                           sizeof(pdu->specific_type));
3538
0
        DEBUGINDENTLESS();
3539
0
        if (cp == NULL)
3540
0
            return NULL;
3541
3542
        /*
3543
         * timestamp  
3544
         */
3545
0
        DEBUGDUMPHEADER("send", "timestamp");
3546
0
        cp = asn_build_unsigned_int(cp, out_length,
3547
0
                                    (u_char) (ASN_TIMETICKS |
3548
0
                                              ASN_PRIMITIVE), &pdu->time,
3549
0
                                    sizeof(pdu->time));
3550
0
        DEBUGINDENTLESS();
3551
0
        if (cp == NULL)
3552
0
            return NULL;
3553
0
    }
3554
3555
    /*
3556
     * Save current location and build SEQUENCE tag and length placeholder
3557
     * for variable-bindings sequence
3558
     * (actual length will be inserted later) 
3559
     */
3560
0
    h2 = cp;
3561
0
    cp = asn_build_sequence(cp, out_length,
3562
0
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
3563
0
    if (cp == NULL)
3564
0
        return NULL;
3565
0
    h2e = cp;
3566
3567
    /*
3568
     * Store variable-bindings 
3569
     */
3570
0
    DEBUGDUMPSECTION("send", "VarBindList");
3571
0
    for (vp = pdu->variables; vp; vp = vp->next_variable) {
3572
        /*
3573
         * if estimated getbulk response size exceeded packet max size,
3574
         * processing was stopped before bulk cache was filled and type
3575
         * was set to ASN_PRIV_STOP, indicating that the rest of the varbinds
3576
         * in the cache are empty and we can stop encoding them.
3577
         */
3578
0
        if (ASN_PRIV_STOP == vp->type)
3579
0
            break;
3580
3581
        /*
3582
         * save current ptr and length so that if we exceed the packet length
3583
         * encoding this varbind and this is a bulk response, we can drop
3584
         * the failed varbind (and any that follow it) and continue encoding
3585
         * the (shorter) bulk response.
3586
         */
3587
0
        save_ptr = cp;
3588
0
        save_length = *out_length;
3589
3590
0
        DEBUGDUMPSECTION("send", "VarBind");
3591
0
        cp = snmp_build_var_op(cp, vp->name, &vp->name_length, vp->type,
3592
0
                               vp->val_len, vp->val.string, out_length);
3593
0
        DEBUGINDENTLESS();
3594
0
        if (cp == NULL) {
3595
0
            if (save_vp && (pdu->flags & UCD_MSG_FLAG_BULK_TOOBIG)) {
3596
0
                DEBUGDUMPSECTION("send",
3597
0
                                 "VarBind would exceed packet size; dropped");
3598
0
                cp = save_ptr;
3599
0
                *out_length = save_length;
3600
0
                break;
3601
0
            } else
3602
0
                return NULL;
3603
0
        }
3604
0
        save_vp = vp;
3605
0
    }
3606
0
    DEBUGINDENTLESS();
3607
3608
    /** did we run out of room? (should only happen for bulk responses) */
3609
0
    if (vp && save_vp) {
3610
0
        save_vp->next_variable = NULL; /* truncate variable list */
3611
        /** count remaining varbinds in list, then free them */
3612
0
        save_vp = vp;
3613
0
        for(save_length = 0; save_vp; save_vp = save_vp->next_variable)
3614
0
            ++save_length;
3615
0
        DEBUGMSGTL(("send", "trimmed %" NETSNMP_PRIz "d variables\n", save_length));
3616
0
        snmp_free_varbind(vp);
3617
0
    }
3618
3619
    /*
3620
     * insert actual length of variable-bindings sequence 
3621
     */
3622
0
    asn_build_sequence(h2, &length,
3623
0
                       (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
3624
0
                       cp - h2e);
3625
3626
    /*
3627
     * insert actual length of PDU sequence 
3628
     */
3629
0
    asn_build_sequence(h1, &length, (u_char) pdu->command, cp - h1e);
3630
3631
0
    return cp;
3632
0
}
3633
3634
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3635
/*
3636
 * On error, returns 0 (likely an encoding problem).  
3637
 */
3638
int
3639
snmp_pdu_realloc_rbuild(u_char ** pkt, size_t * pkt_len, size_t * offset,
3640
                        const netsnmp_pdu *pdu)
3641
0
{
3642
0
#ifndef VPCACHE_SIZE
3643
0
#define VPCACHE_SIZE 50
3644
0
#endif
3645
0
    netsnmp_variable_list *vpcache[VPCACHE_SIZE];
3646
0
    netsnmp_variable_list *vp, *tmpvp;
3647
0
    size_t          start_offset = *offset;
3648
0
    int             i, wrapped = 0, notdone, final, rc = 0;
3649
3650
0
    DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "starting\n"));
3651
0
    for (vp = pdu->variables, i = VPCACHE_SIZE - 1; vp;
3652
0
         vp = vp->next_variable, i--) {
3653
        /*
3654
         * if estimated getbulk response size exceeded packet max size,
3655
         * processing was stopped before bulk cache was filled and type
3656
         * was set to ASN_PRIV_STOP, indicating that the rest of the varbinds
3657
         * in the cache are empty and we can stop encoding them.
3658
         */
3659
0
        if (ASN_PRIV_STOP == vp->type)
3660
0
            break;
3661
0
        if (i < 0) {
3662
0
            wrapped = notdone = 1;
3663
0
            i = VPCACHE_SIZE - 1;
3664
0
            DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "wrapped\n"));
3665
0
        }
3666
0
        vpcache[i] = vp;
3667
0
    }
3668
0
    final = i + 1;
3669
3670
0
    do {
3671
0
        for (i = final; i < VPCACHE_SIZE; i++) {
3672
0
            vp = vpcache[i];
3673
0
            DEBUGDUMPSECTION("send", "VarBind");
3674
0
            rc = snmp_realloc_rbuild_var_op(pkt, pkt_len, offset, 1,
3675
0
                                            vp->name, &vp->name_length,
3676
0
                                            vp->type,
3677
0
                                            (u_char *) vp->val.string,
3678
0
                                            vp->val_len);
3679
0
            DEBUGINDENTLESS();
3680
0
            if (rc == 0) {
3681
0
                return 0;
3682
0
            }
3683
0
        }
3684
3685
0
        DEBUGINDENTLESS();
3686
0
        if (wrapped) {
3687
0
            notdone = 1;
3688
0
            for (i = 0; i < final; i++) {
3689
0
                vp = vpcache[i];
3690
0
                DEBUGDUMPSECTION("send", "VarBind");
3691
0
                rc = snmp_realloc_rbuild_var_op(pkt, pkt_len, offset, 1,
3692
0
                                                vp->name, &vp->name_length,
3693
0
                                                vp->type,
3694
0
                                                (u_char *) vp->val.string,
3695
0
                                                vp->val_len);
3696
0
                DEBUGINDENTLESS();
3697
0
                if (rc == 0) {
3698
0
                    return 0;
3699
0
                }
3700
0
            }
3701
3702
0
            if (final == 0) {
3703
0
                tmpvp = vpcache[VPCACHE_SIZE - 1];
3704
0
            } else {
3705
0
                tmpvp = vpcache[final - 1];
3706
0
            }
3707
0
            wrapped = 0;
3708
3709
0
            for (vp = pdu->variables, i = VPCACHE_SIZE - 1;
3710
0
                 vp && vp != tmpvp; vp = vp->next_variable, i--) {
3711
0
                if (i < 0) {
3712
0
                    wrapped = 1;
3713
0
                    i = VPCACHE_SIZE - 1;
3714
0
                    DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "wrapped\n"));
3715
0
                }
3716
0
                vpcache[i] = vp;
3717
0
            }
3718
0
            final = i + 1;
3719
0
        } else {
3720
0
            notdone = 0;
3721
0
        }
3722
0
    } while (notdone);
3723
3724
    /*
3725
     * Save current location and build SEQUENCE tag and length placeholder for
3726
     * variable-bindings sequence (actual length will be inserted later).  
3727
     */
3728
3729
0
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
3730
0
                                     (u_char) (ASN_SEQUENCE |
3731
0
                                               ASN_CONSTRUCTOR),
3732
0
                                     *offset - start_offset);
3733
0
    if (rc == 0) {
3734
0
        return 0;
3735
0
    }
3736
3737
    /*
3738
     * Store fields in the PDU preceding the variable-bindings sequence.
3739
     */
3740
0
    if (pdu->command != SNMP_MSG_TRAP) {
3741
        /*
3742
         * Error index (getbulk max-repetitions).  
3743
         */
3744
0
        DEBUGDUMPHEADER("send", "error index");
3745
0
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3746
0
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3747
0
                                              | ASN_INTEGER),
3748
0
                                    &pdu->errindex, sizeof(pdu->errindex));
3749
0
        DEBUGINDENTLESS();
3750
0
        if (rc == 0) {
3751
0
            return 0;
3752
0
        }
3753
3754
        /*
3755
         * Error status (getbulk non-repeaters).  
3756
         */
3757
0
        DEBUGDUMPHEADER("send", "error status");
3758
0
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3759
0
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3760
0
                                              | ASN_INTEGER),
3761
0
                                    &pdu->errstat, sizeof(pdu->errstat));
3762
0
        DEBUGINDENTLESS();
3763
0
        if (rc == 0) {
3764
0
            return 0;
3765
0
        }
3766
3767
        /*
3768
         * Request ID.  
3769
         */
3770
0
        DEBUGDUMPHEADER("send", "request_id");
3771
0
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3772
0
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3773
0
                                              | ASN_INTEGER), &pdu->reqid,
3774
0
                                    sizeof(pdu->reqid));
3775
0
        DEBUGINDENTLESS();
3776
0
        if (rc == 0) {
3777
0
            return 0;
3778
0
        }
3779
0
    } else {
3780
        /*
3781
         * An SNMPv1 trap PDU.  
3782
         */
3783
3784
        /*
3785
         * Timestamp.  
3786
         */
3787
0
        DEBUGDUMPHEADER("send", "timestamp");
3788
0
        rc = asn_realloc_rbuild_unsigned_int(pkt, pkt_len, offset, 1,
3789
0
                                             (u_char) (ASN_TIMETICKS |
3790
0
                                                       ASN_PRIMITIVE),
3791
0
                                             &pdu->time,
3792
0
                                             sizeof(pdu->time));
3793
0
        DEBUGINDENTLESS();
3794
0
        if (rc == 0) {
3795
0
            return 0;
3796
0
        }
3797
3798
        /*
3799
         * Specific trap.  
3800
         */
3801
0
        DEBUGDUMPHEADER("send", "specific trap number");
3802
0
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3803
0
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3804
0
                                              | ASN_INTEGER),
3805
0
                                    (const long *) &pdu->specific_type,
3806
0
                                    sizeof(pdu->specific_type));
3807
0
        DEBUGINDENTLESS();
3808
0
        if (rc == 0) {
3809
0
            return 0;
3810
0
        }
3811
3812
        /*
3813
         * Generic trap.  
3814
         */
3815
0
        DEBUGDUMPHEADER("send", "generic trap number");
3816
0
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3817
0
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3818
0
                                              | ASN_INTEGER),
3819
0
                                    (const long *) &pdu->trap_type,
3820
0
                                    sizeof(pdu->trap_type));
3821
0
        DEBUGINDENTLESS();
3822
0
        if (rc == 0) {
3823
0
            return 0;
3824
0
        }
3825
3826
        /*
3827
         * Agent-addr.  
3828
         */
3829
0
        DEBUGDUMPHEADER("send", "agent Address");
3830
0
        rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
3831
0
                                       (u_char) (ASN_IPADDRESS |
3832
0
                                                 ASN_PRIMITIVE),
3833
0
                                       (const u_char *) pdu->agent_addr, 4);
3834
0
        DEBUGINDENTLESS();
3835
0
        if (rc == 0) {
3836
0
            return 0;
3837
0
        }
3838
3839
        /*
3840
         * Enterprise.  
3841
         */
3842
0
        DEBUGDUMPHEADER("send", "enterprise OBJID");
3843
0
        rc = asn_realloc_rbuild_objid(pkt, pkt_len, offset, 1,
3844
0
                                      (u_char) (ASN_UNIVERSAL |
3845
0
                                                ASN_PRIMITIVE |
3846
0
                                                ASN_OBJECT_ID),
3847
0
                                      (oid *) pdu->enterprise,
3848
0
                                      pdu->enterprise_length);
3849
0
        DEBUGINDENTLESS();
3850
0
        if (rc == 0) {
3851
0
            return 0;
3852
0
        }
3853
0
    }
3854
3855
    /*
3856
     * Build the PDU sequence.  
3857
     */
3858
0
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
3859
0
                                     (u_char) pdu->command,
3860
0
                                     *offset - start_offset);
3861
0
    return rc;
3862
0
}
3863
#endif                          /* NETSNMP_USE_REVERSE_ASNENCODING */
3864
3865
/*
3866
 * Parses the packet received to determine version, either directly
3867
 * from packets version field or inferred from ASN.1 construct.
3868
 */
3869
static int
3870
snmp_parse_version(u_char * data, size_t length)
3871
0
{
3872
0
    u_char          type;
3873
0
    long            version = SNMPERR_BAD_VERSION;
3874
3875
0
    data = asn_parse_sequence(data, &length, &type,
3876
0
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR), "version");
3877
0
    if (data) {
3878
0
        DEBUGDUMPHEADER("recv", "SNMP Version");
3879
0
        data =
3880
0
            asn_parse_int(data, &length, &type, &version, sizeof(version));
3881
0
        DEBUGINDENTLESS();
3882
0
        if (!data || type != ASN_INTEGER) {
3883
0
            return SNMPERR_BAD_VERSION;
3884
0
        }
3885
0
    }
3886
0
    return version;
3887
0
}
3888
3889
3890
int
3891
snmpv3_parse(netsnmp_pdu *pdu,
3892
             u_char * data,
3893
             size_t * length,
3894
             u_char ** after_header, netsnmp_session * sess)
3895
0
{
3896
0
    u_char          type, msg_flags;
3897
0
    long            ver, msg_sec_model;
3898
0
    size_t          max_size_response;
3899
0
    u_char          tmp_buf[SNMP_MAX_MSG_SIZE];
3900
0
    size_t          tmp_buf_len;
3901
0
    u_char          pdu_buf[SNMP_MAX_MSG_SIZE];
3902
0
    u_char         *mallocbuf = NULL;
3903
0
    size_t          pdu_buf_len = SNMP_MAX_MSG_SIZE;
3904
0
    u_char         *sec_params;
3905
0
    u_char         *msg_data;
3906
0
    u_char         *cp;
3907
0
    size_t          asn_len, msg_len;
3908
0
    int             ret, ret_val;
3909
0
    struct snmp_secmod_def *sptr;
3910
3911
3912
0
    msg_data = data;
3913
0
    msg_len = *length;
3914
3915
3916
    /*
3917
     * message is an ASN.1 SEQUENCE  
3918
     */
3919
0
    DEBUGDUMPSECTION("recv", "SNMPv3 Message");
3920
0
    data = asn_parse_sequence(data, length, &type,
3921
0
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR), "message");
3922
0
    if (data == NULL) {
3923
        /*
3924
         * error msg detail is set 
3925
         */
3926
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3927
0
        DEBUGINDENTLESS();
3928
0
        return SNMPERR_ASN_PARSE_ERR;
3929
0
    }
3930
3931
    /*
3932
     * parse msgVersion  
3933
     */
3934
0
    DEBUGDUMPHEADER("recv", "SNMP Version Number");
3935
0
    data = asn_parse_int(data, length, &type, &ver, sizeof(ver));
3936
0
    DEBUGINDENTLESS();
3937
0
    if (data == NULL) {
3938
0
        ERROR_MSG("bad parse of version");
3939
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3940
0
        DEBUGINDENTLESS();
3941
0
        return SNMPERR_ASN_PARSE_ERR;
3942
0
    }
3943
0
    pdu->version = ver;
3944
3945
    /*
3946
     * parse msgGlobalData sequence  
3947
     */
3948
0
    cp = data;
3949
0
    asn_len = *length;
3950
0
    DEBUGDUMPSECTION("recv", "msgGlobalData");
3951
0
    data = asn_parse_sequence(data, &asn_len, &type,
3952
0
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR),
3953
0
                              "msgGlobalData");
3954
0
    if (data == NULL) {
3955
        /*
3956
         * error msg detail is set 
3957
         */
3958
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3959
0
        DEBUGINDENTADD(-4);
3960
0
        return SNMPERR_ASN_PARSE_ERR;
3961
0
    }
3962
0
    *length -= data - cp;       /* subtract off the length of the header */
3963
3964
    /*
3965
     * msgID 
3966
     */
3967
0
    DEBUGDUMPHEADER("recv", "msgID");
3968
0
    data =
3969
0
        asn_parse_int(data, length, &type, &pdu->msgid,
3970
0
                      sizeof(pdu->msgid));
3971
0
    DEBUGINDENTLESS();
3972
0
    if (data == NULL || type != ASN_INTEGER) {
3973
0
        ERROR_MSG("error parsing msgID");
3974
0
        DEBUGINDENTADD(-4);
3975
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3976
0
        return SNMPERR_ASN_PARSE_ERR;
3977
0
    }
3978
3979
    /*
3980
     * Check the msgID we received is a legal value.  If not, then increment
3981
     * snmpInASNParseErrs and return the appropriate error (see RFC 2572,
3982
     * para. 7.2, section 2 -- note that a bad msgID means that the received
3983
     * message is NOT a serialization of an SNMPv3Message, since the msgID
3984
     * field is out of bounds).  
3985
     */
3986
3987
0
    if (pdu->msgid < 0 || pdu->msgid > SNMP_MAX_PACKET_LEN) {
3988
0
        snmp_log(LOG_ERR, "Received bad msgID (%ld %s %s).\n", pdu->msgid,
3989
0
                 (pdu->msgid < 0) ? "<" : ">",
3990
0
                 (pdu->msgid < 0) ? "0" : "2^31 - 1");
3991
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3992
0
        DEBUGINDENTADD(-4);
3993
0
        return SNMPERR_ASN_PARSE_ERR;
3994
0
    }
3995
3996
    /*
3997
     * msgMaxSize 
3998
     */
3999
0
    DEBUGDUMPHEADER("recv:msgMaxSize", "msgMaxSize");
4000
0
    data = asn_parse_int(data, length, &type, &pdu->msgMaxSize,
4001
0
                         sizeof(pdu->msgMaxSize));
4002
0
    DEBUGINDENTLESS();
4003
0
    if (data == NULL || type != ASN_INTEGER) {
4004
0
        ERROR_MSG("error parsing msgMaxSize");
4005
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4006
0
        DEBUGINDENTADD(-4);
4007
0
        return SNMPERR_ASN_PARSE_ERR;
4008
0
    }
4009
4010
    /*
4011
     * Check the msgMaxSize we received is a legal value.  If not, then
4012
     * increment snmpInASNParseErrs and return the appropriate error (see RFC
4013
     * 2572, para. 7.2, section 2 -- note that a bad msgMaxSize means that the
4014
     * received message is NOT a serialization of an SNMPv3Message, since the
4015
     * msgMaxSize field is out of bounds).
4016
     */
4017
4018
0
    if (pdu->msgMaxSize < SNMP_MIN_MAX_LEN) {
4019
0
        snmp_log(LOG_ERR, "Received bad msgMaxSize (%lu < 484).\n",
4020
0
                 pdu->msgMaxSize);
4021
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4022
0
        DEBUGINDENTADD(-4);
4023
0
        return SNMPERR_ASN_PARSE_ERR;
4024
0
    } else if (pdu->msgMaxSize > SNMP_MAX_PACKET_LEN) {
4025
0
        snmp_log(LOG_ERR, "Received bad msgMaxSize (%lu > 2^31 - 1).\n",
4026
0
                 pdu->msgMaxSize);
4027
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4028
0
        DEBUGINDENTADD(-4);
4029
0
        return SNMPERR_ASN_PARSE_ERR;
4030
0
    } else {
4031
0
        DEBUGMSGTL(("snmpv3_parse:msgMaxSize", "msgMaxSize %lu received\n",
4032
0
                    pdu->msgMaxSize));
4033
        /** don't increase max msg size if we've already got one */
4034
0
        if (sess->sndMsgMaxSize < pdu->msgMaxSize) {
4035
0
            DEBUGMSGTL(("snmpv3_parse:msgMaxSize",
4036
0
                        "msgMaxSize %" NETSNMP_PRIz "d greater than session max %ld; reducing\n",
4037
0
                        sess->sndMsgMaxSize, pdu->msgMaxSize));
4038
0
            pdu->msgMaxSize = sess->sndMsgMaxSize;
4039
0
        }
4040
0
    }
4041
4042
    /*
4043
     * msgFlags 
4044
     */
4045
0
    tmp_buf_len = SNMP_MAX_MSG_SIZE;
4046
0
    DEBUGDUMPHEADER("recv", "msgFlags");
4047
0
    data = asn_parse_string(data, length, &type, tmp_buf, &tmp_buf_len);
4048
0
    DEBUGINDENTLESS();
4049
0
    if (data == NULL || type != ASN_OCTET_STR || tmp_buf_len != 1) {
4050
0
        ERROR_MSG("error parsing msgFlags");
4051
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4052
0
        DEBUGINDENTADD(-4);
4053
0
        return SNMPERR_ASN_PARSE_ERR;
4054
0
    }
4055
0
    msg_flags = *tmp_buf;
4056
0
    if (msg_flags & SNMP_MSG_FLAG_RPRT_BIT)
4057
0
        pdu->flags |= SNMP_MSG_FLAG_RPRT_BIT;
4058
0
    else
4059
0
        pdu->flags &= (~SNMP_MSG_FLAG_RPRT_BIT);
4060
4061
    /*
4062
     * msgSecurityModel 
4063
     */
4064
0
    DEBUGDUMPHEADER("recv", "msgSecurityModel");
4065
0
    data = asn_parse_int(data, length, &type, &msg_sec_model,
4066
0
                         sizeof(msg_sec_model));
4067
0
    DEBUGINDENTADD(-4);         /* return from global data indent */
4068
0
    if (data == NULL || type != ASN_INTEGER ||
4069
0
        msg_sec_model < 1 || msg_sec_model > 0x7fffffff) {
4070
0
        ERROR_MSG("error parsing msgSecurityModel");
4071
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4072
0
        DEBUGINDENTLESS();
4073
0
        return SNMPERR_ASN_PARSE_ERR;
4074
0
    }
4075
0
    sptr = find_sec_mod(msg_sec_model);
4076
0
    if (!sptr) {
4077
0
        snmp_log(LOG_WARNING, "unknown security model: %ld\n",
4078
0
                 msg_sec_model);
4079
0
        snmp_increment_statistic(STAT_SNMPUNKNOWNSECURITYMODELS);
4080
0
        DEBUGINDENTLESS();
4081
0
        return SNMPERR_UNKNOWN_SEC_MODEL;
4082
0
    }
4083
0
    pdu->securityModel = msg_sec_model;
4084
4085
0
    if (msg_flags & SNMP_MSG_FLAG_PRIV_BIT &&
4086
0
        !(msg_flags & SNMP_MSG_FLAG_AUTH_BIT)) {
4087
0
        ERROR_MSG("invalid message, illegal msgFlags");
4088
0
        snmp_increment_statistic(STAT_SNMPINVALIDMSGS);
4089
0
        DEBUGINDENTLESS();
4090
0
        return SNMPERR_INVALID_MSG;
4091
0
    }
4092
0
    pdu->securityLevel = ((msg_flags & SNMP_MSG_FLAG_AUTH_BIT)
4093
0
                          ? ((msg_flags & SNMP_MSG_FLAG_PRIV_BIT)
4094
0
                             ? SNMP_SEC_LEVEL_AUTHPRIV
4095
0
                             : SNMP_SEC_LEVEL_AUTHNOPRIV)
4096
0
                          : SNMP_SEC_LEVEL_NOAUTH);
4097
    /*
4098
     * end of msgGlobalData 
4099
     */
4100
4101
    /*
4102
     * securtityParameters OCTET STRING begins after msgGlobalData 
4103
     */
4104
0
    sec_params = data;
4105
0
    SNMP_FREE(pdu->contextEngineID);
4106
0
    pdu->contextEngineID = calloc(1, SNMP_MAX_ENG_SIZE);
4107
0
    pdu->contextEngineIDLen = SNMP_MAX_ENG_SIZE;
4108
4109
    /*
4110
     * Note: there is no length limit on the msgAuthoritativeEngineID field,
4111
     * although we would EXPECT it to be limited to 32 (the SnmpEngineID TC
4112
     * limit).  We'll use double that here to be on the safe side.  
4113
     */
4114
4115
0
    SNMP_FREE(pdu->securityEngineID);
4116
0
    pdu->securityEngineID = calloc(1, SNMP_MAX_ENG_SIZE * 2);
4117
0
    pdu->securityEngineIDLen = SNMP_MAX_ENG_SIZE * 2;
4118
0
    SNMP_FREE(pdu->securityName);
4119
0
    pdu->securityName = calloc(1, SNMP_MAX_SEC_NAME_SIZE);
4120
0
    pdu->securityNameLen = SNMP_MAX_SEC_NAME_SIZE;
4121
4122
0
    if ((pdu->securityName == NULL) ||
4123
0
        (pdu->securityEngineID == NULL) ||
4124
0
        (pdu->contextEngineID == NULL)) {
4125
0
        return SNMPERR_MALLOC;
4126
0
    }
4127
4128
0
    if (pdu_buf_len < msg_len
4129
0
        && pdu->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
4130
        /*
4131
         * space needed is larger than we have in the default buffer 
4132
         */
4133
0
        mallocbuf = calloc(1, msg_len);
4134
0
        if (mallocbuf == NULL)
4135
0
            return SNMPERR_MALLOC;
4136
0
        pdu_buf_len = msg_len;
4137
0
        cp = mallocbuf;
4138
0
    } else {
4139
0
        memset(pdu_buf, 0, pdu_buf_len);
4140
0
        cp = pdu_buf;
4141
0
    }
4142
4143
0
    DEBUGDUMPSECTION("recv", "SM msgSecurityParameters");
4144
0
    if (sptr->decode) {
4145
0
        struct snmp_secmod_incoming_params parms;
4146
0
        parms.msgProcModel = pdu->msgParseModel;
4147
0
        parms.maxMsgSize = pdu->msgMaxSize;
4148
0
        parms.secParams = sec_params;
4149
0
        parms.secModel = msg_sec_model;
4150
0
        parms.secLevel = pdu->securityLevel;
4151
0
        parms.wholeMsg = msg_data;
4152
0
        parms.wholeMsgLen = msg_len;
4153
0
        parms.secEngineID = pdu->securityEngineID;
4154
0
        parms.secEngineIDLen = &pdu->securityEngineIDLen;
4155
0
        parms.secName = pdu->securityName;
4156
0
        parms.secNameLen = &pdu->securityNameLen;
4157
0
        parms.scopedPdu = &cp;
4158
0
        parms.scopedPduLen = &pdu_buf_len;
4159
0
        parms.maxSizeResponse = &max_size_response;
4160
0
        parms.secStateRef = &pdu->securityStateRef;
4161
0
        parms.sess = sess;
4162
0
        parms.pdu = pdu;
4163
0
        parms.msg_flags = msg_flags;
4164
0
        ret_val = (*sptr->decode) (&parms);
4165
0
    } else {
4166
0
        SNMP_FREE(mallocbuf);
4167
0
        DEBUGINDENTLESS();
4168
0
        snmp_log(LOG_WARNING, "security service %ld can't decode packets\n",
4169
0
                 msg_sec_model);
4170
0
        return (-1);
4171
0
    }
4172
4173
0
    if (ret_val != SNMPERR_SUCCESS) {
4174
0
        DEBUGDUMPSECTION("recv", "ScopedPDU");
4175
        /*
4176
         * Parse as much as possible -- though I don't see the point? [jbpn].  
4177
         */
4178
0
        if (cp) {
4179
0
            cp = snmpv3_scopedPDU_parse(pdu, cp, &pdu_buf_len);
4180
0
        }
4181
0
        if (cp) {
4182
0
            DEBUGPRINTPDUTYPE("recv", *cp);
4183
0
            snmp_pdu_parse(pdu, cp, &pdu_buf_len);
4184
0
            DEBUGINDENTADD(-8);
4185
0
        } else {
4186
0
            DEBUGINDENTADD(-4);
4187
0
        }
4188
4189
0
        SNMP_FREE(mallocbuf);
4190
0
        return ret_val;
4191
0
    }
4192
4193
    /*
4194
     * parse plaintext ScopedPDU sequence 
4195
     */
4196
0
    *length = pdu_buf_len;
4197
0
    DEBUGDUMPSECTION("recv", "ScopedPDU");
4198
0
    data = snmpv3_scopedPDU_parse(pdu, cp, length);
4199
0
    if (data == NULL) {
4200
0
        snmp_log(LOG_WARNING, "security service %ld error parsing ScopedPDU\n",
4201
0
                 msg_sec_model);
4202
0
        ERROR_MSG("error parsing PDU");
4203
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4204
0
        DEBUGINDENTADD(-4);
4205
0
        SNMP_FREE(mallocbuf);
4206
0
        return SNMPERR_ASN_PARSE_ERR;
4207
0
    }
4208
4209
    /*
4210
     * parse the PDU.  
4211
     */
4212
0
    if (after_header != NULL) {
4213
0
        *after_header = data;
4214
0
        tmp_buf_len = *length;
4215
0
    }
4216
4217
0
    DEBUGPRINTPDUTYPE("recv", *data);
4218
0
    ret = snmp_pdu_parse(pdu, data, length);
4219
0
    DEBUGINDENTADD(-8);
4220
4221
0
    if (after_header != NULL) {
4222
0
        *length = tmp_buf_len;
4223
0
    }
4224
4225
0
    if (ret != SNMPERR_SUCCESS) {
4226
0
        snmp_log(LOG_WARNING, "security service %ld error parsing ScopedPDU\n",
4227
0
                 msg_sec_model);
4228
0
        ERROR_MSG("error parsing PDU");
4229
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4230
0
        SNMP_FREE(mallocbuf);
4231
0
        return SNMPERR_ASN_PARSE_ERR;
4232
0
    }
4233
4234
0
    SNMP_FREE(mallocbuf);
4235
0
    return SNMPERR_SUCCESS;
4236
0
}                               /* end snmpv3_parse() */
4237
4238
static void
4239
free_securityStateRef(netsnmp_pdu* pdu)
4240
557k
{
4241
557k
    struct snmp_secmod_def *sptr;
4242
4243
557k
    if (!pdu->securityStateRef)
4244
557k
        return;
4245
4246
0
    sptr = find_sec_mod(pdu->securityModel);
4247
0
    if (sptr) {
4248
0
        if (sptr->pdu_free_state_ref) {
4249
0
            (*sptr->pdu_free_state_ref) (pdu->securityStateRef);
4250
0
        } else {
4251
0
            snmp_log(LOG_ERR,
4252
0
                     "Security Model %d can't free state references\n",
4253
0
                     pdu->securityModel);
4254
0
  }
4255
0
    } else {
4256
0
  snmp_log(LOG_ERR,
4257
0
     "Can't find security model to free ptr: %d\n",
4258
0
     pdu->securityModel);
4259
0
    }
4260
0
    pdu->securityStateRef = NULL;
4261
0
}
4262
4263
0
#define ERROR_STAT_LENGTH 11
4264
4265
int
4266
snmpv3_make_report(netsnmp_pdu *pdu, int error)
4267
0
{
4268
4269
0
    long            ltmp;
4270
0
    static const oid unknownSecurityLevel[] =
4271
0
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 };
4272
0
    static const oid notInTimeWindow[] =
4273
0
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 };
4274
0
    static const oid unknownUserName[] =
4275
0
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 };
4276
0
    static const oid unknownEngineID[] =
4277
0
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 };
4278
0
    static const oid wrongDigest[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 };
4279
0
    static const oid decryptionError[] =
4280
0
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 };
4281
0
    const oid      *err_var;
4282
0
    int             err_var_len;
4283
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4284
0
    int             stat_ind;
4285
0
#endif
4286
4287
0
    switch (error) {
4288
0
    case SNMPERR_USM_UNKNOWNENGINEID:
4289
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4290
0
        stat_ind = STAT_USMSTATSUNKNOWNENGINEIDS;
4291
0
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4292
0
        err_var = unknownEngineID;
4293
0
        err_var_len = ERROR_STAT_LENGTH;
4294
0
        break;
4295
0
    case SNMPERR_USM_UNKNOWNSECURITYNAME:
4296
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4297
0
        stat_ind = STAT_USMSTATSUNKNOWNUSERNAMES;
4298
0
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4299
0
        err_var = unknownUserName;
4300
0
        err_var_len = ERROR_STAT_LENGTH;
4301
0
        break;
4302
0
    case SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL:
4303
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4304
0
        stat_ind = STAT_USMSTATSUNSUPPORTEDSECLEVELS;
4305
0
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4306
0
        err_var = unknownSecurityLevel;
4307
0
        err_var_len = ERROR_STAT_LENGTH;
4308
0
        break;
4309
0
    case SNMPERR_USM_AUTHENTICATIONFAILURE:
4310
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4311
0
        stat_ind = STAT_USMSTATSWRONGDIGESTS;
4312
0
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4313
0
        err_var = wrongDigest;
4314
0
        err_var_len = ERROR_STAT_LENGTH;
4315
0
        break;
4316
0
    case SNMPERR_USM_NOTINTIMEWINDOW:
4317
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4318
0
        stat_ind = STAT_USMSTATSNOTINTIMEWINDOWS;
4319
0
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4320
0
        err_var = notInTimeWindow;
4321
0
        err_var_len = ERROR_STAT_LENGTH;
4322
0
        break;
4323
0
    case SNMPERR_USM_DECRYPTIONERROR:
4324
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4325
0
        stat_ind = STAT_USMSTATSDECRYPTIONERRORS;
4326
0
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4327
0
        err_var = decryptionError;
4328
0
        err_var_len = ERROR_STAT_LENGTH;
4329
0
        break;
4330
0
    default:
4331
0
        return SNMPERR_GENERR;
4332
0
    }
4333
4334
0
    snmp_free_varbind(pdu->variables);  /* free the current varbind */
4335
4336
0
    pdu->variables = NULL;
4337
0
    SNMP_FREE(pdu->securityEngineID);
4338
0
    pdu->securityEngineID =
4339
0
        snmpv3_generate_engineID(&pdu->securityEngineIDLen);
4340
0
    SNMP_FREE(pdu->contextEngineID);
4341
0
    pdu->contextEngineID =
4342
0
        snmpv3_generate_engineID(&pdu->contextEngineIDLen);
4343
0
    pdu->command = SNMP_MSG_REPORT;
4344
0
    pdu->errstat = 0;
4345
0
    pdu->errindex = 0;
4346
0
    SNMP_FREE(pdu->contextName);
4347
0
    pdu->contextNameLen = 0;
4348
0
    pdu->contextName = strdup("");
4349
0
    if (!pdu->contextName)
4350
0
        return SNMPERR_MALLOC;
4351
0
    pdu->contextNameLen = strlen(pdu->contextName);
4352
4353
    /*
4354
     * reports shouldn't cache previous data. 
4355
     */
4356
    /*
4357
     * FIX - yes they should but USM needs to follow new EoP to determine
4358
     * which cached values to use 
4359
     */
4360
0
    free_securityStateRef(pdu);
4361
4362
0
    if (error == SNMPERR_USM_NOTINTIMEWINDOW) {
4363
0
        pdu->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
4364
0
    } else {
4365
0
        pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
4366
0
    }
4367
4368
    /*
4369
     * find the appropriate error counter  
4370
     */
4371
0
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4372
0
    ltmp = snmp_get_statistic(stat_ind);
4373
#else /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4374
    ltmp = 1;
4375
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4376
4377
    /*
4378
     * return the appropriate error counter  
4379
     */
4380
0
    snmp_pdu_add_variable(pdu, err_var, err_var_len,
4381
0
                          ASN_COUNTER, & ltmp, sizeof(ltmp));
4382
4383
0
    return SNMPERR_SUCCESS;
4384
0
}                               /* end snmpv3_make_report() */
4385
4386
4387
int
4388
snmpv3_get_report_type(netsnmp_pdu *pdu)
4389
0
{
4390
0
    static const oid snmpMPDStats[] = { 1, 3, 6, 1, 6, 3, 11, 2, 1 };
4391
0
    static const oid targetStats[]  = { 1, 3, 6, 1, 6, 3, 12, 1    };
4392
0
    static const oid usmStats[]     = { 1, 3, 6, 1, 6, 3, 15, 1, 1 };
4393
0
    netsnmp_variable_list *vp;
4394
0
    int             rpt_type = SNMPERR_UNKNOWN_REPORT;
4395
4396
0
    if (pdu == NULL || pdu->variables == NULL)
4397
0
        return rpt_type;
4398
0
    vp = pdu->variables;
4399
    /* MPD or USM based report statistics objects have the same length prefix
4400
     *   so the actual statistics OID will have this length,
4401
     *   plus one subidentifier for the scalar MIB object itself,
4402
     *   and one for the instance subidentifier
4403
     */
4404
0
    if (vp->name_length == REPORT_STATS_LEN + 2) {
4405
0
        if (memcmp(snmpMPDStats, vp->name, REPORT_STATS_LEN * sizeof(oid)) == 0) {
4406
0
            switch (vp->name[REPORT_STATS_LEN]) {
4407
0
            case REPORT_snmpUnknownSecurityModels_NUM:
4408
0
                rpt_type = SNMPERR_UNKNOWN_SEC_MODEL;
4409
0
                break;
4410
0
            case REPORT_snmpInvalidMsgs_NUM:
4411
0
                rpt_type = SNMPERR_INVALID_MSG;
4412
0
                break;
4413
0
            case REPORT_snmpUnknownPDUHandlers_NUM:
4414
0
                rpt_type = SNMPERR_BAD_VERSION;
4415
0
                break;
4416
0
            }
4417
0
        } else if (memcmp(usmStats, vp->name, REPORT_STATS_LEN * sizeof(oid)) == 0) {
4418
0
            switch (vp->name[REPORT_STATS_LEN]) {
4419
0
            case REPORT_usmStatsUnsupportedSecLevels_NUM:
4420
0
                rpt_type = SNMPERR_UNSUPPORTED_SEC_LEVEL;
4421
0
                break;
4422
0
            case REPORT_usmStatsNotInTimeWindows_NUM:
4423
0
                rpt_type = SNMPERR_NOT_IN_TIME_WINDOW;
4424
0
                break;
4425
0
            case REPORT_usmStatsUnknownUserNames_NUM:
4426
0
                rpt_type = SNMPERR_UNKNOWN_USER_NAME;
4427
0
                break;
4428
0
            case REPORT_usmStatsUnknownEngineIDs_NUM:
4429
0
                rpt_type = SNMPERR_UNKNOWN_ENG_ID;
4430
0
                break;
4431
0
            case REPORT_usmStatsWrongDigests_NUM:
4432
0
                rpt_type = SNMPERR_AUTHENTICATION_FAILURE;
4433
0
                break;
4434
0
            case REPORT_usmStatsDecryptionErrors_NUM:
4435
0
                rpt_type = SNMPERR_DECRYPTION_ERR;
4436
0
                break;
4437
0
            }
4438
0
        }
4439
0
    }
4440
    /* Context-based report statistics from the Target MIB are similar
4441
     *   but the OID prefix has a different length
4442
     */
4443
0
    if (vp->name_length == REPORT_STATS_LEN2 + 2) {
4444
0
        if (memcmp(targetStats, vp->name, REPORT_STATS_LEN2 * sizeof(oid)) == 0) {
4445
0
            switch (vp->name[REPORT_STATS_LEN2]) {
4446
0
            case REPORT_snmpUnavailableContexts_NUM:
4447
0
                rpt_type = SNMPERR_BAD_CONTEXT;
4448
0
                break;
4449
0
            case REPORT_snmpUnknownContexts_NUM:
4450
0
                rpt_type = SNMPERR_BAD_CONTEXT;
4451
0
                break;
4452
0
            }
4453
0
        }
4454
0
    }
4455
0
    DEBUGMSGTL(("report", "Report type: %d\n", rpt_type));
4456
0
    return rpt_type;
4457
0
}
4458
4459
/*
4460
 * Parses the packet received on the input session, and places the data into
4461
 * the input pdu.  length is the length of the input packet.
4462
 * If any errors are encountered, -1 or USM error is returned.
4463
 * Otherwise, a 0 is returned.
4464
 */
4465
static int
4466
_snmp_parse(struct session_list *slp,
4467
            netsnmp_session * session,
4468
            netsnmp_pdu *pdu, u_char * data, size_t length)
4469
0
{
4470
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
4471
0
    u_char          community[COMMUNITY_MAX_LEN];
4472
0
    size_t          community_length = COMMUNITY_MAX_LEN;
4473
0
#endif
4474
0
    int             result = -1;
4475
4476
0
    static const oid snmpEngineIDoid[]   = { 1,3,6,1,6,3,10,2,1,1,0};
4477
0
    static size_t   snmpEngineIDoid_len = 11;
4478
4479
0
    static char     ourEngineID[SNMP_SEC_PARAM_BUF_SIZE];
4480
0
    static size_t   ourEngineID_len = sizeof(ourEngineID);
4481
4482
0
    netsnmp_pdu    *pdu2 = NULL;
4483
4484
0
    session->s_snmp_errno = 0;
4485
0
    session->s_errno = 0;
4486
4487
    /*
4488
     * Ensure all incoming PDUs have a unique means of identification 
4489
     * (This is not restricted to AgentX handling,
4490
     * though that is where the need becomes visible)   
4491
     */
4492
0
    pdu->transid = snmp_get_next_transid();
4493
4494
0
    if (session->version != SNMP_DEFAULT_VERSION) {
4495
0
        pdu->version = session->version;
4496
0
    } else {
4497
0
        pdu->version = snmp_parse_version(data, length);
4498
0
    }
4499
4500
0
    switch (pdu->version) {
4501
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
4502
0
#ifndef NETSNMP_DISABLE_SNMPV1
4503
0
    case SNMP_VERSION_1:
4504
0
#endif
4505
0
#ifndef NETSNMP_DISABLE_SNMPV2C
4506
0
    case SNMP_VERSION_2c:
4507
0
#endif
4508
0
        NETSNMP_RUNTIME_PROTOCOL_CHECK_V1V2(pdu->version,unsupported_version);
4509
0
        DEBUGMSGTL(("snmp_api", "Parsing SNMPv%ld message...\n",
4510
0
                    (1 + pdu->version)));
4511
4512
        /*
4513
         * authenticates message and returns length if valid 
4514
         */
4515
0
#ifndef NETSNMP_DISABLE_SNMPV1
4516
0
        if (pdu->version == SNMP_VERSION_1) {
4517
0
            DEBUGDUMPSECTION("recv", "SNMPv1 message\n");
4518
0
        } else {
4519
0
#endif
4520
0
            DEBUGDUMPSECTION("recv", "SNMPv2c message\n");
4521
0
#ifndef NETSNMP_DISABLE_SNMPV1
4522
0
        }
4523
0
#endif
4524
0
        data = snmp_comstr_parse(data, &length,
4525
0
                                 community, &community_length,
4526
0
                                 &pdu->version);
4527
0
        if (data == NULL)
4528
0
            return -1;
4529
4530
0
        if (pdu->version != session->version &&
4531
0
            session->version != SNMP_DEFAULT_VERSION) {
4532
0
            session->s_snmp_errno = SNMPERR_BAD_VERSION;
4533
0
            return -1;
4534
0
        }
4535
4536
        /*
4537
         * maybe get the community string. 
4538
         */
4539
0
        pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
4540
0
        pdu->securityModel = 
4541
0
#ifndef NETSNMP_DISABLE_SNMPV1
4542
0
            (pdu->version == SNMP_VERSION_1) ? SNMP_SEC_MODEL_SNMPv1 : 
4543
0
#endif
4544
0
                                               SNMP_SEC_MODEL_SNMPv2c;
4545
0
        SNMP_FREE(pdu->community);
4546
0
        pdu->community_len = 0;
4547
0
        pdu->community = (u_char *) 0;
4548
0
        if (community_length) {
4549
0
            pdu->community_len = community_length;
4550
0
            pdu->community = netsnmp_memdup(community, community_length);
4551
0
            if (pdu->community == NULL) {
4552
0
                session->s_snmp_errno = SNMPERR_MALLOC;
4553
0
                return -1;
4554
0
            }
4555
0
        }
4556
0
        if (session->authenticator) {
4557
0
            data = session->authenticator(data, &length,
4558
0
                                          community, community_length);
4559
0
            if (data == NULL) {
4560
0
                session->s_snmp_errno = SNMPERR_AUTHENTICATION_FAILURE;
4561
0
                return -1;
4562
0
            }
4563
0
        }
4564
4565
0
        DEBUGDUMPSECTION("recv", "PDU");
4566
0
        result = snmp_pdu_parse(pdu, data, &length);
4567
0
        if (result < 0) {
4568
            /*
4569
             * This indicates a parse error.  
4570
             */
4571
0
            snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4572
0
        }
4573
0
        DEBUGINDENTADD(-6);
4574
0
        break;
4575
0
#endif /* support for community based SNMP */
4576
4577
0
    case SNMP_VERSION_3:
4578
0
        NETSNMP_RUNTIME_PROTOCOL_CHECK_V3(SNMP_VERSION_3,unsupported_version);
4579
0
        result = snmpv3_parse(pdu, data, &length, NULL, session);
4580
0
        DEBUGMSGTL(("snmp_parse",
4581
0
                    "Parsed SNMPv3 message (secName:%s, secLevel:%s): %s\n",
4582
0
                    pdu->securityName,
4583
0
                    (pdu->securityLevel >= 0 && pdu->securityLevel < 4) ?
4584
0
                    secLevelName[pdu->securityLevel] : "ERROR: invalid",
4585
0
                    snmp_api_errstring(result)));
4586
4587
0
        if (result == SNMPERR_USM_UNKNOWNSECURITYNAME) {
4588
0
            snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
4589
0
                                SNMPD_CALLBACK_AUTH_FAILURE, pdu);
4590
0
        }
4591
        
4592
0
        if (result) {
4593
0
            struct snmp_secmod_def *secmod =
4594
0
                find_sec_mod(pdu->securityModel);
4595
0
            if (!slp) {
4596
0
                session->s_snmp_errno = result;
4597
0
            } else {
4598
                /*
4599
                 * Call the security model to special handle any errors
4600
                 */
4601
4602
0
                if (secmod && secmod->handle_report) {
4603
0
                    (*secmod->handle_report)(slp, slp->transport, session,
4604
0
                                             result, pdu);
4605
0
                }
4606
0
            }
4607
0
            free_securityStateRef(pdu);
4608
0
        }
4609
4610
        /* Implement RFC5343 here for two reasons:
4611
           1) From a security perspective it handles this otherwise
4612
              always approved request earlier.  It bypasses the need
4613
              for authorization to the snmpEngineID scalar, which is
4614
              what is what RFC3415 appendix A species as ok.  Note
4615
              that we haven't bypassed authentication since if there
4616
              was an authentication error it would have been handled
4617
              above in the if(result) part at the latest.
4618
           2) From an application point of view if we let this request
4619
              get all the way to the application, it'd require that
4620
              all application types supporting discovery also fire up
4621
              a minimal agent in order to handle just this request
4622
              which seems like overkill.  Though there is no other
4623
              application types that currently need discovery (NRs
4624
              accept notifications from contextEngineIDs that derive
4625
              from the NO not the NR).  Also a lame excuse for doing
4626
              it here.
4627
           3) Less important technically, but the net-snmp agent
4628
              doesn't currently handle registrations of different
4629
              engineIDs either and it would have been a lot more work
4630
              to implement there since we'd need to support that
4631
              first. :-/ Supporting multiple context engineIDs should
4632
              be done anyway, so it's not a valid excuse here.
4633
           4) There is a lot less to do if we trump the agent at this
4634
              point; IE, the agent does a lot more unnecessary
4635
              processing when the only thing that should ever be in
4636
              this context by definition is the single scalar.
4637
        */
4638
4639
        /* special RFC5343 engineID discovery engineID check */
4640
0
        if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
4641
0
                                    NETSNMP_DS_LIB_NO_DISCOVERY) &&
4642
0
            SNMP_MSG_RESPONSE       != pdu->command &&
4643
0
            NULL                    != pdu->contextEngineID &&
4644
0
            pdu->contextEngineIDLen == 5 &&
4645
0
            pdu->contextEngineID[0] == 0x80 &&
4646
0
            pdu->contextEngineID[1] == 0x00 &&
4647
0
            pdu->contextEngineID[2] == 0x00 &&
4648
0
            pdu->contextEngineID[3] == 0x00 &&
4649
0
            pdu->contextEngineID[4] == 0x06) {
4650
4651
            /* define a result so it doesn't get past us at this point
4652
               and gets dropped by future parts of the stack */
4653
0
            result = SNMPERR_JUST_A_CONTEXT_PROBE;
4654
4655
0
            DEBUGMSGTL(("snmpv3_contextid", "starting context ID discovery\n"));
4656
            /* ensure exactly one variable */
4657
0
            if (NULL != pdu->variables &&
4658
0
                NULL == pdu->variables->next_variable &&
4659
4660
                /* if it's a GET, match it exactly */
4661
0
                ((SNMP_MSG_GET == pdu->command &&
4662
0
                  snmp_oid_compare(snmpEngineIDoid,
4663
0
                                   snmpEngineIDoid_len,
4664
0
                                   pdu->variables->name,
4665
0
                                   pdu->variables->name_length) == 0)
4666
                 /* if it's a GETNEXT ensure it's less than the engineID oid */
4667
0
                 ||
4668
0
                 (SNMP_MSG_GETNEXT == pdu->command &&
4669
0
                  snmp_oid_compare(snmpEngineIDoid,
4670
0
                                   snmpEngineIDoid_len,
4671
0
                                   pdu->variables->name,
4672
0
                                   pdu->variables->name_length) > 0)
4673
0
                    )) {
4674
4675
0
                DEBUGMSGTL(("snmpv3_contextid",
4676
0
                            "  One correct variable found\n"));
4677
4678
                /* Note: we're explicitly not handling a GETBULK.  Deal. */
4679
4680
                /* set up the response */
4681
0
                pdu2 = snmp_clone_pdu(pdu);
4682
0
                if (NULL == pdu2) {
4683
0
                    snmp_log(LOG_ERR, "failed to clone PDU for rfc5343 probe\n");
4684
0
                    if (pdu->securityStateRef)
4685
0
                        free_securityStateRef(pdu);
4686
0
                    return result;
4687
0
                }
4688
4689
                /* free the current varbind */
4690
0
                snmp_free_varbind(pdu2->variables);
4691
4692
                /* set the variables */
4693
0
                pdu2->variables = NULL;
4694
0
                pdu2->command = SNMP_MSG_RESPONSE;
4695
0
                pdu2->errstat = 0;
4696
0
                pdu2->errindex = 0;
4697
4698
0
                ourEngineID_len =
4699
0
                    snmpv3_get_engineID((u_char*)ourEngineID, ourEngineID_len);
4700
0
                if (0 != ourEngineID_len) {
4701
4702
0
                    DEBUGMSGTL(("snmpv3_contextid",
4703
0
                                "  responding with our engineID\n"));
4704
4705
0
                    snmp_pdu_add_variable(pdu2,
4706
0
                                          snmpEngineIDoid, snmpEngineIDoid_len,
4707
0
                                          ASN_OCTET_STR,
4708
0
                                          ourEngineID, ourEngineID_len);
4709
                    
4710
                    /* send the response */
4711
0
                    if (0 == snmp_sess_send(slp, pdu2)) {
4712
4713
0
                        DEBUGMSGTL(("snmpv3_contextid",
4714
0
                                    "  sent it off!\n"));
4715
4716
0
                        snmp_free_pdu(pdu2);
4717
                        
4718
0
                        snmp_log(LOG_ERR, "sending a response to the context engineID probe failed\n");
4719
0
                    }
4720
0
                } else {
4721
0
                    snmp_log(LOG_ERR, "failed to get our own engineID!\n");
4722
0
                    snmp_free_pdu(pdu2);
4723
0
                }
4724
0
            } else {
4725
0
                snmp_log(LOG_WARNING,
4726
0
                         "received an odd context engineID probe\n");
4727
0
            }
4728
0
            if (pdu->securityStateRef)
4729
0
                free_securityStateRef(pdu);
4730
0
        }
4731
4732
0
        break;
4733
0
    case SNMPERR_BAD_VERSION:
4734
0
        ERROR_MSG("error parsing snmp message version");
4735
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4736
0
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
4737
0
        break;
4738
4739
0
        unsupported_version:  /* goto label */
4740
0
    case SNMP_VERSION_sec:
4741
0
    case SNMP_VERSION_2u:
4742
0
    case SNMP_VERSION_2star:
4743
0
    case SNMP_VERSION_2p:
4744
0
    default:
4745
0
        ERROR_MSG("unsupported snmp message version");
4746
0
        snmp_increment_statistic(STAT_SNMPINBADVERSIONS);
4747
4748
        /*
4749
         * need better way to determine OS independent
4750
         * INT32_MAX value, for now hardcode
4751
         */
4752
0
        if (pdu->version < 0 || pdu->version > 2147483647) {
4753
0
            snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4754
0
        }
4755
0
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
4756
0
        break;
4757
0
    }
4758
4759
0
    return result;
4760
0
}
4761
4762
/**
4763
 * Parse a PDU.
4764
 * @param slp    [in]  Session pointer (struct session_list).
4765
 * @param pss    [in]  Session pointer (netsnmp_session).
4766
 * @param pdu    [out] Parsed PDU.
4767
 * @param data   [in]  PDU to parse.
4768
 * @param length [in]  Length of data.
4769
 *
4770
 * @returns 0 upon success; -1 upon failure.
4771
 */
4772
int
4773
snmp_parse(struct session_list *slp, netsnmp_session *pss,
4774
           netsnmp_pdu *pdu, u_char *data, size_t length)
4775
0
{
4776
0
    int             rc;
4777
4778
0
    rc = _snmp_parse(slp, pss, pdu, data, length);
4779
0
    if (rc) {
4780
0
        if (!pss->s_snmp_errno) {
4781
0
            pss->s_snmp_errno = SNMPERR_BAD_PARSE;
4782
0
        }
4783
0
        SET_SNMP_ERROR(pss->s_snmp_errno);
4784
0
    }
4785
4786
0
    return rc;
4787
0
}
4788
4789
int
4790
snmp_pdu_parse(netsnmp_pdu *pdu, u_char * data, size_t * length)
4791
0
{
4792
0
    u_char          type;
4793
0
    u_char          msg_type;
4794
0
    u_char         *var_val;
4795
0
    size_t          len;
4796
0
    size_t          four;
4797
0
    netsnmp_variable_list *vp = NULL, *vplast = NULL;
4798
0
    oid             objid[MAX_OID_LEN];
4799
0
    u_char         *p;
4800
4801
    /*
4802
     * Get the PDU type 
4803
     */
4804
0
    data = asn_parse_header(data, length, &msg_type);
4805
0
    if (data == NULL)
4806
0
        return -1;
4807
0
    DEBUGMSGTL(("dumpv_recv","    Command %s\n", snmp_pdu_type(msg_type)));
4808
0
    pdu->command = msg_type;
4809
0
    pdu->flags &= (~UCD_MSG_FLAG_RESPONSE_PDU);
4810
4811
    /*
4812
     * get the fields in the PDU preceding the variable-bindings sequence
4813
     */
4814
0
    switch (pdu->command) {
4815
0
    case SNMP_MSG_TRAP:
4816
        /*
4817
         * enterprise 
4818
         */
4819
0
        pdu->enterprise_length = MAX_OID_LEN;
4820
0
        data = asn_parse_objid(data, length, &type, objid,
4821
0
                               &pdu->enterprise_length);
4822
0
        if (data == NULL)
4823
0
            return -1;
4824
0
        SNMP_FREE(pdu->enterprise);
4825
0
        pdu->enterprise = netsnmp_memdup(objid,
4826
0
                                         pdu->enterprise_length * sizeof(oid));
4827
0
        if (pdu->enterprise == NULL) {
4828
0
            return -1;
4829
0
        }
4830
4831
        /*
4832
         * agent-addr 
4833
         */
4834
0
        four = 4;
4835
0
        data = asn_parse_string(data, length, &type,
4836
0
                                (u_char *) pdu->agent_addr, &four);
4837
0
        if (data == NULL)
4838
0
            return -1;
4839
4840
        /*
4841
         * generic trap 
4842
         */
4843
0
        data = asn_parse_int(data, length, &type, (long *) &pdu->trap_type,
4844
0
                             sizeof(pdu->trap_type));
4845
0
        if (data == NULL)
4846
0
            return -1;
4847
        /*
4848
         * specific trap 
4849
         */
4850
0
        data =
4851
0
            asn_parse_int(data, length, &type,
4852
0
                          (long *) &pdu->specific_type,
4853
0
                          sizeof(pdu->specific_type));
4854
0
        if (data == NULL)
4855
0
            return -1;
4856
4857
        /*
4858
         * timestamp  
4859
         */
4860
0
        data = asn_parse_unsigned_int(data, length, &type, &pdu->time,
4861
0
                                      sizeof(pdu->time));
4862
0
        if (data == NULL)
4863
0
            return -1;
4864
4865
0
        break;
4866
4867
0
    case SNMP_MSG_RESPONSE:
4868
0
    case SNMP_MSG_REPORT:
4869
0
        pdu->flags |= UCD_MSG_FLAG_RESPONSE_PDU;
4870
0
        NETSNMP_FALLTHROUGH;
4871
4872
0
    case SNMP_MSG_TRAP2:
4873
0
    case SNMP_MSG_INFORM:
4874
0
#ifndef NETSNMP_NOTIFY_ONLY
4875
0
    case SNMP_MSG_GET:
4876
0
    case SNMP_MSG_GETNEXT:
4877
0
    case SNMP_MSG_GETBULK:
4878
0
#endif /* ! NETSNMP_NOTIFY_ONLY */
4879
0
#ifndef NETSNMP_NO_WRITE_SUPPORT
4880
0
    case SNMP_MSG_SET:
4881
0
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
4882
        /*
4883
         * PDU is not an SNMPv1 TRAP 
4884
         */
4885
4886
        /*
4887
         * request id 
4888
         */
4889
0
        DEBUGDUMPHEADER("recv", "request_id");
4890
0
        data = asn_parse_int(data, length, &type, &pdu->reqid,
4891
0
                             sizeof(pdu->reqid));
4892
0
        DEBUGINDENTLESS();
4893
0
        if (data == NULL) {
4894
0
            return -1;
4895
0
        }
4896
4897
        /*
4898
         * error status (getbulk non-repeaters) 
4899
         */
4900
0
        DEBUGDUMPHEADER("recv", "error status");
4901
0
        data = asn_parse_int(data, length, &type, &pdu->errstat,
4902
0
                             sizeof(pdu->errstat));
4903
0
        DEBUGINDENTLESS();
4904
0
        if (data == NULL) {
4905
0
            return -1;
4906
0
        }
4907
4908
        /*
4909
         * error index (getbulk max-repetitions) 
4910
         */
4911
0
        DEBUGDUMPHEADER("recv", "error index");
4912
0
        data = asn_parse_int(data, length, &type, &pdu->errindex,
4913
0
                             sizeof(pdu->errindex));
4914
0
        DEBUGINDENTLESS();
4915
0
        if (data == NULL) {
4916
0
            return -1;
4917
0
        }
4918
0
  break;
4919
4920
0
    default:
4921
0
        snmp_log(LOG_ERR, "Bad PDU type received: 0x%.2x\n", pdu->command);
4922
0
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4923
0
        return -1;
4924
0
    }
4925
4926
    /*
4927
     * get header for variable-bindings sequence 
4928
     */
4929
0
    DEBUGDUMPSECTION("recv", "VarBindList");
4930
0
    data = asn_parse_sequence(data, length, &type,
4931
0
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR),
4932
0
                              "varbinds");
4933
0
    if (data == NULL)
4934
0
        goto fail;
4935
4936
0
    snmp_free_varbind(pdu->variables);
4937
0
    pdu->variables = NULL;
4938
4939
    /*
4940
     * get each varBind sequence 
4941
     */
4942
0
    while ((int) *length > 0) {
4943
0
        vp = SNMP_MALLOC_TYPEDEF(netsnmp_variable_list);
4944
0
        if (NULL == vp)
4945
0
            goto fail;
4946
4947
0
        vp->name_length = MAX_OID_LEN;
4948
0
        DEBUGDUMPSECTION("recv", "VarBind");
4949
0
        data = snmp_parse_var_op(data, objid, &vp->name_length, &vp->type,
4950
0
                                 &vp->val_len, &var_val, length);
4951
0
        if (data == NULL)
4952
0
            goto fail;
4953
0
        if (snmp_set_var_objid(vp, objid, vp->name_length))
4954
0
            goto fail;
4955
4956
0
        len = SNMP_MAX_PACKET_LEN;
4957
0
        DEBUGDUMPHEADER("recv", "Value");
4958
0
        switch ((short) vp->type) {
4959
0
        case ASN_INTEGER:
4960
0
            vp->val.integer = (long *) vp->buf;
4961
0
            vp->val_len = sizeof(long);
4962
0
            p = asn_parse_int(var_val, &len, &vp->type,
4963
0
                          (long *) vp->val.integer,
4964
0
                          sizeof(*vp->val.integer));
4965
0
            if (!p)
4966
0
                goto fail;
4967
0
            break;
4968
0
        case ASN_COUNTER:
4969
0
        case ASN_GAUGE:
4970
0
        case ASN_TIMETICKS:
4971
0
        case ASN_UINTEGER:
4972
0
            vp->val.integer = (long *) vp->buf;
4973
0
            vp->val_len = sizeof(u_long);
4974
0
            p = asn_parse_unsigned_int(var_val, &len, &vp->type,
4975
0
                                   (u_long *) vp->val.integer,
4976
0
                                   vp->val_len);
4977
0
            if (!p)
4978
0
                goto fail;
4979
0
            break;
4980
0
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
4981
0
        case ASN_OPAQUE_COUNTER64:
4982
0
        case ASN_OPAQUE_U64:
4983
0
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
4984
0
        case ASN_COUNTER64:
4985
0
            vp->val.counter64 = (struct counter64 *) vp->buf;
4986
0
            vp->val_len = sizeof(struct counter64);
4987
0
            p = asn_parse_unsigned_int64(var_val, &len, &vp->type,
4988
0
                                     (struct counter64 *) vp->val.
4989
0
                                     counter64, vp->val_len);
4990
0
            if (!p)
4991
0
                goto fail;
4992
0
            break;
4993
0
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
4994
0
        case ASN_OPAQUE_FLOAT:
4995
0
            vp->val.floatVal = (float *) vp->buf;
4996
0
            vp->val_len = sizeof(float);
4997
0
            p = asn_parse_float(var_val, &len, &vp->type,
4998
0
                            vp->val.floatVal, vp->val_len);
4999
0
            if (!p)
5000
0
                goto fail;
5001
0
            break;
5002
0
        case ASN_OPAQUE_DOUBLE:
5003
0
            vp->val.doubleVal = (double *) vp->buf;
5004
0
            vp->val_len = sizeof(double);
5005
0
            p = asn_parse_double(var_val, &len, &vp->type,
5006
0
                             vp->val.doubleVal, vp->val_len);
5007
0
            if (!p)
5008
0
                goto fail;
5009
0
            break;
5010
0
        case ASN_OPAQUE_I64:
5011
0
            vp->val.counter64 = (struct counter64 *) vp->buf;
5012
0
            vp->val_len = sizeof(struct counter64);
5013
0
            p = asn_parse_signed_int64(var_val, &len, &vp->type,
5014
0
                                   (struct counter64 *) vp->val.counter64,
5015
0
                                   sizeof(*vp->val.counter64));
5016
5017
0
            if (!p)
5018
0
                goto fail;
5019
0
            break;
5020
0
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
5021
0
        case ASN_IPADDRESS:
5022
0
            if (vp->val_len != 4)
5023
0
                goto fail;
5024
0
            NETSNMP_FALLTHROUGH;
5025
0
        case ASN_OCTET_STR:
5026
0
        case ASN_OPAQUE:
5027
0
        case ASN_NSAP:
5028
0
            if (vp->val_len < sizeof(vp->buf)) {
5029
0
                vp->val.string = (u_char *) vp->buf;
5030
0
            } else {
5031
0
                vp->val.string = (u_char *) malloc(vp->val_len);
5032
0
            }
5033
0
            if (vp->val.string == NULL) {
5034
0
                goto fail;
5035
0
            }
5036
0
            p = asn_parse_string(var_val, &len, &vp->type, vp->val.string,
5037
0
                             &vp->val_len);
5038
0
            if (!p)
5039
0
                goto fail;
5040
0
            break;
5041
0
        case ASN_OBJECT_ID:
5042
0
            vp->val_len = MAX_OID_LEN;
5043
0
            p = asn_parse_objid(var_val, &len, &vp->type, objid, &vp->val_len);
5044
0
            if (!p)
5045
0
                goto fail;
5046
0
            vp->val_len *= sizeof(oid);
5047
0
            vp->val.objid = netsnmp_memdup(objid, vp->val_len);
5048
0
            if (vp->val.objid == NULL)
5049
0
                goto fail;
5050
0
            break;
5051
0
        case SNMP_NOSUCHOBJECT:
5052
0
        case SNMP_NOSUCHINSTANCE:
5053
0
        case SNMP_ENDOFMIBVIEW:
5054
0
        case ASN_NULL:
5055
0
            break;
5056
0
        case ASN_BIT_STR:
5057
0
            vp->val.bitstring = (u_char *) malloc(vp->val_len);
5058
0
            if (vp->val.bitstring == NULL) {
5059
0
                goto fail;
5060
0
            }
5061
0
            p = asn_parse_bitstring(var_val, &len, &vp->type,
5062
0
                                vp->val.bitstring, &vp->val_len);
5063
0
            if (!p)
5064
0
                goto fail;
5065
0
            break;
5066
0
        default:
5067
0
            snmp_log(LOG_ERR, "bad type returned (%x)\n", vp->type);
5068
0
            goto fail;
5069
0
            break;
5070
0
        }
5071
0
        DEBUGINDENTADD(-4);
5072
5073
0
        if (NULL == vplast) {
5074
0
            pdu->variables = vp;
5075
0
        } else {
5076
0
            vplast->next_variable = vp;
5077
0
        }
5078
0
        vplast = vp;
5079
0
        vp = NULL;
5080
0
    }
5081
0
    return 0;
5082
5083
0
  fail:
5084
0
    {
5085
0
        const char *errstr = snmp_api_errstring(SNMPERR_SUCCESS);
5086
0
        DEBUGMSGTL(("recv", "error while parsing VarBindList:%s\n", errstr));
5087
0
    }
5088
    /** if we were parsing a var, remove it from the pdu and free it */
5089
0
    if (vp)
5090
0
        snmp_free_var(vp);
5091
5092
0
    return -1;
5093
0
}
5094
5095
/*
5096
 * snmp v3 utility function to parse into the scopedPdu. stores contextName
5097
 * and contextEngineID in pdu struct. Also stores pdu->command (handy for 
5098
 * Report generation).
5099
 * 
5100
 * returns pointer to begining of PDU or NULL on error.
5101
 */
5102
u_char         *
5103
snmpv3_scopedPDU_parse(netsnmp_pdu *pdu, u_char * cp, size_t * length)
5104
0
{
5105
0
    u_char          tmp_buf[SNMP_MAX_MSG_SIZE];
5106
0
    size_t          tmp_buf_len;
5107
0
    u_char          type;
5108
0
    size_t          asn_len;
5109
0
    u_char         *data;
5110
5111
0
    pdu->command = 0;           /* initialize so we know if it got parsed */
5112
0
    asn_len = *length;
5113
0
    data = asn_parse_sequence(cp, &asn_len, &type,
5114
0
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR),
5115
0
                              "plaintext scopedPDU");
5116
0
    if (data == NULL) {
5117
0
        return NULL;
5118
0
    }
5119
0
    *length -= data - cp;
5120
5121
    /*
5122
     * contextEngineID from scopedPdu  
5123
     */
5124
0
    DEBUGDUMPHEADER("recv", "contextEngineID");
5125
0
    data = asn_parse_string(data, length, &type, pdu->contextEngineID,
5126
0
                            &pdu->contextEngineIDLen);
5127
0
    DEBUGINDENTLESS();
5128
0
    if (data == NULL) {
5129
0
        ERROR_MSG("error parsing contextEngineID from scopedPdu");
5130
0
        return NULL;
5131
0
    }
5132
5133
    /*
5134
     * parse contextName from scopedPdu
5135
     */
5136
0
    tmp_buf_len = SNMP_MAX_CONTEXT_SIZE;
5137
0
    DEBUGDUMPHEADER("recv", "contextName");
5138
0
    data = asn_parse_string(data, length, &type, tmp_buf, &tmp_buf_len);
5139
0
    DEBUGINDENTLESS();
5140
0
    if (data == NULL) {
5141
0
        ERROR_MSG("error parsing contextName from scopedPdu");
5142
0
        return NULL;
5143
0
    }
5144
5145
0
    SNMP_FREE(pdu->contextName);
5146
0
    pdu->contextName = netsnmp_memdup_nt(tmp_buf, tmp_buf_len,
5147
0
                                         &pdu->contextNameLen);
5148
0
    if (pdu->contextName == NULL) {
5149
0
        ERROR_MSG("error copying contextName from scopedPdu");
5150
0
        return NULL;
5151
0
    }
5152
5153
    /*
5154
     * Get the PDU type 
5155
     */
5156
0
    asn_len = *length;
5157
0
    cp = asn_parse_header(data, &asn_len, &type);
5158
0
    if (cp == NULL)
5159
0
        return NULL;
5160
5161
0
    pdu->command = type;
5162
5163
0
    return data;
5164
0
}
5165
5166
5167
/* ===========================================================================
5168
 *
5169
 * build pdu packet
5170
 */
5171
static int
5172
netsnmp_build_packet(struct snmp_internal_session *isp, netsnmp_session *sp,
5173
                     netsnmp_pdu *pdu, u_char **pktbuf_p,
5174
                     size_t *pktbuf_len_p, u_char **pkt_p, size_t *len_p)
5175
40.3k
{
5176
40.3k
    size_t offset = 0;
5177
40.3k
    int    result;
5178
5179
40.3k
    if (isp && isp->hook_realloc_build) {
5180
40.3k
        result = isp->hook_realloc_build(sp, pdu, pktbuf_p, pktbuf_len_p,
5181
40.3k
                                         &offset);
5182
5183
40.3k
        *pkt_p = *pktbuf_p;
5184
40.3k
        *len_p = offset;
5185
40.3k
    } else if (isp && isp->hook_build) {
5186
0
        *pkt_p = *pktbuf_p;
5187
0
        *len_p = *pktbuf_len_p;
5188
0
        result = isp->hook_build(sp, pdu, *pktbuf_p, len_p);
5189
0
    } else {
5190
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
5191
0
        if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
5192
0
            result = snmp_build(pktbuf_p, pktbuf_len_p, &offset, sp, pdu);
5193
0
            *pkt_p = *pktbuf_p + *pktbuf_len_p - offset;
5194
0
            *len_p = offset;
5195
0
        } else {
5196
0
#endif
5197
0
            *pkt_p = *pktbuf_p;
5198
0
            *len_p = *pktbuf_len_p;
5199
0
            result = snmp_build(pktbuf_p, len_p, &offset, sp, pdu);
5200
0
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
5201
0
        }
5202
0
#endif
5203
0
    }
5204
5205
40.3k
    return result;
5206
40.3k
}
5207
5208
int
5209
_build_initial_pdu_packet(struct session_list *slp, netsnmp_pdu *pdu, int bulk)
5210
75.8k
{
5211
75.8k
    netsnmp_session *session;
5212
75.8k
    struct snmp_internal_session *isp;
5213
75.8k
    netsnmp_transport *transport = NULL;
5214
75.8k
    u_char         *pktbuf = NULL, *packet = NULL;
5215
75.8k
    size_t          pktbuf_len = 0, length = 0, orig_length = 0;
5216
75.8k
    int             result, orig_count = 0, curr_count = 0;
5217
5218
75.8k
    if (slp == NULL) {
5219
0
        return SNMPERR_GENERR;
5220
0
    }
5221
75.8k
    session = slp->session;
5222
5223
75.8k
    isp = slp->internal;
5224
75.8k
    transport = slp->transport;
5225
75.8k
    if (!session || !isp || !transport) {
5226
0
        DEBUGMSGTL(("sess_async_send", "send fail: closing...\n"));
5227
0
        return SNMPERR_GENERR;
5228
0
    }
5229
5230
75.8k
    if (pdu == NULL) {
5231
0
        session->s_snmp_errno = SNMPERR_NULL_PDU;
5232
0
        return SNMPERR_GENERR;
5233
0
    }
5234
5235
75.8k
    SNMP_FREE(isp->obuf); /* should already be NULL */
5236
5237
75.8k
    session->s_snmp_errno = 0;
5238
75.8k
    session->s_errno = 0;
5239
5240
    /*
5241
     * Check/setup the version.  
5242
     */
5243
75.8k
    if (pdu->version == SNMP_DEFAULT_VERSION) {
5244
0
        if (session->version == SNMP_DEFAULT_VERSION) {
5245
0
            session->s_snmp_errno = SNMPERR_BAD_VERSION;
5246
0
            return SNMPERR_GENERR;
5247
0
        }
5248
0
        pdu->version = session->version;
5249
75.8k
    } else if (session->version == SNMP_DEFAULT_VERSION) {
5250
        /*
5251
         * It's OK  
5252
         */
5253
75.8k
    } else if (pdu->version != session->version) {
5254
        /*
5255
         * ENHANCE: we should support multi-lingual sessions  
5256
         */
5257
35.4k
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
5258
35.4k
        return SNMPERR_GENERR;
5259
35.4k
    }
5260
40.3k
    if (NETSNMP_RUNTIME_PROTOCOL_SKIP(pdu->version)) {
5261
0
        DEBUGMSGTL(("sess_async_send", "version disabled at runtime\n"));
5262
0
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
5263
0
        return SNMPERR_GENERR;
5264
0
    }
5265
5266
    /*
5267
     * do we expect a response?
5268
     */
5269
40.3k
    switch (pdu->command) {
5270
5271
0
        case SNMP_MSG_RESPONSE:
5272
0
        case SNMP_MSG_TRAP:
5273
0
        case SNMP_MSG_TRAP2:
5274
0
        case SNMP_MSG_REPORT:
5275
0
        case AGENTX_MSG_CLEANUPSET:
5276
40.3k
        case AGENTX_MSG_RESPONSE:
5277
40.3k
            pdu->flags &= ~UCD_MSG_FLAG_EXPECT_RESPONSE;
5278
40.3k
            break;
5279
            
5280
0
        default:
5281
0
            pdu->flags |= UCD_MSG_FLAG_EXPECT_RESPONSE;
5282
0
            break;
5283
40.3k
    }
5284
5285
    /*
5286
     * Check if we need to perform a v3 engineID probe. Call post probe hook to
5287
     * create user from information in a session even if SNMP_FLAGS_DONT_PROBE
5288
     * is set, as this may indicate that probe was already sent by other means
5289
     * for example asynchronously.
5290
     */
5291
40.3k
    if ((pdu->version == SNMP_VERSION_3) &&
5292
0
        (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE)) {
5293
0
        int rc;
5294
0
        DEBUGMSGTL(("snmpv3_build", "delayed probe for engineID\n"));
5295
0
        rc = snmpv3_engineID_probe(slp, session);
5296
0
        if (rc == 0)
5297
0
            return 0; /* s_snmp_errno already set */
5298
0
    }
5299
5300
    /*
5301
     * determine max packet size
5302
     */
5303
40.3k
    if (pdu->msgMaxSize == 0) {
5304
40.3k
        pdu->msgMaxSize = netsnmp_max_send_msg_size();
5305
40.3k
        if (pdu->msgMaxSize > transport->msgMaxSize)
5306
40.3k
            pdu->msgMaxSize = transport->msgMaxSize;
5307
40.3k
        if (pdu->msgMaxSize > session->sndMsgMaxSize)
5308
0
            pdu->msgMaxSize = session->sndMsgMaxSize;
5309
40.3k
        DEBUGMSGTL(("sess_async_send", "max PDU size: %ld\n",
5310
40.3k
                    pdu->msgMaxSize));
5311
40.3k
    }
5312
40.3k
    netsnmp_assert(pdu->msgMaxSize > 0);
5313
5314
    /*
5315
     * allocate initial packet buffer. Buffer will be grown as needed
5316
     * while building the packet.
5317
     */
5318
40.3k
    pktbuf_len = SNMP_MIN_MAX_LEN;
5319
40.3k
    if ((pktbuf = (u_char *)malloc(pktbuf_len)) == NULL) {
5320
0
        DEBUGMSGTL(("sess_async_send",
5321
0
                    "couldn't malloc initial packet buffer\n"));
5322
0
        session->s_snmp_errno = SNMPERR_MALLOC;
5323
0
        return SNMPERR_MALLOC;
5324
0
    }
5325
5326
#ifdef TEMPORARILY_DISABLED
5327
    /*
5328
     *  NULL variable are allowed in certain PDU types.
5329
     *  In particular, SNMPv3 engineID probes are of this form.
5330
     *  There is an internal PDU flag to indicate that this
5331
     *    is acceptable, but until the construction of engineID
5332
     *    probes can be amended to set this flag, we'll simply
5333
     *    skip this test altogether.
5334
     */
5335
    if (pdu->variables == NULL) {
5336
        switch (pdu->command) {
5337
#ifndef NETSNMP_NO_WRITE_SUPPORT
5338
        case SNMP_MSG_SET:
5339
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
5340
        case SNMP_MSG_GET:
5341
        case SNMP_MSG_GETNEXT:
5342
        case SNMP_MSG_GETBULK:
5343
        case SNMP_MSG_RESPONSE:
5344
        case SNMP_MSG_TRAP2:
5345
        case SNMP_MSG_REPORT:
5346
        case SNMP_MSG_INFORM:
5347
            session->s_snmp_errno = snmp_errno = SNMPERR_NO_VARS;
5348
            return SNMPERR_NO_VARS;
5349
        case SNMP_MSG_TRAP:
5350
            break;
5351
        }
5352
    }
5353
#endif
5354
5355
5356
    /*
5357
     * Build the message to send. If a bulk response is too big, switch to
5358
     * forward encoding and set a flag to drop varbinds to make it fit.
5359
     */
5360
40.3k
    do {
5361
40.3k
        packet = NULL;
5362
40.3k
        length = 0;
5363
40.3k
        result = netsnmp_build_packet(isp, session, pdu, &pktbuf, &pktbuf_len,
5364
40.3k
                                      &packet, &length);
5365
40.3k
        if (0 != result)
5366
0
            break;
5367
5368
40.3k
        if (orig_count) { /* 2nd pass, see how many varbinds remain */
5369
0
            curr_count = count_varbinds(pdu->variables);
5370
0
            DEBUGMSGTL(("sess_async_send", " vb count: %d -> %d\n", orig_count,
5371
0
                        curr_count));
5372
0
            DEBUGMSGTL(("sess_async_send", " pdu_len: %" NETSNMP_PRIz "d -> %" NETSNMP_PRIz "d (max %ld)\n",
5373
0
                        orig_length, length, pdu->msgMaxSize));
5374
0
        }
5375
5376
        /** if length is less than max size, we're done (success). */
5377
40.3k
        if (length <= pdu->msgMaxSize)
5378
40.3k
            break;
5379
5380
29
        DEBUGMSGTL(("sess_async_send", "length %" NETSNMP_PRIz "d exceeds maximum %ld\n",
5381
29
                    length, pdu->msgMaxSize));
5382
5383
        /** packet too big. if this is not a bulk request, we're done (err). */
5384
29
        if (!bulk) {
5385
29
           session->s_snmp_errno = SNMPERR_TOO_LONG;
5386
29
           break;
5387
29
        }
5388
5389
        /** rebuild bulk response with truncation and fixed size */
5390
0
        pdu->flags |= UCD_MSG_FLAG_FORWARD_ENCODE | UCD_MSG_FLAG_BULK_TOOBIG;
5391
0
        pktbuf_len = pdu->msgMaxSize;
5392
5393
        /** save original number of varbinds & length */
5394
0
        if (0 == orig_count) {
5395
0
            curr_count = orig_count = count_varbinds(pdu->variables);
5396
0
            orig_length = length;
5397
0
        }
5398
5399
0
    } while(1);
5400
5401
40.3k
    DEBUGMSGTL(("sess_async_send",
5402
40.3k
                "final pktbuf_len after building packet %" NETSNMP_PRIz "u\n",
5403
40.3k
                pktbuf_len));
5404
40.3k
    if (curr_count != orig_count)
5405
0
        DEBUGMSGTL(("sess_async_send",
5406
40.3k
                    "sending %d of %d varbinds (-%d) from bulk response\n",
5407
40.3k
                    curr_count, orig_count, orig_count - curr_count));
5408
5409
40.3k
    if (length > pdu->msgMaxSize) {
5410
29
        DEBUGMSGTL(("sess_async_send",
5411
29
                    "length of packet (%" NETSNMP_PRIz "u) exceeded pdu maximum (%lu)\n",
5412
29
                    length, pdu->msgMaxSize));
5413
29
        netsnmp_assert(SNMPERR_TOO_LONG == session->s_snmp_errno);
5414
29
    }
5415
5416
40.3k
    if ((SNMPERR_TOO_LONG == session->s_snmp_errno) || (result < 0)) {
5417
29
        DEBUGMSGTL(("sess_async_send", "encoding failure\n"));
5418
29
        SNMP_FREE(pktbuf);
5419
29
        return SNMPERR_GENERR;
5420
29
    }
5421
5422
40.3k
    isp->obuf = pktbuf;
5423
40.3k
    isp->obuf_size = pktbuf_len;
5424
40.3k
    isp->opacket = packet;
5425
40.3k
    isp->opacket_len = length;
5426
5427
40.3k
    return SNMPERR_SUCCESS;
5428
40.3k
}
5429
5430
/*
5431
 * These functions send PDUs using an active session:
5432
 * snmp_send             - traditional API, no callback
5433
 * snmp_async_send       - traditional API, with callback
5434
 * snmp_sess_send        - single session API, no callback
5435
 * snmp_sess_async_send  - single session API, with callback
5436
 *
5437
 * Call snmp_build to create a serialized packet (the pdu).
5438
 * If necessary, set some of the pdu data from the
5439
 * session defaults.
5440
 * If there is an expected response for this PDU,
5441
 * queue a corresponding request on the list
5442
 * of outstanding requests for this session,
5443
 * and store the callback vectors in the request.
5444
 *
5445
 * Send the pdu to the target identified by this session.
5446
 * Return on success:
5447
 *   The request id of the pdu is returned, and the pdu is freed.
5448
 * Return on failure:
5449
 *   Zero (0) is returned.
5450
 *   The caller must call snmp_free_pdu if 0 is returned.
5451
 */
5452
int
5453
snmp_send(netsnmp_session * session, netsnmp_pdu *pdu)
5454
75.8k
{
5455
75.8k
    return snmp_async_send(session, pdu, NULL, NULL);
5456
75.8k
}
5457
5458
int
5459
snmp_sess_send(struct session_list *slp, netsnmp_pdu *pdu)
5460
0
{
5461
0
    return snmp_sess_async_send(slp, pdu, NULL, NULL);
5462
0
}
5463
5464
int
5465
snmp_async_send(netsnmp_session * session,
5466
                netsnmp_pdu *pdu, snmp_callback callback, void *cb_data)
5467
75.8k
{
5468
75.8k
    struct session_list *sessp = snmp_sess_pointer(session);
5469
75.8k
    return snmp_sess_async_send(sessp, pdu, callback, cb_data);
5470
75.8k
}
5471
5472
int
5473
snmp_async_send_cp(netsnmp_session * session, netsnmp_pdu *pdu,
5474
                   snmp_callback callback, void *cb_data, int cp_inc)
5475
0
{
5476
0
    void           *sessp = snmp_sess_pointer(session);
5477
0
    return snmp_sess_async_send_cp(sessp, pdu, callback, cb_data, cp_inc);
5478
0
}
5479
5480
/**
5481
 * Send a PDU asynchronously.
5482
 *
5483
 * @param[in] slp      Session pointer.
5484
 * @param[in] pdu      PDU to send.
5485
 * @param[in] callback Callback function called after processing of the PDU
5486
 *                     finished. This function is called if the PDU has not
5487
 *                     been sent or after a response has been received. Must
5488
 *                     not free @pdu.
5489
 * @param[in] cb_data  Will be passed as fifth argument to @callback.
5490
 *
5491
 * @return If successful, returns the request id of @pdu and frees @pdu.
5492
 * If not successful, returns zero and expects the caller to free @pdu.
5493
 */
5494
static int
5495
_sess_async_send(struct session_list *slp,
5496
                 netsnmp_pdu *pdu, snmp_callback callback, void *cb_data,
5497
                 int cp_inc)
5498
75.8k
{
5499
75.8k
    netsnmp_session *session;
5500
75.8k
    struct snmp_internal_session *isp;
5501
75.8k
    netsnmp_transport *transport = NULL;
5502
75.8k
    int             result;
5503
75.8k
    long            reqid;
5504
5505
75.8k
    if (slp == NULL || NULL == slp->session || NULL ==slp->internal ||
5506
75.8k
                NULL == slp->transport) {
5507
0
        return 0;
5508
0
    }
5509
5510
75.8k
    session = slp->session;
5511
75.8k
    isp = slp->internal;
5512
75.8k
    transport = slp->transport;
5513
5514
75.8k
    if (NULL == isp->opacket) {
5515
75.8k
        result = _build_initial_pdu_packet(slp, pdu, 0);
5516
75.8k
        if ((SNMPERR_SUCCESS != result) || (NULL == isp->opacket)) {
5517
35.4k
            if (callback) {
5518
0
                switch (session->s_snmp_errno) {
5519
                    /*
5520
                     * some of these probably don't make sense here, but
5521
                     * it's a rough first cut.
5522
                     */
5523
0
                    case SNMPERR_BAD_ENG_ID:
5524
0
                    case SNMPERR_BAD_SEC_LEVEL:
5525
0
                    case SNMPERR_UNKNOWN_SEC_MODEL:
5526
0
                    case SNMPERR_UNKNOWN_ENG_ID:
5527
0
                    case SNMPERR_UNKNOWN_USER_NAME:
5528
0
                    case SNMPERR_UNSUPPORTED_SEC_LEVEL:
5529
0
                    case SNMPERR_AUTHENTICATION_FAILURE:
5530
0
                    case SNMPERR_NOT_IN_TIME_WINDOW:
5531
0
                    case SNMPERR_USM_GENERICERROR:
5532
0
                    case SNMPERR_USM_UNKNOWNSECURITYNAME:
5533
0
                    case SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL:
5534
0
                    case SNMPERR_USM_ENCRYPTIONERROR:
5535
0
                    case SNMPERR_USM_AUTHENTICATIONFAILURE:
5536
0
                    case SNMPERR_USM_PARSEERROR:
5537
0
                    case SNMPERR_USM_UNKNOWNENGINEID:
5538
0
                    case SNMPERR_USM_NOTINTIMEWINDOW:
5539
0
                        callback(NETSNMP_CALLBACK_OP_SEC_ERROR, session,
5540
0
                                 pdu->reqid, pdu, cb_data);
5541
0
                        break;
5542
0
                    case SNMPERR_TIMEOUT: /* engineID probe timed out */
5543
0
                        callback(NETSNMP_CALLBACK_OP_TIMED_OUT, session,
5544
0
                                 pdu->reqid, pdu, cb_data);
5545
0
                        break;
5546
0
                    default:
5547
0
                        callback(NETSNMP_CALLBACK_OP_SEND_FAILED, session,
5548
0
                                 pdu->reqid, pdu, cb_data);
5549
0
                        break;
5550
0
                }
5551
0
            }
5552
            /** no packet to send?? */
5553
35.4k
            return 0;
5554
35.4k
        }
5555
75.8k
    }
5556
5557
    /*
5558
     * Send the message.  
5559
     */
5560
5561
40.3k
    DEBUGMSGTL(("sess_process_packet", "sending message id#%ld reqid#%ld len %"
5562
40.3k
                NETSNMP_PRIz "u\n", pdu->msgid, pdu->reqid, isp->opacket_len));
5563
40.3k
    result = netsnmp_transport_send(transport, isp->opacket, isp->opacket_len,
5564
40.3k
                                    &(pdu->transport_data),
5565
40.3k
                                    &(pdu->transport_data_length));
5566
5567
40.3k
    SNMP_FREE(isp->obuf);
5568
40.3k
    isp->opacket = NULL; /* opacket was in obuf, so no free needed */
5569
40.3k
    isp->opacket_len = 0;
5570
5571
40.3k
    if (result < 0) {
5572
0
        session->s_snmp_errno = SNMPERR_BAD_SENDTO;
5573
0
        session->s_errno = errno;
5574
0
        if (callback)
5575
0
            callback(NETSNMP_CALLBACK_OP_SEND_FAILED, session,
5576
0
                     pdu->reqid, pdu, cb_data);
5577
0
        return 0;
5578
0
    }
5579
5580
40.3k
    reqid = pdu->reqid;
5581
5582
    /*
5583
     * Bug 2387: 0 is a valid request id, so since reqid is used as a return
5584
     * code with 0 meaning an error, set reqid to 1 if there is no error. This
5585
     * does not affect the request id in the packet and fixes a memory leak
5586
     * for incoming PDUs with a request id of 0. This could cause some
5587
     * confusion if the caller is expecting the request id to match the
5588
     * return code, as the documentation states it will. Most example code
5589
     * just checks for non-zero, so hopefully this wont be an issue.
5590
     */
5591
40.3k
    if (0 == reqid && (SNMPERR_SUCCESS == session->s_snmp_errno))
5592
7.70k
        ++reqid;
5593
5594
    /*
5595
     * Add to pending requests list if we expect a response.  
5596
     */
5597
40.3k
    if (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE) {
5598
0
        netsnmp_request_list *rp;
5599
0
        struct timeval  tv;
5600
5601
0
        rp = calloc(1, sizeof(netsnmp_request_list));
5602
0
        if (rp == NULL) {
5603
0
            session->s_snmp_errno = SNMPERR_GENERR;
5604
0
            return 0;
5605
0
        }
5606
5607
0
        netsnmp_get_monotonic_clock(&tv);
5608
0
        rp->pdu = pdu;
5609
0
        rp->request_id = pdu->reqid;
5610
0
        rp->message_id = pdu->msgid;
5611
0
        rp->callback = callback;
5612
0
        if (cp_inc && cb_data) {
5613
0
            netsnmp_refcnt_void *aux_cb_data = (netsnmp_refcnt_void*) cb_data;
5614
0
            aux_cb_data->refcnt++;
5615
0
            rp->cb_data_refcounted = 1;
5616
0
  }
5617
0
        rp->cb_data = cb_data;
5618
0
        rp->retries = 0;
5619
0
        if (pdu->flags & UCD_MSG_FLAG_PDU_TIMEOUT) {
5620
0
            rp->timeout = pdu->time * 1000000L;
5621
0
        } else {
5622
0
            rp->timeout = session->timeout;
5623
0
        }
5624
0
        rp->timeM = tv;
5625
0
        tv.tv_usec += rp->timeout;
5626
0
        tv.tv_sec += tv.tv_usec / 1000000L;
5627
0
        tv.tv_usec %= 1000000L;
5628
0
        rp->expireM = tv;
5629
5630
        /*
5631
         * XX lock should be per session ! 
5632
         */
5633
0
        snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
5634
0
        if (isp->requestsEnd) {
5635
0
            rp->next_request = isp->requestsEnd->next_request;
5636
0
            isp->requestsEnd->next_request = rp;
5637
0
            isp->requestsEnd = rp;
5638
0
        } else {
5639
0
            rp->next_request = isp->requests;
5640
0
            isp->requests = rp;
5641
0
            isp->requestsEnd = rp;
5642
0
        }
5643
0
        snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
5644
40.3k
    } else {
5645
        /*
5646
         * No response expected...  
5647
         */
5648
40.3k
        if (reqid) {
5649
            /*
5650
             * Free v1 or v2 TRAP PDU iff no error  
5651
             */
5652
40.3k
            snmp_free_pdu(pdu);
5653
40.3k
        }
5654
40.3k
    }
5655
5656
40.3k
    return reqid;
5657
40.3k
}
5658
5659
/**
5660
 * Send a PDU asynchronously.
5661
 *
5662
 * @param[in] sessp    Session pointer.
5663
 * @param[in] pdu      PDU to send.
5664
 * @param[in] callback Callback function called after processing of the PDU
5665
 *                     finished. This function is called if the PDU has not
5666
 *                     been sent or after a response has been received. Must
5667
 *                     not free @p pdu.
5668
 * @param[in] cb_data  Will be passed as fifth argument to @p callback.
5669
 *
5670
 * @return If successful, returns the request id of @p pdu and frees @p pdu.
5671
 * If not successful, returns zero and expects the caller to free @p pdu.
5672
 */
5673
int
5674
snmp_sess_async_send(struct session_list *slp,
5675
                     netsnmp_pdu *pdu,
5676
                     snmp_callback callback, void *cb_data)
5677
75.8k
{
5678
5679
75.8k
    return snmp_sess_async_send_cp(slp, pdu, callback, cb_data, 0);
5680
75.8k
}
5681
5682
int
5683
snmp_sess_async_send_cp(struct session_list *slp, netsnmp_pdu *pdu,
5684
                        snmp_callback callback, void *cb_data,
5685
                        int cp_inc)
5686
75.8k
{
5687
75.8k
    int             rc;
5688
5689
75.8k
    if (slp == NULL) {
5690
0
        snmp_errno = SNMPERR_BAD_SESSION;       /*MTCRITICAL_RESOURCE */
5691
0
        return (0);
5692
0
    }
5693
    /*
5694
     * send pdu
5695
     */
5696
5697
75.8k
    rc = _sess_async_send(slp, pdu, callback, cb_data, cp_inc);
5698
75.8k
    if (rc == 0)
5699
35.4k
        SET_SNMP_ERROR(slp->session->s_snmp_errno);
5700
75.8k
    return rc;
5701
75.8k
}
5702
5703
5704
/*
5705
 * Frees the variable and any malloc'd data associated with it.
5706
 */
5707
void
5708
snmp_free_var_internals(netsnmp_variable_list * var)
5709
577k
{
5710
577k
    if (!var)
5711
0
        return;
5712
5713
577k
    if (var->name != var->name_loc)
5714
0
        SNMP_FREE(var->name);
5715
577k
    if (var->val.string != var->buf)
5716
10.0k
        SNMP_FREE(var->val.string);
5717
577k
    if (var->data) {
5718
0
        if (var->dataFreeHook) {
5719
0
            var->dataFreeHook(var->data);
5720
0
            var->data = NULL;
5721
0
        } else {
5722
0
            SNMP_FREE(var->data);
5723
0
        }
5724
0
    }
5725
577k
}
5726
5727
void
5728
snmp_free_var(netsnmp_variable_list * var)
5729
577k
{
5730
577k
    snmp_free_var_internals(var);
5731
577k
    free(var);
5732
577k
}
5733
5734
void
5735
snmp_free_varbind(netsnmp_variable_list * var)
5736
557k
{
5737
557k
    netsnmp_variable_list *ptr;
5738
1.13M
    while (var) {
5739
577k
        ptr = var->next_variable;
5740
577k
        snmp_free_var(var);
5741
577k
        var = ptr;
5742
577k
    }
5743
557k
}
5744
5745
/*
5746
 * Frees the pdu and any malloc'd data associated with it.
5747
 */
5748
void
5749
snmp_free_pdu(netsnmp_pdu *pdu)
5750
557k
{
5751
557k
    struct snmp_secmod_def *sptr;
5752
5753
557k
    if (!pdu)
5754
0
        return;
5755
5756
557k
    free_securityStateRef(pdu);
5757
5758
557k
    sptr = find_sec_mod(pdu->securityModel);
5759
557k
    if (sptr && sptr->pdu_free)
5760
0
        (*sptr->pdu_free)(pdu);
5761
5762
557k
    snmp_free_varbind(pdu->variables);
5763
557k
    free(pdu->enterprise);
5764
557k
    free(pdu->community);
5765
557k
    free(pdu->contextEngineID);
5766
557k
    free(pdu->securityEngineID);
5767
557k
    free(pdu->contextName);
5768
557k
    free(pdu->securityName);
5769
557k
    free(pdu->transport_data);
5770
557k
    free(pdu);
5771
557k
}
5772
5773
netsnmp_pdu    *
5774
snmp_create_sess_pdu(netsnmp_transport *transport, void *opaque,
5775
                     size_t olength)
5776
0
{
5777
0
    netsnmp_pdu *pdu = calloc(1, sizeof(netsnmp_pdu));
5778
0
    if (pdu == NULL) {
5779
0
        DEBUGMSGTL(("sess_process_packet", "can't malloc space for PDU\n"));
5780
0
        return NULL;
5781
0
    }
5782
5783
    /*
5784
     * Save the transport-level data specific to this reception (e.g. UDP
5785
     * source address).  
5786
     */
5787
5788
0
    pdu->transport_data = opaque;
5789
0
    pdu->transport_data_length = olength;
5790
0
    pdu->tDomain = transport->domain;
5791
0
    pdu->tDomainLen = transport->domain_length;
5792
0
    return pdu;
5793
0
}
5794
5795
5796
/*
5797
 * This function parses a packet into a PDU
5798
 */
5799
static netsnmp_pdu *
5800
_sess_process_packet_parse_pdu(struct session_list *slp, netsnmp_session * sp,
5801
                               struct snmp_internal_session *isp,
5802
                               netsnmp_transport *transport,
5803
                               void *opaque, int olength,
5804
                               u_char * packetptr, int length)
5805
0
{
5806
0
  netsnmp_pdu    *pdu;
5807
0
  int             ret = 0;
5808
0
  int             dump = 0, filter = 0;
5809
5810
0
  debug_indent_reset();
5811
5812
0
  DEBUGMSGTL(("sess_process_packet",
5813
0
        "session %p fd %" NETSNMP_FMT_SKT " pkt %p length %d\n", slp,
5814
0
        transport->sock, packetptr, length));
5815
5816
0
  dump = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
5817
0
                                NETSNMP_DS_LIB_DUMP_PACKET);
5818
0
#ifndef NETSNMP_FEATURE_REMOVE_FILTER_SOURCE
5819
0
  filter = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
5820
0
                                  NETSNMP_DS_LIB_FILTER_TYPE);
5821
0
#endif
5822
0
  if (dump || filter) {
5823
0
      int filtered = 0;
5824
0
      char *addrtxt = netsnmp_transport_peer_string(transport, opaque, olength);
5825
5826
0
      if (!addrtxt) {
5827
0
          DEBUGMSGTL(("sess_process_packet",
5828
0
                      "Failed to resolve peer address\n"));
5829
0
          SNMP_FREE(opaque);
5830
0
          return NULL;
5831
0
      }
5832
5833
0
      snmp_log(LOG_DEBUG, "\nReceived %d byte packet from %s\n",
5834
0
               length, addrtxt);
5835
5836
0
      if (dump)
5837
0
          xdump(packetptr, length, "");
5838
5839
0
#ifndef NETSNMP_FEATURE_REMOVE_FILTER_SOURCE
5840
0
      if (filter) {
5841
0
          char *sourceaddr = NULL, *c = strchr(addrtxt, '[');
5842
0
          const char *dropstr = NULL;
5843
0
          if (c) {
5844
0
              sourceaddr = ++c;
5845
0
              c = strchr(sourceaddr, ']');
5846
0
              if (c)
5847
0
                  *c = 0;
5848
0
              filtered = netsnmp_transport_filter_check(sourceaddr);
5849
0
          }
5850
0
          else if (!strncmp(addrtxt, "callback", 8)) {
5851
              /* do not filter internal request */
5852
0
              DEBUGMSGTL(("sess_process_packet:filter",
5853
0
                          "bypass packet from %s \n",
5854
0
                          addrtxt));
5855
0
              filtered = 1;
5856
0
          }
5857
0
          if ((filter == -1) && filtered)
5858
0
              dropstr = "matched blacklist";
5859
0
          else if ((filter == 1) && !filtered)
5860
0
              dropstr = "didn't match whitelist";
5861
0
          if (dropstr) {
5862
0
              DEBUGMSGTL(("sess_process_packet:filter",
5863
0
                          "packet from %s %s\n",
5864
0
                          sourceaddr ? sourceaddr : "UNKNOWN", dropstr));
5865
0
              SNMP_FREE(opaque);
5866
0
              SNMP_FREE(addrtxt);
5867
0
              return NULL;
5868
0
          }
5869
0
      }
5870
0
#endif
5871
5872
0
      SNMP_FREE(addrtxt);
5873
0
  }
5874
5875
  /*
5876
   * Do transport-level filtering (e.g. IP-address based allow/deny).  
5877
   */
5878
5879
0
  if (isp->hook_pre) {
5880
0
    if (isp->hook_pre(sp, transport, opaque, olength) == 0) {
5881
0
      DEBUGMSGTL(("sess_process_packet", "pre-parse fail\n"));
5882
0
      SNMP_FREE(opaque);
5883
0
      return NULL;
5884
0
    }
5885
0
  }
5886
5887
0
  if (isp->hook_create_pdu) {
5888
0
    pdu = isp->hook_create_pdu(transport, opaque, olength);
5889
0
  } else {
5890
0
    pdu = snmp_create_sess_pdu(transport, opaque, olength);
5891
0
  }
5892
5893
0
  if (pdu == NULL) {
5894
0
    snmp_log(LOG_ERR, "pdu failed to be created\n");
5895
0
    SNMP_FREE(opaque);
5896
0
    return NULL;
5897
0
  }
5898
5899
  /* if the transport was a magic tunnel, mark the PDU as having come
5900
     through one. */
5901
0
  if (transport->flags & NETSNMP_TRANSPORT_FLAG_TUNNELED) {
5902
0
      pdu->flags |= UCD_MSG_FLAG_TUNNELED;
5903
0
  }
5904
5905
0
  if (isp->hook_parse) {
5906
0
    ret = isp->hook_parse(sp, pdu, packetptr, length);
5907
0
  } else {
5908
0
    ret = snmp_parse(slp, sp, pdu, packetptr, length);
5909
0
  }
5910
5911
0
  DEBUGMSGTL(("sess_process_packet", "received message id#%ld reqid#%ld len "
5912
0
              "%u\n", pdu->msgid, pdu->reqid, length));
5913
5914
0
  if (ret != SNMP_ERR_NOERROR) {
5915
0
    DEBUGMSGTL(("sess_process_packet", "parse fail\n"));
5916
0
  }
5917
5918
0
  if (isp->hook_post) {
5919
0
    if (isp->hook_post(sp, pdu, ret) == 0) {
5920
0
      DEBUGMSGTL(("sess_process_packet", "post-parse fail\n"));
5921
0
      ret = SNMPERR_ASN_PARSE_ERR;
5922
0
    }
5923
0
  }
5924
5925
0
  if (ret != SNMP_ERR_NOERROR) {
5926
0
    snmp_free_pdu(pdu);
5927
0
    return NULL;
5928
0
  }
5929
5930
0
  return pdu;
5931
0
}
5932
5933
static int
5934
snmp_resend_request(struct session_list *slp, netsnmp_request_list *orp,
5935
                    netsnmp_request_list *rp, int incr_retries)
5936
0
{
5937
0
    struct snmp_internal_session *isp;
5938
0
    netsnmp_session *sp;
5939
0
    netsnmp_transport *transport;
5940
0
    u_char         *pktbuf = NULL, *packet = NULL;
5941
0
    size_t          pktbuf_len = 0, length = 0;
5942
0
    struct timeval  tv, now;
5943
0
    int             result = 0;
5944
5945
0
    sp = slp->session;
5946
0
    isp = slp->internal;
5947
0
    transport = slp->transport;
5948
0
    if (!sp || !isp || !transport) {
5949
0
        DEBUGMSGTL(("sess_read", "resend fail: closing...\n"));
5950
0
        return 0;
5951
0
    }
5952
5953
0
    if ((pktbuf = (u_char *)malloc(2048)) == NULL) {
5954
0
        DEBUGMSGTL(("sess_resend",
5955
0
                    "couldn't malloc initial packet buffer\n"));
5956
0
        return 0;
5957
0
    } else {
5958
0
        pktbuf_len = 2048;
5959
0
    }
5960
5961
0
    if (incr_retries) {
5962
0
        rp->retries++;
5963
0
    }
5964
5965
    /*
5966
     * Always increment msgId for resent messages.  
5967
     */
5968
0
    rp->pdu->msgid = rp->message_id = snmp_get_next_msgid();
5969
5970
0
    result = netsnmp_build_packet(isp, sp, rp->pdu, &pktbuf, &pktbuf_len,
5971
0
                                  &packet, &length);
5972
0
    if (result < 0) {
5973
        /*
5974
         * This should never happen.  
5975
         */
5976
0
        DEBUGMSGTL(("sess_resend", "encoding failure\n"));
5977
0
        SNMP_FREE(pktbuf);
5978
0
        return -1;
5979
0
    }
5980
5981
0
    DEBUGMSGTL(("sess_process_packet", "resending message id#%ld reqid#%ld "
5982
0
                "rp_reqid#%ld rp_msgid#%ld len %" NETSNMP_PRIz "u\n",
5983
0
                rp->pdu->msgid, rp->pdu->reqid, rp->request_id, rp->message_id, length));
5984
0
    result = netsnmp_transport_send(transport, packet, length,
5985
0
                                    &(rp->pdu->transport_data),
5986
0
                                    &(rp->pdu->transport_data_length));
5987
5988
    /*
5989
     * We are finished with the local packet buffer, if we allocated one (due
5990
     * to there being no saved packet).  
5991
     */
5992
5993
0
    if (pktbuf != NULL) {
5994
0
        SNMP_FREE(pktbuf);
5995
0
        packet = NULL;
5996
0
    }
5997
5998
0
    if (result < 0) {
5999
0
        sp->s_snmp_errno = SNMPERR_BAD_SENDTO;
6000
0
        sp->s_errno = errno;
6001
0
        snmp_set_detail(strerror(errno));
6002
0
        if (rp->callback) {
6003
0
            rp->callback(NETSNMP_CALLBACK_OP_SEND_FAILED, sp,
6004
0
                         rp->pdu->reqid, rp->pdu, rp->cb_data);
6005
0
            remove_request(isp, orp, rp);
6006
0
            free(rp);
6007
0
  }
6008
0
        return -1;
6009
0
    } else {
6010
0
        netsnmp_get_monotonic_clock(&now);
6011
0
        tv = now;
6012
0
        rp->timeM = tv;
6013
0
        tv.tv_usec += rp->timeout;
6014
0
        tv.tv_sec += tv.tv_usec / 1000000L;
6015
0
        tv.tv_usec %= 1000000L;
6016
0
        rp->expireM = tv;
6017
0
        if (rp->callback)
6018
0
            rp->callback(NETSNMP_CALLBACK_OP_RESEND, sp,
6019
0
                         rp->pdu->reqid, rp->pdu, rp->cb_data);
6020
0
    }
6021
0
    return 0;
6022
0
}
6023
6024
/*
6025
 * This function processes a PDU and calls the relevant callbacks.
6026
 */
6027
static int
6028
_sess_process_packet_handle_pdu(struct session_list *slp, netsnmp_session * sp,
6029
                                struct snmp_internal_session *isp,
6030
                                netsnmp_transport *transport, netsnmp_pdu *pdu)
6031
0
{
6032
0
  netsnmp_request_list *rp, *orp = NULL;
6033
0
  int             handled = 0;
6034
6035
0
  if (pdu->flags & UCD_MSG_FLAG_RESPONSE_PDU) {
6036
    /*
6037
     * Call USM to free any securityStateRef supplied with the message.  
6038
     */
6039
0
    free_securityStateRef(pdu);
6040
6041
0
    for (rp = isp->requests; rp; orp = rp, rp = rp->next_request) {
6042
0
      snmp_callback   callback;
6043
0
      void           *magic;
6044
6045
0
      if (pdu->version == SNMP_VERSION_3) {
6046
  /*
6047
   * msgId must match for v3 messages.  
6048
   */
6049
0
  if (rp->message_id != pdu->msgid) {
6050
0
            DEBUGMSGTL(("sess_process_packet", "unmatched msg id: %ld != %ld\n",
6051
0
                        rp->message_id, pdu->msgid));
6052
0
      continue;
6053
0
  }
6054
6055
  /*
6056
   * Check that message fields match original, if not, no further
6057
   * processing.  
6058
   */
6059
0
  if (!snmpv3_verify_msg(rp, pdu)) {
6060
0
    break;
6061
0
  }
6062
0
      } else {
6063
0
  if (rp->request_id != pdu->reqid) {
6064
0
    continue;
6065
0
  }
6066
0
      }
6067
6068
0
      if (rp->callback) {
6069
0
  callback = rp->callback;
6070
0
  magic = rp->cb_data;
6071
0
      } else {
6072
0
  callback = sp->callback;
6073
0
  magic = sp->callback_magic;
6074
0
      }
6075
0
      handled = 1;
6076
6077
      /*
6078
       * MTR snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);  ?* XX lock
6079
       * should be per session ! 
6080
       */
6081
6082
0
      if (pdu->command == SNMP_MSG_REPORT) {
6083
0
        if (sp->s_snmp_errno == SNMPERR_NOT_IN_TIME_WINDOW ||
6084
0
            snmpv3_get_report_type(pdu) == SNMPERR_NOT_IN_TIME_WINDOW) {
6085
          /*
6086
           * trigger immediate retry on recoverable Reports 
6087
           * * (notInTimeWindow), incr_retries == TRUE to prevent
6088
           * * inifinite resend                      
6089
           */
6090
0
          if (rp->retries <= sp->retries) {
6091
0
            snmp_resend_request(slp, orp, rp, TRUE);
6092
0
            break;
6093
0
          } else {
6094
            /* We're done with retries, so no longer waiting for a response */
6095
0
            if (callback) {
6096
0
              callback(NETSNMP_CALLBACK_OP_SEC_ERROR, sp, pdu->reqid, pdu,
6097
0
                       magic);
6098
0
            }
6099
0
          }
6100
0
        } else {
6101
0
          if (SNMPV3_IGNORE_UNAUTH_REPORTS) {
6102
0
            break;
6103
0
          } else { /* We're done with retries */
6104
0
            if (callback) {
6105
0
              callback(NETSNMP_CALLBACK_OP_SEC_ERROR, sp, pdu->reqid, pdu,
6106
0
                       magic);
6107
0
            }
6108
0
          }
6109
0
        }
6110
6111
        /*
6112
         * Handle engineID discovery.  
6113
         */
6114
0
        if (!sp->securityEngineIDLen && pdu->securityEngineIDLen) {
6115
0
          sp->securityEngineID = malloc(pdu->securityEngineIDLen);
6116
0
          if (sp->securityEngineID == NULL) {
6117
            /*
6118
             * TODO FIX: recover after message callback *?
6119
             */
6120
0
            snmp_log(LOG_ERR, "malloc failed handling pdu\n");
6121
0
            snmp_free_pdu(pdu);
6122
0
            return -1;
6123
0
          }
6124
0
          memcpy(sp->securityEngineID, pdu->securityEngineID,
6125
0
                 pdu->securityEngineIDLen);
6126
0
          sp->securityEngineIDLen = pdu->securityEngineIDLen;
6127
0
          if (!sp->contextEngineIDLen) {
6128
0
            sp->contextEngineID = malloc(pdu->securityEngineIDLen);
6129
0
            if (sp->contextEngineID == NULL) {
6130
              /*
6131
               * TODO FIX: recover after message callback *?
6132
               */
6133
0
              snmp_log(LOG_ERR, "malloc failed handling pdu\n");
6134
0
              snmp_free_pdu(pdu);
6135
0
              return -1;
6136
0
            }
6137
0
            memcpy(sp->contextEngineID, pdu->securityEngineID,
6138
0
                   pdu->securityEngineIDLen);
6139
0
            sp->contextEngineIDLen = pdu->securityEngineIDLen;
6140
0
          }
6141
0
        }
6142
0
      }
6143
6144
0
      if (callback == NULL
6145
0
    || callback(NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE, sp,
6146
0
          pdu->reqid, pdu, magic) == 1) {
6147
  /*
6148
   * Successful, so delete request.  
6149
   */
6150
0
  remove_request(isp, orp, rp);
6151
0
  free(rp);
6152
  /*
6153
   * There shouldn't be any more requests with the same reqid.  
6154
   */
6155
0
  break;
6156
0
      }
6157
      /*
6158
       * MTR snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);  ?* XX lock should be per session ! 
6159
       */
6160
0
    }
6161
0
  } else {
6162
0
    if (sp->callback) {
6163
      /*
6164
       * MTR snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION); 
6165
       */
6166
0
      handled = 1;
6167
0
      sp->callback(NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE,
6168
0
       sp, pdu->reqid, pdu, sp->callback_magic);
6169
      /*
6170
       * MTR snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION); 
6171
       */
6172
0
    }
6173
0
  }
6174
6175
0
  if (!handled) {
6176
0
    if (sp->flags & SNMP_FLAGS_SHARED_SOCKET)
6177
0
      return -2;
6178
0
    snmp_increment_statistic(STAT_SNMPUNKNOWNPDUHANDLERS);
6179
0
    DEBUGMSGTL(("sess_process_packet", "unhandled PDU\n"));
6180
0
  }
6181
6182
0
  snmp_free_pdu(pdu);
6183
0
  return 0;
6184
0
}
6185
6186
/*
6187
 * This function processes a complete (according to asn_check_packet or the
6188
 * AgentX equivalent) packet, parsing it into a PDU and calling the relevant
6189
 * callbacks.  On entry, packetptr points at the packet in the session's
6190
 * buffer and length is the length of the packet.  Return codes:
6191
 *   0: pdu handled (pdu deleted)
6192
 *  -1: parse error (pdu deleted)
6193
 *  -2: pdu not found for shared session (pdu NOT deleted)
6194
 */
6195
static int
6196
_sess_process_packet(struct session_list *slp, netsnmp_session * sp,
6197
                     struct snmp_internal_session *isp,
6198
                     netsnmp_transport *transport,
6199
                     void *opaque, int olength,
6200
                     u_char * packetptr, int length)
6201
0
{
6202
0
    netsnmp_pdu         *pdu;
6203
0
    int                  rc;
6204
6205
0
    pdu = _sess_process_packet_parse_pdu(slp, sp, isp, transport, opaque,
6206
0
                                         olength, packetptr, length);
6207
0
    if (NULL == pdu)
6208
0
        return -1;
6209
6210
    /*
6211
     * find session to process pdu. usually that will be the current session,
6212
     * but with the introduction of shared transports, another session may
6213
     * have the same socket.
6214
     */
6215
0
    do {
6216
0
        rc = _sess_process_packet_handle_pdu(slp, sp, isp, transport, pdu);
6217
0
        if (-2 != rc || !(transport->flags & NETSNMP_TRANSPORT_FLAG_SHARED))
6218
0
            break;
6219
6220
        /** -2 means pdu not in request list. check other sessions */
6221
0
        do  {
6222
0
            slp = slp->next;
6223
0
        } while (slp && slp->transport->sock != transport->sock);
6224
0
        if (!slp)
6225
0
            break; /* no more sessions with same socket */
6226
6227
0
        sp = slp->session;
6228
0
        isp = slp->internal;
6229
0
        transport = slp->transport;
6230
0
    } while(slp);
6231
6232
0
    if (-2 == rc) { /* did not find session for pdu */
6233
0
        snmp_increment_statistic(STAT_SNMPUNKNOWNPDUHANDLERS);
6234
0
        DEBUGMSGTL(("sess_process_packet", "unhandled PDU\n"));
6235
0
        snmp_free_pdu(pdu);
6236
0
    }
6237
6238
0
  return rc;
6239
0
}
6240
6241
static void
6242
_sess_set_packet_deadline(struct snmp_internal_session *isp)
6243
0
{
6244
0
    netsnmp_get_monotonic_clock(&isp->packet_deadline);
6245
0
    isp->packet_deadline.tv_sec += NETSNMP_STREAM_FRAME_TIMEOUT;
6246
0
}
6247
6248
static int
6249
_sess_packet_deadline_expired(struct snmp_internal_session *isp)
6250
0
{
6251
0
    struct timeval now;
6252
6253
0
    if (isp == NULL || !timerisset(&isp->packet_deadline))
6254
0
        return 0;
6255
0
    netsnmp_get_monotonic_clock(&now);
6256
0
    return !timercmp(&now, &isp->packet_deadline, <);
6257
0
}
6258
6259
static int
6260
_sess_same_stream_peer(const netsnmp_sockaddr_storage *a,
6261
                       const netsnmp_sockaddr_storage *b)
6262
0
{
6263
0
    if (a->sa.sa_family != b->sa.sa_family)
6264
0
        return 0;
6265
0
    if (a->sa.sa_family == AF_INET)
6266
0
        return memcmp(&a->sin.sin_addr, &b->sin.sin_addr,
6267
0
                      sizeof(a->sin.sin_addr)) == 0;
6268
0
#ifdef NETSNMP_ENABLE_IPV6
6269
0
    if (a->sa.sa_family == AF_INET6)
6270
0
        return memcmp(&a->sin6.sin6_addr, &b->sin6.sin6_addr,
6271
0
                      sizeof(a->sin6.sin6_addr)) == 0;
6272
0
#endif
6273
0
    return 0;
6274
0
}
6275
6276
static int
6277
_sess_stream_accept_allowed(NETSNMP_SOCKET sock,
6278
                            netsnmp_sockaddr_storage *peer,
6279
                            int *peer_valid)
6280
0
{
6281
0
    struct session_list *slp;
6282
0
    socklen_t peer_len = sizeof(*peer);
6283
0
    int accepted = 0, same_peer = 0;
6284
6285
0
    memset(peer, 0, sizeof(*peer));
6286
0
    *peer_valid = getpeername(sock, &peer->sa, &peer_len) == 0;
6287
0
    for (slp = Sessions; slp; slp = slp->next) {
6288
0
        struct snmp_internal_session *isp = slp->internal;
6289
6290
0
        if (isp == NULL || !isp->accepted_stream || slp->transport == NULL ||
6291
0
            !NETSNMP_IS_VALID_SOCKET(slp->transport->sock))
6292
0
            continue;
6293
0
        accepted++;
6294
0
        if (*peer_valid && isp->stream_peer_valid &&
6295
0
            _sess_same_stream_peer(peer, &isp->stream_peer))
6296
0
            same_peer++;
6297
0
    }
6298
0
    return accepted < NETSNMP_STREAM_MAX_SESSIONS &&
6299
0
        same_peer < NETSNMP_STREAM_MAX_SESSIONS_PER_PEER;
6300
0
}
6301
6302
static void
6303
_sess_close_stream(struct session_list *slp)
6304
0
{
6305
0
    netsnmp_session *sp = slp->session;
6306
0
    struct snmp_internal_session *isp = slp->internal;
6307
0
    netsnmp_transport *transport = slp->transport;
6308
6309
0
    if (sp->callback != NULL) {
6310
0
        DEBUGMSGTL(("sess_read", "perform callback with op=DISCONNECT\n"));
6311
0
        (void)sp->callback(NETSNMP_CALLBACK_OP_DISCONNECT, sp, 0, NULL,
6312
0
                           sp->callback_magic);
6313
0
    }
6314
0
    DEBUGMSGTL(("sess_read", "fd %" NETSNMP_FMT_SKT " closed\n",
6315
0
                transport->sock));
6316
0
    transport->f_close(transport);
6317
0
    SNMP_FREE(isp->packet);
6318
0
    isp->packet_size = 0;
6319
0
    isp->packet_len = 0;
6320
0
    isp->accepted_stream = 0;
6321
0
    timerclear(&isp->packet_deadline);
6322
0
}
6323
6324
/*
6325
 * Checks to see if any of the fd's set in the fdset belong to
6326
 * snmp.  Each socket with it's fd set has a packet read from it
6327
 * and snmp_parse is called on the packet received.  The resulting pdu
6328
 * is passed to the callback routine for that session.  If the callback
6329
 * routine returns successfully, the pdu and it's request are deleted.
6330
 */
6331
void
6332
snmp_read(fd_set * fdset)
6333
0
{
6334
0
    netsnmp_large_fd_set lfdset;
6335
6336
0
    netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
6337
0
    netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
6338
0
    snmp_read2(&lfdset);
6339
0
    netsnmp_large_fd_set_cleanup(&lfdset);
6340
0
}
6341
6342
void
6343
snmp_read2(netsnmp_large_fd_set * fdset)
6344
0
{
6345
0
    struct session_list *slp, *next;
6346
6347
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
6348
0
    for (slp = Sessions; slp; slp = next) {
6349
0
        next = slp->next;
6350
0
        if (_sess_packet_deadline_expired(slp->internal)) {
6351
0
            _sess_close_stream(slp);
6352
0
            continue;
6353
0
        }
6354
0
        snmp_sess_read2(slp, fdset);
6355
0
    }
6356
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
6357
0
}
6358
6359
/*
6360
 * accept new connections
6361
 * returns 0 if success, -1 if fail
6362
 */
6363
static int
6364
_sess_read_accept(struct session_list *slp)
6365
0
{
6366
0
    netsnmp_session *sp = slp ? slp->session : NULL;
6367
0
    struct snmp_internal_session *isp = slp ? slp->internal : NULL;
6368
0
    netsnmp_transport *transport = slp ? slp->transport : NULL;
6369
0
    netsnmp_transport *new_transport;
6370
0
    struct session_list *nslp;
6371
0
    netsnmp_sockaddr_storage peer;
6372
0
    int             peer_valid;
6373
0
    NETSNMP_SOCKET    data_sock;
6374
6375
0
    if (NULL == slp || NULL == sp || NULL == transport || NULL == isp ||
6376
0
        !(transport->flags & NETSNMP_TRANSPORT_FLAG_LISTEN))
6377
0
        return -1;
6378
6379
0
    data_sock = transport->f_accept(transport);
6380
0
    if (!NETSNMP_IS_VALID_SOCKET(data_sock)) {
6381
0
        sp->s_snmp_errno = SNMPERR_BAD_RECVFROM;
6382
0
        sp->s_errno = errno;
6383
0
        snmp_set_detail(strerror(errno));
6384
0
        return -1;
6385
0
    }
6386
0
    if (!_sess_stream_accept_allowed(data_sock, &peer, &peer_valid)) {
6387
0
#ifndef HAVE_CLOSESOCKET
6388
0
        close(data_sock);
6389
#else
6390
        closesocket(data_sock);
6391
#endif
6392
0
        return 0;
6393
0
    }
6394
6395
    /*
6396
     * We've successfully accepted a new stream-based connection.
6397
     * It's not too clear what should happen here if we are using the
6398
     * single-session API at this point.  Basically a "session
6399
     * accepted" callback is probably needed to hand the new session
6400
     * over to the application.
6401
     *
6402
     * However, for now, as in th original snmp_api, we will ASSUME
6403
     * that we're using the traditional API, and simply add the new
6404
     * session to the list.  Note we don't have to get the Session
6405
     * list lock here, because under that assumption we already hold
6406
     * it (this is also why we don't just use snmp_add).
6407
     *
6408
     * The moral of the story is: don't use listening stream-based
6409
     * transports in a multi-threaded environment because something
6410
     * will go HORRIBLY wrong (and also that SNMP/TCP is not trivial).
6411
     *
6412
     * Another open issue: what should happen to sockets that have
6413
     * been accept()ed from a listening socket when that original
6414
     * socket is closed?  If they are left open, then attempting to
6415
     * re-open the listening socket will fail, which is semantically
6416
     * confusing.  Perhaps there should be some kind of chaining in
6417
     * the transport structure so that they can all be closed.
6418
     * Discuss.  ;-)
6419
     */
6420
0
    new_transport=netsnmp_transport_copy(transport);
6421
0
    if (new_transport == NULL) {
6422
0
        sp->s_snmp_errno = SNMPERR_MALLOC;
6423
0
        sp->s_errno = errno;
6424
0
        snmp_set_detail(strerror(errno));
6425
0
#ifndef HAVE_CLOSESOCKET
6426
0
        close(data_sock);
6427
#else
6428
        closesocket(data_sock);
6429
#endif
6430
0
        return -1;
6431
0
    }
6432
0
    nslp = NULL;
6433
6434
0
    new_transport->sock = data_sock;
6435
0
    new_transport->flags &= ~NETSNMP_TRANSPORT_FLAG_LISTEN;
6436
6437
0
    nslp = snmp_sess_add_ex(sp, new_transport, isp->hook_pre, isp->hook_parse,
6438
0
                         isp->hook_post, isp->hook_build,
6439
0
                         isp->hook_realloc_build, isp->check_packet,
6440
0
                         isp->hook_create_pdu);
6441
6442
0
    if (nslp != NULL) {
6443
0
        nslp->internal->accepted_stream = 1;
6444
0
        nslp->internal->stream_peer_valid = peer_valid;
6445
0
        if (peer_valid)
6446
0
            nslp->internal->stream_peer = peer;
6447
0
        _sess_set_packet_deadline(nslp->internal);
6448
0
        snmp_session_insert(nslp);
6449
        /** Tell the new session about its existence if possible. */
6450
0
        DEBUGMSGTL(("sess_read",
6451
0
                    "perform callback with op=CONNECT\n"));
6452
0
        if (nslp->session->callback)
6453
0
            (void)nslp->session->callback(NETSNMP_CALLBACK_OP_CONNECT,
6454
0
                                          nslp->session, 0, NULL,
6455
0
                                          sp->callback_magic);
6456
0
    }
6457
6458
0
    return 0;
6459
0
}
6460
6461
/*
6462
 * Same as snmp_read, but works just one non-stream session.
6463
 * returns 0 if success, -1 if protocol err, -2 if no packet to process
6464
 * MTR: can't lock here and at snmp_read
6465
 * Beware recursive send maybe inside snmp_read callback function.
6466
 */
6467
static int
6468
_sess_read_dgram_packet(struct session_list *slp, snmp_rcv_packet *rcvp)
6469
0
{
6470
0
    netsnmp_session *sp = slp ? slp->session : NULL;
6471
0
    struct snmp_internal_session *isp = slp ? slp->internal : NULL;
6472
0
    netsnmp_transport *transport = slp ? slp->transport : NULL;
6473
6474
0
    if (!sp || !isp || !transport || !rcvp ) {
6475
0
        DEBUGMSGTL(("sess_read_packet", "missing arguments\n"));
6476
0
        return -2;
6477
0
    }
6478
6479
0
    if (transport->flags & NETSNMP_TRANSPORT_FLAG_STREAM)
6480
0
        return -2;
6481
6482
0
    if (NULL != rcvp->packet) {
6483
0
        snmp_log(LOG_WARNING, "overwriting existing saved packet; sess %p\n",
6484
0
                 sp);
6485
0
        SNMP_FREE(rcvp->packet);
6486
0
    }
6487
6488
0
    if ((rcvp->packet = (u_char *) malloc(SNMP_MAX_RCV_MSG_SIZE)) == NULL) {
6489
0
        DEBUGMSGTL(("sess_read_packet", "can't malloc %u bytes for packet\n",
6490
0
                    SNMP_MAX_RCV_MSG_SIZE));
6491
0
        return -2;
6492
0
    }
6493
6494
0
    rcvp->packet_len = netsnmp_transport_recv(transport, rcvp->packet,
6495
0
                                              SNMP_MAX_RCV_MSG_SIZE,
6496
0
                                              &rcvp->opaque, &rcvp->olength);
6497
0
    if (rcvp->packet_len == -1) {
6498
0
        sp->s_snmp_errno = SNMPERR_BAD_RECVFROM;
6499
0
        sp->s_errno = errno;
6500
0
        snmp_set_detail(strerror(errno));
6501
0
        SNMP_FREE(rcvp->packet);
6502
0
        SNMP_FREE(rcvp->opaque);
6503
0
        return -1;
6504
0
    }
6505
6506
0
    if (0 == rcvp->packet_len &&
6507
0
        transport->flags & NETSNMP_TRANSPORT_FLAG_EMPTY_PKT) {
6508
        /* this allows for a transport that needs to return from
6509
         * packet processing that doesn't necessarily have any
6510
         * consumable data in it. */
6511
6512
        /* reset the flag since it's a per-message flag */
6513
0
        transport->flags &= (~NETSNMP_TRANSPORT_FLAG_EMPTY_PKT);
6514
6515
        /** free packet */
6516
0
        SNMP_FREE(rcvp->packet);
6517
0
        SNMP_FREE(rcvp->opaque);
6518
6519
0
        return -2;
6520
0
    }
6521
6522
0
    return 0;
6523
0
}
6524
6525
static int
6526
__sess_read(struct session_list *slp)
6527
0
{
6528
0
    netsnmp_session *sp = slp ? slp->session : NULL;
6529
0
    struct snmp_internal_session *isp = slp ? slp->internal : NULL;
6530
0
    netsnmp_transport *transport = slp ? slp->transport : NULL;
6531
0
    size_t          pdulen = 0;
6532
0
    size_t          rxbuf_len;
6533
0
    size_t          stream_limit;
6534
0
    u_char         *rxbuf = NULL;
6535
0
    int             length = 0, olength = 0, rc = 0;
6536
0
    void           *opaque = NULL;
6537
6538
0
    if (NULL == slp || NULL == sp || NULL == isp || NULL == transport) {
6539
0
        snmp_log(LOG_ERR, "bad parameters to __sess_read\n");
6540
0
        return SNMPERR_GENERR;
6541
0
    }
6542
6543
    /* to avoid subagent crash */
6544
0
    if (!NETSNMP_IS_VALID_SOCKET(transport->sock)) {
6545
0
        snmp_log(LOG_INFO, "transport->sock is invalid\n");
6546
0
        return 0; 
6547
0
    }
6548
6549
0
    sp->s_snmp_errno = 0;
6550
0
    sp->s_errno = 0;
6551
6552
0
    stream_limit = sp->rcvMsgMaxSize ?
6553
0
        SNMP_MIN(SNMP_MAX_PACKET_LEN, sp->rcvMsgMaxSize) :
6554
0
        SNMP_MAX_PACKET_LEN;
6555
0
    rxbuf_len = SNMP_MIN(SNMP_MAX_RCV_MSG_SIZE, stream_limit);
6556
6557
0
    if (transport->flags & NETSNMP_TRANSPORT_FLAG_LISTEN)
6558
0
        return _sess_read_accept(slp);
6559
6560
0
    if (!(transport->flags & NETSNMP_TRANSPORT_FLAG_STREAM)) {
6561
0
        snmp_rcv_packet rcvp;
6562
0
        u_char *pptr;
6563
0
        size_t len_remaining, pdulen;
6564
0
        void *ocopy = NULL;
6565
6566
0
        memset(&rcvp, 0x0, sizeof(rcvp));
6567
6568
        /** read the packet */
6569
0
        rc = _sess_read_dgram_packet(slp, &rcvp);
6570
0
        if (-1 == rc) /* protocol error */
6571
0
            return -1;
6572
0
        else if (-2 == rc) /* no packet to process */
6573
0
            return 0;
6574
6575
0
        pptr = rcvp.packet;
6576
0
        len_remaining = rcvp.packet_len;
6577
0
        rc = 0;
6578
6579
0
        while (len_remaining > 0) {
6580
0
            if (isp->check_packet) {
6581
0
                pdulen = isp->check_packet(pptr, len_remaining);
6582
0
            } else {
6583
0
                pdulen = asn_check_packet(pptr, len_remaining);
6584
0
            }
6585
0
            if (pdulen == 0 || pdulen > len_remaining || pdulen > SNMP_MAX_PACKET_LEN) {
6586
                /* Not a valid packet or incomplete in datagram mode */
6587
0
                if (pptr == rcvp.packet) {
6588
0
                    SNMP_FREE(rcvp.opaque);
6589
0
                }
6590
0
                break;
6591
0
            }
6592
0
            if (pdulen < len_remaining) {
6593
0
                if (rcvp.olength > 0 && rcvp.opaque != NULL) {
6594
0
                    ocopy = malloc(rcvp.olength);
6595
0
                    if (ocopy != NULL) {
6596
0
                        memcpy(ocopy, rcvp.opaque, rcvp.olength);
6597
0
                    }
6598
0
                }
6599
0
            } else {
6600
0
                ocopy = rcvp.opaque;
6601
0
                rcvp.opaque = NULL;
6602
0
            }
6603
0
            rc = _sess_process_packet(slp, sp, isp, transport,
6604
0
                                      ocopy, ocopy ? rcvp.olength : 0,
6605
0
                                      pptr, pdulen);
6606
0
            ocopy = NULL;
6607
0
            pptr += pdulen;
6608
0
            len_remaining -= pdulen;
6609
0
        }
6610
0
        SNMP_FREE(rcvp.packet);
6611
0
        SNMP_FREE(rcvp.opaque);
6612
0
        return rc;
6613
0
    }
6614
6615
    /** stream transport */
6616
6617
0
        if (isp->packet_len >= stream_limit) {
6618
0
            _sess_close_stream(slp);
6619
0
            return -1;
6620
0
        }
6621
0
        rxbuf_len = SNMP_MIN(rxbuf_len, stream_limit - isp->packet_len);
6622
6623
0
        if (isp->packet == NULL) {
6624
            /*
6625
             * We have no saved packet.  Allocate one.  
6626
             */
6627
0
            if ((isp->packet = (u_char *) malloc(rxbuf_len)) == NULL) {
6628
0
                DEBUGMSGTL(("sess_read", "can't malloc %" NETSNMP_PRIz
6629
0
                            "u bytes for rxbuf\n", rxbuf_len));
6630
0
                return 0;
6631
0
            } else {
6632
0
                rxbuf = isp->packet;
6633
0
                isp->packet_size = rxbuf_len;
6634
0
                isp->packet_len = 0;
6635
0
            }
6636
0
        } else {
6637
            /*
6638
             * We have saved a partial packet from last time.  Extend that, if
6639
             * necessary, and receive new data after the old data.  
6640
             */
6641
0
            u_char         *newbuf;
6642
6643
0
            if (isp->packet_size < isp->packet_len + rxbuf_len) {
6644
0
                newbuf =
6645
0
                    (u_char *) realloc(isp->packet,
6646
0
                                       isp->packet_len + rxbuf_len);
6647
0
                if (newbuf == NULL) {
6648
0
                    DEBUGMSGTL(("sess_read",
6649
0
                                "can't malloc %" NETSNMP_PRIz
6650
0
                                "u more for rxbuf (%" NETSNMP_PRIz "u tot)\n",
6651
0
                                rxbuf_len, isp->packet_len + rxbuf_len));
6652
0
                    return 0;
6653
0
                } else {
6654
0
                    isp->packet = newbuf;
6655
0
                    isp->packet_size = isp->packet_len + rxbuf_len;
6656
0
                    rxbuf = isp->packet + isp->packet_len;
6657
0
                }
6658
0
            } else {
6659
0
                rxbuf = isp->packet + isp->packet_len;
6660
0
                rxbuf_len = isp->packet_size - isp->packet_len;
6661
0
            }
6662
0
        }
6663
6664
0
    length = netsnmp_transport_recv(transport, rxbuf, rxbuf_len, &opaque,
6665
0
                                    &olength);
6666
6667
0
    if (0 == length && transport->flags & NETSNMP_TRANSPORT_FLAG_EMPTY_PKT) {
6668
        /* this allows for a transport that needs to return from
6669
         * packet processing that doesn't necessarily have any
6670
         * consumable data in it. */
6671
6672
        /* reset the flag since it's a per-message flag */
6673
0
        transport->flags &= (~NETSNMP_TRANSPORT_FLAG_EMPTY_PKT);
6674
6675
0
        return 0;
6676
0
    }
6677
6678
    /*
6679
     * Remote end closed connection.  
6680
     */
6681
0
    if (length <= 0) {
6682
        /*
6683
         * Alert the application if possible.  
6684
         */
6685
0
        _sess_close_stream(slp);
6686
0
        SNMP_FREE(opaque);
6687
0
        return -1;
6688
0
    }
6689
6690
0
    {
6691
0
        u_char *pptr = isp->packet;
6692
0
  void *ocopy = NULL;
6693
6694
0
        isp->packet_len += length;
6695
6696
0
        while (isp->packet_len > 0) {
6697
6698
            /*
6699
             * Get the total data length we're expecting (and need to wait
6700
             * for).
6701
             */
6702
0
            if (isp->check_packet) {
6703
0
                pdulen = isp->check_packet(pptr, isp->packet_len);
6704
0
            } else {
6705
0
                pdulen = asn_check_packet(pptr, isp->packet_len);
6706
0
            }
6707
6708
0
            DEBUGMSGTL(("sess_read",
6709
0
                        "  loop packet_len %" NETSNMP_PRIz "u, PDU length %"
6710
0
                        NETSNMP_PRIz "u\n", isp->packet_len, pdulen));
6711
6712
0
            if ((int)pdulen < 0 || pdulen > SNMP_MAX_PACKET_LEN ||
6713
0
                (sp->rcvMsgMaxSize && pdulen > sp->rcvMsgMaxSize)) {
6714
                /*
6715
                 * Illegal length, drop the connection.  
6716
                 */
6717
0
                snmp_log(LOG_ERR, 
6718
0
       "Received broken packet. Closing session.\n");
6719
0
                _sess_close_stream(slp);
6720
0
                SNMP_FREE(opaque);
6721
0
                return -1;
6722
0
            }
6723
6724
0
            if (pdulen > isp->packet_len || pdulen == 0) {
6725
                /*
6726
                 * We don't have a complete packet yet.  If we've already
6727
                 * processed a packet, break out so we'll shift this packet
6728
                 * to the start of the buffer. If we're already at the
6729
                 * start, simply return and wait for more data to arrive.
6730
                 */
6731
0
                DEBUGMSGTL(("sess_read",
6732
0
                            "pkt not complete (need %" NETSNMP_PRIz "u got %"
6733
0
                            NETSNMP_PRIz "u so far)\n", pdulen,
6734
0
                            isp->packet_len));
6735
6736
0
                if (pptr != isp->packet)
6737
0
                    break; /* opaque freed for us outside of loop. */
6738
6739
0
                if (!timerisset(&isp->packet_deadline))
6740
0
                    _sess_set_packet_deadline(isp);
6741
0
                SNMP_FREE(opaque);
6742
0
                return 0;
6743
0
            }
6744
6745
            /*  We have *at least* one complete packet in the buffer now.  If
6746
    we have possibly more than one packet, we must copy the opaque
6747
    pointer because we may need to reuse it for a later packet.  */
6748
6749
0
      if (pdulen < isp->packet_len) {
6750
0
    if (olength > 0 && opaque != NULL) {
6751
0
        ocopy = malloc(olength);
6752
0
        if (ocopy != NULL) {
6753
0
      memcpy(ocopy, opaque, olength);
6754
0
        }
6755
0
    }
6756
0
      } else if (pdulen == isp->packet_len) {
6757
    /*  Common case -- exactly one packet.  No need to copy the
6758
        opaque pointer.  */
6759
0
    ocopy = opaque;
6760
0
    opaque = NULL;
6761
0
      }
6762
6763
0
            if ((rc = _sess_process_packet(slp, sp, isp, transport,
6764
0
                                           ocopy, ocopy?olength:0, pptr,
6765
0
                                           pdulen))) {
6766
                /*
6767
                 * Something went wrong while processing this packet -- set the
6768
                 * errno.  
6769
                 */
6770
0
                if (sp->s_snmp_errno != 0) {
6771
0
                    SET_SNMP_ERROR(sp->s_snmp_errno);
6772
0
                }
6773
0
            }
6774
0
            timerclear(&isp->packet_deadline);
6775
6776
      /*  ocopy has been free()d by _sess_process_packet by this point,
6777
    so set it to NULL.  */
6778
6779
0
      ocopy = NULL;
6780
6781
      /*  Step past the packet we've just dealt with.  */
6782
6783
0
            pptr += pdulen;
6784
0
            isp->packet_len -= pdulen;
6785
0
        }
6786
6787
  /*  If we had more than one packet, then we were working with copies
6788
      of the opaque pointer, so we still need to free() the opaque
6789
      pointer itself.  */
6790
6791
0
  SNMP_FREE(opaque);
6792
6793
0
        if (isp->packet_len >= stream_limit) {
6794
            /*
6795
             * Obviously this should never happen!  
6796
             */
6797
0
            snmp_log(LOG_ERR,
6798
0
                     "too large packet_len = %" NETSNMP_PRIz
6799
0
                     "u, dropping connection %" NETSNMP_FMT_SKT "\n",
6800
0
                     isp->packet_len, transport->sock);
6801
0
            _sess_close_stream(slp);
6802
0
            return -1;
6803
0
        } else if (isp->packet_len == 0) {
6804
            /*
6805
             * This is good: it means the packet buffer contained an integral
6806
             * number of PDUs, so we don't have to save any data for next
6807
             * time.  We can free() the buffer now to keep the memory
6808
             * footprint down.
6809
             */
6810
0
            SNMP_FREE(isp->packet);
6811
0
            isp->packet_size = 0;
6812
0
            isp->packet_len = 0;
6813
0
            timerclear(&isp->packet_deadline);
6814
0
            return rc;
6815
0
        }
6816
6817
        /*
6818
         * If we get here, then there is a partial packet of length
6819
         * isp->packet_len bytes starting at pptr left over.  Move that to the
6820
         * start of the buffer, and then realloc() the buffer down to size to
6821
         * reduce the memory footprint.  
6822
         */
6823
6824
0
        memmove(isp->packet, pptr, isp->packet_len);
6825
0
        if (!timerisset(&isp->packet_deadline))
6826
0
            _sess_set_packet_deadline(isp);
6827
0
        DEBUGMSGTL(("sess_read",
6828
0
                    "end: memmove(%p, %p, %" NETSNMP_PRIz "u); realloc(%p, %"
6829
0
                    NETSNMP_PRIz "u)\n",
6830
0
                    isp->packet, pptr, isp->packet_len,
6831
0
        isp->packet, isp->packet_len));
6832
6833
0
        if ((rxbuf = (u_char *)realloc(isp->packet, isp->packet_len)) == NULL) {
6834
            /*
6835
             * I don't see why this should ever fail, but it's not a big deal.
6836
             */
6837
0
            DEBUGMSGTL(("sess_read", "realloc() failed\n"));
6838
0
        } else {
6839
0
            DEBUGMSGTL(("sess_read", "realloc() okay, old buffer %p, new %p\n",
6840
0
                        isp->packet, rxbuf));
6841
0
            isp->packet = rxbuf;
6842
0
            isp->packet_size = isp->packet_len;
6843
0
        }
6844
0
    }
6845
6846
0
    return rc;
6847
0
}
6848
6849
/*
6850
 * Same as snmp_read, but works just one session.
6851
 * returns 0 if success, -1 if fail
6852
 * MTR: can't lock here and at snmp_read
6853
 * Beware recursive send maybe inside snmp_read callback function.
6854
 */
6855
int
6856
_sess_read(struct session_list *slp, netsnmp_large_fd_set * fdset)
6857
0
{
6858
0
    netsnmp_transport *transport;
6859
6860
0
    if (!slp || !fdset)
6861
0
        return 0;
6862
6863
0
    transport = slp->transport;
6864
6865
0
    if (!transport || !NETSNMP_LARGE_FD_ISSET(transport->sock, fdset)) {
6866
0
        DEBUGMSGTL(("sess_read", "not reading transport socket\n"));
6867
0
        return 0;
6868
0
    }
6869
6870
0
    return __sess_read(slp);
6871
0
}
6872
6873
6874
6875
/*
6876
 * returns 0 if success, -1 if fail 
6877
 */
6878
int
6879
snmp_sess_read(struct session_list *slp, fd_set * fdset)
6880
0
{
6881
0
  int rc;
6882
0
  netsnmp_large_fd_set lfdset;
6883
  
6884
0
  netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
6885
0
  netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
6886
0
  rc = snmp_sess_read2(slp, &lfdset);
6887
0
  netsnmp_large_fd_set_cleanup(&lfdset);
6888
0
  return rc;
6889
0
}
6890
6891
int
6892
snmp_sess_read2(struct session_list *slp, netsnmp_large_fd_set * fdset)
6893
0
{
6894
0
    netsnmp_session *pss;
6895
0
    int             rc;
6896
6897
0
    rc = _sess_read(slp, fdset);
6898
0
    pss = slp->session;
6899
0
    if (rc && pss->s_snmp_errno) {
6900
0
        SET_SNMP_ERROR(pss->s_snmp_errno);
6901
0
    }
6902
0
    return rc;
6903
0
}
6904
6905
/**
6906
 * For the transport of the specified session, check if pending buffered data
6907
 * is available (via the .f_pending() callback) and read it into the session.
6908
 * The .f_pending() callback is only defined by transports such as TLS-TCP that
6909
 * buffer data in memory. Must be called before waiting for socket events in an
6910
 * event loop.
6911
 *
6912
 * @param[in] sessp Pointer to the session to poll. Must not be NULL.
6913
 *
6914
 * @see snmp_poll
6915
 */
6916
void
6917
snmp_sess_poll(struct session_list *sessp)
6918
0
{
6919
0
    netsnmp_assert(sessp);
6920
6921
0
    while (sessp->transport && sessp->transport->f_pending &&
6922
0
           sessp->transport->f_pending(sessp->transport))
6923
0
        __sess_read(sessp);
6924
0
}
6925
6926
/**
6927
 * Poll all active sessions in the global session list for pending buffered
6928
 * transport data and process any data found.
6929
 *
6930
 * @see snmp_sess_poll
6931
 */
6932
void
6933
snmp_poll(void)
6934
0
{
6935
0
    struct session_list *slp;
6936
6937
0
    for (slp = Sessions; slp; slp = slp->next)
6938
0
        snmp_sess_poll(slp);
6939
0
}
6940
6941
/**
6942
 * Returns info about what snmp requires from a select statement.
6943
 * numfds is the number of fds in the list that are significant.
6944
 * All file descriptors opened for SNMP are OR'd into the fdset.
6945
 * If activity occurs on any of these file descriptors, snmp_read
6946
 * should be called with that file descriptor set
6947
 *
6948
 * The timeout is the latest time that SNMP can wait for a timeout.  The
6949
 * select should be done with the minimum time between timeout and any other
6950
 * timeouts necessary.  This should be checked upon each invocation of select.
6951
 * If a timeout is received, snmp_timeout should be called to check if the
6952
 * timeout was for SNMP.  (snmp_timeout is idempotent)
6953
 *
6954
 * The value of block indicates how the timeout value is interpreted.
6955
 * If block is true on input, the timeout value will be treated as undefined,
6956
 * but it must be available for setting in snmp_select_info.  On return,
6957
 * block is set to true if the value returned for timeout is undefined;
6958
 * when block is set to false, timeout may be used as a parameter to 'select'.
6959
 *
6960
 * snmp_select_info returns the number of open sockets.  (i.e. The number of
6961
 * sessions open)
6962
 *
6963
 * @see See also snmp_sess_select_info2_flags().
6964
 */
6965
int
6966
snmp_select_info(int *numfds, fd_set *fdset, struct timeval *timeout,
6967
                 int *block)
6968
0
{
6969
0
    return snmp_sess_select_info(NULL, numfds, fdset, timeout, block);
6970
0
}
6971
6972
/**
6973
 * @see See also snmp_sess_select_info2_flags().
6974
 */
6975
int
6976
snmp_select_info2(int *numfds, netsnmp_large_fd_set *fdset,
6977
      struct timeval *timeout, int *block)
6978
0
{
6979
0
    return snmp_sess_select_info2(NULL, numfds, fdset, timeout, block);
6980
0
}
6981
6982
/**
6983
 * @see See also snmp_sess_select_info2_flags().
6984
 */
6985
int
6986
snmp_sess_select_info(struct session_list *slp, int *numfds, fd_set *fdset,
6987
                      struct timeval *timeout, int *block)
6988
0
{
6989
0
    return snmp_sess_select_info_flags(slp, numfds, fdset, timeout, block,
6990
0
                                       NETSNMP_SELECT_NOFLAGS);
6991
0
}
6992
        
6993
/**
6994
 * @see See also snmp_sess_select_info2_flags().
6995
 */
6996
int
6997
snmp_sess_select_info_flags(struct session_list *slp, int *numfds, fd_set *fdset,
6998
                            struct timeval *timeout, int *block, int flags)
6999
0
{
7000
0
  int rc;
7001
0
  netsnmp_large_fd_set lfdset;
7002
7003
0
  netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
7004
0
  netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
7005
0
  rc = snmp_sess_select_info2_flags(slp, numfds, &lfdset, timeout,
7006
0
                                    block, flags);
7007
0
  if (netsnmp_copy_large_fd_set_to_fd_set(fdset, &lfdset) < 0) {
7008
0
      snmp_log(LOG_ERR,
7009
0
       "Use snmp_sess_select_info2() for processing"
7010
0
       " large file descriptors\n");
7011
0
  }
7012
0
  netsnmp_large_fd_set_cleanup(&lfdset);
7013
0
  return rc;
7014
0
}
7015
7016
/**
7017
 * @see See also snmp_sess_select_info2_flags().
7018
 */
7019
int
7020
snmp_sess_select_info2(struct session_list *slp, int *numfds, netsnmp_large_fd_set *fdset,
7021
           struct timeval *timeout, int *block)
7022
0
{
7023
0
    return snmp_sess_select_info2_flags(slp, numfds, fdset, timeout, block,
7024
0
                                        NETSNMP_SELECT_NOFLAGS);
7025
0
}
7026
7027
/**
7028
 * Compute/update the arguments to be passed to select().
7029
 *
7030
 * @param[in]     sessp   Which sessions to process: either a pointer to a
7031
 *   specific session or NULL which means to process all sessions.
7032
 * @param[in,out] numfds  On POSIX systems one more than the the largest file
7033
 *   descriptor that is present in *fdset. On systems that use Winsock (MinGW
7034
 *   and MSVC), do not use the value written into *numfds.
7035
 * @param[in,out] fdset   A large file descriptor set to which all file
7036
 *   descriptors will be added that are associated with one of the examined
7037
 *   sessions.
7038
 * @param[in,out] timeout On input, if *block = 1, the maximum time the caller
7039
 *   will block while waiting for Net-SNMP activity. On output, if this function
7040
 *   has set *block to 0, the maximum time the caller is allowed to wait before
7041
 *   invoking the Net-SNMP processing functions (snmp_read(), snmp_timeout()
7042
 *   and run_alarms()). If this function has set *block to 1, *timeout won't
7043
 *   have been modified and no alarms are active.
7044
 * @param[in,out] block   On input, whether the caller prefers to block forever
7045
 *   when no alarms are active. On output, 0 means that no alarms are active
7046
 *   nor that there is a timeout pending for any of the processed sessions.
7047
 * @param[in]     flags   Either 0 or NETSNMP_SELECT_NOALARMS.
7048
 *
7049
 * @return Number of sessions processed by this function.
7050
 *
7051
 * @see See also agent_check_and_process() for an example of how to use this
7052
 *   function.
7053
 */
7054
int
7055
snmp_sess_select_info2_flags(struct session_list *sessp, int *numfds,
7056
                             netsnmp_large_fd_set * fdset,
7057
                             struct timeval *timeout, int *block, int flags)
7058
0
{
7059
0
    struct session_list *slp, *next = NULL;
7060
0
    netsnmp_request_list *rp;
7061
0
    struct timeval  now, earliest, alarm_tm;
7062
0
    int             active = 0, requests = 0;
7063
0
    int             next_alarm = 0;
7064
0
    int             has_pending_data = 0;
7065
0
    int             packet_deadlines = 0;
7066
7067
0
    timerclear(&earliest);
7068
7069
    /*
7070
     * For each session examined, add its socket to the fdset,
7071
     * and if it is the earliest timeout to expire, mark it as lowest.
7072
     * If a single session is specified, do just for that session.
7073
     */
7074
7075
0
    DEBUGMSGTL(("sess_select", "for %s session%s: ",
7076
0
                sessp ? "single" : "all", sessp ? "" : "s"));
7077
7078
0
    for (slp = sessp ? sessp : Sessions; slp; slp = next) {
7079
0
        next = slp->next;
7080
7081
0
        if (slp->transport == NULL) {
7082
            /*
7083
             * Close in progress -- skip this one.  
7084
             */
7085
0
            DEBUGMSG(("sess_select", "skip "));
7086
0
            continue;
7087
0
        }
7088
7089
0
        if (!NETSNMP_IS_VALID_SOCKET(slp->transport->sock)) {
7090
            /*
7091
             * This session was marked for deletion.  
7092
             */
7093
0
            DEBUGMSG(("sess_select", "delete\n"));
7094
0
            if (sessp == NULL) {
7095
0
                snmp_close(slp->session);
7096
0
            } else {
7097
0
                snmp_sess_close(slp);
7098
0
            }
7099
0
            DEBUGMSGTL(("sess_select", "for %s session%s: ",
7100
0
                        sessp ? "single" : "all", sessp ? "" : "s"));
7101
0
            continue;
7102
0
        }
7103
7104
0
        DEBUGMSG(("sess_select", "%" NETSNMP_FMT_SKT " ",
7105
0
                  slp->transport->sock));
7106
0
        if ((slp->transport->sock + 1) > *numfds) {
7107
0
            *numfds = (slp->transport->sock + 1);
7108
0
        }
7109
7110
0
        NETSNMP_LARGE_FD_SET(slp->transport->sock, fdset);
7111
0
        if (slp->transport->f_pending &&
7112
0
            slp->transport->f_pending(slp->transport)) {
7113
0
            has_pending_data = 1;
7114
0
        }
7115
0
        if (slp->internal != NULL && slp->internal->requests) {
7116
            /*
7117
             * Found another session with outstanding requests.  
7118
             */
7119
0
            requests++;
7120
0
            for (rp = slp->internal->requests; rp; rp = rp->next_request) {
7121
0
                if (!timerisset(&earliest)
7122
0
                    || (timerisset(&rp->expireM)
7123
0
                        && timercmp(&rp->expireM, &earliest, <))) {
7124
0
                    earliest = rp->expireM;
7125
0
                    DEBUGMSG(("verbose:sess_select","(to in %d.%06d sec) ",
7126
0
                               (int)earliest.tv_sec, (int)earliest.tv_usec));
7127
0
                }
7128
0
            }
7129
0
        }
7130
0
        if (slp->internal != NULL &&
7131
0
            timerisset(&slp->internal->packet_deadline)) {
7132
0
            packet_deadlines++;
7133
0
            if (!timerisset(&earliest) ||
7134
0
                timercmp(&slp->internal->packet_deadline, &earliest, <))
7135
0
                earliest = slp->internal->packet_deadline;
7136
0
        }
7137
7138
0
        active++;
7139
0
        if (sessp) {
7140
            /*
7141
             * Single session processing.  
7142
             */
7143
0
            break;
7144
0
        }
7145
0
    }
7146
0
    DEBUGMSG(("sess_select", "\n"));
7147
7148
0
    if (has_pending_data) {
7149
0
        DEBUGMSGT(("sess_select",
7150
0
                   "pending transport data present, setting timeout to 0\n"));
7151
0
        timerclear(timeout);
7152
0
        *block = 0;
7153
0
        return active;
7154
0
    }
7155
7156
0
    netsnmp_get_monotonic_clock(&now);
7157
7158
0
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7159
0
                               NETSNMP_DS_LIB_ALARM_DONT_USE_SIG) &&
7160
0
        !(flags & NETSNMP_SELECT_NOALARMS)) {
7161
0
        next_alarm = netsnmp_get_next_alarm_time(&alarm_tm, &now);
7162
0
        if (next_alarm)
7163
0
            DEBUGMSGT(("sess_select","next alarm at %ld.%06ld sec\n",
7164
0
                       (long)alarm_tm.tv_sec, (long)alarm_tm.tv_usec));
7165
0
    }
7166
0
    if (next_alarm == 0 && requests == 0 && packet_deadlines == 0) {
7167
        /*
7168
         * If none are active, skip arithmetic.  
7169
         */
7170
0
        DEBUGMSGT(("sess_select","blocking:no session requests or alarms.\n"));
7171
0
        *block = 1; /* can block - timeout value is undefined if no requests */
7172
0
        return active;
7173
0
    }
7174
7175
0
    if (next_alarm &&
7176
0
        (!timerisset(&earliest) || timercmp(&alarm_tm, &earliest, <)))
7177
0
        earliest = alarm_tm;
7178
7179
0
    NETSNMP_TIMERSUB(&earliest, &now, &earliest);
7180
0
    if (earliest.tv_sec < 0) {
7181
0
        time_t overdue_ms = -(earliest.tv_sec * 1000 + earliest.tv_usec / 1000);
7182
0
        if (overdue_ms >= 10)
7183
0
            DEBUGMSGT(("verbose:sess_select","timer overdue by %ld ms\n",
7184
0
                       (long) overdue_ms));
7185
0
        timerclear(&earliest);
7186
0
    } else {
7187
0
        DEBUGMSGT(("verbose:sess_select","timer due in %d.%06d sec\n",
7188
0
                   (int)earliest.tv_sec, (int)earliest.tv_usec));
7189
0
    }
7190
7191
    /*
7192
     * if it was blocking before or our delta time is less, reset timeout 
7193
     */
7194
0
    if ((*block || (timercmp(&earliest, timeout, <)))) {
7195
0
        DEBUGMSGT(("verbose:sess_select",
7196
0
                   "setting timer to %d.%06d sec, clear block (was %d)\n",
7197
0
                   (int)earliest.tv_sec, (int)earliest.tv_usec, *block));
7198
0
        *timeout = earliest;
7199
0
        *block = 0;
7200
0
    }
7201
0
    return active;
7202
0
}
7203
7204
/*
7205
 * snmp_timeout should be called whenever the timeout from snmp_select_info
7206
 * expires, but it is idempotent, so snmp_timeout can be polled (probably a
7207
 * cpu expensive proposition).  snmp_timeout checks to see if any of the
7208
 * sessions have an outstanding request that has timed out.  If it finds one
7209
 * (or more), and that pdu has more retries available, a new packet is formed
7210
 * from the pdu and is resent.  If there are no more retries available, the
7211
 *  callback for the session is used to alert the user of the timeout.
7212
 */
7213
void
7214
snmp_timeout(void)
7215
0
{
7216
0
    struct session_list *slp, *next;
7217
7218
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
7219
0
    for (slp = Sessions; slp; slp = next) {
7220
0
        next = slp->next;
7221
0
        snmp_sess_timeout(slp);
7222
0
    }
7223
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
7224
0
}
7225
7226
void
7227
snmp_sess_timeout(struct session_list *slp)
7228
0
{
7229
0
    netsnmp_session *sp;
7230
0
    struct snmp_internal_session *isp;
7231
0
    netsnmp_request_list *rp, *orp = NULL, *freeme = NULL;
7232
0
    struct timeval  now;
7233
0
    snmp_callback   callback;
7234
0
    void           *magic;
7235
0
    struct snmp_secmod_def *sptr;
7236
7237
0
    sp = slp->session;
7238
0
    isp = slp->internal;
7239
0
    if (!sp || !isp) {
7240
0
        DEBUGMSGTL(("sess_read", "timeout fail: closing...\n"));
7241
0
        return;
7242
0
    }
7243
7244
0
    netsnmp_get_monotonic_clock(&now);
7245
7246
0
    if (_sess_packet_deadline_expired(isp)) {
7247
0
        snmp_log(LOG_WARNING,
7248
0
                 "Incomplete stream frame timed out. Closing session.\n");
7249
0
        _sess_close_stream(slp);
7250
0
        return;
7251
0
    }
7252
7253
    /*
7254
     * For each request outstanding, check to see if it has expired.
7255
     */
7256
0
    for (rp = isp->requests; rp; rp = rp->next_request) {
7257
0
        if (freeme != NULL) {
7258
            /*
7259
             * frees rp's after the for loop goes on to the next_request 
7260
             */
7261
0
            free(freeme);
7262
0
            freeme = NULL;
7263
0
        }
7264
7265
0
        if ((timercmp(&rp->expireM, &now, <))) {
7266
0
            if ((sptr = find_sec_mod(rp->pdu->securityModel)) != NULL &&
7267
0
                sptr->pdu_timeout != NULL) {
7268
                /*
7269
                 * call security model if it needs to know about this 
7270
                 */
7271
0
                (*sptr->pdu_timeout) (rp->pdu);
7272
0
            }
7273
7274
            /*
7275
             * this timer has expired 
7276
             */
7277
0
            if (rp->retries >= sp->retries) {
7278
0
                if (rp->callback) {
7279
0
                    callback = rp->callback;
7280
0
                    magic = rp->cb_data;
7281
0
                } else {
7282
0
                    callback = sp->callback;
7283
0
                    magic = sp->callback_magic;
7284
0
                }
7285
7286
                /*
7287
                 * No more chances, delete this entry 
7288
                 */
7289
0
                if (callback) {
7290
0
                    callback(NETSNMP_CALLBACK_OP_TIMED_OUT, sp,
7291
0
                             rp->pdu->reqid, rp->pdu, magic);
7292
0
                }
7293
0
                remove_request(isp, orp, rp);
7294
0
                freeme = rp;
7295
0
                continue;       /* don't update orp below */
7296
0
            } else {
7297
0
                if (snmp_resend_request(slp, orp, rp, TRUE)) {
7298
0
                    break;
7299
0
                }
7300
0
            }
7301
0
        }
7302
0
        orp = rp;
7303
0
    }
7304
7305
0
    if (freeme != NULL) {
7306
0
        free(freeme);
7307
0
        freeme = NULL;
7308
0
    }
7309
0
}
7310
7311
/*
7312
 * lexicographical compare two object identifiers.
7313
 * * Returns -1 if name1 < name2,
7314
 * *          0 if name1 = name2,
7315
 * *          1 if name1 > name2
7316
 * *
7317
 * * Caution: this method is called often by
7318
 * *          command responder applications (ie, agent).
7319
 */
7320
int
7321
snmp_oid_ncompare(const oid * in_name1,
7322
                  size_t len1,
7323
                  const oid * in_name2, size_t len2, size_t max_len)
7324
0
{
7325
0
    register int    len;
7326
0
    register const oid *name1 = in_name1;
7327
0
    register const oid *name2 = in_name2;
7328
0
    size_t          min_len;
7329
7330
    /*
7331
     * len = minimum of len1 and len2 
7332
     */
7333
0
    if (len1 < len2)
7334
0
        min_len = len1;
7335
0
    else
7336
0
        min_len = len2;
7337
7338
0
    if (min_len > max_len)
7339
0
        min_len = max_len;
7340
7341
0
    len = min_len;
7342
7343
    /*
7344
     * find first non-matching OID 
7345
     */
7346
0
    while (len-- > 0) {
7347
        /*
7348
         * these must be done in separate comparisons, since
7349
         * subtracting them and using that result has problems with
7350
         * subids > 2^31. 
7351
         */
7352
0
        if (*(name1) != *(name2)) {
7353
0
            if (*(name1) < *(name2))
7354
0
                return -1;
7355
0
            return 1;
7356
0
        }
7357
0
        name1++;
7358
0
        name2++;
7359
0
    }
7360
7361
0
    if (min_len != max_len) {
7362
        /*
7363
         * both OIDs equal up to length of shorter OID 
7364
         */
7365
0
        if (len1 < len2)
7366
0
            return -1;
7367
0
        if (len2 < len1)
7368
0
            return 1;
7369
0
    }
7370
7371
0
    return 0;
7372
0
}
7373
7374
/**
7375
 * Lexicographically compare two object identifiers.
7376
 *
7377
 * @param[in] in_name1 Left hand side OID.
7378
 * @param[in] len1     Length of LHS OID.
7379
 * @param[in] in_name2 Right hand side OID.
7380
 * @param[in] len2     Length of RHS OID.
7381
 * 
7382
 * Caution: this method is called often by
7383
 *          command responder applications (ie, agent).
7384
 *
7385
 * @return -1 if name1 < name2, 0 if name1 = name2, 1 if name1 > name2
7386
 */
7387
int
7388
snmp_oid_compare(const oid * in_name1,
7389
                 size_t len1, const oid * in_name2, size_t len2)
7390
58
{
7391
58
    register int    len;
7392
58
    register const oid *name1 = in_name1;
7393
58
    register const oid *name2 = in_name2;
7394
7395
    /*
7396
     * len = minimum of len1 and len2 
7397
     */
7398
58
    if (len1 < len2)
7399
0
        len = len1;
7400
58
    else
7401
58
        len = len2;
7402
    /*
7403
     * find first non-matching OID 
7404
     */
7405
216
    while (len-- > 0) {
7406
        /*
7407
         * these must be done in separate comparisons, since
7408
         * subtracting them and using that result has problems with
7409
         * subids > 2^31. 
7410
         */
7411
196
        if (*(name1) != *(name2)) {
7412
38
            if (*(name1) < *(name2))
7413
28
                return -1;
7414
10
            return 1;
7415
38
        }
7416
158
        name1++;
7417
158
        name2++;
7418
158
    }
7419
    /*
7420
     * both OIDs equal up to length of shorter OID 
7421
     */
7422
20
    if (len1 < len2)
7423
0
        return -1;
7424
20
    if (len2 < len1)
7425
0
        return 1;
7426
20
    return 0;
7427
20
}
7428
7429
/**
7430
 * Lexicographically compare two object identifiers.
7431
 *
7432
 * @param[in] in_name1 Left hand side OID.
7433
 * @param[in] len1     Length of LHS OID.
7434
 * @param[in] in_name2 Right hand side OID.
7435
 * @param[in] len2     Length of RHS OID.
7436
 * @param[out] offpt   First offset at which the two OIDs differ.
7437
 * 
7438
 * Caution: this method is called often by command responder applications (i.e.,
7439
 * agent).
7440
 *
7441
 * @return -1 if name1 < name2, 0 if name1 = name2, 1 if name1 > name2 and
7442
 * offpt = len where name1 != name2
7443
 */
7444
int
7445
netsnmp_oid_compare_ll(const oid * in_name1, size_t len1, const oid * in_name2,
7446
                       size_t len2, size_t *offpt)
7447
42
{
7448
42
    register int    len;
7449
42
    register const oid *name1 = in_name1;
7450
42
    register const oid *name2 = in_name2;
7451
42
    int initlen;
7452
7453
    /*
7454
     * len = minimum of len1 and len2 
7455
     */
7456
42
    if (len1 < len2)
7457
0
        initlen = len = len1;
7458
42
    else
7459
42
        initlen = len = len2;
7460
    /*
7461
     * find first non-matching OID 
7462
     */
7463
48
    while (len-- > 0) {
7464
        /*
7465
         * these must be done in separate comparisons, since
7466
         * subtracting them and using that result has problems with
7467
         * subids > 2^31. 
7468
         */
7469
42
        if (*(name1) != *(name2)) {
7470
36
            *offpt = initlen - len;
7471
36
            if (*(name1) < *(name2))
7472
12
                return -1;
7473
24
            return 1;
7474
36
        }
7475
6
        name1++;
7476
6
        name2++;
7477
6
    }
7478
    /*
7479
     * both OIDs equal up to length of shorter OID 
7480
     */
7481
6
    *offpt = initlen - len;
7482
6
    if (len1 < len2)
7483
0
        return -1;
7484
6
    if (len2 < len1)
7485
0
        return 1;
7486
6
    return 0;
7487
6
}
7488
7489
/** Compares 2 OIDs to determine if they are equal up until the shortest length.
7490
 * @param in_name1 A pointer to the first oid.
7491
 * @param len1     length of the first OID (in segments, not bytes)
7492
 * @param in_name2 A pointer to the second oid.
7493
 * @param len2     length of the second OID (in segments, not bytes)
7494
 * @return 0 if they are equal, 1 if in_name1 is > in_name2, or -1 if <.
7495
 */ 
7496
int
7497
snmp_oidtree_compare(const oid * in_name1,
7498
                     size_t len1, const oid * in_name2, size_t len2)
7499
0
{
7500
0
    int len = len1 < len2 ? len1 : len2;
7501
7502
0
    return snmp_oid_compare(in_name1, len, in_name2, len);
7503
0
}
7504
7505
int
7506
snmp_oidsubtree_compare(const oid * in_name1,
7507
                     size_t len1, const oid * in_name2, size_t len2)
7508
0
{
7509
0
    int len = len1 < len2 ? len1 : len2;
7510
7511
0
    return snmp_oid_compare(in_name1, len1, in_name2, len);
7512
0
}
7513
7514
/** Compares 2 OIDs to determine if they are exactly equal.
7515
 *  This should be faster than doing a snmp_oid_compare for different
7516
 *  length OIDs, since the length is checked first and if != returns
7517
 *  immediately.  Might be very slightly faster if lengths are ==.
7518
 * @param in_name1 A pointer to the first oid.
7519
 * @param len1     length of the first OID (in segments, not bytes)
7520
 * @param in_name2 A pointer to the second oid.
7521
 * @param len2     length of the second OID (in segments, not bytes)
7522
 * @return 0 if they are equal, 1 if they are not.
7523
 */ 
7524
int
7525
netsnmp_oid_equals(const oid * in_name1,
7526
                   size_t len1, const oid * in_name2, size_t len2)
7527
138
{
7528
138
    register const oid *name1 = in_name1;
7529
138
    register const oid *name2 = in_name2;
7530
138
    register int    len = len1;
7531
7532
    /*
7533
     * len = minimum of len1 and len2 
7534
     */
7535
138
    if (len1 != len2)
7536
88
        return 1;
7537
    /*
7538
     * Handle 'null' OIDs
7539
     */
7540
50
    if (len1 == 0)
7541
0
        return 0;   /* Two null OIDs are (trivially) the same */
7542
50
    if (!name1 || !name2)
7543
0
        return 1;   /* Otherwise something's wrong, so report a non-match */
7544
    /*
7545
     * find first non-matching OID 
7546
     */
7547
386
    while (len-- > 0) {
7548
        /*
7549
         * these must be done in separate comparisons, since
7550
         * subtracting them and using that result has problems with
7551
         * subids > 2^31. 
7552
         */
7553
380
        if (*(name1++) != *(name2++))
7554
44
            return 1;
7555
380
    }
7556
6
    return 0;
7557
50
}
7558
7559
#ifndef NETSNMP_FEATURE_REMOVE_OID_IS_SUBTREE
7560
/** Identical to netsnmp_oid_equals, except only the length up to len1 is compared.
7561
 * Functionally, this determines if in_name2 is equal or a subtree of in_name1
7562
 * @param in_name1 A pointer to the first oid.
7563
 * @param len1     length of the first OID (in segments, not bytes)
7564
 * @param in_name2 A pointer to the second oid.
7565
 * @param len2     length of the second OID (in segments, not bytes)
7566
 * @return 0 if one is a common prefix of the other.
7567
 */ 
7568
int
7569
netsnmp_oid_is_subtree(const oid * in_name1,
7570
                       size_t len1, const oid * in_name2, size_t len2)
7571
0
{
7572
0
    if (len1 > len2)
7573
0
        return 1;
7574
7575
0
    if (memcmp(in_name1, in_name2, len1 * sizeof(oid)))
7576
0
        return 1;
7577
7578
0
    return 0;
7579
0
}
7580
#endif /* NETSNMP_FEATURE_REMOVE_OID_IS_SUBTREE */
7581
7582
/** Given two OIDs, determine the common prefix to them both.
7583
 * @param in_name1 A pointer to the first oid.
7584
 * @param len1     Length of the first oid.
7585
 * @param in_name2 A pointer to the second oid.
7586
 * @param len2     Length of the second oid.
7587
 * @return         length of common prefix
7588
 *                 0 if no common prefix, -1 on error.
7589
 */
7590
int
7591
netsnmp_oid_find_prefix(const oid * in_name1, size_t len1,
7592
                        const oid * in_name2, size_t len2)
7593
0
{
7594
0
    int i;
7595
0
    size_t min_size;
7596
7597
0
    if (!in_name1 || !in_name2 || !len1 || !len2)
7598
0
        return -1;
7599
7600
0
    if (in_name1[0] != in_name2[0])
7601
0
        return 0;   /* No match */
7602
0
    min_size = SNMP_MIN(len1, len2);
7603
0
    for(i = 0; i < (int)min_size; i++) {
7604
0
        if (in_name1[i] != in_name2[i])
7605
0
            return i;    /* 'i' is the first differing subidentifier
7606
                            So the common prefix is 0..(i-1), of length i */
7607
0
    }
7608
0
    return min_size; /* The shorter OID is a prefix of the longer, and
7609
                           hence is precisely the common prefix of the two.
7610
                           Return its length. */
7611
0
}
7612
7613
#ifndef NETSNMP_DISABLE_MIB_LOADING
7614
static int _check_range(struct tree *tp, long ltmp, int *resptr,
7615
                  const char *errmsg)
7616
0
{
7617
0
    char *cp   = NULL;
7618
0
    char *temp = NULL;
7619
0
    int   temp_len = 0;
7620
0
    size_t temp_sz = 0;
7621
0
    int check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7622
0
                                  NETSNMP_DS_LIB_DONT_CHECK_RANGE);
7623
  
7624
0
    if (check && tp && tp->ranges) {
7625
0
  struct range_list *rp = tp->ranges;
7626
0
  while (rp) {
7627
0
      if (rp->low <= ltmp && ltmp <= rp->high) break;
7628
                                  /* Allow four digits per range value */
7629
0
            temp_len += ((rp->low != rp->high) ? 27 : 15 );
7630
0
      rp = rp->next;
7631
0
  }
7632
0
  if (!rp) {
7633
0
      *resptr = SNMPERR_RANGE;
7634
0
            temp_sz = temp_len + strlen(errmsg) + 7;
7635
0
            temp = (char *)malloc(temp_sz);
7636
0
            if ( temp ) {
7637
                /* Append the Display Hint range information to the error message */
7638
0
                snprintf( temp, temp_sz, "%s :: {", errmsg );
7639
0
                cp = temp+(strlen(temp));
7640
0
                for ( rp = tp->ranges; rp; rp=rp->next ) {
7641
0
                    if ( rp->low != rp->high ) 
7642
0
                        snprintf( cp, temp_sz - (cp - temp), "(%d..%d), ", rp->low, rp->high );
7643
0
                    else
7644
0
                        snprintf( cp, temp_sz - (cp - temp), "(%d), ", rp->low );
7645
0
                    cp += strlen(cp);
7646
0
                }
7647
0
                *(cp-2) = '}';   /* Replace the final comma with a '}' */
7648
0
                *(cp-1) = 0;
7649
0
          snmp_set_detail(temp);
7650
0
          free(temp);
7651
0
            }
7652
0
      return 0;
7653
0
  }
7654
0
    }
7655
0
    free(temp);
7656
0
    return 1;
7657
0
}
7658
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7659
7660
/*
7661
 * Add a variable with the requested name to the end of the list of
7662
 * variables for this pdu.
7663
 */
7664
netsnmp_variable_list *
7665
snmp_pdu_add_variable(netsnmp_pdu *pdu,
7666
                      const oid * name,
7667
                      size_t name_length,
7668
                      u_char type, const void * value, size_t len)
7669
195k
{
7670
195k
    return snmp_varlist_add_variable(&pdu->variables, name, name_length,
7671
195k
                                     type, value, len);
7672
195k
}
7673
7674
/*
7675
 * Add a variable with the requested name to the end of the list of
7676
 * variables for this pdu.
7677
 */
7678
netsnmp_variable_list *
7679
snmp_varlist_add_variable(netsnmp_variable_list ** varlist,
7680
                          const oid * name,
7681
                          size_t name_length,
7682
                          u_char type, const void * value, size_t len)
7683
195k
{
7684
195k
    netsnmp_variable_list *vars, *vtmp;
7685
195k
    int rc;
7686
7687
195k
    if (varlist == NULL)
7688
0
        return NULL;
7689
7690
195k
    vars = SNMP_MALLOC_TYPEDEF(netsnmp_variable_list);
7691
195k
    if (vars == NULL)
7692
0
        return NULL;
7693
7694
195k
    vars->type = type;
7695
7696
195k
    rc = snmp_set_var_value( vars, value, len );
7697
195k
    if (( 0 != rc ) ||
7698
195k
        (name != NULL && snmp_set_var_objid(vars, name, name_length))) {
7699
0
        snmp_free_var(vars);
7700
0
        return NULL;
7701
0
    }
7702
7703
    /*
7704
     * put only qualified variable onto varlist 
7705
     */
7706
195k
    if (*varlist == NULL) {
7707
65.0k
        *varlist = vars;
7708
130k
    } else {
7709
175M
        for (vtmp = *varlist; vtmp->next_variable;
7710
175M
             vtmp = vtmp->next_variable);
7711
7712
130k
        vtmp->next_variable = vars;
7713
130k
    }
7714
7715
195k
    return vars;
7716
195k
}
7717
7718
/*
7719
 * BITS values are encoded as an OCTET STRING and the size of an OCTET STRING
7720
 * is limited to 65535 octets (RFC 2578, section 7.1.2).
7721
 */
7722
0
#define NETSNMP_MAX_BITS_OCTETS 65535
7723
7724
/*
7725
 * Make sure that the BITS buffer *buf is at least @needed bytes large and
7726
 * zero-initialize any newly allocated bytes. Grow the buffer geometrically
7727
 * to avoid quadratic behavior. Returns 1 upon success and 0 upon failure.
7728
 */
7729
static int
7730
_bits_buf_grow(u_char **buf, size_t *buf_len, size_t needed)
7731
0
{
7732
0
    u_char         *new_buf;
7733
0
    size_t          new_len;
7734
7735
0
    if (needed <= *buf_len)
7736
0
        return 1;
7737
0
    if (needed > NETSNMP_MAX_BITS_OCTETS)
7738
0
        return 0;
7739
0
    new_len = *buf_len * 2;
7740
0
    if (new_len < needed)
7741
0
        new_len = needed;
7742
0
    if (new_len > NETSNMP_MAX_BITS_OCTETS)
7743
0
        new_len = NETSNMP_MAX_BITS_OCTETS;
7744
0
    new_buf = realloc(*buf, new_len);
7745
0
    if (!new_buf)
7746
0
        return 0;
7747
0
    memset(new_buf + *buf_len, 0, new_len - *buf_len);
7748
0
    *buf = new_buf;
7749
0
    *buf_len = new_len;
7750
0
    return 1;
7751
0
}
7752
7753
/*
7754
 * Add a variable with the requested name to the end of the list of
7755
 * variables for this pdu.
7756
 * Returns:
7757
 * may set these error types :
7758
 * SNMPERR_RANGE - type, value, or length not found or out of range
7759
 * SNMPERR_VALUE - value is not correct
7760
 * SNMPERR_VAR_TYPE - type is not correct
7761
 * SNMPERR_BAD_NAME - name is not found
7762
 *
7763
 * returns 0 if success, error if failure.
7764
 */
7765
int
7766
snmp_add_var(netsnmp_pdu *pdu,
7767
             const oid * name, size_t name_length, char type, const char *value)
7768
0
{
7769
0
    char           *st;
7770
0
    const char     *cp;
7771
0
    char           *ecp, *vp = NULL;
7772
0
    int             result = SNMPERR_SUCCESS;
7773
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7774
0
    int             check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7775
0
               NETSNMP_DS_LIB_DONT_CHECK_RANGE);
7776
0
    int             do_hint = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7777
0
               NETSNMP_DS_LIB_NO_DISPLAY_HINT);
7778
0
    u_char         *hintptr;
7779
0
    struct tree    *tp;
7780
0
    struct enum_list *ep;
7781
0
    int             itmp;
7782
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7783
0
    u_char         *buf = NULL;
7784
0
    const u_char   *buf_ptr = NULL;
7785
0
    size_t          buf_len = 0, value_len = 0, tint;
7786
0
    in_addr_t       atmp;
7787
0
    long            ltmp;
7788
0
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
7789
0
    double          dtmp;
7790
0
    float           ftmp;
7791
0
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
7792
0
    struct counter64 c64tmp;
7793
7794
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7795
0
    tp = get_tree(name, name_length, get_tree_head());
7796
0
    if (!tp || !tp->type || tp->type > TYPE_SIMPLE_LAST) {
7797
0
        check = 0;
7798
0
    }
7799
0
    if (!(tp && tp->hint))
7800
0
  do_hint = 0;
7801
7802
0
    if (tp && type == '=') {
7803
        /*
7804
         * generic assignment - let the tree node decide value format 
7805
         */
7806
0
        switch (tp->type) {
7807
0
        case TYPE_INTEGER:
7808
0
        case TYPE_INTEGER32:
7809
0
            type = 'i';
7810
0
            break;
7811
0
        case TYPE_GAUGE:
7812
0
        case TYPE_UNSIGNED32:
7813
0
            type = 'u';
7814
0
            break;
7815
0
        case TYPE_UINTEGER:
7816
0
            type = '3';
7817
0
            break;
7818
0
        case TYPE_COUNTER:
7819
0
            type = 'c';
7820
0
            break;
7821
0
        case TYPE_COUNTER64:
7822
0
            type = 'C';
7823
0
            break;
7824
0
        case TYPE_TIMETICKS:
7825
0
            type = 't';
7826
0
            break;
7827
0
        case TYPE_OCTETSTR:
7828
0
            type = 's';
7829
0
            break;
7830
0
        case TYPE_BITSTRING:
7831
0
            type = 'b';
7832
0
            break;
7833
0
        case TYPE_IPADDR:
7834
0
            type = 'a';
7835
0
            break;
7836
0
        case TYPE_OBJID:
7837
0
            type = 'o';
7838
0
            break;
7839
0
        }
7840
0
    }
7841
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7842
7843
0
    switch (type) {
7844
0
    case 'i':
7845
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7846
0
        if (check && tp->type != TYPE_INTEGER
7847
0
            && tp->type != TYPE_INTEGER32) {
7848
0
            value = "INTEGER";
7849
0
            result = SNMPERR_VALUE;
7850
0
            goto type_error;
7851
0
        }
7852
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7853
0
        if (!*value)
7854
0
            goto value_error;
7855
0
        ltmp = strtol(value, &ecp, 10);
7856
0
        if (*ecp) {
7857
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7858
0
            ep = tp ? tp->enums : NULL;
7859
0
            while (ep) {
7860
0
                if (strcmp(value, ep->label) == 0) {
7861
0
                    ltmp = ep->value;
7862
0
                    break;
7863
0
                }
7864
0
                ep = ep->next;
7865
0
            }
7866
0
            if (!ep) {
7867
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7868
0
                result = SNMPERR_RANGE;   /* ?? or SNMPERR_VALUE; */
7869
0
                snmp_set_detail(value);
7870
0
                break;
7871
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7872
0
            }
7873
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7874
0
        }
7875
7876
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7877
0
        if (!_check_range(tp, ltmp, &result, value))
7878
0
            break;
7879
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7880
0
        snmp_pdu_add_variable(pdu, name, name_length, ASN_INTEGER,
7881
0
                              &ltmp, sizeof(ltmp));
7882
0
        break;
7883
7884
0
    case 'u':
7885
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7886
0
        if (check && tp->type != TYPE_GAUGE && tp->type != TYPE_UNSIGNED32) {
7887
0
            value = "Unsigned32";
7888
0
            result = SNMPERR_VALUE;
7889
0
            goto type_error;
7890
0
        }
7891
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7892
0
        ltmp = strtoul(value, &ecp, 10);
7893
0
        if (*value && !*ecp)
7894
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_UNSIGNED,
7895
0
                                  &ltmp, sizeof(ltmp));
7896
0
        else
7897
0
            goto value_error;
7898
0
        break;
7899
7900
0
    case '3':
7901
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7902
0
        if (check && tp->type != TYPE_UINTEGER) {
7903
0
            value = "UInteger32";
7904
0
            result = SNMPERR_VALUE;
7905
0
            goto type_error;
7906
0
        }
7907
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7908
0
        ltmp = strtoul(value, &ecp, 10);
7909
0
        if (*value && !*ecp)
7910
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_UINTEGER,
7911
0
                                  &ltmp, sizeof(ltmp));
7912
0
        else
7913
0
            goto value_error;
7914
0
        break;
7915
7916
0
    case 'c':
7917
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7918
0
        if (check && tp->type != TYPE_COUNTER) {
7919
0
            value = "Counter32";
7920
0
            result = SNMPERR_VALUE;
7921
0
            goto type_error;
7922
0
        }
7923
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7924
0
        ltmp = strtoul(value, &ecp, 10);
7925
0
        if (*value && !*ecp)
7926
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_COUNTER,
7927
0
                                  &ltmp, sizeof(ltmp));
7928
0
        else
7929
0
            goto value_error;
7930
0
        break;
7931
7932
0
    case 'C':
7933
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7934
0
        if (check && tp->type != TYPE_COUNTER64) {
7935
0
            value = "Counter64";
7936
0
            result = SNMPERR_VALUE;
7937
0
            goto type_error;
7938
0
        }
7939
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7940
0
        if (read64(&c64tmp, value))
7941
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_COUNTER64,
7942
0
                                  &c64tmp, sizeof(c64tmp));
7943
0
        else
7944
0
            goto value_error;
7945
0
        break;
7946
7947
0
    case 't':
7948
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7949
0
        if (check && tp->type != TYPE_TIMETICKS) {
7950
0
            value = "Timeticks";
7951
0
            result = SNMPERR_VALUE;
7952
0
            goto type_error;
7953
0
        }
7954
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7955
0
        ltmp = strtoul(value, &ecp, 10);
7956
0
        if (*value && !*ecp)
7957
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_TIMETICKS,
7958
0
                                  &ltmp, sizeof(long));
7959
0
        else
7960
0
            goto value_error;
7961
0
        break;
7962
7963
0
    case 'a':
7964
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7965
0
        if (check && tp->type != TYPE_IPADDR) {
7966
0
            value = "IpAddress";
7967
0
            result = SNMPERR_VALUE;
7968
0
            goto type_error;
7969
0
        }
7970
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7971
0
        atmp = inet_addr(value);
7972
0
        if (atmp != (in_addr_t) -1 || !strcmp(value, "255.255.255.255"))
7973
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_IPADDRESS,
7974
0
                                  &atmp, sizeof(atmp));
7975
0
        else
7976
0
            goto value_error;
7977
0
        break;
7978
7979
0
    case 'o':
7980
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
7981
0
        if (check && tp->type != TYPE_OBJID) {
7982
0
            value = "OBJECT IDENTIFIER";
7983
0
            result = SNMPERR_VALUE;
7984
0
            goto type_error;
7985
0
        }
7986
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7987
0
        buf = malloc(sizeof(oid) * MAX_OID_LEN);
7988
0
        if (buf == NULL) {
7989
0
            result = SNMPERR_MALLOC;
7990
0
            break;
7991
0
        }
7992
0
        tint = MAX_OID_LEN;
7993
0
        if (snmp_parse_oid(value, (oid *) buf, &tint)) {
7994
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OBJECT_ID,
7995
0
                                  buf, sizeof(oid) * tint);
7996
0
        } else {
7997
0
            result = snmp_errno;    /*MTCRITICAL_RESOURCE */
7998
0
        }
7999
0
        break;
8000
8001
0
    case 's':
8002
0
    case 'x':
8003
0
    case 'd':
8004
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8005
0
        if (check && tp->type != TYPE_OCTETSTR && tp->type != TYPE_BITSTRING) {
8006
0
            value = "OCTET STRING";
8007
0
            result = SNMPERR_VALUE;
8008
0
            goto type_error;
8009
0
        }
8010
0
  if ('s' == type && do_hint && !parse_octet_hint(tp->hint, value, &hintptr, &itmp)) {
8011
0
            if (_check_range(tp, itmp, &result, "Value does not match DISPLAY-HINT")) {
8012
0
                snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
8013
0
                                      hintptr, itmp);
8014
0
            }
8015
0
            SNMP_FREE(hintptr);
8016
0
            hintptr = buf;
8017
0
            break;
8018
0
        }
8019
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8020
0
        if (type == 'd') {
8021
0
            if (!snmp_decimal_to_binary
8022
0
                (&buf, &buf_len, &value_len, 1, value)) {
8023
0
                result = SNMPERR_VALUE;
8024
0
                snmp_set_detail(value);
8025
0
                break;
8026
0
            }
8027
0
            buf_ptr = buf;
8028
0
        } else if (type == 'x') {
8029
0
            if (!snmp_hex_to_binary(&buf, &buf_len, &value_len, 1, value)) {
8030
0
                result = SNMPERR_VALUE;
8031
0
                snmp_set_detail(value);
8032
0
                break;
8033
0
            }
8034
0
            buf_ptr = buf;
8035
0
        } else if (type == 's') {
8036
0
            buf_ptr = (const u_char *)value;
8037
0
            value_len = strlen(value);
8038
0
        }
8039
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8040
0
        if (!_check_range(tp, value_len, &result, "Bad string length"))
8041
0
            break;
8042
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8043
0
        snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
8044
0
                              buf_ptr, value_len);
8045
0
        break;
8046
8047
0
    case 'n':
8048
0
        snmp_pdu_add_variable(pdu, name, name_length, ASN_NULL, NULL, 0);
8049
0
        break;
8050
8051
0
    case 'b':
8052
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8053
0
        if (check && (tp->type != TYPE_BITSTRING || !tp->enums)) {
8054
0
            value = "BITS";
8055
0
            result = SNMPERR_VALUE;
8056
0
            goto type_error;
8057
0
        }
8058
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8059
0
        tint = 0;
8060
0
        buf_len = 256;
8061
0
        buf = calloc(1, buf_len);
8062
0
        if (buf == NULL) {
8063
0
            result = SNMPERR_MALLOC;
8064
0
            break;
8065
0
        }
8066
8067
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8068
0
        for (ep = tp ? tp->enums : NULL; ep; ep = ep->next) {
8069
0
            if (ep->value / 8 >= (int) tint) {
8070
0
                tint = ep->value / 8 + 1;
8071
0
            }
8072
0
        }
8073
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8074
0
        if (tint > NETSNMP_MAX_BITS_OCTETS) {
8075
0
            result = SNMPERR_RANGE;
8076
0
            snmp_set_detail(value);
8077
0
            goto err;
8078
0
        }
8079
0
        if (!_bits_buf_grow(&buf, &buf_len, tint)) {
8080
0
            result = SNMPERR_MALLOC;
8081
0
            goto err;
8082
0
        }
8083
8084
0
  vp = strdup(value);
8085
0
        if (!vp)
8086
0
            goto value_error;
8087
8088
0
  for (cp = strtok_r(vp, " ,\t", &st); cp; cp = strtok_r(NULL, " ,\t", &st)) {
8089
0
            int             ix, bit;
8090
8091
0
            ltmp = strtoul(cp, &ecp, 0);
8092
0
            if (ltmp < 0) {
8093
0
                result = SNMPERR_VALUE;
8094
0
                snmp_set_detail(cp);
8095
0
                goto err;
8096
0
            }
8097
0
            if (*ecp != 0) {
8098
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8099
0
                for (ep = tp ? tp->enums : NULL; ep != NULL; ep = ep->next) {
8100
0
                    if (strcmp(ep->label, cp) == 0) {
8101
0
                        break;
8102
0
                    }
8103
0
                }
8104
0
                if (ep != NULL) {
8105
0
                    ltmp = ep->value;
8106
0
                } else {
8107
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8108
0
                    result = SNMPERR_RANGE;   /* ?? or SNMPERR_VALUE; */
8109
0
                    snmp_set_detail(cp);
8110
0
                    goto err;
8111
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8112
0
                }
8113
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8114
0
            }
8115
8116
0
            if (ltmp < 0 || ltmp / 8 >= NETSNMP_MAX_BITS_OCTETS) {
8117
0
                result = SNMPERR_RANGE;
8118
0
                snmp_set_detail(cp);
8119
0
                goto err;
8120
0
            }
8121
0
            ix = ltmp / 8;
8122
0
            if (ix >= (int) tint) {
8123
0
                tint = ix + 1;
8124
0
            }
8125
0
            if (!_bits_buf_grow(&buf, &buf_len, ix + 1)) {
8126
0
                result = SNMPERR_MALLOC;
8127
0
                goto err;
8128
0
            }
8129
0
            bit = 0x80 >> ltmp % 8;
8130
0
            buf[ix] |= bit;
8131
      
8132
0
        }
8133
0
  SNMP_FREE(vp);
8134
0
        snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
8135
0
                              buf, tint);
8136
0
        break;
8137
8138
0
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
8139
0
    case 'U':
8140
0
        if (read64(&c64tmp, value))
8141
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_U64,
8142
0
                                  &c64tmp, sizeof(c64tmp));
8143
0
        else
8144
0
            goto value_error;
8145
0
        break;
8146
8147
0
    case 'I':
8148
0
        if (read64(&c64tmp, value))
8149
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_I64,
8150
0
                                  &c64tmp, sizeof(c64tmp));
8151
0
        else
8152
0
            goto value_error;
8153
0
        break;
8154
8155
0
    case 'F':
8156
0
        if (sscanf(value, "%f", &ftmp) == 1)
8157
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_FLOAT,
8158
0
                                  &ftmp, sizeof(ftmp));
8159
0
        else
8160
0
            goto value_error;
8161
0
        break;
8162
8163
0
    case 'D':
8164
0
        if (sscanf(value, "%lf", &dtmp) == 1)
8165
0
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_DOUBLE,
8166
0
                                  &dtmp, sizeof(dtmp));
8167
0
        else
8168
0
            goto value_error;
8169
0
        break;
8170
0
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
8171
8172
0
    default:
8173
0
        result = SNMPERR_VAR_TYPE;
8174
0
  buf = calloc(1, 4);
8175
0
  if (buf != NULL) {
8176
0
      snprintf((char *)buf, 4, "\"%c\"", type);
8177
0
      snmp_set_detail((char *)buf);
8178
0
  }
8179
0
        break;
8180
0
    }
8181
8182
0
    SNMP_FREE(buf);
8183
0
    SET_SNMP_ERROR(result);
8184
0
    return result;
8185
8186
0
#ifndef NETSNMP_DISABLE_MIB_LOADING
8187
0
  type_error:
8188
0
    {
8189
0
        char            error_msg[256];
8190
0
        char            undef_msg[32];
8191
0
        const char     *var_type;
8192
0
        switch (tp->type) {
8193
0
        case TYPE_OBJID:
8194
0
            var_type = "OBJECT IDENTIFIER";
8195
0
            break;
8196
0
        case TYPE_OCTETSTR:
8197
0
            var_type = "OCTET STRING";
8198
0
            break;
8199
0
        case TYPE_INTEGER:
8200
0
            var_type = "INTEGER";
8201
0
            break;
8202
0
        case TYPE_NETADDR:
8203
0
            var_type = "NetworkAddress";
8204
0
            break;
8205
0
        case TYPE_IPADDR:
8206
0
            var_type = "IpAddress";
8207
0
            break;
8208
0
        case TYPE_COUNTER:
8209
0
            var_type = "Counter32";
8210
0
            break;
8211
0
        case TYPE_GAUGE:
8212
0
            var_type = "Gauge32";
8213
0
            break;
8214
0
        case TYPE_TIMETICKS:
8215
0
            var_type = "Timeticks";
8216
0
            break;
8217
0
        case TYPE_OPAQUE:
8218
0
            var_type = "Opaque";
8219
0
            break;
8220
0
        case TYPE_NULL:
8221
0
            var_type = "Null";
8222
0
            break;
8223
0
        case TYPE_COUNTER64:
8224
0
            var_type = "Counter64";
8225
0
            break;
8226
0
        case TYPE_BITSTRING:
8227
0
            var_type = "BITS";
8228
0
            break;
8229
0
        case TYPE_NSAPADDRESS:
8230
0
            var_type = "NsapAddress";
8231
0
            break;
8232
0
        case TYPE_UINTEGER:
8233
0
            var_type = "UInteger";
8234
0
            break;
8235
0
        case TYPE_UNSIGNED32:
8236
0
            var_type = "Unsigned32";
8237
0
            break;
8238
0
        case TYPE_INTEGER32:
8239
0
            var_type = "Integer32";
8240
0
            break;
8241
0
        default:
8242
0
            snprintf(undef_msg, sizeof(undef_msg), "TYPE_%d", tp->type);
8243
0
            var_type = undef_msg;
8244
0
        }
8245
0
        snprintf(error_msg, sizeof(error_msg),
8246
0
                 "Type of attribute is %s, not %s", var_type, value);
8247
0
        result = SNMPERR_VAR_TYPE;
8248
0
        snmp_set_detail(error_msg);
8249
0
        goto out;
8250
0
    }
8251
0
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8252
8253
0
value_error:
8254
0
    result = SNMPERR_VALUE;
8255
0
    snmp_set_detail(value);
8256
8257
0
err:
8258
0
    free(buf);
8259
0
    free(vp);
8260
8261
0
out:
8262
0
    SET_SNMP_ERROR(result);
8263
0
    return result;
8264
0
}
8265
8266
/*
8267
 * returns NULL or internal pointer to session
8268
 * use this pointer for the other snmp_sess* routines,
8269
 * which guarantee action will occur ONLY for this given session.
8270
 */
8271
struct session_list *
8272
snmp_sess_pointer(netsnmp_session * session)
8273
75.8k
{
8274
75.8k
    struct session_list *slp;
8275
8276
75.8k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
8277
75.8k
    for (slp = Sessions; slp; slp = slp->next) {
8278
75.8k
        if (slp->session == session) {
8279
75.8k
            break;
8280
75.8k
        }
8281
75.8k
    }
8282
75.8k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
8283
8284
75.8k
    if (slp == NULL) {
8285
0
        snmp_errno = SNMPERR_BAD_SESSION;       /*MTCRITICAL_RESOURCE */
8286
0
        return (NULL);
8287
0
    }
8288
75.8k
    return slp;
8289
75.8k
}
8290
8291
/*
8292
 * Input : an opaque pointer, returned by snmp_sess_open.
8293
 * returns NULL or pointer to session.
8294
 */
8295
netsnmp_session *
8296
snmp_sess_session(struct session_list *slp)
8297
0
{
8298
0
    if (slp == NULL)
8299
0
        return (NULL);
8300
0
    return (slp->session);
8301
0
}
8302
8303
/**
8304
 * Look up a session that already may have been closed.
8305
 *
8306
 * @param sessp Opaque pointer, returned by snmp_sess_open.
8307
 *
8308
 * @return Pointer to session upon success or NULL upon failure.
8309
 *
8310
 * @see snmp_sess_session()
8311
 */
8312
netsnmp_session *
8313
snmp_sess_session_lookup(struct session_list *sessp)
8314
0
{
8315
0
    struct session_list *slp;
8316
8317
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
8318
0
    for (slp = Sessions; slp; slp = slp->next) {
8319
0
        if (slp == sessp) {
8320
0
            break;
8321
0
        }
8322
0
    }
8323
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
8324
8325
0
    return (netsnmp_session *)slp;
8326
0
}
8327
8328
8329
/*
8330
 * returns NULL or internal pointer to session
8331
 * use this pointer for the other snmp_sess* routines,
8332
 * which guarantee action will occur ONLY for this given session.
8333
 */
8334
netsnmp_session *
8335
snmp_sess_lookup_by_name(const char *paramName)
8336
0
{
8337
0
    struct session_list *slp;
8338
8339
0
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
8340
0
    for (slp = Sessions; slp; slp = slp->next) {
8341
0
        if (NULL == slp->session->paramName)
8342
0
            continue;
8343
0
        if (strcmp(paramName, slp->session->paramName)  == 0)
8344
0
            break;
8345
0
    }
8346
0
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
8347
8348
0
    if (slp == NULL)
8349
0
        return NULL;
8350
8351
0
    return slp->session;
8352
0
}
8353
8354
8355
/*
8356
 * snmp_sess_transport: takes an opaque pointer (as returned by
8357
 * snmp_sess_open or snmp_sess_pointer) and returns the corresponding
8358
 * netsnmp_transport pointer (or NULL if the opaque pointer does not correspond
8359
 * to an active internal session).  
8360
 */
8361
8362
netsnmp_transport *
8363
snmp_sess_transport(struct session_list *slp)
8364
0
{
8365
0
    if (slp == NULL) {
8366
0
        return NULL;
8367
0
    } else {
8368
0
        return slp->transport;
8369
0
    }
8370
0
}
8371
8372
8373
8374
/*
8375
 * snmp_sess_transport_set: set the transport pointer for the
8376
 * session pointer slp.
8377
 */
8378
8379
void
8380
snmp_sess_transport_set(struct session_list *slp, netsnmp_transport *t)
8381
0
{
8382
0
    if (slp != NULL) {
8383
0
        slp->transport = t;
8384
0
    }
8385
0
}
8386
8387
8388
/*
8389
 * snmp_duplicate_objid: duplicates (mallocs) an objid based on the
8390
 * input objid 
8391
 */
8392
oid            *
8393
snmp_duplicate_objid(const oid * objToCopy, size_t objToCopyLen)
8394
40.6k
{
8395
40.6k
    oid            *returnOid;
8396
40.6k
    if (objToCopy != NULL && objToCopyLen != 0) {
8397
40.6k
        returnOid = (oid *) malloc(objToCopyLen * sizeof(oid));
8398
40.6k
        if (returnOid) {
8399
40.6k
            memcpy(returnOid, objToCopy, objToCopyLen * sizeof(oid));
8400
40.6k
        }
8401
40.6k
    } else
8402
0
        returnOid = NULL;
8403
40.6k
    return returnOid;
8404
40.6k
}
8405
8406
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
8407
/*
8408
 * generic statistics counter functions 
8409
 */
8410
static u_int    statistics[NETSNMP_STAT_MAX_STATS];
8411
8412
u_int
8413
snmp_increment_statistic(int which)
8414
0
{
8415
0
    if (which >= 0 && which < NETSNMP_STAT_MAX_STATS) {
8416
0
        statistics[which]++;
8417
0
        return statistics[which];
8418
0
    }
8419
0
    return 0;
8420
0
}
8421
8422
u_int
8423
snmp_increment_statistic_by(int which, int count)
8424
0
{
8425
0
    if (which >= 0 && which < NETSNMP_STAT_MAX_STATS) {
8426
0
        statistics[which] += count;
8427
0
        return statistics[which];
8428
0
    }
8429
0
    return 0;
8430
0
}
8431
8432
u_int
8433
snmp_get_statistic(int which)
8434
0
{
8435
0
    if (which >= 0 && which < NETSNMP_STAT_MAX_STATS)
8436
0
        return statistics[which];
8437
0
    return 0;
8438
0
}
8439
8440
void
8441
snmp_init_statistics(void)
8442
2
{
8443
2
    memset(statistics, 0, sizeof(statistics));
8444
2
}
8445
#endif /* NETSNMP_FEATURE_REMOVE_STATISTICS */
8446
/**  @} */