Coverage Report

Created: 2026-11-25 06:27

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
3.65k
#define DEFAULT_RETRIES     5
192
9.31k
#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
80.8k
{
374
80.8k
    u_int max = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
375
80.8k
                                   NETSNMP_DS_LIB_MSG_SEND_MAX);
376
80.8k
    if (0 == max)
377
80.7k
        max = SNMP_MAX_PACKET_LEN;
378
156
    else if (max < SNMP_MIN_MAX_LEN)
379
156
        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
80.8k
    return max;
384
80.8k
}
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
48.5k
{
402
48.5k
    static char unknown[20];
403
48.5k
    switch(type) {
404
7.24k
    case SNMP_MSG_GET:
405
7.24k
        return "GET";
406
4.45k
    case SNMP_MSG_GETNEXT:
407
4.45k
        return "GETNEXT";
408
1.70k
    case SNMP_MSG_GETBULK:
409
1.70k
        return "GETBULK";
410
0
#ifndef NETSNMP_NO_WRITE_SUPPORT
411
7.36k
    case SNMP_MSG_SET:
412
7.36k
        return "SET";
413
0
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
414
9.16k
    case SNMP_MSG_RESPONSE:
415
9.16k
        return "RESPONSE";
416
11.8k
    case SNMP_MSG_TRAP:
417
11.8k
        return "TRAP";
418
1.42k
    case SNMP_MSG_INFORM:
419
1.42k
        return "INFORM";
420
1.04k
    case SNMP_MSG_TRAP2:
421
1.04k
        return "TRAP2";
422
3.05k
    case SNMP_MSG_REPORT:
423
3.05k
        return "REPORT";
424
1.28k
    default:
425
1.28k
        snprintf(unknown, sizeof(unknown), "?0x%2X?", type);
426
1.28k
  return unknown;
427
48.5k
    }
428
48.5k
}
429
430
#define DEBUGPRINTPDUTYPE(token, type) \
431
2.09k
    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
38.0k
{
478
38.0k
    long            retVal;
479
38.0k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSIONID);
480
38.0k
    retVal = 1 + Sessid;        /*MTCRITICAL_RESOURCE */
481
38.0k
    if (!retVal)
482
0
        retVal = 2;
483
38.0k
    Sessid = retVal;
484
38.0k
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
485
0
        retVal &= 0x7fff; /* mask to 15 bits */
486
38.0k
    else
487
38.0k
        retVal &= 0x7fffffff; /* mask to 31 bits */
488
489
38.0k
    if (!retVal) {
490
0
        Sessid = retVal = 2;
491
0
    }
492
38.0k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSIONID);
493
38.0k
    return retVal;
494
38.0k
}
495
496
long
497
snmp_get_next_transid(void)
498
56.7k
{
499
56.7k
    long            retVal;
500
56.7k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_TRANSID);
501
56.7k
    retVal = 1 + Transid;       /*MTCRITICAL_RESOURCE */
502
56.7k
    if (!retVal)
503
0
        retVal = 2;
504
56.7k
    Transid = retVal;
505
56.7k
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
506
307
        retVal &= 0x7fff;  /* mask to 15 bits */
507
56.3k
    else
508
56.3k
        retVal &= 0x7fffffff; /* mask to 31 bits */
509
510
56.7k
    if (!retVal) {
511
0
        Transid = retVal = 2;
512
0
    }
513
56.7k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_TRANSID);
514
56.7k
    return retVal;
515
56.7k
}
516
517
void
518
snmp_perror(const char *prog_string)
519
30
{
520
30
    const char     *str;
521
30
    int             xerr;
522
30
    xerr = snmp_errno;          /*MTCRITICAL_RESOURCE */
523
30
    str = snmp_api_errstring(xerr);
524
30
    snmp_log(LOG_ERR, "%s: %s\n", prog_string, str);
525
30
}
526
527
void
528
snmp_set_detail(const char *detail_string)
529
112k
{
530
112k
    if (detail_string != NULL) {
531
112k
        strlcpy(snmp_detail, detail_string, sizeof(snmp_detail));
532
112k
        snmp_detail_f = 1;
533
112k
    }
534
112k
}
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
19.8k
{
545
19.8k
    const char     *msg = "";
546
19.8k
    static char     msg_buf[SPRINT_MAX_LEN];
547
548
19.8k
    if (snmp_errnumber >= SNMPERR_MAX && snmp_errnumber <= SNMPERR_GENERR) {
549
0
        msg = api_errors[-snmp_errnumber];
550
19.8k
    } else if (snmp_errnumber != SNMPERR_SUCCESS) {
551
0
        msg = NULL;
552
0
    }
553
19.8k
    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
19.8k
    } else if (snmp_detail_f) {
557
19.3k
        snprintf(msg_buf, sizeof(msg_buf), "%s (%s)", msg, snmp_detail);
558
19.3k
        msg_buf[sizeof(msg_buf)-1] = '\0';
559
19.3k
        snmp_detail_f = 0;
560
19.3k
    } else {
561
428
        strlcpy(msg_buf, msg, sizeof(msg_buf));
562
428
    }
563
564
19.8k
    return (msg_buf);
565
19.8k
}
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
27.6k
{
576
27.6k
    char            buf[SPRINT_MAX_LEN];
577
27.6k
    int             snmp_errnumber;
578
579
27.6k
    if (p_errno)
580
27.6k
        *p_errno = psess->s_errno;
581
27.6k
    if (p_snmp_errno)
582
27.6k
        *p_snmp_errno = psess->s_snmp_errno;
583
27.6k
    if (p_str == NULL)
584
0
        return;
585
586
27.6k
    strcpy(buf, "");
587
27.6k
    snmp_errnumber = psess->s_snmp_errno;
588
27.6k
    if (snmp_errnumber >= SNMPERR_MAX && snmp_errnumber <= SNMPERR_GENERR) {
589
27.6k
  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
27.6k
  else
596
27.6k
      strlcpy(buf, api_errors[-snmp_errnumber], sizeof(buf));
597
27.6k
    } 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
27.6k
    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
27.6k
    buf[sizeof(buf)-1] = '\0';
615
27.6k
    *p_str = strdup(buf);
616
27.6k
}
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
7.37k
{
653
7.37k
#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
7.37k
    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
7.37k
}
683
684
void netsnmp_srandom(unsigned int seed)
685
3.65k
{
686
3.65k
#if defined(HAVE_SRANDOM)
687
3.65k
    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
3.65k
}
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
34.5k
{
711
712
34.5k
    struct timeval  tv;
713
34.5k
    long            tmpReqid, tmpMsgid;
714
715
34.5k
    if (_init_snmp_init_done)
716
30.9k
        return;
717
3.65k
    _init_snmp_init_done = 1;
718
3.65k
    Reqid = 1;
719
720
3.65k
    snmp_res_init();            /* initialize the mt locking structures */
721
3.65k
#ifndef NETSNMP_DISABLE_MIB_LOADING
722
3.65k
    netsnmp_init_mib_internals();
723
3.65k
#endif /* NETSNMP_DISABLE_MIB_LOADING */
724
3.65k
    netsnmp_tdomain_init();
725
726
3.65k
    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
3.65k
    netsnmp_srandom((unsigned)(tv.tv_sec ^ tv.tv_usec));
735
3.65k
    tmpReqid = netsnmp_random();
736
3.65k
    tmpMsgid = netsnmp_random();
737
738
    /*
739
     * don't allow zero value to repeat init 
740
     */
741
3.65k
    if (tmpReqid == 0)
742
0
        tmpReqid = 1;
743
3.65k
    if (tmpMsgid == 0)
744
0
        tmpMsgid = 1;
745
3.65k
    Reqid = tmpReqid;
746
3.65k
    Msgid = tmpMsgid;
747
748
3.65k
    netsnmp_register_default_domain("snmp", "udp udp6");
749
3.65k
    netsnmp_register_default_domain("snmptrap", "udp udp6");
750
751
3.65k
    netsnmp_register_default_target("snmp", "udp", ":161");
752
3.65k
    netsnmp_register_default_target("snmp", "tcp", ":161");
753
3.65k
    netsnmp_register_default_target("snmp", "udp6", ":161");
754
3.65k
    netsnmp_register_default_target("snmp", "tcp6", ":161");
755
3.65k
    netsnmp_register_default_target("snmp", "dtlsudp", ":10161");
756
3.65k
    netsnmp_register_default_target("snmp", "tlstcp", ":10161");
757
3.65k
    netsnmp_register_default_target("snmp", "ipx", "/36879");
758
759
3.65k
    netsnmp_register_default_target("snmptrap", "udp", ":162");
760
3.65k
    netsnmp_register_default_target("snmptrap", "tcp", ":162");
761
3.65k
    netsnmp_register_default_target("snmptrap", "udp6", ":162");
762
3.65k
    netsnmp_register_default_target("snmptrap", "tcp6", ":162");
763
3.65k
    netsnmp_register_default_target("snmptrap", "dtlsudp", ":10162");
764
3.65k
    netsnmp_register_default_target("snmptrap", "tlstcp", ":10162");
765
3.65k
    netsnmp_register_default_target("snmptrap", "ipx", "/36880");
766
767
3.65k
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, 
768
3.65k
                       NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH, 16);
769
3.65k
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES,
770
3.65k
                       DEFAULT_RETRIES);
771
3.65k
    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
772
3.65k
         NETSNMP_DS_LIB_MIB_ERRORS, 1);
773
774
3.65k
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
775
3.65k
    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
776
3.65k
         NETSNMP_DS_LIB_REVERSE_ENCODE,
777
3.65k
         NETSNMP_DEFAULT_ASNENCODING_DIRECTION);
778
3.65k
#endif
779
3.65k
}
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
18.0k
{
789
18.0k
    _init_snmp();
790
791
    /*
792
     * initialize session to default values 
793
     */
794
795
18.0k
    memset(session, 0, sizeof(netsnmp_session));
796
18.0k
    session->timeout = SNMP_DEFAULT_TIMEOUT;
797
18.0k
    session->retries = SNMP_DEFAULT_RETRIES;
798
18.0k
    session->version = SNMP_DEFAULT_VERSION;
799
18.0k
    session->securityModel = SNMP_DEFAULT_SECMODEL;
800
18.0k
    session->rcvMsgMaxSize = netsnmp_max_send_msg_size();
801
18.0k
    session->sndMsgMaxSize = netsnmp_max_send_msg_size();
802
18.0k
    session->flags |= SNMP_FLAGS_DONT_PROBE;
803
18.0k
}
804
805
806
static void
807
register_default_handlers(void)
808
3.65k
{
809
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "dumpPacket",
810
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DUMP_PACKET);
811
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "reverseEncodeBER",
812
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REVERSE_ENCODE);
813
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "defaultPort",
814
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DEFAULT_PORT);
815
3.65k
#ifndef NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION
816
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv3",
817
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V3);
818
3.65k
#endif /* NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION */
819
3.65k
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
820
3.65k
#ifndef NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION
821
3.65k
#if !defined(NETSNMP_DISABLE_SNMPV1)
822
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv1",
823
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V1);
824
3.65k
#endif
825
3.65k
#if !defined(NETSNMP_DISABLE_SNMPV2C)
826
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv2c",
827
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V2c);
828
3.65k
#endif
829
3.65k
#endif /* NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION */
830
3.65k
    netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "defCommunity",
831
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_COMMUNITY);
832
3.65k
#endif /* !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C) */
833
3.65k
    netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "noTokenWarnings",
834
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_TOKEN_WARNINGS);
835
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noRangeCheck",
836
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE);
837
3.65k
    netsnmp_ds_register_premib(ASN_OCTET_STR, "snmp", "persistentDir",
838
3.65k
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PERSISTENT_DIR);
839
3.65k
    netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "tempFilePattern",
840
3.65k
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TEMP_FILE_PATTERN);
841
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noDisplayHint",
842
3.65k
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT);
843
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "16bitIDs",
844
3.65k
                NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS);
845
3.65k
    netsnmp_ds_register_premib(ASN_OCTET_STR, "snmp", "clientaddr",
846
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENT_ADDR);
847
3.65k
    netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "clientaddrUsesPort",
848
3.65k
                      NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENT_ADDR_USES_PORT);
849
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "serverSendBuf",
850
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SERVERSENDBUF);
851
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "serverRecvBuf",
852
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SERVERRECVBUF);
853
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "clientSendBuf",
854
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENTSENDBUF);
855
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "clientRecvBuf",
856
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENTRECVBUF);
857
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "sendMessageMaxSize",
858
3.65k
                               NETSNMP_DS_LIBRARY_ID,
859
3.65k
                               NETSNMP_DS_LIB_MSG_SEND_MAX);
860
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noPersistentLoad",
861
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_PERSISTENT_LOAD);
862
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noPersistentSave",
863
3.65k
          NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_PERSISTENT_SAVE);
864
3.65k
    netsnmp_ds_register_config(ASN_BOOLEAN, "snmp",
865
3.65k
                               "noContextEngineIDDiscovery",
866
3.65k
                               NETSNMP_DS_LIBRARY_ID,
867
3.65k
                               NETSNMP_DS_LIB_NO_DISCOVERY);
868
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "timeout",
869
3.65k
                   NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TIMEOUT);
870
3.65k
    netsnmp_ds_register_config(ASN_INTEGER, "snmp", "retries",
871
3.65k
                   NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES);
872
3.65k
    netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "outputPrecision",
873
3.65k
                               NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION);
874
875
876
3.65k
    netsnmp_register_service_handlers();
877
3.65k
}
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
10.7k
{
893
10.7k
    if (init_snmp_init_done) {
894
7.13k
        return;
895
7.13k
    }
896
897
3.65k
    init_snmp_init_done = 1;
898
899
    /*
900
     * make the type available everywhere else 
901
     */
902
3.65k
    if (type && !netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
903
3.65k
               NETSNMP_DS_LIB_APPTYPE)) {
904
65
        netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, 
905
65
            NETSNMP_DS_LIB_APPTYPE, type);
906
65
    }
907
908
3.65k
    _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
3.65k
#if defined(HAVE_SETLOCALE) && !defined(__QNX__)
917
3.65k
    setlocale(LC_CTYPE, "");
918
3.65k
#endif
919
920
3.65k
    snmp_debug_init();    /* should be done first, to turn on debugging ASAP */
921
3.65k
    netsnmp_container_init_list();
922
3.65k
    init_callbacks();
923
3.65k
    init_snmp_logging();
924
3.65k
    snmp_init_statistics();
925
3.65k
    register_mib_handlers();
926
3.65k
    register_default_handlers();
927
3.65k
    init_snmp_transport();
928
3.65k
    init_snmpv3(type);
929
3.65k
    init_snmp_alarm();
930
3.65k
    init_snmp_enum(type);
931
3.65k
    init_vacm();
932
3.65k
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL) && NETSNMP_TRANSPORT_TLSBASE_DOMAIN
933
3.65k
    netsnmp_certs_init();
934
3.65k
#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
3.65k
    read_premib_configs();
942
3.65k
#ifndef NETSNMP_DISABLE_MIB_LOADING
943
3.65k
    netsnmp_init_mib();
944
3.65k
#endif /* NETSNMP_DISABLE_MIB_LOADING */
945
946
3.65k
    read_configs();
947
948
3.65k
}                               /* 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
3.64k
{
975
3.64k
    DEBUGMSGTL(("snmp_store", "storing stuff...\n"));
976
3.64k
    snmp_save_persistent(type);
977
3.64k
    snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_STORE_DATA, NULL);
978
3.64k
    snmp_clean_persistent(type);
979
3.64k
}
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
3.64k
{
993
3.64k
    snmp_store(type);
994
3.64k
    snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SHUTDOWN, NULL);
995
3.64k
    shutdown_snmp_logging();
996
3.64k
    snmp_alarm_unregister_all();
997
3.64k
    netsnmp_query_shutdown();
998
3.64k
    snmp_close_sessions();
999
3.64k
#ifndef NETSNMP_DISABLE_MIB_LOADING
1000
3.64k
    shutdown_mib();
1001
3.64k
#endif /* NETSNMP_DISABLE_MIB_LOADING */
1002
3.64k
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL) && NETSNMP_TRANSPORT_TLSBASE_DOMAIN
1003
3.64k
    netsnmp_certs_shutdown();
1004
3.64k
#endif
1005
3.64k
#if !defined(NETSNMP_FEATURE_REMOVE_FILTER_SOURCE)
1006
3.64k
    netsnmp_transport_filter_cleanup();
1007
3.64k
#endif
1008
3.64k
    unregister_all_config_handlers();
1009
3.64k
    netsnmp_container_free_list();
1010
3.64k
    clear_sec_mod();
1011
3.64k
    clear_snmp_enum();
1012
3.64k
    netsnmp_clear_tdomain_list();
1013
3.64k
    clear_callback();
1014
3.64k
    netsnmp_ds_shutdown();
1015
3.64k
    netsnmp_clear_default_target();
1016
3.64k
    netsnmp_clear_default_domain();
1017
3.64k
    shutdown_secmod();
1018
3.64k
    shutdown_snmp_transport();
1019
3.64k
    shutdown_data_list();
1020
3.64k
    snmp_debug_shutdown();    /* should be done last */
1021
1022
3.64k
    init_snmp_init_done  = 0;
1023
3.64k
    _init_snmp_init_done = 0;
1024
3.64k
}
1025
1026
/*
1027
 * inserts session into session list
1028
 */
1029
void  snmp_session_insert(struct session_list *slp)
1030
12.9k
{
1031
12.9k
    if (NULL == slp)
1032
0
        return;
1033
1034
12.9k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
1035
12.9k
    slp->next = Sessions;
1036
12.9k
    Sessions = slp;
1037
12.9k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
1038
12.9k
}
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
12.9k
{
1108
12.9k
    struct session_list *slp;
1109
12.9k
    struct snmp_internal_session *isp;
1110
12.9k
    netsnmp_session *session;
1111
12.9k
    struct snmp_secmod_def *sptr;
1112
12.9k
    char           *cp;
1113
12.9k
    u_char         *ucp;
1114
1115
12.9k
    in_session->s_snmp_errno = 0;
1116
12.9k
    in_session->s_errno = 0;
1117
1118
    /*
1119
     * Copy session structure and link into list 
1120
     */
1121
12.9k
    slp = calloc(1, sizeof(struct session_list));
1122
12.9k
    if (slp == NULL) {
1123
0
        in_session->s_snmp_errno = SNMPERR_MALLOC;
1124
0
        return (NULL);
1125
0
    }
1126
1127
12.9k
    slp->transport = NULL;
1128
1129
12.9k
    isp = calloc(1, sizeof(struct snmp_internal_session));
1130
1131
12.9k
    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
12.9k
    slp->internal = isp;
1138
12.9k
    slp->session = netsnmp_memdup(in_session, sizeof(netsnmp_session));
1139
12.9k
    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
12.9k
    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
12.9k
    session->localname = NULL;
1151
12.9k
    session->peername = NULL;
1152
12.9k
    session->community = NULL;
1153
12.9k
    session->contextEngineID = NULL;
1154
12.9k
    session->contextName = NULL;
1155
12.9k
    session->securityEngineID = NULL;
1156
12.9k
    session->securityName = NULL;
1157
12.9k
    session->securityAuthProto = NULL;
1158
12.9k
    session->securityAuthLocalKey = NULL;
1159
12.9k
    session->securityPrivProto = NULL;
1160
12.9k
    session->securityPrivLocalKey = NULL;
1161
12.9k
    session->sessUser = NULL;
1162
12.9k
    session->paramName = NULL;
1163
12.9k
#ifndef NETSNMP_NO_TRAP_STATS
1164
12.9k
    session->trap_stats = NULL;
1165
12.9k
#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
12.9k
    if (in_session->peername != NULL) {
1173
2.90k
        session->peername =
1174
2.90k
            netsnmp_strdup_and_null((u_char*)in_session->peername,
1175
2.90k
                                    strlen(in_session->peername));
1176
2.90k
        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
2.90k
    }
1182
1183
    /*
1184
     * Fill in defaults if necessary 
1185
     */
1186
12.9k
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
1187
12.9k
    if (in_session->community_len != SNMP_DEFAULT_COMMUNITY_LEN) {
1188
0
        ucp = netsnmp_memdup(in_session->community, in_session->community_len);
1189
12.9k
    } else {
1190
12.9k
        if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
1191
12.9k
          NETSNMP_DS_LIB_COMMUNITY)) != NULL) {
1192
0
            session->community_len = strlen(cp);
1193
0
            ucp = (u_char *) strdup(cp);
1194
12.9k
        } 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
12.9k
            ucp = (u_char *) strdup("");
1200
12.9k
#endif
1201
12.9k
        }
1202
12.9k
    }
1203
1204
12.9k
    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
12.9k
    session->community = ucp;   /* replace pointer with pointer to new data */
1210
12.9k
#endif
1211
1212
12.9k
    if (session->securityLevel <= 0) {
1213
12.9k
        session->securityLevel =
1214
12.9k
            netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECLEVEL);
1215
12.9k
    }
1216
1217
12.9k
    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
12.9k
    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
12.9k
    } 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
12.9k
    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
12.9k
    } else {
1262
12.9k
        if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
1263
12.9k
                                        NETSNMP_DS_LIB_CONTEXT)) != NULL)
1264
0
            cp = strdup(cp);
1265
12.9k
        else
1266
12.9k
            cp = strdup(SNMP_DEFAULT_CONTEXT);
1267
12.9k
        if (cp == NULL) {
1268
0
            snmp_sess_close(slp);
1269
0
            return (NULL);
1270
0
        }
1271
12.9k
        session->contextName = cp;
1272
12.9k
        session->contextNameLen = strlen(cp);
1273
12.9k
    }
1274
1275
12.9k
    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
12.9k
    } else if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
1282
12.9k
             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
12.9k
    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
12.9k
    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
12.9k
    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
12.9k
    if (session->retries == SNMP_DEFAULT_RETRIES) {
1318
9.31k
        int retry = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
1319
9.31k
                                       NETSNMP_DS_LIB_RETRIES);
1320
9.31k
        if (retry < 0)
1321
0
            session->retries = DEFAULT_RETRIES;
1322
9.31k
        else
1323
9.31k
            session->retries = retry;
1324
9.31k
    }
1325
12.9k
    if (session->timeout == SNMP_DEFAULT_TIMEOUT) {
1326
9.31k
        int timeout = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
1327
9.31k
                                         NETSNMP_DS_LIB_TIMEOUT);
1328
9.31k
        if (timeout <= 0)
1329
9.31k
            session->timeout = DEFAULT_TIMEOUT;
1330
0
        else
1331
0
            session->timeout = timeout * 1000L * 1000L;
1332
9.31k
    }
1333
12.9k
    session->sessid = snmp_get_next_sessid();
1334
1335
12.9k
    snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SESSION_INIT,
1336
12.9k
                        session);
1337
1338
12.9k
    if ((sptr = find_sec_mod(session->securityModel)) != NULL) {
1339
        /*
1340
         * security module specific copying 
1341
         */
1342
9.31k
        if (sptr->session_setup) {
1343
9.31k
            int ret = (*sptr->session_setup) (in_session, session);
1344
9.31k
            if (ret != SNMPERR_SUCCESS) {
1345
0
                snmp_sess_close(slp);
1346
0
                return NULL;
1347
0
            }
1348
9.31k
        }
1349
1350
        /*
1351
         * security module specific opening
1352
         */
1353
9.31k
        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
9.31k
    }
1361
1362
12.9k
#ifndef NETSNMP_NO_WRITE_SUPPORT
1363
12.9k
    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
12.9k
#endif /* NETSNMP_NO_WRITE_SUPPORT */
1379
1380
12.9k
    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
12.9k
#ifndef NETSNMP_NO_TRAP_STATS
1388
12.9k
    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
12.9k
#endif
1397
1398
12.9k
    return (slp);
1399
12.9k
}
1400
1401
static struct session_list *
1402
snmp_sess_copy(netsnmp_session * pss)
1403
12.9k
{
1404
12.9k
    struct session_list *psl;
1405
12.9k
    psl = _sess_copy(pss);
1406
12.9k
    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
12.9k
    return psl;
1413
12.9k
}
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
12.9k
{
1636
    /* Optional supplemental transport configuration information and
1637
       final call to actually open the transport */
1638
12.9k
    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
12.9k
    return SNMPERR_SUCCESS;
1665
12.9k
}
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
12.9k
{
1698
12.9k
    int rc;
1699
    
1700
12.9k
    DEBUGMSGTL(("snmp_sess", "opening transport: %x\n", transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED));
1701
1702
    /* don't double open */
1703
12.9k
    if (transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED)
1704
3.58k
        return SNMPERR_SUCCESS;
1705
1706
9.32k
    if ((rc = netsnmp_sess_config_transport(in_session->transport_configuration,
1707
9.32k
                                            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
9.32k
    if (transport->f_open)
1714
0
        transport = transport->f_open(transport);
1715
1716
9.32k
    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
9.32k
    if (in_session->rcvMsgMaxSize > transport->msgMaxSize) {
1726
5.73k
        DEBUGMSGTL(("snmp_sess",
1727
5.73k
                    "limiting session rcv size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1728
5.73k
                    in_session->rcvMsgMaxSize, transport->msgMaxSize));
1729
5.73k
        in_session->rcvMsgMaxSize = transport->msgMaxSize;
1730
5.73k
    }
1731
1732
9.32k
    if (in_session->sndMsgMaxSize > transport->msgMaxSize) {
1733
5.73k
        DEBUGMSGTL(("snmp_sess",
1734
5.73k
                    "limiting session snd size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1735
5.73k
                    in_session->sndMsgMaxSize, transport->msgMaxSize));
1736
5.73k
        in_session->sndMsgMaxSize = transport->msgMaxSize;
1737
5.73k
    }
1738
1739
9.32k
    transport->flags |= NETSNMP_TRANSPORT_FLAG_OPENED;
1740
9.32k
    DEBUGMSGTL(("snmp_sess", "done opening transport: %x\n", transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED));
1741
9.32k
    return SNMPERR_SUCCESS;
1742
9.32k
}
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
6.55k
{
1859
6.55k
    struct session_list *slp;
1860
1861
6.55k
    slp = snmp_sess_add_ex(in_session, transport, fpre_parse, NULL,
1862
6.55k
                           fpost_parse, NULL, NULL, NULL, NULL);
1863
6.55k
    if (slp == NULL) {
1864
0
        return NULL;
1865
0
    }
1866
1867
6.55k
    snmp_session_insert(slp);
1868
1869
6.55k
    return (slp->session);
1870
6.55k
}
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
6.35k
{
1890
6.35k
    struct session_list *slp;
1891
1892
6.35k
    slp = snmp_sess_add_ex(in_session, transport, fpre_parse, fparse,
1893
6.35k
                           fpost_parse, fbuild, frbuild, fcheck, fcreate_pdu);
1894
6.35k
    if (slp == NULL) {
1895
0
        return NULL;
1896
0
    }
1897
1898
6.35k
    snmp_session_insert(slp);
1899
1900
6.35k
    return (slp->session);
1901
6.35k
}
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
12.9k
{
1920
12.9k
    struct session_list *slp;
1921
12.9k
    int rc;
1922
    
1923
12.9k
    _init_snmp();
1924
1925
12.9k
    if (transport == NULL)
1926
0
        return NULL;
1927
1928
12.9k
    if (NULL != in_session && (in_session->rcvMsgMaxSize < SNMP_MIN_MAX_LEN ||
1929
12.9k
                               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
12.9k
    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
12.9k
    if ((rc = netsnmp_sess_config_and_open_transport(in_session, transport))
1943
12.9k
        != SNMPERR_SUCCESS) {
1944
0
        return NULL;
1945
0
    }
1946
1947
12.9k
    DEBUGMSGTL(("snmp_sess_add", "fd %" NETSNMP_FMT_SKT "\n",
1948
12.9k
                transport->sock));
1949
1950
12.9k
    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
12.9k
    slp->transport = transport;
1957
12.9k
    slp->internal->hook_pre = fpre_parse;
1958
12.9k
    slp->internal->hook_parse = fparse;
1959
12.9k
    slp->internal->hook_post = fpost_parse;
1960
12.9k
    slp->internal->hook_build = fbuild;
1961
12.9k
    slp->internal->hook_realloc_build = frbuild;
1962
12.9k
    slp->internal->check_packet = fcheck;
1963
12.9k
    slp->internal->hook_create_pdu = fcreate_pdu;
1964
1965
    /** don't let session max exceed transport max */
1966
12.9k
    if (slp->session->rcvMsgMaxSize > transport->msgMaxSize) {
1967
3.58k
        DEBUGMSGTL(("snmp_sess_add",
1968
3.58k
                    "limiting session rcv size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1969
3.58k
                    slp->session->rcvMsgMaxSize, transport->msgMaxSize));
1970
3.58k
        slp->session->rcvMsgMaxSize = transport->msgMaxSize;
1971
3.58k
    }
1972
12.9k
    if (slp->session->sndMsgMaxSize > transport->msgMaxSize) {
1973
3.58k
        DEBUGMSGTL(("snmp_sess_add",
1974
3.58k
                    "limiting session snd size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
1975
3.58k
                    slp->session->sndMsgMaxSize, transport->msgMaxSize));
1976
3.58k
        slp->session->sndMsgMaxSize = transport->msgMaxSize;
1977
3.58k
    }
1978
1979
12.9k
    if (transport->f_setup_session &&
1980
3.64k
        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
12.9k
    if (slp->session->securityLevel == 0)
1986
12.9k
        slp->session->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
1987
1988
12.9k
    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
12.9k
    slp->session->flags &= ~SNMP_FLAGS_DONT_PROBE;
1998
1999
12.9k
    return slp;
2000
2001
0
close_session:
2002
0
    snmp_sess_close(slp);
2003
0
    return NULL;
2004
12.9k
}                               /*  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
2.90k
create_user_from_session(netsnmp_session * session) {
2035
2.90k
#ifdef NETSNMP_SECMOD_USM
2036
2.90k
    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
2.90k
}
2043
2044
static void netsnmp_free_one_tr_cfg(void *data, void *context)
2045
104
{
2046
104
    netsnmp_transport_config *c = data;
2047
2048
104
    free(c->key);
2049
104
    free(c->value);
2050
104
    free(c);
2051
104
}
2052
2053
static void netsnmp_free_transport_config(netsnmp_container *tc)
2054
50.7k
{
2055
50.7k
    if (!tc)
2056
50.6k
        return;
2057
2058
15
    CONTAINER_CLEAR(tc, netsnmp_free_one_tr_cfg, NULL);
2059
15
    CONTAINER_FREE(tc);
2060
15
}
2061
2062
/* Free the memory owned by a session but not the session object itself. */
2063
void netsnmp_cleanup_session(netsnmp_session *s)
2064
50.7k
{
2065
50.7k
    free(s->localname);
2066
50.7k
    free(s->peername);
2067
50.7k
    free(s->community);
2068
50.7k
    free(s->contextEngineID);
2069
50.7k
    free(s->contextName);
2070
50.7k
    free(s->securityEngineID);
2071
50.7k
    free(s->securityName);
2072
50.7k
    free(s->securityAuthProto);
2073
50.7k
    free(s->securityAuthLocalKey);
2074
50.7k
    free(s->securityPrivProto);
2075
50.7k
    free(s->securityPrivLocalKey);
2076
50.7k
    free(s->paramName);
2077
50.7k
#ifndef NETSNMP_NO_TRAP_STATS
2078
50.7k
    free(s->trap_stats);
2079
50.7k
#endif /* NETSNMP_NO_TRAP_STATS */
2080
50.7k
    usm_free_user(s->sessUser);
2081
50.7k
    netsnmp_free_transport_config(s->transport_configuration);
2082
50.7k
    memset(s, 0, sizeof(*s));
2083
50.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
38.0k
{
2094
38.0k
    if (!s)
2095
0
        return;
2096
2097
38.0k
    netsnmp_cleanup_session(s);
2098
2099
    /*
2100
     * clear session from any callbacks
2101
     */
2102
38.0k
    netsnmp_callback_clear_client_arg(s, 0, 0);
2103
2104
38.0k
    free(s);
2105
38.0k
}
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
12.9k
{
2138
12.9k
    netsnmp_transport *transport;
2139
12.9k
    struct snmp_internal_session *isp;
2140
12.9k
    netsnmp_session *sesp = NULL;
2141
12.9k
    struct snmp_secmod_def *sptr;
2142
2143
12.9k
    if (slp == NULL) {
2144
0
        return 0;
2145
0
    }
2146
2147
12.9k
    if (slp->session != NULL &&
2148
12.9k
        (sptr = find_sec_mod(slp->session->securityModel)) != NULL &&
2149
9.31k
        sptr->session_close != NULL) {
2150
0
        (*sptr->session_close) (slp->session);
2151
0
    }
2152
2153
12.9k
    isp = slp->internal;
2154
12.9k
    slp->internal = NULL;
2155
2156
12.9k
    if (isp) {
2157
12.9k
        netsnmp_request_list *rp, *orp;
2158
2159
12.9k
        SNMP_FREE(isp->packet);
2160
2161
        /*
2162
         * Free each element in the input request list.  
2163
         */
2164
12.9k
        rp = isp->requests;
2165
12.9k
        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
12.9k
        free(isp);
2178
12.9k
    }
2179
2180
12.9k
    transport = slp->transport;
2181
12.9k
    slp->transport = NULL;
2182
2183
12.9k
    if (transport) {
2184
12.9k
        transport->f_close(transport);
2185
12.9k
        netsnmp_transport_free(transport);
2186
12.9k
    }
2187
2188
12.9k
    sesp = slp->session;
2189
12.9k
    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
12.9k
    if (sesp != NULL && sesp->subsession != NULL) {
2198
782
        netsnmp_session *subsession = sesp->subsession, *tmpsub;
2199
2200
25.9k
        while (subsession != NULL) {
2201
25.1k
            DEBUGMSGTL(("snmp_sess_close",
2202
25.1k
                        "closing session %p, subsession %p\n", sesp,
2203
25.1k
                        subsession));
2204
25.1k
            tmpsub = subsession->next;
2205
25.1k
            snmp_free_session(subsession);
2206
25.1k
            subsession = tmpsub;
2207
25.1k
        }
2208
782
    }
2209
2210
12.9k
    snmp_free_session(sesp);
2211
12.9k
    free(slp);
2212
12.9k
    return 1;
2213
12.9k
}
2214
2215
int
2216
snmp_close(netsnmp_session * session)
2217
14.4k
{
2218
14.4k
    struct session_list *slp = NULL, *oslp = NULL;
2219
2220
14.4k
    {                           /*MTCRITICAL_RESOURCE */
2221
14.4k
        snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
2222
14.4k
        if (Sessions && Sessions->session == session) { /* If first entry */
2223
9.25k
            slp = Sessions;
2224
9.25k
            Sessions = slp->next;
2225
9.25k
        } else {
2226
5.17k
            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
5.17k
        }
2235
14.4k
        snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
2236
14.4k
    }                           /*END MTCRITICAL_RESOURCE */
2237
14.4k
    if (slp == NULL) {
2238
5.17k
        return 0;
2239
5.17k
    }
2240
9.25k
    return snmp_sess_close(slp);
2241
14.4k
}
2242
2243
int
2244
snmp_close_sessions(void)
2245
3.64k
{
2246
3.64k
    struct session_list *slp;
2247
2248
3.64k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
2249
7.29k
    while (Sessions) {
2250
3.64k
        slp = Sessions;
2251
3.64k
        Sessions = Sessions->next;
2252
3.64k
        snmp_sess_close(slp);
2253
3.64k
    }
2254
3.64k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
2255
3.64k
    return 1;
2256
3.64k
}
2257
2258
static void
2259
snmpv3_calc_msg_flags(int sec_level, int msg_command, u_char * flags)
2260
5
{
2261
5
    *flags = 0;
2262
5
    if (sec_level == SNMP_SEC_LEVEL_AUTHNOPRIV)
2263
0
        *flags = SNMP_MSG_FLAG_AUTH_BIT;
2264
5
    else if (sec_level == SNMP_SEC_LEVEL_AUTHPRIV)
2265
0
        *flags = SNMP_MSG_FLAG_AUTH_BIT | SNMP_MSG_FLAG_PRIV_BIT;
2266
2267
5
    if (SNMP_CMD_CONFIRMED(msg_command))
2268
0
        *flags |= SNMP_MSG_FLAG_RPRT_BIT;
2269
2270
5
    return;
2271
5
}
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
252
{
2337
252
    int             ret;
2338
2339
252
    session->s_snmp_errno = 0;
2340
252
    session->s_errno = 0;
2341
2342
    /*
2343
     * do validation for PDU types 
2344
     */
2345
252
    switch (pdu->command) {
2346
0
    case SNMP_MSG_RESPONSE:
2347
0
    case SNMP_MSG_TRAP2:
2348
5
    case SNMP_MSG_REPORT:
2349
5
        netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
2350
5
        NETSNMP_FALLTHROUGH;
2351
5
    case SNMP_MSG_INFORM:
2352
5
#ifndef NETSNMP_NOTIFY_ONLY
2353
5
    case SNMP_MSG_GET:
2354
5
    case SNMP_MSG_GETNEXT:
2355
5
#endif /* ! NETSNMP_NOTIFY_ONLY */
2356
5
#ifndef NETSNMP_NO_WRITE_SUPPORT
2357
5
    case SNMP_MSG_SET:
2358
5
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
2359
5
        if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
2360
0
            pdu->errstat = 0;
2361
5
        if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
2362
0
            pdu->errindex = 0;
2363
5
        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
247
    default:
2383
247
        session->s_snmp_errno = SNMPERR_UNKNOWN_PDU;
2384
247
        return -1;
2385
252
    }
2386
2387
    /* Do we need to set the session security engineid? */
2388
5
    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
5
    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
5
    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
5
    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
5
    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
5
    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
5
    DEBUGMSGTL(("snmp_build",
2466
5
                "Building SNMPv3 message (secName:\"%s\", secLevel:%s)...\n",
2467
5
                ((session->securityName) ? (char *) session->securityName :
2468
5
                 ((pdu->securityName) ? (char *) pdu->securityName :
2469
5
                  "ERROR: undefined")),
2470
5
                (pdu->securityLevel >= 0 && pdu->securityLevel < 4) ?
2471
5
                secLevelName[pdu->securityLevel] : "ERROR: invalid"));
2472
2473
5
    DEBUGDUMPSECTION("send", "SNMPv3 Message");
2474
5
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
2475
5
    if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
2476
5
        ret = snmpv3_packet_realloc_rbuild(pkt, pkt_len, offset,
2477
5
                                           session, pdu, NULL, 0);
2478
5
    } 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
5
#endif
2484
5
    DEBUGINDENTLESS();
2485
5
    if (-1 != ret) {
2486
5
        session->s_snmp_errno = ret;
2487
5
    }
2488
2489
5
    return ret;
2490
2491
5
}                               /* 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
5
{
2630
5
    size_t          start_offset = *offset;
2631
5
    u_char          msg_flags;
2632
5
    long            max_size, sec_model;
2633
5
    int             rc = 0;
2634
2635
    /*
2636
     * msgSecurityModel.  
2637
     */
2638
5
    sec_model = pdu->securityModel;
2639
5
    DEBUGDUMPHEADER("send", "msgSecurityModel");
2640
5
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2641
5
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2642
5
                                          ASN_INTEGER), &sec_model,
2643
5
                                sizeof(sec_model));
2644
5
    DEBUGINDENTLESS();
2645
5
    if (rc == 0) {
2646
0
        return 0;
2647
0
    }
2648
2649
    /*
2650
     * msgFlags.  
2651
     */
2652
5
    snmpv3_calc_msg_flags(pdu->securityLevel, pdu->command, &msg_flags);
2653
5
    DEBUGDUMPHEADER("send", "msgFlags");
2654
5
    rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
2655
5
                                   (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
2656
5
                                             | ASN_OCTET_STR), &msg_flags,
2657
5
                                   sizeof(msg_flags));
2658
5
    DEBUGINDENTLESS();
2659
5
    if (rc == 0) {
2660
0
        return 0;
2661
0
    }
2662
2663
    /*
2664
     * msgMaxSize.  
2665
     */
2666
5
    max_size = netsnmp_max_send_msg_size();
2667
5
    if (session->rcvMsgMaxSize < max_size)
2668
5
        max_size = session->rcvMsgMaxSize;
2669
5
    DEBUGDUMPHEADER("send:msgMaxSize2", "msgMaxSize");
2670
5
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2671
5
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2672
5
                                          ASN_INTEGER), &max_size,
2673
5
                                sizeof(max_size));
2674
5
    DEBUGINDENTLESS();
2675
5
    if (rc == 0) {
2676
0
        return 0;
2677
0
    }
2678
2679
    /*
2680
     * msgID.  
2681
     */
2682
5
    DEBUGDUMPHEADER("send", "msgID");
2683
5
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2684
5
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2685
5
                                          ASN_INTEGER), &pdu->msgid,
2686
5
                                sizeof(pdu->msgid));
2687
5
    DEBUGINDENTLESS();
2688
5
    if (rc == 0) {
2689
0
        return 0;
2690
0
    }
2691
2692
    /*
2693
     * Global data sequence.  
2694
     */
2695
5
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
2696
5
                                     (u_char) (ASN_SEQUENCE |
2697
5
                                               ASN_CONSTRUCTOR),
2698
5
                                     *offset - start_offset);
2699
5
    if (rc == 0) {
2700
0
        return 0;
2701
0
    }
2702
2703
    /*
2704
     * Store the version field - msgVersion.  
2705
     */
2706
5
    DEBUGDUMPHEADER("send", "SNMP Version Number");
2707
5
    rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
2708
5
                                (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
2709
5
                                          ASN_INTEGER),
2710
5
                                (long *) &pdu->version,
2711
5
                                sizeof(pdu->version));
2712
5
    DEBUGINDENTLESS();
2713
5
    return rc;
2714
5
}                               /* 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
5
{
2760
5
    size_t          start_offset = *offset;
2761
5
    int             rc = 0;
2762
2763
    /*
2764
     * contextName.  
2765
     */
2766
5
    DEBUGDUMPHEADER("send", "contextName");
2767
5
    rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
2768
5
                                   (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
2769
5
                                             | ASN_OCTET_STR),
2770
5
                                   (u_char *) pdu->contextName,
2771
5
                                   pdu->contextNameLen);
2772
5
    DEBUGINDENTLESS();
2773
5
    if (rc == 0) {
2774
0
        return 0;
2775
0
    }
2776
2777
    /*
2778
     * contextEngineID.  
2779
     */
2780
5
    DEBUGDUMPHEADER("send", "contextEngineID");
2781
5
    rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
2782
5
                                   (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
2783
5
                                             | ASN_OCTET_STR),
2784
5
                                   pdu->contextEngineID,
2785
5
                                   pdu->contextEngineIDLen);
2786
5
    DEBUGINDENTLESS();
2787
5
    if (rc == 0) {
2788
0
        return 0;
2789
0
    }
2790
2791
5
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
2792
5
                                     (u_char) (ASN_SEQUENCE |
2793
5
                                               ASN_CONSTRUCTOR),
2794
5
                                     *offset - start_offset + body_len);
2795
2796
5
    return rc;
2797
5
}                               /* 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
5
{
2810
5
    u_char         *scoped_pdu, *hdrbuf = NULL, *hdr = NULL;
2811
5
    size_t          hdrbuf_len = SNMP_MAX_MSG_V3_HDRS, hdr_offset =
2812
5
        0, spdu_offset = 0;
2813
5
    size_t          body_end_offset = *offset, body_len = 0;
2814
5
    struct snmp_secmod_def *sptr = NULL;
2815
5
    int             rc = 0;
2816
2817
    /*
2818
     * Build a scopedPDU structure into the packet buffer.  
2819
     */
2820
5
    DEBUGPRINTPDUTYPE("send", pdu->command);
2821
5
    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
5
    } else {
2831
5
        rc = snmp_pdu_realloc_rbuild(pkt, pkt_len, offset, pdu);
2832
5
        if (rc == 0) {
2833
0
            return -1;
2834
0
        }
2835
5
    }
2836
5
    body_len = *offset - body_end_offset;
2837
2838
5
    DEBUGDUMPSECTION("send", "ScopedPdu");
2839
5
    rc = snmpv3_scopedPDU_header_realloc_rbuild(pkt, pkt_len, offset,
2840
5
                                                pdu, body_len);
2841
5
    if (rc == 0) {
2842
0
        return -1;
2843
0
    }
2844
5
    spdu_offset = *offset;
2845
5
    DEBUGINDENTADD(-4);         /*  Return from Scoped PDU.  */
2846
2847
5
    if ((hdrbuf = (u_char *) malloc(hdrbuf_len)) == NULL) {
2848
0
        return -1;
2849
0
    }
2850
2851
5
    rc = snmpv3_header_realloc_rbuild(&hdrbuf, &hdrbuf_len, &hdr_offset,
2852
5
                                      session, pdu);
2853
5
    if (rc == 0) {
2854
0
        SNMP_FREE(hdrbuf);
2855
0
        return -1;
2856
0
    }
2857
5
    hdr = hdrbuf + hdrbuf_len - hdr_offset;
2858
5
    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
5
    sptr = find_sec_mod(pdu->securityModel);
2866
5
    DEBUGDUMPSECTION("send", "SM msgSecurityParameters");
2867
5
    if (sptr && sptr->encode_reverse) {
2868
5
        struct snmp_secmod_outgoing_params parms;
2869
2870
5
        parms.msgProcModel = pdu->msgParseModel;
2871
5
        parms.globalData = hdr;
2872
5
        parms.globalDataLen = hdr_offset;
2873
5
        parms.maxMsgSize = SNMP_MAX_MSG_SIZE;
2874
5
        parms.secModel = pdu->securityModel;
2875
5
        parms.secEngineID = pdu->securityEngineID;
2876
5
        parms.secEngineIDLen = pdu->securityEngineIDLen;
2877
5
        parms.secName = pdu->securityName;
2878
5
        parms.secNameLen = pdu->securityNameLen;
2879
5
        parms.secLevel = pdu->securityLevel;
2880
5
        parms.scopedPdu = scoped_pdu;
2881
5
        parms.scopedPduLen = spdu_offset;
2882
5
        parms.secStateRef = pdu->securityStateRef;
2883
5
        parms.wholeMsg = pkt;
2884
5
        parms.wholeMsgLen = pkt_len;
2885
5
        parms.wholeMsgOffset = offset;
2886
5
        parms.session = session;
2887
5
        parms.pdu = pdu;
2888
2889
5
        rc = (*sptr->encode_reverse) (&parms);
2890
5
    } 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
5
    DEBUGINDENTLESS();
2904
5
    SNMP_FREE(hdrbuf);
2905
5
    return rc;
2906
5
}                               /* 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
3.58k
{
3037
3.58k
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3038
3.58k
    u_char         *h0e = NULL;
3039
3.58k
    size_t          start_offset = *offset;
3040
3.58k
    long            version;
3041
3.58k
    int             rc = 0;
3042
3.58k
    size_t          length;
3043
3.58k
#endif /* support for community based SNMP */
3044
3045
3.58k
    u_char         *cp;
3046
3047
3.58k
    if (NETSNMP_RUNTIME_PROTOCOL_SKIP(pdu->version)) {
3048
393
        DEBUGMSGTL(("snmp_send", "build packet (version 0x%02x disabled)\n",
3049
393
                    (u_int)pdu->version));
3050
393
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
3051
393
        return -1;
3052
393
    }
3053
3054
3.19k
    session->s_snmp_errno = 0;
3055
3.19k
    session->s_errno = 0;
3056
3057
3.19k
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3058
3.19k
    if ((pdu->flags & UCD_MSG_FLAG_BULK_TOOBIG) ||
3059
3.19k
        (0 == netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
3060
3.19k
                                     NETSNMP_DS_LIB_REVERSE_ENCODE))) {
3061
1.02k
        pdu->flags |= UCD_MSG_FLAG_FORWARD_ENCODE;
3062
1.02k
    }
3063
3.19k
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
3064
3065
3.19k
    if (pdu->version == SNMP_VERSION_3) {
3066
252
        return snmpv3_build(pkt, pkt_len, offset, session, pdu);
3067
252
    }
3068
3069
2.94k
    switch (pdu->command) {
3070
64
    case SNMP_MSG_RESPONSE:
3071
64
        netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
3072
64
#ifndef NETSNMP_NOTIFY_ONLY
3073
64
        NETSNMP_FALLTHROUGH;
3074
135
    case SNMP_MSG_GET:
3075
256
    case SNMP_MSG_GETNEXT:
3076
256
#endif /* ! NETSNMP_NOTIFY_ONLY */
3077
256
#ifndef NETSNMP_NO_WRITE_SUPPORT
3078
336
    case SNMP_MSG_SET:
3079
336
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
3080
        /*
3081
         * all versions support these PDU types 
3082
         */
3083
        /*
3084
         * initialize defaulted PDU fields 
3085
         */
3086
3087
336
        if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
3088
1
            pdu->errstat = 0;
3089
336
        if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
3090
6
            pdu->errindex = 0;
3091
336
        break;
3092
3093
149
    case SNMP_MSG_TRAP2:
3094
149
        netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
3095
149
        NETSNMP_FALLTHROUGH;
3096
304
    case SNMP_MSG_INFORM:
3097
304
#ifndef NETSNMP_DISABLE_SNMPV1
3098
        /*
3099
         * not supported in SNMPv1 and SNMPsec 
3100
         */
3101
304
        if (pdu->version == SNMP_VERSION_1) {
3102
0
            session->s_snmp_errno = SNMPERR_V2_IN_V1;
3103
0
            return -1;
3104
0
        }
3105
304
#endif
3106
304
        if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
3107
1
            pdu->errstat = 0;
3108
304
        if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
3109
6
            pdu->errindex = 0;
3110
304
        break;
3111
3112
0
#ifndef NETSNMP_NOTIFY_ONLY
3113
242
    case SNMP_MSG_GETBULK:
3114
        /*
3115
         * not supported in SNMPv1 and SNMPsec 
3116
         */
3117
242
#ifndef NETSNMP_DISABLE_SNMPV1
3118
242
        if (pdu->version == SNMP_VERSION_1) {
3119
0
            session->s_snmp_errno = SNMPERR_V2_IN_V1;
3120
0
            return -1;
3121
0
        }
3122
242
#endif
3123
242
        if (pdu->max_repetitions < 0) {
3124
41
            session->s_snmp_errno = SNMPERR_BAD_REPETITIONS;
3125
41
            return -1;
3126
41
        }
3127
201
        if (pdu->non_repeaters < 0) {
3128
50
            session->s_snmp_errno = SNMPERR_BAD_REPEATERS;
3129
50
            return -1;
3130
50
        }
3131
151
        break;
3132
151
#endif /* ! NETSNMP_NOTIFY_ONLY */
3133
3134
151
    case SNMP_MSG_TRAP:
3135
        /*
3136
         * *only* supported in SNMPv1 and SNMPsec 
3137
         */
3138
131
#ifndef NETSNMP_DISABLE_SNMPV1
3139
131
        if (pdu->version != SNMP_VERSION_1) {
3140
131
            session->s_snmp_errno = SNMPERR_V1_IN_V2;
3141
131
            return -1;
3142
131
        }
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
2
    case SNMP_MSG_REPORT:      /* SNMPv3 only */
3167
1.92k
    default:
3168
1.92k
        session->s_snmp_errno = SNMPERR_UNKNOWN_PDU;
3169
1.92k
        return -1;
3170
2.94k
    }
3171
3172
    /*
3173
     * save length 
3174
     */
3175
791
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3176
791
    length = *pkt_len;
3177
791
#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
791
    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
789
    case SNMP_VERSION_2c:
3193
789
#endif
3194
789
#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
789
        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
789
#endif                          /* !NETSNMP_NO_ZEROLENGTH_COMMUNITY */
3231
3232
789
        DEBUGMSGTL(("snmp_send", "Building SNMPv%ld message...\n",
3233
789
                    (1 + pdu->version)));
3234
789
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3235
789
        if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
3236
560
            DEBUGPRINTPDUTYPE("send", pdu->command);
3237
560
            rc = snmp_pdu_realloc_rbuild(pkt, pkt_len, offset, pdu);
3238
560
            if (rc == 0) {
3239
0
                return -1;
3240
0
            }
3241
3242
560
            DEBUGDUMPHEADER("send", "Community String");
3243
560
            rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
3244
560
                                           (u_char) (ASN_UNIVERSAL |
3245
560
                                                     ASN_PRIMITIVE |
3246
560
                                                     ASN_OCTET_STR),
3247
560
                                           pdu->community,
3248
560
                                           pdu->community_len);
3249
560
            DEBUGINDENTLESS();
3250
560
            if (rc == 0) {
3251
0
                return -1;
3252
0
            }
3253
3254
3255
            /*
3256
             * Store the version field.  
3257
             */
3258
560
            DEBUGDUMPHEADER("send", "SNMP Version Number");
3259
3260
560
            version = pdu->version;
3261
560
            rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3262
560
                                        (u_char) (ASN_UNIVERSAL |
3263
560
                                                  ASN_PRIMITIVE |
3264
560
                                                  ASN_INTEGER),
3265
560
                                        (long *) &version,
3266
560
                                        sizeof(version));
3267
560
            DEBUGINDENTLESS();
3268
560
            if (rc == 0) {
3269
0
                return -1;
3270
0
            }
3271
3272
            /*
3273
             * Build the final sequence.  
3274
             */
3275
560
#ifndef NETSNMP_DISABLE_SNMPV1
3276
560
            if (pdu->version == SNMP_VERSION_1) {
3277
0
                DEBUGDUMPSECTION("send", "SNMPv1 Message");
3278
560
            } else {
3279
560
#endif
3280
560
                DEBUGDUMPSECTION("send", "SNMPv2c Message");
3281
560
#ifndef NETSNMP_DISABLE_SNMPV1
3282
560
            }
3283
560
#endif
3284
560
            rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
3285
560
                                             (u_char) (ASN_SEQUENCE |
3286
560
                                                       ASN_CONSTRUCTOR),
3287
560
                                             *offset - start_offset);
3288
560
            DEBUGINDENTLESS();
3289
3290
560
            if (rc == 0) {
3291
0
                return -1;
3292
0
            }
3293
560
            return 0;
3294
560
        } else {
3295
3296
229
#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
229
            cp = asn_build_sequence(*pkt, pkt_len,
3303
229
                                    (u_char) (ASN_SEQUENCE |
3304
229
                                              ASN_CONSTRUCTOR), 0);
3305
229
            if (cp == NULL) {
3306
0
                return -1;
3307
0
            }
3308
229
            h0e = cp;
3309
3310
229
#ifndef NETSNMP_DISABLE_SNMPV1
3311
229
            if (pdu->version == SNMP_VERSION_1) {
3312
0
                DEBUGDUMPSECTION("send", "SNMPv1 Message");
3313
229
            } else {
3314
229
#endif
3315
229
                DEBUGDUMPSECTION("send", "SNMPv2c Message");
3316
229
#ifndef NETSNMP_DISABLE_SNMPV1
3317
229
            }
3318
229
#endif
3319
3320
            /*
3321
             * store the version field 
3322
             */
3323
229
            DEBUGDUMPHEADER("send", "SNMP Version Number");
3324
3325
229
            version = pdu->version;
3326
229
            cp = asn_build_int(cp, pkt_len,
3327
229
                               (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3328
229
                                         ASN_INTEGER), (long *) &version,
3329
229
                               sizeof(version));
3330
229
            DEBUGINDENTLESS();
3331
229
            if (cp == NULL)
3332
0
                return -1;
3333
3334
            /*
3335
             * store the community string 
3336
             */
3337
229
            DEBUGDUMPHEADER("send", "Community String");
3338
229
            cp = asn_build_string(cp, pkt_len,
3339
229
                                  (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3340
229
                                            ASN_OCTET_STR), pdu->community,
3341
229
                                  pdu->community_len);
3342
229
            DEBUGINDENTLESS();
3343
229
            if (cp == NULL)
3344
0
                return -1;
3345
229
            break;
3346
3347
229
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
3348
229
        }
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
2
    default:
3357
2
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
3358
2
        return -1;
3359
791
    }
3360
3361
229
    DEBUGPRINTPDUTYPE("send", pdu->command);
3362
229
    cp = snmp_pdu_build(pdu, cp, pkt_len);
3363
229
    DEBUGINDENTADD(-4);         /* return from entire v1/v2c message */
3364
229
    if (cp == NULL)
3365
0
        return -1;
3366
3367
    /*
3368
     * insert the actual length of the message sequence 
3369
     */
3370
229
    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
229
    case SNMP_VERSION_2c:
3376
229
#endif
3377
229
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
3378
229
        asn_build_sequence(*pkt, &length,
3379
229
                           (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
3380
229
                           cp - h0e);
3381
229
        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
229
    }
3392
229
    *pkt_len = cp - *pkt;
3393
229
    return 0;
3394
229
}
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
3.58k
{
3410
3.58k
    int             rc;
3411
3412
3.58k
    rc = _snmp_build(pkt, pkt_len, offset, pss, pdu);
3413
3.58k
    if (rc) {
3414
2.79k
        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
2.79k
        SET_SNMP_ERROR(pss->s_snmp_errno);
3419
2.79k
        rc = -1;
3420
2.79k
    }
3421
3.58k
    return rc;
3422
3.58k
}
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
3.81k
{
3430
3.81k
    u_char         *h1, *h1e, *h2, *h2e, *save_ptr;
3431
3.81k
    netsnmp_variable_list *vp, *save_vp = NULL;
3432
3.81k
    size_t          length, save_length;
3433
3434
3.81k
    length = *out_length;
3435
    /*
3436
     * Save current location and build PDU tag and length placeholder
3437
     * (actual length will be inserted later) 
3438
     */
3439
3.81k
    h1 = cp;
3440
3.81k
    cp = asn_build_sequence(cp, out_length, (u_char) pdu->command, 0);
3441
3.81k
    if (cp == NULL)
3442
1.02k
        return NULL;
3443
2.78k
    h1e = cp;
3444
3445
    /*
3446
     * store fields in the PDU preceding the variable-bindings sequence
3447
     */
3448
2.78k
    if (pdu->command != SNMP_MSG_TRAP) {
3449
        /*
3450
         * PDU is not an SNMPv1 trap 
3451
         */
3452
3453
2.75k
        DEBUGDUMPHEADER("send", "request_id");
3454
        /*
3455
         * request id 
3456
         */
3457
2.75k
        cp = asn_build_int(cp, out_length,
3458
2.75k
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3459
2.75k
                                     ASN_INTEGER), &pdu->reqid,
3460
2.75k
                           sizeof(pdu->reqid));
3461
2.75k
        DEBUGINDENTLESS();
3462
2.75k
        if (cp == NULL)
3463
270
            return NULL;
3464
3465
        /*
3466
         * error status (getbulk non-repeaters) 
3467
         */
3468
2.48k
        DEBUGDUMPHEADER("send", "error status");
3469
2.48k
        cp = asn_build_int(cp, out_length,
3470
2.48k
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3471
2.48k
                                     ASN_INTEGER), &pdu->errstat,
3472
2.48k
                           sizeof(pdu->errstat));
3473
2.48k
        DEBUGINDENTLESS();
3474
2.48k
        if (cp == NULL)
3475
145
            return NULL;
3476
3477
        /*
3478
         * error index (getbulk max-repetitions) 
3479
         */
3480
2.33k
        DEBUGDUMPHEADER("send", "error index");
3481
2.33k
        cp = asn_build_int(cp, out_length,
3482
2.33k
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3483
2.33k
                                     ASN_INTEGER), &pdu->errindex,
3484
2.33k
                           sizeof(pdu->errindex));
3485
2.33k
        DEBUGINDENTLESS();
3486
2.33k
        if (cp == NULL)
3487
88
            return NULL;
3488
2.33k
    } else {
3489
        /*
3490
         * an SNMPv1 trap PDU 
3491
         */
3492
3493
        /*
3494
         * enterprise 
3495
         */
3496
37
        DEBUGDUMPHEADER("send", "enterprise OBJID");
3497
37
        cp = asn_build_objid(cp, out_length,
3498
37
                             (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3499
37
                                       ASN_OBJECT_ID),
3500
37
                             pdu->enterprise, pdu->enterprise_length);
3501
37
        DEBUGINDENTLESS();
3502
37
        if (cp == NULL)
3503
3
            return NULL;
3504
3505
        /*
3506
         * agent-addr 
3507
         */
3508
34
        DEBUGDUMPHEADER("send", "agent Address");
3509
34
        cp = asn_build_string(cp, out_length,
3510
34
                              (u_char) (ASN_IPADDRESS | ASN_PRIMITIVE),
3511
34
                              (const u_char *) pdu->agent_addr, 4);
3512
34
        DEBUGINDENTLESS();
3513
34
        if (cp == NULL)
3514
6
            return NULL;
3515
3516
        /*
3517
         * generic trap 
3518
         */
3519
28
        DEBUGDUMPHEADER("send", "generic trap number");
3520
28
        cp = asn_build_int(cp, out_length,
3521
28
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3522
28
                                     ASN_INTEGER),
3523
28
                           (const long *) &pdu->trap_type,
3524
28
                           sizeof(pdu->trap_type));
3525
28
        DEBUGINDENTLESS();
3526
28
        if (cp == NULL)
3527
3
            return NULL;
3528
3529
        /*
3530
         * specific trap 
3531
         */
3532
25
        DEBUGDUMPHEADER("send", "specific trap number");
3533
25
        cp = asn_build_int(cp, out_length,
3534
25
                           (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
3535
25
                                     ASN_INTEGER),
3536
25
                           (const long *) &pdu->specific_type,
3537
25
                           sizeof(pdu->specific_type));
3538
25
        DEBUGINDENTLESS();
3539
25
        if (cp == NULL)
3540
3
            return NULL;
3541
3542
        /*
3543
         * timestamp  
3544
         */
3545
22
        DEBUGDUMPHEADER("send", "timestamp");
3546
22
        cp = asn_build_unsigned_int(cp, out_length,
3547
22
                                    (u_char) (ASN_TIMETICKS |
3548
22
                                              ASN_PRIMITIVE), &pdu->time,
3549
22
                                    sizeof(pdu->time));
3550
22
        DEBUGINDENTLESS();
3551
22
        if (cp == NULL)
3552
1
            return NULL;
3553
22
    }
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
2.26k
    h2 = cp;
3561
2.26k
    cp = asn_build_sequence(cp, out_length,
3562
2.26k
                            (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
3563
2.26k
    if (cp == NULL)
3564
121
        return NULL;
3565
2.14k
    h2e = cp;
3566
3567
    /*
3568
     * Store variable-bindings 
3569
     */
3570
2.14k
    DEBUGDUMPSECTION("send", "VarBindList");
3571
3.60k
    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
2.04k
        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
2.04k
        save_ptr = cp;
3588
2.04k
        save_length = *out_length;
3589
3590
2.04k
        DEBUGDUMPSECTION("send", "VarBind");
3591
2.04k
        cp = snmp_build_var_op(cp, vp->name, &vp->name_length, vp->type,
3592
2.04k
                               vp->val_len, vp->val.string, out_length);
3593
2.04k
        DEBUGINDENTLESS();
3594
2.04k
        if (cp == NULL) {
3595
585
            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
585
                return NULL;
3603
585
        }
3604
1.45k
        save_vp = vp;
3605
1.45k
    }
3606
1.56k
    DEBUGINDENTLESS();
3607
3608
    /** did we run out of room? (should only happen for bulk responses) */
3609
1.56k
    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
1.56k
    asn_build_sequence(h2, &length,
3623
1.56k
                       (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
3624
1.56k
                       cp - h2e);
3625
3626
    /*
3627
     * insert actual length of PDU sequence 
3628
     */
3629
1.56k
    asn_build_sequence(h1, &length, (u_char) pdu->command, cp - h1e);
3630
3631
1.56k
    return cp;
3632
2.14k
}
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
565
{
3642
565
#ifndef VPCACHE_SIZE
3643
2.75k
#define VPCACHE_SIZE 50
3644
565
#endif
3645
565
    netsnmp_variable_list *vpcache[VPCACHE_SIZE];
3646
565
    netsnmp_variable_list *vp, *tmpvp;
3647
565
    size_t          start_offset = *offset;
3648
565
    int             i, wrapped = 0, notdone, final, rc = 0;
3649
3650
565
    DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "starting\n"));
3651
2.19k
    for (vp = pdu->variables, i = VPCACHE_SIZE - 1; vp;
3652
1.62k
         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
1.62k
        if (ASN_PRIV_STOP == vp->type)
3660
0
            break;
3661
1.62k
        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
1.62k
        vpcache[i] = vp;
3667
1.62k
    }
3668
565
    final = i + 1;
3669
3670
565
    do {
3671
2.19k
        for (i = final; i < VPCACHE_SIZE; i++) {
3672
1.62k
            vp = vpcache[i];
3673
1.62k
            DEBUGDUMPSECTION("send", "VarBind");
3674
1.62k
            rc = snmp_realloc_rbuild_var_op(pkt, pkt_len, offset, 1,
3675
1.62k
                                            vp->name, &vp->name_length,
3676
1.62k
                                            vp->type,
3677
1.62k
                                            (u_char *) vp->val.string,
3678
1.62k
                                            vp->val_len);
3679
1.62k
            DEBUGINDENTLESS();
3680
1.62k
            if (rc == 0) {
3681
0
                return 0;
3682
0
            }
3683
1.62k
        }
3684
3685
565
        DEBUGINDENTLESS();
3686
565
        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
565
        } else {
3720
565
            notdone = 0;
3721
565
        }
3722
565
    } 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
565
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
3730
565
                                     (u_char) (ASN_SEQUENCE |
3731
565
                                               ASN_CONSTRUCTOR),
3732
565
                                     *offset - start_offset);
3733
565
    if (rc == 0) {
3734
0
        return 0;
3735
0
    }
3736
3737
    /*
3738
     * Store fields in the PDU preceding the variable-bindings sequence.
3739
     */
3740
565
    if (pdu->command != SNMP_MSG_TRAP) {
3741
        /*
3742
         * Error index (getbulk max-repetitions).  
3743
         */
3744
565
        DEBUGDUMPHEADER("send", "error index");
3745
565
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3746
565
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3747
565
                                              | ASN_INTEGER),
3748
565
                                    &pdu->errindex, sizeof(pdu->errindex));
3749
565
        DEBUGINDENTLESS();
3750
565
        if (rc == 0) {
3751
0
            return 0;
3752
0
        }
3753
3754
        /*
3755
         * Error status (getbulk non-repeaters).  
3756
         */
3757
565
        DEBUGDUMPHEADER("send", "error status");
3758
565
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3759
565
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3760
565
                                              | ASN_INTEGER),
3761
565
                                    &pdu->errstat, sizeof(pdu->errstat));
3762
565
        DEBUGINDENTLESS();
3763
565
        if (rc == 0) {
3764
0
            return 0;
3765
0
        }
3766
3767
        /*
3768
         * Request ID.  
3769
         */
3770
565
        DEBUGDUMPHEADER("send", "request_id");
3771
565
        rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
3772
565
                                    (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
3773
565
                                              | ASN_INTEGER), &pdu->reqid,
3774
565
                                    sizeof(pdu->reqid));
3775
565
        DEBUGINDENTLESS();
3776
565
        if (rc == 0) {
3777
0
            return 0;
3778
0
        }
3779
565
    } 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
565
    rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
3859
565
                                     (u_char) pdu->command,
3860
565
                                     *offset - start_offset);
3861
565
    return rc;
3862
565
}
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
1.71k
{
3872
1.71k
    u_char          type;
3873
1.71k
    long            version = SNMPERR_BAD_VERSION;
3874
3875
1.71k
    data = asn_parse_sequence(data, &length, &type,
3876
1.71k
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR), "version");
3877
1.71k
    if (data) {
3878
1.69k
        DEBUGDUMPHEADER("recv", "SNMP Version");
3879
1.69k
        data =
3880
1.69k
            asn_parse_int(data, &length, &type, &version, sizeof(version));
3881
1.69k
        DEBUGINDENTLESS();
3882
1.69k
        if (!data || type != ASN_INTEGER) {
3883
269
            return SNMPERR_BAD_VERSION;
3884
269
        }
3885
1.69k
    }
3886
1.44k
    return version;
3887
1.71k
}
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
6.07k
{
3896
6.07k
    u_char          type, msg_flags;
3897
6.07k
    long            ver, msg_sec_model;
3898
6.07k
    size_t          max_size_response;
3899
6.07k
    u_char          tmp_buf[SNMP_MAX_MSG_SIZE];
3900
6.07k
    size_t          tmp_buf_len;
3901
6.07k
    u_char          pdu_buf[SNMP_MAX_MSG_SIZE];
3902
6.07k
    u_char         *mallocbuf = NULL;
3903
6.07k
    size_t          pdu_buf_len = SNMP_MAX_MSG_SIZE;
3904
6.07k
    u_char         *sec_params;
3905
6.07k
    u_char         *msg_data;
3906
6.07k
    u_char         *cp;
3907
6.07k
    size_t          asn_len, msg_len;
3908
6.07k
    int             ret, ret_val;
3909
6.07k
    struct snmp_secmod_def *sptr;
3910
3911
3912
6.07k
    msg_data = data;
3913
6.07k
    msg_len = *length;
3914
3915
3916
    /*
3917
     * message is an ASN.1 SEQUENCE  
3918
     */
3919
6.07k
    DEBUGDUMPSECTION("recv", "SNMPv3 Message");
3920
6.07k
    data = asn_parse_sequence(data, length, &type,
3921
6.07k
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR), "message");
3922
6.07k
    if (data == NULL) {
3923
        /*
3924
         * error msg detail is set 
3925
         */
3926
588
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3927
588
        DEBUGINDENTLESS();
3928
588
        return SNMPERR_ASN_PARSE_ERR;
3929
588
    }
3930
3931
    /*
3932
     * parse msgVersion  
3933
     */
3934
5.49k
    DEBUGDUMPHEADER("recv", "SNMP Version Number");
3935
5.49k
    data = asn_parse_int(data, length, &type, &ver, sizeof(ver));
3936
5.49k
    DEBUGINDENTLESS();
3937
5.49k
    if (data == NULL) {
3938
341
        ERROR_MSG("bad parse of version");
3939
341
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3940
341
        DEBUGINDENTLESS();
3941
341
        return SNMPERR_ASN_PARSE_ERR;
3942
341
    }
3943
5.15k
    pdu->version = ver;
3944
3945
    /*
3946
     * parse msgGlobalData sequence  
3947
     */
3948
5.15k
    cp = data;
3949
5.15k
    asn_len = *length;
3950
5.15k
    DEBUGDUMPSECTION("recv", "msgGlobalData");
3951
5.15k
    data = asn_parse_sequence(data, &asn_len, &type,
3952
5.15k
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR),
3953
5.15k
                              "msgGlobalData");
3954
5.15k
    if (data == NULL) {
3955
        /*
3956
         * error msg detail is set 
3957
         */
3958
1.98k
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3959
1.98k
        DEBUGINDENTADD(-4);
3960
1.98k
        return SNMPERR_ASN_PARSE_ERR;
3961
1.98k
    }
3962
3.16k
    *length -= data - cp;       /* subtract off the length of the header */
3963
3964
    /*
3965
     * msgID 
3966
     */
3967
3.16k
    DEBUGDUMPHEADER("recv", "msgID");
3968
3.16k
    data =
3969
3.16k
        asn_parse_int(data, length, &type, &pdu->msgid,
3970
3.16k
                      sizeof(pdu->msgid));
3971
3.16k
    DEBUGINDENTLESS();
3972
3.16k
    if (data == NULL || type != ASN_INTEGER) {
3973
77
        ERROR_MSG("error parsing msgID");
3974
77
        DEBUGINDENTADD(-4);
3975
77
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3976
77
        return SNMPERR_ASN_PARSE_ERR;
3977
77
    }
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
3.08k
    if (pdu->msgid < 0 || pdu->msgid > SNMP_MAX_PACKET_LEN) {
3988
144
        snmp_log(LOG_ERR, "Received bad msgID (%ld %s %s).\n", pdu->msgid,
3989
144
                 (pdu->msgid < 0) ? "<" : ">",
3990
144
                 (pdu->msgid < 0) ? "0" : "2^31 - 1");
3991
144
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
3992
144
        DEBUGINDENTADD(-4);
3993
144
        return SNMPERR_ASN_PARSE_ERR;
3994
144
    }
3995
3996
    /*
3997
     * msgMaxSize 
3998
     */
3999
2.94k
    DEBUGDUMPHEADER("recv:msgMaxSize", "msgMaxSize");
4000
2.94k
    data = asn_parse_int(data, length, &type, &pdu->msgMaxSize,
4001
2.94k
                         sizeof(pdu->msgMaxSize));
4002
2.94k
    DEBUGINDENTLESS();
4003
2.94k
    if (data == NULL || type != ASN_INTEGER) {
4004
135
        ERROR_MSG("error parsing msgMaxSize");
4005
135
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4006
135
        DEBUGINDENTADD(-4);
4007
135
        return SNMPERR_ASN_PARSE_ERR;
4008
135
    }
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
2.80k
    if (pdu->msgMaxSize < SNMP_MIN_MAX_LEN) {
4019
164
        snmp_log(LOG_ERR, "Received bad msgMaxSize (%lu < 484).\n",
4020
164
                 pdu->msgMaxSize);
4021
164
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4022
164
        DEBUGINDENTADD(-4);
4023
164
        return SNMPERR_ASN_PARSE_ERR;
4024
2.64k
    } else if (pdu->msgMaxSize > SNMP_MAX_PACKET_LEN) {
4025
14
        snmp_log(LOG_ERR, "Received bad msgMaxSize (%lu > 2^31 - 1).\n",
4026
14
                 pdu->msgMaxSize);
4027
14
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4028
14
        DEBUGINDENTADD(-4);
4029
14
        return SNMPERR_ASN_PARSE_ERR;
4030
2.63k
    } else {
4031
2.63k
        DEBUGMSGTL(("snmpv3_parse:msgMaxSize", "msgMaxSize %lu received\n",
4032
2.63k
                    pdu->msgMaxSize));
4033
        /** don't increase max msg size if we've already got one */
4034
2.63k
        if (sess->sndMsgMaxSize < pdu->msgMaxSize) {
4035
2.63k
            DEBUGMSGTL(("snmpv3_parse:msgMaxSize",
4036
2.63k
                        "msgMaxSize %" NETSNMP_PRIz "d greater than session max %ld; reducing\n",
4037
2.63k
                        sess->sndMsgMaxSize, pdu->msgMaxSize));
4038
2.63k
            pdu->msgMaxSize = sess->sndMsgMaxSize;
4039
2.63k
        }
4040
2.63k
    }
4041
4042
    /*
4043
     * msgFlags 
4044
     */
4045
2.63k
    tmp_buf_len = SNMP_MAX_MSG_SIZE;
4046
2.63k
    DEBUGDUMPHEADER("recv", "msgFlags");
4047
2.63k
    data = asn_parse_string(data, length, &type, tmp_buf, &tmp_buf_len);
4048
2.63k
    DEBUGINDENTLESS();
4049
2.63k
    if (data == NULL || type != ASN_OCTET_STR || tmp_buf_len != 1) {
4050
317
        ERROR_MSG("error parsing msgFlags");
4051
317
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4052
317
        DEBUGINDENTADD(-4);
4053
317
        return SNMPERR_ASN_PARSE_ERR;
4054
317
    }
4055
2.31k
    msg_flags = *tmp_buf;
4056
2.31k
    if (msg_flags & SNMP_MSG_FLAG_RPRT_BIT)
4057
395
        pdu->flags |= SNMP_MSG_FLAG_RPRT_BIT;
4058
1.91k
    else
4059
1.91k
        pdu->flags &= (~SNMP_MSG_FLAG_RPRT_BIT);
4060
4061
    /*
4062
     * msgSecurityModel 
4063
     */
4064
2.31k
    DEBUGDUMPHEADER("recv", "msgSecurityModel");
4065
2.31k
    data = asn_parse_int(data, length, &type, &msg_sec_model,
4066
2.31k
                         sizeof(msg_sec_model));
4067
2.31k
    DEBUGINDENTADD(-4);         /* return from global data indent */
4068
2.31k
    if (data == NULL || type != ASN_INTEGER ||
4069
2.30k
        msg_sec_model < 1 || msg_sec_model > 0x7fffffff) {
4070
160
        ERROR_MSG("error parsing msgSecurityModel");
4071
160
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4072
160
        DEBUGINDENTLESS();
4073
160
        return SNMPERR_ASN_PARSE_ERR;
4074
160
    }
4075
2.15k
    sptr = find_sec_mod(msg_sec_model);
4076
2.15k
    if (!sptr) {
4077
177
        snmp_log(LOG_WARNING, "unknown security model: %ld\n",
4078
177
                 msg_sec_model);
4079
177
        snmp_increment_statistic(STAT_SNMPUNKNOWNSECURITYMODELS);
4080
177
        DEBUGINDENTLESS();
4081
177
        return SNMPERR_UNKNOWN_SEC_MODEL;
4082
177
    }
4083
1.97k
    pdu->securityModel = msg_sec_model;
4084
4085
1.97k
    if (msg_flags & SNMP_MSG_FLAG_PRIV_BIT &&
4086
263
        !(msg_flags & SNMP_MSG_FLAG_AUTH_BIT)) {
4087
1
        ERROR_MSG("invalid message, illegal msgFlags");
4088
1
        snmp_increment_statistic(STAT_SNMPINVALIDMSGS);
4089
1
        DEBUGINDENTLESS();
4090
1
        return SNMPERR_INVALID_MSG;
4091
1
    }
4092
1.97k
    pdu->securityLevel = ((msg_flags & SNMP_MSG_FLAG_AUTH_BIT)
4093
1.97k
                          ? ((msg_flags & SNMP_MSG_FLAG_PRIV_BIT)
4094
819
                             ? SNMP_SEC_LEVEL_AUTHPRIV
4095
819
                             : SNMP_SEC_LEVEL_AUTHNOPRIV)
4096
1.97k
                          : SNMP_SEC_LEVEL_NOAUTH);
4097
    /*
4098
     * end of msgGlobalData 
4099
     */
4100
4101
    /*
4102
     * securtityParameters OCTET STRING begins after msgGlobalData 
4103
     */
4104
1.97k
    sec_params = data;
4105
1.97k
    SNMP_FREE(pdu->contextEngineID);
4106
1.97k
    pdu->contextEngineID = calloc(1, SNMP_MAX_ENG_SIZE);
4107
1.97k
    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
1.97k
    SNMP_FREE(pdu->securityEngineID);
4116
1.97k
    pdu->securityEngineID = calloc(1, SNMP_MAX_ENG_SIZE * 2);
4117
1.97k
    pdu->securityEngineIDLen = SNMP_MAX_ENG_SIZE * 2;
4118
1.97k
    SNMP_FREE(pdu->securityName);
4119
1.97k
    pdu->securityName = calloc(1, SNMP_MAX_SEC_NAME_SIZE);
4120
1.97k
    pdu->securityNameLen = SNMP_MAX_SEC_NAME_SIZE;
4121
4122
1.97k
    if ((pdu->securityName == NULL) ||
4123
1.97k
        (pdu->securityEngineID == NULL) ||
4124
1.97k
        (pdu->contextEngineID == NULL)) {
4125
0
        return SNMPERR_MALLOC;
4126
0
    }
4127
4128
1.97k
    if (pdu_buf_len < msg_len
4129
204
        && pdu->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
4130
        /*
4131
         * space needed is larger than we have in the default buffer 
4132
         */
4133
47
        mallocbuf = calloc(1, msg_len);
4134
47
        if (mallocbuf == NULL)
4135
0
            return SNMPERR_MALLOC;
4136
47
        pdu_buf_len = msg_len;
4137
47
        cp = mallocbuf;
4138
1.92k
    } else {
4139
1.92k
        memset(pdu_buf, 0, pdu_buf_len);
4140
1.92k
        cp = pdu_buf;
4141
1.92k
    }
4142
4143
1.97k
    DEBUGDUMPSECTION("recv", "SM msgSecurityParameters");
4144
1.97k
    if (sptr->decode) {
4145
1.97k
        struct snmp_secmod_incoming_params parms;
4146
1.97k
        parms.msgProcModel = pdu->msgParseModel;
4147
1.97k
        parms.maxMsgSize = pdu->msgMaxSize;
4148
1.97k
        parms.secParams = sec_params;
4149
1.97k
        parms.secModel = msg_sec_model;
4150
1.97k
        parms.secLevel = pdu->securityLevel;
4151
1.97k
        parms.wholeMsg = msg_data;
4152
1.97k
        parms.wholeMsgLen = msg_len;
4153
1.97k
        parms.secEngineID = pdu->securityEngineID;
4154
1.97k
        parms.secEngineIDLen = &pdu->securityEngineIDLen;
4155
1.97k
        parms.secName = pdu->securityName;
4156
1.97k
        parms.secNameLen = &pdu->securityNameLen;
4157
1.97k
        parms.scopedPdu = &cp;
4158
1.97k
        parms.scopedPduLen = &pdu_buf_len;
4159
1.97k
        parms.maxSizeResponse = &max_size_response;
4160
1.97k
        parms.secStateRef = &pdu->securityStateRef;
4161
1.97k
        parms.sess = sess;
4162
1.97k
        parms.pdu = pdu;
4163
1.97k
        parms.msg_flags = msg_flags;
4164
1.97k
        ret_val = (*sptr->decode) (&parms);
4165
1.97k
    } 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
1.97k
    if (ret_val != SNMPERR_SUCCESS) {
4174
873
        DEBUGDUMPSECTION("recv", "ScopedPDU");
4175
        /*
4176
         * Parse as much as possible -- though I don't see the point? [jbpn].  
4177
         */
4178
873
        if (cp) {
4179
873
            cp = snmpv3_scopedPDU_parse(pdu, cp, &pdu_buf_len);
4180
873
        }
4181
873
        if (cp) {
4182
314
            DEBUGPRINTPDUTYPE("recv", *cp);
4183
314
            snmp_pdu_parse(pdu, cp, &pdu_buf_len);
4184
314
            DEBUGINDENTADD(-8);
4185
559
        } else {
4186
559
            DEBUGINDENTADD(-4);
4187
559
        }
4188
4189
873
        SNMP_FREE(mallocbuf);
4190
873
        return ret_val;
4191
873
    }
4192
4193
    /*
4194
     * parse plaintext ScopedPDU sequence 
4195
     */
4196
1.10k
    *length = pdu_buf_len;
4197
1.10k
    DEBUGDUMPSECTION("recv", "ScopedPDU");
4198
1.10k
    data = snmpv3_scopedPDU_parse(pdu, cp, length);
4199
1.10k
    if (data == NULL) {
4200
112
        snmp_log(LOG_WARNING, "security service %ld error parsing ScopedPDU\n",
4201
112
                 msg_sec_model);
4202
112
        ERROR_MSG("error parsing PDU");
4203
112
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4204
112
        DEBUGINDENTADD(-4);
4205
112
        SNMP_FREE(mallocbuf);
4206
112
        return SNMPERR_ASN_PARSE_ERR;
4207
112
    }
4208
4209
    /*
4210
     * parse the PDU.  
4211
     */
4212
990
    if (after_header != NULL) {
4213
0
        *after_header = data;
4214
0
        tmp_buf_len = *length;
4215
0
    }
4216
4217
990
    DEBUGPRINTPDUTYPE("recv", *data);
4218
990
    ret = snmp_pdu_parse(pdu, data, length);
4219
990
    DEBUGINDENTADD(-8);
4220
4221
990
    if (after_header != NULL) {
4222
0
        *length = tmp_buf_len;
4223
0
    }
4224
4225
990
    if (ret != SNMPERR_SUCCESS) {
4226
880
        snmp_log(LOG_WARNING, "security service %ld error parsing ScopedPDU\n",
4227
880
                 msg_sec_model);
4228
880
        ERROR_MSG("error parsing PDU");
4229
880
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4230
880
        SNMP_FREE(mallocbuf);
4231
880
        return SNMPERR_ASN_PARSE_ERR;
4232
880
    }
4233
4234
110
    SNMP_FREE(mallocbuf);
4235
110
    return SNMPERR_SUCCESS;
4236
990
}                               /* end snmpv3_parse() */
4237
4238
static void
4239
free_securityStateRef(netsnmp_pdu* pdu)
4240
631k
{
4241
631k
    struct snmp_secmod_def *sptr;
4242
4243
631k
    if (!pdu->securityStateRef)
4244
630k
        return;
4245
4246
1.11k
    sptr = find_sec_mod(pdu->securityModel);
4247
1.11k
    if (sptr) {
4248
1.11k
        if (sptr->pdu_free_state_ref) {
4249
1.11k
            (*sptr->pdu_free_state_ref) (pdu->securityStateRef);
4250
1.11k
        } 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
1.11k
    } 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
1.11k
    pdu->securityStateRef = NULL;
4261
1.11k
}
4262
4263
11
#define ERROR_STAT_LENGTH 11
4264
4265
int
4266
snmpv3_make_report(netsnmp_pdu *pdu, int error)
4267
3.58k
{
4268
4269
3.58k
    long            ltmp;
4270
3.58k
    static const oid unknownSecurityLevel[] =
4271
3.58k
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 };
4272
3.58k
    static const oid notInTimeWindow[] =
4273
3.58k
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 };
4274
3.58k
    static const oid unknownUserName[] =
4275
3.58k
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 };
4276
3.58k
    static const oid unknownEngineID[] =
4277
3.58k
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 };
4278
3.58k
    static const oid wrongDigest[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 };
4279
3.58k
    static const oid decryptionError[] =
4280
3.58k
        { 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 };
4281
3.58k
    const oid      *err_var;
4282
3.58k
    int             err_var_len;
4283
3.58k
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4284
3.58k
    int             stat_ind;
4285
3.58k
#endif
4286
4287
3.58k
    switch (error) {
4288
4
    case SNMPERR_USM_UNKNOWNENGINEID:
4289
4
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4290
4
        stat_ind = STAT_USMSTATSUNKNOWNENGINEIDS;
4291
4
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4292
4
        err_var = unknownEngineID;
4293
4
        err_var_len = ERROR_STAT_LENGTH;
4294
4
        break;
4295
2
    case SNMPERR_USM_UNKNOWNSECURITYNAME:
4296
2
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4297
2
        stat_ind = STAT_USMSTATSUNKNOWNUSERNAMES;
4298
2
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4299
2
        err_var = unknownUserName;
4300
2
        err_var_len = ERROR_STAT_LENGTH;
4301
2
        break;
4302
1
    case SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL:
4303
1
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4304
1
        stat_ind = STAT_USMSTATSUNSUPPORTEDSECLEVELS;
4305
1
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4306
1
        err_var = unknownSecurityLevel;
4307
1
        err_var_len = ERROR_STAT_LENGTH;
4308
1
        break;
4309
2
    case SNMPERR_USM_AUTHENTICATIONFAILURE:
4310
2
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4311
2
        stat_ind = STAT_USMSTATSWRONGDIGESTS;
4312
2
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4313
2
        err_var = wrongDigest;
4314
2
        err_var_len = ERROR_STAT_LENGTH;
4315
2
        break;
4316
1
    case SNMPERR_USM_NOTINTIMEWINDOW:
4317
1
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4318
1
        stat_ind = STAT_USMSTATSNOTINTIMEWINDOWS;
4319
1
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4320
1
        err_var = notInTimeWindow;
4321
1
        err_var_len = ERROR_STAT_LENGTH;
4322
1
        break;
4323
1
    case SNMPERR_USM_DECRYPTIONERROR:
4324
1
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4325
1
        stat_ind = STAT_USMSTATSDECRYPTIONERRORS;
4326
1
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
4327
1
        err_var = decryptionError;
4328
1
        err_var_len = ERROR_STAT_LENGTH;
4329
1
        break;
4330
3.57k
    default:
4331
3.57k
        return SNMPERR_GENERR;
4332
3.58k
    }
4333
4334
11
    snmp_free_varbind(pdu->variables);  /* free the current varbind */
4335
4336
11
    pdu->variables = NULL;
4337
11
    SNMP_FREE(pdu->securityEngineID);
4338
11
    pdu->securityEngineID =
4339
11
        snmpv3_generate_engineID(&pdu->securityEngineIDLen);
4340
11
    SNMP_FREE(pdu->contextEngineID);
4341
11
    pdu->contextEngineID =
4342
11
        snmpv3_generate_engineID(&pdu->contextEngineIDLen);
4343
11
    pdu->command = SNMP_MSG_REPORT;
4344
11
    pdu->errstat = 0;
4345
11
    pdu->errindex = 0;
4346
11
    SNMP_FREE(pdu->contextName);
4347
11
    pdu->contextNameLen = 0;
4348
11
    pdu->contextName = strdup("");
4349
11
    if (!pdu->contextName)
4350
0
        return SNMPERR_MALLOC;
4351
11
    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
11
    free_securityStateRef(pdu);
4361
4362
11
    if (error == SNMPERR_USM_NOTINTIMEWINDOW) {
4363
1
        pdu->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
4364
10
    } else {
4365
10
        pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
4366
10
    }
4367
4368
    /*
4369
     * find the appropriate error counter  
4370
     */
4371
11
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
4372
11
    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
11
    snmp_pdu_add_variable(pdu, err_var, err_var_len,
4381
11
                          ASN_COUNTER, & ltmp, sizeof(ltmp));
4382
4383
11
    return SNMPERR_SUCCESS;
4384
11
}                               /* end snmpv3_make_report() */
4385
4386
4387
int
4388
snmpv3_get_report_type(netsnmp_pdu *pdu)
4389
3.58k
{
4390
3.58k
    static const oid snmpMPDStats[] = { 1, 3, 6, 1, 6, 3, 11, 2, 1 };
4391
3.58k
    static const oid targetStats[]  = { 1, 3, 6, 1, 6, 3, 12, 1    };
4392
3.58k
    static const oid usmStats[]     = { 1, 3, 6, 1, 6, 3, 15, 1, 1 };
4393
3.58k
    netsnmp_variable_list *vp;
4394
3.58k
    int             rpt_type = SNMPERR_UNKNOWN_REPORT;
4395
4396
3.58k
    if (pdu == NULL || pdu->variables == NULL)
4397
2.91k
        return rpt_type;
4398
666
    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
666
    if (vp->name_length == REPORT_STATS_LEN + 2) {
4405
87
        if (memcmp(snmpMPDStats, vp->name, REPORT_STATS_LEN * sizeof(oid)) == 0) {
4406
17
            switch (vp->name[REPORT_STATS_LEN]) {
4407
1
            case REPORT_snmpUnknownSecurityModels_NUM:
4408
1
                rpt_type = SNMPERR_UNKNOWN_SEC_MODEL;
4409
1
                break;
4410
0
            case REPORT_snmpInvalidMsgs_NUM:
4411
0
                rpt_type = SNMPERR_INVALID_MSG;
4412
0
                break;
4413
1
            case REPORT_snmpUnknownPDUHandlers_NUM:
4414
1
                rpt_type = SNMPERR_BAD_VERSION;
4415
1
                break;
4416
17
            }
4417
70
        } else if (memcmp(usmStats, vp->name, REPORT_STATS_LEN * sizeof(oid)) == 0) {
4418
18
            switch (vp->name[REPORT_STATS_LEN]) {
4419
1
            case REPORT_usmStatsUnsupportedSecLevels_NUM:
4420
1
                rpt_type = SNMPERR_UNSUPPORTED_SEC_LEVEL;
4421
1
                break;
4422
1
            case REPORT_usmStatsNotInTimeWindows_NUM:
4423
1
                rpt_type = SNMPERR_NOT_IN_TIME_WINDOW;
4424
1
                break;
4425
2
            case REPORT_usmStatsUnknownUserNames_NUM:
4426
2
                rpt_type = SNMPERR_UNKNOWN_USER_NAME;
4427
2
                break;
4428
1
            case REPORT_usmStatsUnknownEngineIDs_NUM:
4429
1
                rpt_type = SNMPERR_UNKNOWN_ENG_ID;
4430
1
                break;
4431
0
            case REPORT_usmStatsWrongDigests_NUM:
4432
0
                rpt_type = SNMPERR_AUTHENTICATION_FAILURE;
4433
0
                break;
4434
1
            case REPORT_usmStatsDecryptionErrors_NUM:
4435
1
                rpt_type = SNMPERR_DECRYPTION_ERR;
4436
1
                break;
4437
18
            }
4438
18
        }
4439
87
    }
4440
    /* Context-based report statistics from the Target MIB are similar
4441
     *   but the OID prefix has a different length
4442
     */
4443
666
    if (vp->name_length == REPORT_STATS_LEN2 + 2) {
4444
32
        if (memcmp(targetStats, vp->name, REPORT_STATS_LEN2 * sizeof(oid)) == 0) {
4445
2
            switch (vp->name[REPORT_STATS_LEN2]) {
4446
1
            case REPORT_snmpUnavailableContexts_NUM:
4447
1
                rpt_type = SNMPERR_BAD_CONTEXT;
4448
1
                break;
4449
0
            case REPORT_snmpUnknownContexts_NUM:
4450
0
                rpt_type = SNMPERR_BAD_CONTEXT;
4451
0
                break;
4452
2
            }
4453
2
        }
4454
32
    }
4455
666
    DEBUGMSGTL(("report", "Report type: %d\n", rpt_type));
4456
666
    return rpt_type;
4457
666
}
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
56.7k
{
4470
56.7k
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
4471
56.7k
    u_char          community[COMMUNITY_MAX_LEN];
4472
56.7k
    size_t          community_length = COMMUNITY_MAX_LEN;
4473
56.7k
#endif
4474
56.7k
    int             result = -1;
4475
4476
56.7k
    static const oid snmpEngineIDoid[]   = { 1,3,6,1,6,3,10,2,1,1,0};
4477
56.7k
    static size_t   snmpEngineIDoid_len = 11;
4478
4479
56.7k
    static char     ourEngineID[SNMP_SEC_PARAM_BUF_SIZE];
4480
56.7k
    static size_t   ourEngineID_len = sizeof(ourEngineID);
4481
4482
56.7k
    netsnmp_pdu    *pdu2 = NULL;
4483
4484
56.7k
    session->s_snmp_errno = 0;
4485
56.7k
    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
56.7k
    pdu->transid = snmp_get_next_transid();
4493
4494
56.7k
    if (session->version != SNMP_DEFAULT_VERSION) {
4495
54.9k
        pdu->version = session->version;
4496
54.9k
    } else {
4497
1.71k
        pdu->version = snmp_parse_version(data, length);
4498
1.71k
    }
4499
4500
56.7k
    switch (pdu->version) {
4501
0
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
4502
0
#ifndef NETSNMP_DISABLE_SNMPV1
4503
3.35k
    case SNMP_VERSION_1:
4504
3.35k
#endif
4505
3.35k
#ifndef NETSNMP_DISABLE_SNMPV2C
4506
52.5k
    case SNMP_VERSION_2c:
4507
52.5k
#endif
4508
52.5k
        NETSNMP_RUNTIME_PROTOCOL_CHECK_V1V2(pdu->version,unsupported_version);
4509
52.5k
        DEBUGMSGTL(("snmp_api", "Parsing SNMPv%ld message...\n",
4510
52.5k
                    (1 + pdu->version)));
4511
4512
        /*
4513
         * authenticates message and returns length if valid 
4514
         */
4515
52.5k
#ifndef NETSNMP_DISABLE_SNMPV1
4516
52.5k
        if (pdu->version == SNMP_VERSION_1) {
4517
3.34k
            DEBUGDUMPSECTION("recv", "SNMPv1 message\n");
4518
49.1k
        } else {
4519
49.1k
#endif
4520
49.1k
            DEBUGDUMPSECTION("recv", "SNMPv2c message\n");
4521
49.1k
#ifndef NETSNMP_DISABLE_SNMPV1
4522
49.1k
        }
4523
52.5k
#endif
4524
52.5k
        data = snmp_comstr_parse(data, &length,
4525
52.5k
                                 community, &community_length,
4526
52.5k
                                 &pdu->version);
4527
52.5k
        if (data == NULL)
4528
22.0k
            return -1;
4529
4530
30.4k
        if (pdu->version != session->version &&
4531
2.30k
            session->version != SNMP_DEFAULT_VERSION) {
4532
1.27k
            session->s_snmp_errno = SNMPERR_BAD_VERSION;
4533
1.27k
            return -1;
4534
1.27k
        }
4535
4536
        /*
4537
         * maybe get the community string. 
4538
         */
4539
29.2k
        pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
4540
29.2k
        pdu->securityModel = 
4541
29.2k
#ifndef NETSNMP_DISABLE_SNMPV1
4542
29.2k
            (pdu->version == SNMP_VERSION_1) ? SNMP_SEC_MODEL_SNMPv1 : 
4543
29.2k
#endif
4544
29.2k
                                               SNMP_SEC_MODEL_SNMPv2c;
4545
29.2k
        SNMP_FREE(pdu->community);
4546
29.2k
        pdu->community_len = 0;
4547
29.2k
        pdu->community = (u_char *) 0;
4548
29.2k
        if (community_length) {
4549
11.2k
            pdu->community_len = community_length;
4550
11.2k
            pdu->community = netsnmp_memdup(community, community_length);
4551
11.2k
            if (pdu->community == NULL) {
4552
0
                session->s_snmp_errno = SNMPERR_MALLOC;
4553
0
                return -1;
4554
0
            }
4555
11.2k
        }
4556
29.2k
        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
29.2k
        DEBUGDUMPSECTION("recv", "PDU");
4566
29.2k
        result = snmp_pdu_parse(pdu, data, &length);
4567
29.2k
        if (result < 0) {
4568
            /*
4569
             * This indicates a parse error.  
4570
             */
4571
27.4k
            snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4572
27.4k
        }
4573
29.2k
        DEBUGINDENTADD(-6);
4574
29.2k
        break;
4575
0
#endif /* support for community based SNMP */
4576
4577
3.42k
    case SNMP_VERSION_3:
4578
3.42k
        NETSNMP_RUNTIME_PROTOCOL_CHECK_V3(SNMP_VERSION_3,unsupported_version);
4579
3.40k
        result = snmpv3_parse(pdu, data, &length, NULL, session);
4580
3.40k
        DEBUGMSGTL(("snmp_parse",
4581
3.40k
                    "Parsed SNMPv3 message (secName:%s, secLevel:%s): %s\n",
4582
3.40k
                    pdu->securityName,
4583
3.40k
                    (pdu->securityLevel >= 0 && pdu->securityLevel < 4) ?
4584
3.40k
                    secLevelName[pdu->securityLevel] : "ERROR: invalid",
4585
3.40k
                    snmp_api_errstring(result)));
4586
4587
3.40k
        if (result == SNMPERR_USM_UNKNOWNSECURITYNAME) {
4588
201
            snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
4589
201
                                SNMPD_CALLBACK_AUTH_FAILURE, pdu);
4590
201
        }
4591
        
4592
3.40k
        if (result) {
4593
3.29k
            struct snmp_secmod_def *secmod =
4594
3.29k
                find_sec_mod(pdu->securityModel);
4595
3.29k
            if (!slp) {
4596
3.21k
                session->s_snmp_errno = result;
4597
3.21k
            } else {
4598
                /*
4599
                 * Call the security model to special handle any errors
4600
                 */
4601
4602
76
                if (secmod && secmod->handle_report) {
4603
11
                    (*secmod->handle_report)(slp, slp->transport, session,
4604
11
                                             result, pdu);
4605
11
                }
4606
76
            }
4607
3.29k
            free_securityStateRef(pdu);
4608
3.29k
        }
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
3.40k
        if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
4641
3.40k
                                    NETSNMP_DS_LIB_NO_DISCOVERY) &&
4642
3.37k
            SNMP_MSG_RESPONSE       != pdu->command &&
4643
3.40k
            NULL                    != pdu->contextEngineID &&
4644
1.91k
            pdu->contextEngineIDLen == 5 &&
4645
187
            pdu->contextEngineID[0] == 0x80 &&
4646
168
            pdu->contextEngineID[1] == 0x00 &&
4647
160
            pdu->contextEngineID[2] == 0x00 &&
4648
150
            pdu->contextEngineID[3] == 0x00 &&
4649
142
            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
132
            result = SNMPERR_JUST_A_CONTEXT_PROBE;
4654
4655
132
            DEBUGMSGTL(("snmpv3_contextid", "starting context ID discovery\n"));
4656
            /* ensure exactly one variable */
4657
132
            if (NULL != pdu->variables &&
4658
132
                NULL == pdu->variables->next_variable &&
4659
4660
                /* if it's a GET, match it exactly */
4661
123
                ((SNMP_MSG_GET == pdu->command &&
4662
47
                  snmp_oid_compare(snmpEngineIDoid,
4663
47
                                   snmpEngineIDoid_len,
4664
47
                                   pdu->variables->name,
4665
47
                                   pdu->variables->name_length) == 0)
4666
                 /* if it's a GETNEXT ensure it's less than the engineID oid */
4667
121
                 ||
4668
121
                 (SNMP_MSG_GETNEXT == pdu->command &&
4669
74
                  snmp_oid_compare(snmpEngineIDoid,
4670
74
                                   snmpEngineIDoid_len,
4671
74
                                   pdu->variables->name,
4672
74
                                   pdu->variables->name_length) > 0)
4673
123
                    )) {
4674
4675
39
                DEBUGMSGTL(("snmpv3_contextid",
4676
39
                            "  One correct variable found\n"));
4677
4678
                /* Note: we're explicitly not handling a GETBULK.  Deal. */
4679
4680
                /* set up the response */
4681
39
                pdu2 = snmp_clone_pdu(pdu);
4682
39
                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
39
                snmp_free_varbind(pdu2->variables);
4691
4692
                /* set the variables */
4693
39
                pdu2->variables = NULL;
4694
39
                pdu2->command = SNMP_MSG_RESPONSE;
4695
39
                pdu2->errstat = 0;
4696
39
                pdu2->errindex = 0;
4697
4698
39
                ourEngineID_len =
4699
39
                    snmpv3_get_engineID((u_char*)ourEngineID, ourEngineID_len);
4700
39
                if (0 != ourEngineID_len) {
4701
4702
39
                    DEBUGMSGTL(("snmpv3_contextid",
4703
39
                                "  responding with our engineID\n"));
4704
4705
39
                    snmp_pdu_add_variable(pdu2,
4706
39
                                          snmpEngineIDoid, snmpEngineIDoid_len,
4707
39
                                          ASN_OCTET_STR,
4708
39
                                          ourEngineID, ourEngineID_len);
4709
                    
4710
                    /* send the response */
4711
39
                    if (0 == snmp_sess_send(slp, pdu2)) {
4712
4713
39
                        DEBUGMSGTL(("snmpv3_contextid",
4714
39
                                    "  sent it off!\n"));
4715
4716
39
                        snmp_free_pdu(pdu2);
4717
                        
4718
39
                        snmp_log(LOG_ERR, "sending a response to the context engineID probe failed\n");
4719
39
                    }
4720
39
                } else {
4721
0
                    snmp_log(LOG_ERR, "failed to get our own engineID!\n");
4722
0
                    snmp_free_pdu(pdu2);
4723
0
                }
4724
93
            } else {
4725
93
                snmp_log(LOG_WARNING,
4726
93
                         "received an odd context engineID probe\n");
4727
93
            }
4728
132
            if (pdu->securityStateRef)
4729
45
                free_securityStateRef(pdu);
4730
132
        }
4731
4732
3.40k
        break;
4733
3.40k
    case SNMPERR_BAD_VERSION:
4734
287
        ERROR_MSG("error parsing snmp message version");
4735
287
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4736
287
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
4737
287
        break;
4738
4739
87
        unsupported_version:  /* goto label */
4740
87
    case SNMP_VERSION_sec:
4741
87
    case SNMP_VERSION_2u:
4742
87
    case SNMP_VERSION_2star:
4743
87
    case SNMP_VERSION_2p:
4744
507
    default:
4745
507
        ERROR_MSG("unsupported snmp message version");
4746
507
        snmp_increment_statistic(STAT_SNMPINBADVERSIONS);
4747
4748
        /*
4749
         * need better way to determine OS independent
4750
         * INT32_MAX value, for now hardcode
4751
         */
4752
507
        if (pdu->version < 0 || pdu->version > 2147483647) {
4753
120
            snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4754
120
        }
4755
507
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
4756
507
        break;
4757
56.7k
    }
4758
4759
33.4k
    return result;
4760
56.7k
}
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
56.7k
{
4776
56.7k
    int             rc;
4777
4778
56.7k
    rc = _snmp_parse(slp, pss, pdu, data, length);
4779
56.7k
    if (rc) {
4780
54.8k
        if (!pss->s_snmp_errno) {
4781
49.5k
            pss->s_snmp_errno = SNMPERR_BAD_PARSE;
4782
49.5k
        }
4783
54.8k
        SET_SNMP_ERROR(pss->s_snmp_errno);
4784
54.8k
    }
4785
4786
56.7k
    return rc;
4787
56.7k
}
4788
4789
int
4790
snmp_pdu_parse(netsnmp_pdu *pdu, u_char * data, size_t * length)
4791
47.2k
{
4792
47.2k
    u_char          type;
4793
47.2k
    u_char          msg_type;
4794
47.2k
    u_char         *var_val;
4795
47.2k
    size_t          len;
4796
47.2k
    size_t          four;
4797
47.2k
    netsnmp_variable_list *vp = NULL, *vplast = NULL;
4798
47.2k
    oid             objid[MAX_OID_LEN];
4799
47.2k
    u_char         *p;
4800
4801
    /*
4802
     * Get the PDU type 
4803
     */
4804
47.2k
    data = asn_parse_header(data, length, &msg_type);
4805
47.2k
    if (data == NULL)
4806
12.5k
        return -1;
4807
34.6k
    DEBUGMSGTL(("dumpv_recv","    Command %s\n", snmp_pdu_type(msg_type)));
4808
34.6k
    pdu->command = msg_type;
4809
34.6k
    pdu->flags &= (~UCD_MSG_FLAG_RESPONSE_PDU);
4810
4811
    /*
4812
     * get the fields in the PDU preceding the variable-bindings sequence
4813
     */
4814
34.6k
    switch (pdu->command) {
4815
9.57k
    case SNMP_MSG_TRAP:
4816
        /*
4817
         * enterprise 
4818
         */
4819
9.57k
        pdu->enterprise_length = MAX_OID_LEN;
4820
9.57k
        data = asn_parse_objid(data, length, &type, objid,
4821
9.57k
                               &pdu->enterprise_length);
4822
9.57k
        if (data == NULL)
4823
2.07k
            return -1;
4824
7.50k
        SNMP_FREE(pdu->enterprise);
4825
7.50k
        pdu->enterprise = netsnmp_memdup(objid,
4826
7.50k
                                         pdu->enterprise_length * sizeof(oid));
4827
7.50k
        if (pdu->enterprise == NULL) {
4828
0
            return -1;
4829
0
        }
4830
4831
        /*
4832
         * agent-addr 
4833
         */
4834
7.50k
        four = 4;
4835
7.50k
        data = asn_parse_string(data, length, &type,
4836
7.50k
                                (u_char *) pdu->agent_addr, &four);
4837
7.50k
        if (data == NULL)
4838
1.84k
            return -1;
4839
4840
        /*
4841
         * generic trap 
4842
         */
4843
5.66k
        data = asn_parse_int(data, length, &type, (long *) &pdu->trap_type,
4844
5.66k
                             sizeof(pdu->trap_type));
4845
5.66k
        if (data == NULL)
4846
330
            return -1;
4847
        /*
4848
         * specific trap 
4849
         */
4850
5.33k
        data =
4851
5.33k
            asn_parse_int(data, length, &type,
4852
5.33k
                          (long *) &pdu->specific_type,
4853
5.33k
                          sizeof(pdu->specific_type));
4854
5.33k
        if (data == NULL)
4855
312
            return -1;
4856
4857
        /*
4858
         * timestamp  
4859
         */
4860
5.02k
        data = asn_parse_unsigned_int(data, length, &type, &pdu->time,
4861
5.02k
                                      sizeof(pdu->time));
4862
5.02k
        if (data == NULL)
4863
2.00k
            return -1;
4864
4865
3.01k
        break;
4866
4867
4.93k
    case SNMP_MSG_RESPONSE:
4868
6.66k
    case SNMP_MSG_REPORT:
4869
6.66k
        pdu->flags |= UCD_MSG_FLAG_RESPONSE_PDU;
4870
6.66k
        NETSNMP_FALLTHROUGH;
4871
4872
7.51k
    case SNMP_MSG_TRAP2:
4873
8.59k
    case SNMP_MSG_INFORM:
4874
8.59k
#ifndef NETSNMP_NOTIFY_ONLY
4875
12.6k
    case SNMP_MSG_GET:
4876
15.6k
    case SNMP_MSG_GETNEXT:
4877
17.5k
    case SNMP_MSG_GETBULK:
4878
17.5k
#endif /* ! NETSNMP_NOTIFY_ONLY */
4879
17.5k
#ifndef NETSNMP_NO_WRITE_SUPPORT
4880
21.9k
    case SNMP_MSG_SET:
4881
21.9k
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
4882
        /*
4883
         * PDU is not an SNMPv1 TRAP 
4884
         */
4885
4886
        /*
4887
         * request id 
4888
         */
4889
21.9k
        DEBUGDUMPHEADER("recv", "request_id");
4890
21.9k
        data = asn_parse_int(data, length, &type, &pdu->reqid,
4891
21.9k
                             sizeof(pdu->reqid));
4892
21.9k
        DEBUGINDENTLESS();
4893
21.9k
        if (data == NULL) {
4894
855
            return -1;
4895
855
        }
4896
4897
        /*
4898
         * error status (getbulk non-repeaters) 
4899
         */
4900
21.0k
        DEBUGDUMPHEADER("recv", "error status");
4901
21.0k
        data = asn_parse_int(data, length, &type, &pdu->errstat,
4902
21.0k
                             sizeof(pdu->errstat));
4903
21.0k
        DEBUGINDENTLESS();
4904
21.0k
        if (data == NULL) {
4905
1.36k
            return -1;
4906
1.36k
        }
4907
4908
        /*
4909
         * error index (getbulk max-repetitions) 
4910
         */
4911
19.7k
        DEBUGDUMPHEADER("recv", "error index");
4912
19.7k
        data = asn_parse_int(data, length, &type, &pdu->errindex,
4913
19.7k
                             sizeof(pdu->errindex));
4914
19.7k
        DEBUGINDENTLESS();
4915
19.7k
        if (data == NULL) {
4916
762
            return -1;
4917
762
        }
4918
18.9k
  break;
4919
4920
18.9k
    default:
4921
3.16k
        snmp_log(LOG_ERR, "Bad PDU type received: 0x%.2x\n", pdu->command);
4922
3.16k
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
4923
3.16k
        return -1;
4924
34.6k
    }
4925
4926
    /*
4927
     * get header for variable-bindings sequence 
4928
     */
4929
21.9k
    DEBUGDUMPSECTION("recv", "VarBindList");
4930
21.9k
    data = asn_parse_sequence(data, length, &type,
4931
21.9k
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR),
4932
21.9k
                              "varbinds");
4933
21.9k
    if (data == NULL)
4934
3.38k
        goto fail;
4935
4936
18.6k
    snmp_free_varbind(pdu->variables);
4937
18.6k
    pdu->variables = NULL;
4938
4939
    /*
4940
     * get each varBind sequence 
4941
     */
4942
63.6k
    while ((int) *length > 0) {
4943
61.4k
        vp = SNMP_MALLOC_TYPEDEF(netsnmp_variable_list);
4944
61.4k
        if (NULL == vp)
4945
0
            goto fail;
4946
4947
61.4k
        vp->name_length = MAX_OID_LEN;
4948
61.4k
        DEBUGDUMPSECTION("recv", "VarBind");
4949
61.4k
        data = snmp_parse_var_op(data, objid, &vp->name_length, &vp->type,
4950
61.4k
                                 &vp->val_len, &var_val, length);
4951
61.4k
        if (data == NULL)
4952
11.2k
            goto fail;
4953
50.2k
        if (snmp_set_var_objid(vp, objid, vp->name_length))
4954
0
            goto fail;
4955
4956
50.2k
        len = SNMP_MAX_PACKET_LEN;
4957
50.2k
        DEBUGDUMPHEADER("recv", "Value");
4958
50.2k
        switch ((short) vp->type) {
4959
3.24k
        case ASN_INTEGER:
4960
3.24k
            vp->val.integer = (long *) vp->buf;
4961
3.24k
            vp->val_len = sizeof(long);
4962
3.24k
            p = asn_parse_int(var_val, &len, &vp->type,
4963
3.24k
                          (long *) vp->val.integer,
4964
3.24k
                          sizeof(*vp->val.integer));
4965
3.24k
            if (!p)
4966
332
                goto fail;
4967
2.91k
            break;
4968
2.99k
        case ASN_COUNTER:
4969
4.68k
        case ASN_GAUGE:
4970
6.28k
        case ASN_TIMETICKS:
4971
7.93k
        case ASN_UINTEGER:
4972
7.93k
            vp->val.integer = (long *) vp->buf;
4973
7.93k
            vp->val_len = sizeof(u_long);
4974
7.93k
            p = asn_parse_unsigned_int(var_val, &len, &vp->type,
4975
7.93k
                                   (u_long *) vp->val.integer,
4976
7.93k
                                   vp->val_len);
4977
7.93k
            if (!p)
4978
920
                goto fail;
4979
7.01k
            break;
4980
7.01k
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
4981
7.01k
        case ASN_OPAQUE_COUNTER64:
4982
3.10k
        case ASN_OPAQUE_U64:
4983
3.10k
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
4984
8.23k
        case ASN_COUNTER64:
4985
8.23k
            vp->val.counter64 = (struct counter64 *) vp->buf;
4986
8.23k
            vp->val_len = sizeof(struct counter64);
4987
8.23k
            p = asn_parse_unsigned_int64(var_val, &len, &vp->type,
4988
8.23k
                                     (struct counter64 *) vp->val.
4989
8.23k
                                     counter64, vp->val_len);
4990
8.23k
            if (!p)
4991
930
                goto fail;
4992
7.30k
            break;
4993
7.30k
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
4994
7.30k
        case ASN_OPAQUE_FLOAT:
4995
2.46k
            vp->val.floatVal = (float *) vp->buf;
4996
2.46k
            vp->val_len = sizeof(float);
4997
2.46k
            p = asn_parse_float(var_val, &len, &vp->type,
4998
2.46k
                            vp->val.floatVal, vp->val_len);
4999
2.46k
            if (!p)
5000
412
                goto fail;
5001
2.05k
            break;
5002
2.62k
        case ASN_OPAQUE_DOUBLE:
5003
2.62k
            vp->val.doubleVal = (double *) vp->buf;
5004
2.62k
            vp->val_len = sizeof(double);
5005
2.62k
            p = asn_parse_double(var_val, &len, &vp->type,
5006
2.62k
                             vp->val.doubleVal, vp->val_len);
5007
2.62k
            if (!p)
5008
753
                goto fail;
5009
1.87k
            break;
5010
5.18k
        case ASN_OPAQUE_I64:
5011
5.18k
            vp->val.counter64 = (struct counter64 *) vp->buf;
5012
5.18k
            vp->val_len = sizeof(struct counter64);
5013
5.18k
            p = asn_parse_signed_int64(var_val, &len, &vp->type,
5014
5.18k
                                   (struct counter64 *) vp->val.counter64,
5015
5.18k
                                   sizeof(*vp->val.counter64));
5016
5017
5.18k
            if (!p)
5018
896
                goto fail;
5019
4.29k
            break;
5020
4.29k
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
5021
4.29k
        case ASN_IPADDRESS:
5022
1.43k
            if (vp->val_len != 4)
5023
274
                goto fail;
5024
1.16k
            NETSNMP_FALLTHROUGH;
5025
3.00k
        case ASN_OCTET_STR:
5026
6.97k
        case ASN_OPAQUE:
5027
8.64k
        case ASN_NSAP:
5028
8.64k
            if (vp->val_len < sizeof(vp->buf)) {
5029
7.94k
                vp->val.string = (u_char *) vp->buf;
5030
7.94k
            } else {
5031
692
                vp->val.string = (u_char *) malloc(vp->val_len);
5032
692
            }
5033
8.64k
            if (vp->val.string == NULL) {
5034
0
                goto fail;
5035
0
            }
5036
8.64k
            p = asn_parse_string(var_val, &len, &vp->type, vp->val.string,
5037
8.64k
                             &vp->val_len);
5038
8.64k
            if (!p)
5039
0
                goto fail;
5040
8.64k
            break;
5041
8.64k
        case ASN_OBJECT_ID:
5042
3.28k
            vp->val_len = MAX_OID_LEN;
5043
3.28k
            p = asn_parse_objid(var_val, &len, &vp->type, objid, &vp->val_len);
5044
3.28k
            if (!p)
5045
226
                goto fail;
5046
3.05k
            vp->val_len *= sizeof(oid);
5047
3.05k
            vp->val.objid = netsnmp_memdup(objid, vp->val_len);
5048
3.05k
            if (vp->val.objid == NULL)
5049
0
                goto fail;
5050
3.05k
            break;
5051
3.05k
        case SNMP_NOSUCHOBJECT:
5052
3.13k
        case SNMP_NOSUCHINSTANCE:
5053
4.32k
        case SNMP_ENDOFMIBVIEW:
5054
5.71k
        case ASN_NULL:
5055
5.71k
            break;
5056
2.27k
        case ASN_BIT_STR:
5057
2.27k
            vp->val.bitstring = (u_char *) malloc(vp->val_len);
5058
2.27k
            if (vp->val.bitstring == NULL) {
5059
0
                goto fail;
5060
0
            }
5061
2.27k
            p = asn_parse_bitstring(var_val, &len, &vp->type,
5062
2.27k
                                vp->val.bitstring, &vp->val_len);
5063
2.27k
            if (!p)
5064
91
                goto fail;
5065
2.18k
            break;
5066
2.18k
        default:
5067
334
            snmp_log(LOG_ERR, "bad type returned (%x)\n", vp->type);
5068
334
            goto fail;
5069
0
            break;
5070
50.2k
        }
5071
45.0k
        DEBUGINDENTADD(-4);
5072
5073
45.0k
        if (NULL == vplast) {
5074
11.1k
            pdu->variables = vp;
5075
33.9k
        } else {
5076
33.9k
            vplast->next_variable = vp;
5077
33.9k
        }
5078
45.0k
        vplast = vp;
5079
45.0k
        vp = NULL;
5080
45.0k
    }
5081
2.21k
    return 0;
5082
5083
19.7k
  fail:
5084
19.7k
    {
5085
19.7k
        const char *errstr = snmp_api_errstring(SNMPERR_SUCCESS);
5086
19.7k
        DEBUGMSGTL(("recv", "error while parsing VarBindList:%s\n", errstr));
5087
19.7k
    }
5088
    /** if we were parsing a var, remove it from the pdu and free it */
5089
19.7k
    if (vp)
5090
16.3k
        snmp_free_var(vp);
5091
5092
19.7k
    return -1;
5093
18.6k
}
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
5.57k
{
5105
5.57k
    u_char          tmp_buf[SNMP_MAX_MSG_SIZE];
5106
5.57k
    size_t          tmp_buf_len;
5107
5.57k
    u_char          type;
5108
5.57k
    size_t          asn_len;
5109
5.57k
    u_char         *data;
5110
5111
5.57k
    pdu->command = 0;           /* initialize so we know if it got parsed */
5112
5.57k
    asn_len = *length;
5113
5.57k
    data = asn_parse_sequence(cp, &asn_len, &type,
5114
5.57k
                              (ASN_SEQUENCE | ASN_CONSTRUCTOR),
5115
5.57k
                              "plaintext scopedPDU");
5116
5.57k
    if (data == NULL) {
5117
1.33k
        return NULL;
5118
1.33k
    }
5119
4.24k
    *length -= data - cp;
5120
5121
    /*
5122
     * contextEngineID from scopedPdu  
5123
     */
5124
4.24k
    DEBUGDUMPHEADER("recv", "contextEngineID");
5125
4.24k
    data = asn_parse_string(data, length, &type, pdu->contextEngineID,
5126
4.24k
                            &pdu->contextEngineIDLen);
5127
4.24k
    DEBUGINDENTLESS();
5128
4.24k
    if (data == NULL) {
5129
2.85k
        ERROR_MSG("error parsing contextEngineID from scopedPdu");
5130
2.85k
        return NULL;
5131
2.85k
    }
5132
5133
    /*
5134
     * parse contextName from scopedPdu
5135
     */
5136
1.39k
    tmp_buf_len = SNMP_MAX_CONTEXT_SIZE;
5137
1.39k
    DEBUGDUMPHEADER("recv", "contextName");
5138
1.39k
    data = asn_parse_string(data, length, &type, tmp_buf, &tmp_buf_len);
5139
1.39k
    DEBUGINDENTLESS();
5140
1.39k
    if (data == NULL) {
5141
75
        ERROR_MSG("error parsing contextName from scopedPdu");
5142
75
        return NULL;
5143
75
    }
5144
5145
1.31k
    SNMP_FREE(pdu->contextName);
5146
1.31k
    pdu->contextName = netsnmp_memdup_nt(tmp_buf, tmp_buf_len,
5147
1.31k
                                         &pdu->contextNameLen);
5148
1.31k
    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
1.31k
    asn_len = *length;
5157
1.31k
    cp = asn_parse_header(data, &asn_len, &type);
5158
1.31k
    if (cp == NULL)
5159
15
        return NULL;
5160
5161
1.30k
    pdu->command = type;
5162
5163
1.30k
    return data;
5164
1.31k
}
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
31.8k
{
5176
31.8k
    size_t offset = 0;
5177
31.8k
    int    result;
5178
5179
31.8k
    if (isp && isp->hook_realloc_build) {
5180
31.8k
        result = isp->hook_realloc_build(sp, pdu, pktbuf_p, pktbuf_len_p,
5181
31.8k
                                         &offset);
5182
5183
31.8k
        *pkt_p = *pktbuf_p;
5184
31.8k
        *len_p = offset;
5185
31.8k
    } 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
5
    } else {
5190
5
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
5191
5
        if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
5192
5
            result = snmp_build(pktbuf_p, pktbuf_len_p, &offset, sp, pdu);
5193
5
            *pkt_p = *pktbuf_p + *pktbuf_len_p - offset;
5194
5
            *len_p = offset;
5195
5
        } 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
5
#endif
5203
5
    }
5204
5205
31.8k
    return result;
5206
31.8k
}
5207
5208
int
5209
_build_initial_pdu_packet(struct session_list *slp, netsnmp_pdu *pdu, int bulk)
5210
70.6k
{
5211
70.6k
    netsnmp_session *session;
5212
70.6k
    struct snmp_internal_session *isp;
5213
70.6k
    netsnmp_transport *transport = NULL;
5214
70.6k
    u_char         *pktbuf = NULL, *packet = NULL;
5215
70.6k
    size_t          pktbuf_len = 0, length = 0, orig_length = 0;
5216
70.6k
    int             result, orig_count = 0, curr_count = 0;
5217
5218
70.6k
    if (slp == NULL) {
5219
11.1k
        return SNMPERR_GENERR;
5220
11.1k
    }
5221
59.4k
    session = slp->session;
5222
5223
59.4k
    isp = slp->internal;
5224
59.4k
    transport = slp->transport;
5225
59.4k
    if (!session || !isp || !transport) {
5226
0
        DEBUGMSGTL(("sess_async_send", "send fail: closing...\n"));
5227
0
        return SNMPERR_GENERR;
5228
0
    }
5229
5230
59.4k
    if (pdu == NULL) {
5231
0
        session->s_snmp_errno = SNMPERR_NULL_PDU;
5232
0
        return SNMPERR_GENERR;
5233
0
    }
5234
5235
59.4k
    SNMP_FREE(isp->obuf); /* should already be NULL */
5236
5237
59.4k
    session->s_snmp_errno = 0;
5238
59.4k
    session->s_errno = 0;
5239
5240
    /*
5241
     * Check/setup the version.  
5242
     */
5243
59.4k
    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
59.4k
    } else if (session->version == SNMP_DEFAULT_VERSION) {
5250
        /*
5251
         * It's OK  
5252
         */
5253
59.4k
    } else if (pdu->version != session->version) {
5254
        /*
5255
         * ENHANCE: we should support multi-lingual sessions  
5256
         */
5257
27.6k
        session->s_snmp_errno = SNMPERR_BAD_VERSION;
5258
27.6k
        return SNMPERR_GENERR;
5259
27.6k
    }
5260
31.8k
    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
31.8k
    switch (pdu->command) {
5270
5271
0
        case SNMP_MSG_RESPONSE:
5272
0
        case SNMP_MSG_TRAP:
5273
0
        case SNMP_MSG_TRAP2:
5274
5
        case SNMP_MSG_REPORT:
5275
5
        case AGENTX_MSG_CLEANUPSET:
5276
31.8k
        case AGENTX_MSG_RESPONSE:
5277
31.8k
            pdu->flags &= ~UCD_MSG_FLAG_EXPECT_RESPONSE;
5278
31.8k
            break;
5279
            
5280
0
        default:
5281
0
            pdu->flags |= UCD_MSG_FLAG_EXPECT_RESPONSE;
5282
0
            break;
5283
31.8k
    }
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
31.8k
    if ((pdu->version == SNMP_VERSION_3) &&
5292
5
        (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
31.8k
    if (pdu->msgMaxSize == 0) {
5304
31.8k
        pdu->msgMaxSize = netsnmp_max_send_msg_size();
5305
31.8k
        if (pdu->msgMaxSize > transport->msgMaxSize)
5306
31.8k
            pdu->msgMaxSize = transport->msgMaxSize;
5307
31.8k
        if (pdu->msgMaxSize > session->sndMsgMaxSize)
5308
0
            pdu->msgMaxSize = session->sndMsgMaxSize;
5309
31.8k
        DEBUGMSGTL(("sess_async_send", "max PDU size: %ld\n",
5310
31.8k
                    pdu->msgMaxSize));
5311
31.8k
    }
5312
31.8k
    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
31.8k
    pktbuf_len = SNMP_MIN_MAX_LEN;
5319
31.8k
    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
31.8k
    do {
5361
31.8k
        packet = NULL;
5362
31.8k
        length = 0;
5363
31.8k
        result = netsnmp_build_packet(isp, session, pdu, &pktbuf, &pktbuf_len,
5364
31.8k
                                      &packet, &length);
5365
31.8k
        if (0 != result)
5366
0
            break;
5367
5368
31.8k
        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
31.8k
        if (length <= pdu->msgMaxSize)
5378
31.7k
            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
31.8k
    DEBUGMSGTL(("sess_async_send",
5402
31.8k
                "final pktbuf_len after building packet %" NETSNMP_PRIz "u\n",
5403
31.8k
                pktbuf_len));
5404
31.8k
    if (curr_count != orig_count)
5405
0
        DEBUGMSGTL(("sess_async_send",
5406
31.8k
                    "sending %d of %d varbinds (-%d) from bulk response\n",
5407
31.8k
                    curr_count, orig_count, orig_count - curr_count));
5408
5409
31.8k
    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
31.8k
    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
31.7k
    isp->obuf = pktbuf;
5423
31.7k
    isp->obuf_size = pktbuf_len;
5424
31.7k
    isp->opacket = packet;
5425
31.7k
    isp->opacket_len = length;
5426
5427
31.7k
    return SNMPERR_SUCCESS;
5428
31.8k
}
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
73.1k
{
5455
73.1k
    return snmp_async_send(session, pdu, NULL, NULL);
5456
73.1k
}
5457
5458
int
5459
snmp_sess_send(struct session_list *slp, netsnmp_pdu *pdu)
5460
44
{
5461
44
    return snmp_sess_async_send(slp, pdu, NULL, NULL);
5462
44
}
5463
5464
int
5465
snmp_async_send(netsnmp_session * session,
5466
                netsnmp_pdu *pdu, snmp_callback callback, void *cb_data)
5467
73.1k
{
5468
73.1k
    struct session_list *sessp = snmp_sess_pointer(session);
5469
73.1k
    return snmp_sess_async_send(sessp, pdu, callback, cb_data);
5470
73.1k
}
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
59.4k
{
5499
59.4k
    netsnmp_session *session;
5500
59.4k
    struct snmp_internal_session *isp;
5501
59.4k
    netsnmp_transport *transport = NULL;
5502
59.4k
    int             result;
5503
59.4k
    long            reqid;
5504
5505
59.4k
    if (slp == NULL || NULL == slp->session || NULL ==slp->internal ||
5506
59.4k
                NULL == slp->transport) {
5507
0
        return 0;
5508
0
    }
5509
5510
59.4k
    session = slp->session;
5511
59.4k
    isp = slp->internal;
5512
59.4k
    transport = slp->transport;
5513
5514
59.4k
    if (NULL == isp->opacket) {
5515
59.4k
        result = _build_initial_pdu_packet(slp, pdu, 0);
5516
59.4k
        if ((SNMPERR_SUCCESS != result) || (NULL == isp->opacket)) {
5517
27.6k
            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
27.6k
            return 0;
5554
27.6k
        }
5555
59.4k
    }
5556
5557
    /*
5558
     * Send the message.  
5559
     */
5560
5561
31.7k
    DEBUGMSGTL(("sess_process_packet", "sending message id#%ld reqid#%ld len %"
5562
31.7k
                NETSNMP_PRIz "u\n", pdu->msgid, pdu->reqid, isp->opacket_len));
5563
31.7k
    result = netsnmp_transport_send(transport, isp->opacket, isp->opacket_len,
5564
31.7k
                                    &(pdu->transport_data),
5565
31.7k
                                    &(pdu->transport_data_length));
5566
5567
31.7k
    SNMP_FREE(isp->obuf);
5568
31.7k
    isp->opacket = NULL; /* opacket was in obuf, so no free needed */
5569
31.7k
    isp->opacket_len = 0;
5570
5571
31.7k
    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
31.7k
    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
31.7k
    if (0 == reqid && (SNMPERR_SUCCESS == session->s_snmp_errno))
5592
6.96k
        ++reqid;
5593
5594
    /*
5595
     * Add to pending requests list if we expect a response.  
5596
     */
5597
31.7k
    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
31.7k
    } else {
5645
        /*
5646
         * No response expected...  
5647
         */
5648
31.7k
        if (reqid) {
5649
            /*
5650
             * Free v1 or v2 TRAP PDU iff no error  
5651
             */
5652
31.7k
            snmp_free_pdu(pdu);
5653
31.7k
        }
5654
31.7k
    }
5655
5656
31.7k
    return reqid;
5657
31.7k
}
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
73.1k
{
5678
5679
73.1k
    return snmp_sess_async_send_cp(slp, pdu, callback, cb_data, 0);
5680
73.1k
}
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
73.1k
{
5687
73.1k
    int             rc;
5688
5689
73.1k
    if (slp == NULL) {
5690
13.6k
        snmp_errno = SNMPERR_BAD_SESSION;       /*MTCRITICAL_RESOURCE */
5691
13.6k
        return (0);
5692
13.6k
    }
5693
    /*
5694
     * send pdu
5695
     */
5696
5697
59.4k
    rc = _sess_async_send(slp, pdu, callback, cb_data, cp_inc);
5698
59.4k
    if (rc == 0)
5699
27.6k
        SET_SNMP_ERROR(slp->session->s_snmp_errno);
5700
59.4k
    return rc;
5701
73.1k
}
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
669k
{
5710
669k
    if (!var)
5711
0
        return;
5712
5713
669k
    if (var->name != var->name_loc)
5714
11.2k
        SNMP_FREE(var->name);
5715
669k
    if (var->val.string != var->buf)
5716
36.5k
        SNMP_FREE(var->val.string);
5717
669k
    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
669k
}
5726
5727
void
5728
snmp_free_var(netsnmp_variable_list * var)
5729
669k
{
5730
669k
    snmp_free_var_internals(var);
5731
669k
    free(var);
5732
669k
}
5733
5734
void
5735
snmp_free_varbind(netsnmp_variable_list * var)
5736
646k
{
5737
646k
    netsnmp_variable_list *ptr;
5738
1.29M
    while (var) {
5739
652k
        ptr = var->next_variable;
5740
652k
        snmp_free_var(var);
5741
652k
        var = ptr;
5742
652k
    }
5743
646k
}
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
628k
{
5751
628k
    struct snmp_secmod_def *sptr;
5752
5753
628k
    if (!pdu)
5754
0
        return;
5755
5756
628k
    free_securityStateRef(pdu);
5757
5758
628k
    sptr = find_sec_mod(pdu->securityModel);
5759
628k
    if (sptr && sptr->pdu_free)
5760
111
        (*sptr->pdu_free)(pdu);
5761
5762
628k
    snmp_free_varbind(pdu->variables);
5763
628k
    free(pdu->enterprise);
5764
628k
    free(pdu->community);
5765
628k
    free(pdu->contextEngineID);
5766
628k
    free(pdu->securityEngineID);
5767
628k
    free(pdu->contextName);
5768
628k
    free(pdu->securityName);
5769
628k
    free(pdu->transport_data);
5770
628k
    free(pdu);
5771
628k
}
5772
5773
netsnmp_pdu    *
5774
snmp_create_sess_pdu(netsnmp_transport *transport, void *opaque,
5775
                     size_t olength)
5776
48.5k
{
5777
48.5k
    netsnmp_pdu *pdu = calloc(1, sizeof(netsnmp_pdu));
5778
48.5k
    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
48.5k
    pdu->transport_data = opaque;
5789
48.5k
    pdu->transport_data_length = olength;
5790
48.5k
    pdu->tDomain = transport->domain;
5791
48.5k
    pdu->tDomainLen = transport->domain_length;
5792
48.5k
    return pdu;
5793
48.5k
}
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
48.5k
{
5806
48.5k
  netsnmp_pdu    *pdu;
5807
48.5k
  int             ret = 0;
5808
48.5k
  int             dump = 0, filter = 0;
5809
5810
48.5k
  debug_indent_reset();
5811
5812
48.5k
  DEBUGMSGTL(("sess_process_packet",
5813
48.5k
        "session %p fd %" NETSNMP_FMT_SKT " pkt %p length %d\n", slp,
5814
48.5k
        transport->sock, packetptr, length));
5815
5816
48.5k
  dump = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
5817
48.5k
                                NETSNMP_DS_LIB_DUMP_PACKET);
5818
48.5k
#ifndef NETSNMP_FEATURE_REMOVE_FILTER_SOURCE
5819
48.5k
  filter = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
5820
48.5k
                                  NETSNMP_DS_LIB_FILTER_TYPE);
5821
48.5k
#endif
5822
48.5k
  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
48.5k
  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
48.5k
  if (isp->hook_create_pdu) {
5888
0
    pdu = isp->hook_create_pdu(transport, opaque, olength);
5889
48.5k
  } else {
5890
48.5k
    pdu = snmp_create_sess_pdu(transport, opaque, olength);
5891
48.5k
  }
5892
5893
48.5k
  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
48.5k
  if (transport->flags & NETSNMP_TRANSPORT_FLAG_TUNNELED) {
5902
0
      pdu->flags |= UCD_MSG_FLAG_TUNNELED;
5903
0
  }
5904
5905
48.5k
  if (isp->hook_parse) {
5906
0
    ret = isp->hook_parse(sp, pdu, packetptr, length);
5907
48.5k
  } else {
5908
48.5k
    ret = snmp_parse(slp, sp, pdu, packetptr, length);
5909
48.5k
  }
5910
5911
48.5k
  DEBUGMSGTL(("sess_process_packet", "received message id#%ld reqid#%ld len "
5912
48.5k
              "%u\n", pdu->msgid, pdu->reqid, length));
5913
5914
48.5k
  if (ret != SNMP_ERR_NOERROR) {
5915
46.9k
    DEBUGMSGTL(("sess_process_packet", "parse fail\n"));
5916
46.9k
  }
5917
5918
48.5k
  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
48.5k
  if (ret != SNMP_ERR_NOERROR) {
5926
46.9k
    snmp_free_pdu(pdu);
5927
46.9k
    return NULL;
5928
46.9k
  }
5929
5930
1.57k
  return pdu;
5931
48.5k
}
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
1.57k
{
6032
1.57k
  netsnmp_request_list *rp, *orp = NULL;
6033
1.57k
  int             handled = 0;
6034
6035
1.57k
  if (pdu->flags & UCD_MSG_FLAG_RESPONSE_PDU) {
6036
    /*
6037
     * Call USM to free any securityStateRef supplied with the message.  
6038
     */
6039
284
    free_securityStateRef(pdu);
6040
6041
284
    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
1.29k
  } else {
6162
1.29k
    if (sp->callback) {
6163
      /*
6164
       * MTR snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION); 
6165
       */
6166
1.29k
      handled = 1;
6167
1.29k
      sp->callback(NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE,
6168
1.29k
       sp, pdu->reqid, pdu, sp->callback_magic);
6169
      /*
6170
       * MTR snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION); 
6171
       */
6172
1.29k
    }
6173
1.29k
  }
6174
6175
1.57k
  if (!handled) {
6176
284
    if (sp->flags & SNMP_FLAGS_SHARED_SOCKET)
6177
0
      return -2;
6178
284
    snmp_increment_statistic(STAT_SNMPUNKNOWNPDUHANDLERS);
6179
284
    DEBUGMSGTL(("sess_process_packet", "unhandled PDU\n"));
6180
284
  }
6181
6182
1.57k
  snmp_free_pdu(pdu);
6183
1.57k
  return 0;
6184
1.57k
}
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
48.5k
{
6202
48.5k
    netsnmp_pdu         *pdu;
6203
48.5k
    int                  rc;
6204
6205
48.5k
    pdu = _sess_process_packet_parse_pdu(slp, sp, isp, transport, opaque,
6206
48.5k
                                         olength, packetptr, length);
6207
48.5k
    if (NULL == pdu)
6208
46.9k
        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
1.57k
    do {
6216
1.57k
        rc = _sess_process_packet_handle_pdu(slp, sp, isp, transport, pdu);
6217
1.57k
        if (-2 != rc || !(transport->flags & NETSNMP_TRANSPORT_FLAG_SHARED))
6218
1.57k
            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
1.57k
    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
1.57k
  return rc;
6239
48.5k
}
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
2.96k
{
6251
2.96k
    struct timeval now;
6252
6253
2.96k
    if (isp == NULL || !timerisset(&isp->packet_deadline))
6254
2.96k
        return 0;
6255
0
    netsnmp_get_monotonic_clock(&now);
6256
0
    return !timercmp(&now, &isp->packet_deadline, <);
6257
2.96k
}
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
60
{
6334
60
    netsnmp_large_fd_set lfdset;
6335
6336
60
    netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
6337
60
    netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
6338
60
    snmp_read2(&lfdset);
6339
60
    netsnmp_large_fd_set_cleanup(&lfdset);
6340
60
}
6341
6342
void
6343
snmp_read2(netsnmp_large_fd_set * fdset)
6344
2.96k
{
6345
2.96k
    struct session_list *slp, *next;
6346
6347
2.96k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
6348
5.92k
    for (slp = Sessions; slp; slp = next) {
6349
2.96k
        next = slp->next;
6350
2.96k
        if (_sess_packet_deadline_expired(slp->internal)) {
6351
0
            _sess_close_stream(slp);
6352
0
            continue;
6353
0
        }
6354
2.96k
        snmp_sess_read2(slp, fdset);
6355
2.96k
    }
6356
2.96k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
6357
2.96k
}
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
2.96k
{
6470
2.96k
    netsnmp_session *sp = slp ? slp->session : NULL;
6471
2.96k
    struct snmp_internal_session *isp = slp ? slp->internal : NULL;
6472
2.96k
    netsnmp_transport *transport = slp ? slp->transport : NULL;
6473
6474
2.96k
    if (!sp || !isp || !transport || !rcvp ) {
6475
0
        DEBUGMSGTL(("sess_read_packet", "missing arguments\n"));
6476
0
        return -2;
6477
0
    }
6478
6479
2.96k
    if (transport->flags & NETSNMP_TRANSPORT_FLAG_STREAM)
6480
0
        return -2;
6481
6482
2.96k
    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
2.96k
    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
2.96k
    rcvp->packet_len = netsnmp_transport_recv(transport, rcvp->packet,
6495
2.96k
                                              SNMP_MAX_RCV_MSG_SIZE,
6496
2.96k
                                              &rcvp->opaque, &rcvp->olength);
6497
2.96k
    if (rcvp->packet_len == -1) {
6498
5
        sp->s_snmp_errno = SNMPERR_BAD_RECVFROM;
6499
5
        sp->s_errno = errno;
6500
5
        snmp_set_detail(strerror(errno));
6501
5
        SNMP_FREE(rcvp->packet);
6502
5
        SNMP_FREE(rcvp->opaque);
6503
5
        return -1;
6504
5
    }
6505
6506
2.95k
    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
2.95k
    return 0;
6523
2.95k
}
6524
6525
static int
6526
__sess_read(struct session_list *slp)
6527
2.96k
{
6528
2.96k
    netsnmp_session *sp = slp ? slp->session : NULL;
6529
2.96k
    struct snmp_internal_session *isp = slp ? slp->internal : NULL;
6530
2.96k
    netsnmp_transport *transport = slp ? slp->transport : NULL;
6531
2.96k
    size_t          pdulen = 0;
6532
2.96k
    size_t          rxbuf_len;
6533
2.96k
    size_t          stream_limit;
6534
2.96k
    u_char         *rxbuf = NULL;
6535
2.96k
    int             length = 0, olength = 0, rc = 0;
6536
2.96k
    void           *opaque = NULL;
6537
6538
2.96k
    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
2.96k
    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
2.96k
    sp->s_snmp_errno = 0;
6550
2.96k
    sp->s_errno = 0;
6551
6552
2.96k
    stream_limit = sp->rcvMsgMaxSize ?
6553
60
        SNMP_MIN(SNMP_MAX_PACKET_LEN, sp->rcvMsgMaxSize) :
6554
2.96k
        SNMP_MAX_PACKET_LEN;
6555
2.96k
    rxbuf_len = SNMP_MIN(SNMP_MAX_RCV_MSG_SIZE, stream_limit);
6556
6557
2.96k
    if (transport->flags & NETSNMP_TRANSPORT_FLAG_LISTEN)
6558
0
        return _sess_read_accept(slp);
6559
6560
2.96k
    if (!(transport->flags & NETSNMP_TRANSPORT_FLAG_STREAM)) {
6561
2.96k
        snmp_rcv_packet rcvp;
6562
2.96k
        u_char *pptr;
6563
2.96k
        size_t len_remaining, pdulen;
6564
2.96k
        void *ocopy = NULL;
6565
6566
2.96k
        memset(&rcvp, 0x0, sizeof(rcvp));
6567
6568
        /** read the packet */
6569
2.96k
        rc = _sess_read_dgram_packet(slp, &rcvp);
6570
2.96k
        if (-1 == rc) /* protocol error */
6571
5
            return -1;
6572
2.95k
        else if (-2 == rc) /* no packet to process */
6573
0
            return 0;
6574
6575
2.95k
        pptr = rcvp.packet;
6576
2.95k
        len_remaining = rcvp.packet_len;
6577
2.95k
        rc = 0;
6578
6579
51.4k
        while (len_remaining > 0) {
6580
49.2k
            if (isp->check_packet) {
6581
0
                pdulen = isp->check_packet(pptr, len_remaining);
6582
49.2k
            } else {
6583
49.2k
                pdulen = asn_check_packet(pptr, len_remaining);
6584
49.2k
            }
6585
49.2k
            if (pdulen == 0 || pdulen > len_remaining || pdulen > SNMP_MAX_PACKET_LEN) {
6586
                /* Not a valid packet or incomplete in datagram mode */
6587
786
                if (pptr == rcvp.packet) {
6588
321
                    SNMP_FREE(rcvp.opaque);
6589
321
                }
6590
786
                break;
6591
786
            }
6592
48.5k
            if (pdulen < len_remaining) {
6593
46.3k
                if (rcvp.olength > 0 && rcvp.opaque != NULL) {
6594
357
                    ocopy = malloc(rcvp.olength);
6595
357
                    if (ocopy != NULL) {
6596
357
                        memcpy(ocopy, rcvp.opaque, rcvp.olength);
6597
357
                    }
6598
357
                }
6599
46.3k
            } else {
6600
2.17k
                ocopy = rcvp.opaque;
6601
2.17k
                rcvp.opaque = NULL;
6602
2.17k
            }
6603
48.5k
            rc = _sess_process_packet(slp, sp, isp, transport,
6604
48.5k
                                      ocopy, ocopy ? rcvp.olength : 0,
6605
48.5k
                                      pptr, pdulen);
6606
48.5k
            ocopy = NULL;
6607
48.5k
            pptr += pdulen;
6608
48.5k
            len_remaining -= pdulen;
6609
48.5k
        }
6610
2.95k
        SNMP_FREE(rcvp.packet);
6611
2.95k
        SNMP_FREE(rcvp.opaque);
6612
2.95k
        return rc;
6613
2.96k
    }
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
2.96k
{
6858
2.96k
    netsnmp_transport *transport;
6859
6860
2.96k
    if (!slp || !fdset)
6861
0
        return 0;
6862
6863
2.96k
    transport = slp->transport;
6864
6865
2.96k
    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
2.96k
    return __sess_read(slp);
6871
2.96k
}
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
2.96k
{
6894
2.96k
    netsnmp_session *pss;
6895
2.96k
    int             rc;
6896
6897
2.96k
    rc = _sess_read(slp, fdset);
6898
2.96k
    pss = slp->session;
6899
2.96k
    if (rc && pss->s_snmp_errno) {
6900
2.59k
        SET_SNMP_ERROR(pss->s_snmp_errno);
6901
2.59k
    }
6902
2.96k
    return rc;
6903
2.96k
}
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
60
{
6969
60
    return snmp_sess_select_info(NULL, numfds, fdset, timeout, block);
6970
60
}
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
60
{
6989
60
    return snmp_sess_select_info_flags(slp, numfds, fdset, timeout, block,
6990
60
                                       NETSNMP_SELECT_NOFLAGS);
6991
60
}
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
60
{
7000
60
  int rc;
7001
60
  netsnmp_large_fd_set lfdset;
7002
7003
60
  netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
7004
60
  netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
7005
60
  rc = snmp_sess_select_info2_flags(slp, numfds, &lfdset, timeout,
7006
60
                                    block, flags);
7007
60
  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
60
  netsnmp_large_fd_set_cleanup(&lfdset);
7013
60
  return rc;
7014
60
}
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
60
{
7059
60
    struct session_list *slp, *next = NULL;
7060
60
    netsnmp_request_list *rp;
7061
60
    struct timeval  now, earliest, alarm_tm;
7062
60
    int             active = 0, requests = 0;
7063
60
    int             next_alarm = 0;
7064
60
    int             has_pending_data = 0;
7065
60
    int             packet_deadlines = 0;
7066
7067
60
    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
60
    DEBUGMSGTL(("sess_select", "for %s session%s: ",
7076
60
                sessp ? "single" : "all", sessp ? "" : "s"));
7077
7078
120
    for (slp = sessp ? sessp : Sessions; slp; slp = next) {
7079
60
        next = slp->next;
7080
7081
60
        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
60
        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
60
        DEBUGMSG(("sess_select", "%" NETSNMP_FMT_SKT " ",
7105
60
                  slp->transport->sock));
7106
60
        if ((slp->transport->sock + 1) > *numfds) {
7107
60
            *numfds = (slp->transport->sock + 1);
7108
60
        }
7109
7110
60
        NETSNMP_LARGE_FD_SET(slp->transport->sock, fdset);
7111
60
        if (slp->transport->f_pending &&
7112
0
            slp->transport->f_pending(slp->transport)) {
7113
0
            has_pending_data = 1;
7114
0
        }
7115
60
        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
60
        if (slp->internal != NULL &&
7131
60
            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
60
        active++;
7139
60
        if (sessp) {
7140
            /*
7141
             * Single session processing.  
7142
             */
7143
0
            break;
7144
0
        }
7145
60
    }
7146
60
    DEBUGMSG(("sess_select", "\n"));
7147
7148
60
    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
60
    netsnmp_get_monotonic_clock(&now);
7157
7158
60
    if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7159
60
                               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
60
    if (next_alarm == 0 && requests == 0 && packet_deadlines == 0) {
7167
        /*
7168
         * If none are active, skip arithmetic.  
7169
         */
7170
60
        DEBUGMSGT(("sess_select","blocking:no session requests or alarms.\n"));
7171
60
        *block = 1; /* can block - timeout value is undefined if no requests */
7172
60
        return active;
7173
60
    }
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
60
}
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
130k
{
7391
130k
    register int    len;
7392
130k
    register const oid *name1 = in_name1;
7393
130k
    register const oid *name2 = in_name2;
7394
7395
    /*
7396
     * len = minimum of len1 and len2 
7397
     */
7398
130k
    if (len1 < len2)
7399
8
        len = len1;
7400
130k
    else
7401
130k
        len = len2;
7402
    /*
7403
     * find first non-matching OID 
7404
     */
7405
438k
    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
401k
        if (*(name1) != *(name2)) {
7412
93.3k
            if (*(name1) < *(name2))
7413
73.9k
                return -1;
7414
19.3k
            return 1;
7415
93.3k
        }
7416
307k
        name1++;
7417
307k
        name2++;
7418
307k
    }
7419
    /*
7420
     * both OIDs equal up to length of shorter OID 
7421
     */
7422
37.1k
    if (len1 < len2)
7423
2
        return -1;
7424
37.1k
    if (len2 < len1)
7425
372
        return 1;
7426
36.7k
    return 0;
7427
37.1k
}
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
120k
{
7448
120k
    register int    len;
7449
120k
    register const oid *name1 = in_name1;
7450
120k
    register const oid *name2 = in_name2;
7451
120k
    int initlen;
7452
7453
    /*
7454
     * len = minimum of len1 and len2 
7455
     */
7456
120k
    if (len1 < len2)
7457
0
        initlen = len = len1;
7458
120k
    else
7459
120k
        initlen = len = len2;
7460
    /*
7461
     * find first non-matching OID 
7462
     */
7463
153k
    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
120k
        if (*(name1) != *(name2)) {
7470
87.0k
            *offpt = initlen - len;
7471
87.0k
            if (*(name1) < *(name2))
7472
22.1k
                return -1;
7473
64.8k
            return 1;
7474
87.0k
        }
7475
33.0k
        name1++;
7476
33.0k
        name2++;
7477
33.0k
    }
7478
    /*
7479
     * both OIDs equal up to length of shorter OID 
7480
     */
7481
33.0k
    *offpt = initlen - len;
7482
33.0k
    if (len1 < len2)
7483
0
        return -1;
7484
33.0k
    if (len2 < len1)
7485
739
        return 1;
7486
32.2k
    return 0;
7487
33.0k
}
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
275k
{
7528
275k
    register const oid *name1 = in_name1;
7529
275k
    register const oid *name2 = in_name2;
7530
275k
    register int    len = len1;
7531
7532
    /*
7533
     * len = minimum of len1 and len2 
7534
     */
7535
275k
    if (len1 != len2)
7536
175k
        return 1;
7537
    /*
7538
     * Handle 'null' OIDs
7539
     */
7540
100k
    if (len1 == 0)
7541
0
        return 0;   /* Two null OIDs are (trivially) the same */
7542
100k
    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
701k
    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
680k
        if (*(name1++) != *(name2++))
7554
78.8k
            return 1;
7555
680k
    }
7556
21.5k
    return 0;
7557
100k
}
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
1.07k
{
7594
1.07k
    int i;
7595
1.07k
    size_t min_size;
7596
7597
1.07k
    if (!in_name1 || !in_name2 || !len1 || !len2)
7598
0
        return -1;
7599
7600
1.07k
    if (in_name1[0] != in_name2[0])
7601
1.07k
        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
171
{
7617
171
    char *cp   = NULL;
7618
171
    char *temp = NULL;
7619
171
    int   temp_len = 0;
7620
171
    size_t temp_sz = 0;
7621
171
    int check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7622
171
                                  NETSNMP_DS_LIB_DONT_CHECK_RANGE);
7623
  
7624
171
    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
171
    free(temp);
7656
171
    return 1;
7657
171
}
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
250k
{
7670
250k
    return snmp_varlist_add_variable(&pdu->variables, name, name_length,
7671
250k
                                     type, value, len);
7672
250k
}
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
250k
{
7684
250k
    netsnmp_variable_list *vars, *vtmp;
7685
250k
    int rc;
7686
7687
250k
    if (varlist == NULL)
7688
0
        return NULL;
7689
7690
250k
    vars = SNMP_MALLOC_TYPEDEF(netsnmp_variable_list);
7691
250k
    if (vars == NULL)
7692
0
        return NULL;
7693
7694
250k
    vars->type = type;
7695
7696
250k
    rc = snmp_set_var_value( vars, value, len );
7697
250k
    if (( 0 != rc ) ||
7698
250k
        (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
250k
    if (*varlist == NULL) {
7707
51.0k
        *varlist = vars;
7708
199k
    } else {
7709
242M
        for (vtmp = *varlist; vtmp->next_variable;
7710
242M
             vtmp = vtmp->next_variable);
7711
7712
199k
        vtmp->next_variable = vars;
7713
199k
    }
7714
7715
250k
    return vars;
7716
250k
}
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
902
#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
555
{
7732
555
    u_char         *new_buf;
7733
555
    size_t          new_len;
7734
7735
555
    if (needed <= *buf_len)
7736
423
        return 1;
7737
132
    if (needed > NETSNMP_MAX_BITS_OCTETS)
7738
0
        return 0;
7739
132
    new_len = *buf_len * 2;
7740
132
    if (new_len < needed)
7741
91
        new_len = needed;
7742
132
    if (new_len > NETSNMP_MAX_BITS_OCTETS)
7743
10
        new_len = NETSNMP_MAX_BITS_OCTETS;
7744
132
    new_buf = realloc(*buf, new_len);
7745
132
    if (!new_buf)
7746
0
        return 0;
7747
132
    memset(new_buf + *buf_len, 0, new_len - *buf_len);
7748
132
    *buf = new_buf;
7749
132
    *buf_len = new_len;
7750
132
    return 1;
7751
132
}
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
5.30k
{
7769
5.30k
    char           *st;
7770
5.30k
    const char     *cp;
7771
5.30k
    char           *ecp, *vp = NULL;
7772
5.30k
    int             result = SNMPERR_SUCCESS;
7773
5.30k
#ifndef NETSNMP_DISABLE_MIB_LOADING
7774
5.30k
    int             check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7775
5.30k
               NETSNMP_DS_LIB_DONT_CHECK_RANGE);
7776
5.30k
    int             do_hint = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
7777
5.30k
               NETSNMP_DS_LIB_NO_DISPLAY_HINT);
7778
5.30k
    u_char         *hintptr;
7779
5.30k
    struct tree    *tp;
7780
5.30k
    struct enum_list *ep;
7781
5.30k
    int             itmp;
7782
5.30k
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7783
5.30k
    u_char         *buf = NULL;
7784
5.30k
    const u_char   *buf_ptr = NULL;
7785
5.30k
    size_t          buf_len = 0, value_len = 0, tint;
7786
5.30k
    in_addr_t       atmp;
7787
5.30k
    long            ltmp;
7788
5.30k
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
7789
5.30k
    double          dtmp;
7790
5.30k
    float           ftmp;
7791
5.30k
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
7792
5.30k
    struct counter64 c64tmp;
7793
7794
5.30k
#ifndef NETSNMP_DISABLE_MIB_LOADING
7795
5.30k
    tp = get_tree(name, name_length, get_tree_head());
7796
5.30k
    if (!tp || !tp->type || tp->type > TYPE_SIMPLE_LAST) {
7797
5.30k
        check = 0;
7798
5.30k
    }
7799
5.30k
    if (!(tp && tp->hint))
7800
5.30k
  do_hint = 0;
7801
7802
5.30k
    if (tp && type == '=') {
7803
        /*
7804
         * generic assignment - let the tree node decide value format 
7805
         */
7806
7
        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
7
        }
7840
7
    }
7841
5.30k
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7842
7843
5.30k
    switch (type) {
7844
151
    case 'i':
7845
151
#ifndef NETSNMP_DISABLE_MIB_LOADING
7846
151
        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
151
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7853
151
        if (!*value)
7854
2
            goto value_error;
7855
149
        ltmp = strtol(value, &ecp, 10);
7856
149
        if (*ecp) {
7857
25
#ifndef NETSNMP_DISABLE_MIB_LOADING
7858
25
            ep = tp ? tp->enums : NULL;
7859
25
            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
25
            if (!ep) {
7867
25
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7868
25
                result = SNMPERR_RANGE;   /* ?? or SNMPERR_VALUE; */
7869
25
                snmp_set_detail(value);
7870
25
                break;
7871
25
#ifndef NETSNMP_DISABLE_MIB_LOADING
7872
25
            }
7873
25
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7874
25
        }
7875
7876
124
#ifndef NETSNMP_DISABLE_MIB_LOADING
7877
124
        if (!_check_range(tp, ltmp, &result, value))
7878
0
            break;
7879
124
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7880
124
        snmp_pdu_add_variable(pdu, name, name_length, ASN_INTEGER,
7881
124
                              &ltmp, sizeof(ltmp));
7882
124
        break;
7883
7884
31
    case 'u':
7885
31
#ifndef NETSNMP_DISABLE_MIB_LOADING
7886
31
        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
31
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7892
31
        ltmp = strtoul(value, &ecp, 10);
7893
31
        if (*value && !*ecp)
7894
15
            snmp_pdu_add_variable(pdu, name, name_length, ASN_UNSIGNED,
7895
15
                                  &ltmp, sizeof(ltmp));
7896
16
        else
7897
16
            goto value_error;
7898
15
        break;
7899
7900
101
    case '3':
7901
101
#ifndef NETSNMP_DISABLE_MIB_LOADING
7902
101
        if (check && tp->type != TYPE_UINTEGER) {
7903
0
            value = "UInteger32";
7904
0
            result = SNMPERR_VALUE;
7905
0
            goto type_error;
7906
0
        }
7907
101
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7908
101
        ltmp = strtoul(value, &ecp, 10);
7909
101
        if (*value && !*ecp)
7910
91
            snmp_pdu_add_variable(pdu, name, name_length, ASN_UINTEGER,
7911
91
                                  &ltmp, sizeof(ltmp));
7912
10
        else
7913
10
            goto value_error;
7914
91
        break;
7915
7916
91
    case 'c':
7917
40
#ifndef NETSNMP_DISABLE_MIB_LOADING
7918
40
        if (check && tp->type != TYPE_COUNTER) {
7919
0
            value = "Counter32";
7920
0
            result = SNMPERR_VALUE;
7921
0
            goto type_error;
7922
0
        }
7923
40
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7924
40
        ltmp = strtoul(value, &ecp, 10);
7925
40
        if (*value && !*ecp)
7926
24
            snmp_pdu_add_variable(pdu, name, name_length, ASN_COUNTER,
7927
24
                                  &ltmp, sizeof(ltmp));
7928
16
        else
7929
16
            goto value_error;
7930
24
        break;
7931
7932
202
    case 'C':
7933
202
#ifndef NETSNMP_DISABLE_MIB_LOADING
7934
202
        if (check && tp->type != TYPE_COUNTER64) {
7935
0
            value = "Counter64";
7936
0
            result = SNMPERR_VALUE;
7937
0
            goto type_error;
7938
0
        }
7939
202
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7940
202
        if (read64(&c64tmp, value))
7941
145
            snmp_pdu_add_variable(pdu, name, name_length, ASN_COUNTER64,
7942
145
                                  &c64tmp, sizeof(c64tmp));
7943
57
        else
7944
57
            goto value_error;
7945
145
        break;
7946
7947
145
    case 't':
7948
26
#ifndef NETSNMP_DISABLE_MIB_LOADING
7949
26
        if (check && tp->type != TYPE_TIMETICKS) {
7950
0
            value = "Timeticks";
7951
0
            result = SNMPERR_VALUE;
7952
0
            goto type_error;
7953
0
        }
7954
26
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7955
26
        ltmp = strtoul(value, &ecp, 10);
7956
26
        if (*value && !*ecp)
7957
13
            snmp_pdu_add_variable(pdu, name, name_length, ASN_TIMETICKS,
7958
13
                                  &ltmp, sizeof(long));
7959
13
        else
7960
13
            goto value_error;
7961
13
        break;
7962
7963
185
    case 'a':
7964
185
#ifndef NETSNMP_DISABLE_MIB_LOADING
7965
185
        if (check && tp->type != TYPE_IPADDR) {
7966
0
            value = "IpAddress";
7967
0
            result = SNMPERR_VALUE;
7968
0
            goto type_error;
7969
0
        }
7970
185
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7971
185
        atmp = inet_addr(value);
7972
185
        if (atmp != (in_addr_t) -1 || !strcmp(value, "255.255.255.255"))
7973
52
            snmp_pdu_add_variable(pdu, name, name_length, ASN_IPADDRESS,
7974
52
                                  &atmp, sizeof(atmp));
7975
133
        else
7976
133
            goto value_error;
7977
52
        break;
7978
7979
763
    case 'o':
7980
763
#ifndef NETSNMP_DISABLE_MIB_LOADING
7981
763
        if (check && tp->type != TYPE_OBJID) {
7982
0
            value = "OBJECT IDENTIFIER";
7983
0
            result = SNMPERR_VALUE;
7984
0
            goto type_error;
7985
0
        }
7986
763
#endif /* NETSNMP_DISABLE_MIB_LOADING */
7987
763
        buf = malloc(sizeof(oid) * MAX_OID_LEN);
7988
763
        if (buf == NULL) {
7989
0
            result = SNMPERR_MALLOC;
7990
0
            break;
7991
0
        }
7992
763
        tint = MAX_OID_LEN;
7993
763
        if (snmp_parse_oid(value, (oid *) buf, &tint)) {
7994
268
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OBJECT_ID,
7995
268
                                  buf, sizeof(oid) * tint);
7996
495
        } else {
7997
495
            result = snmp_errno;    /*MTCRITICAL_RESOURCE */
7998
495
        }
7999
763
        break;
8000
8001
14
    case 's':
8002
61
    case 'x':
8003
155
    case 'd':
8004
155
#ifndef NETSNMP_DISABLE_MIB_LOADING
8005
155
        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
155
  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
155
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8020
155
        if (type == 'd') {
8021
94
            if (!snmp_decimal_to_binary
8022
94
                (&buf, &buf_len, &value_len, 1, value)) {
8023
70
                result = SNMPERR_VALUE;
8024
70
                snmp_set_detail(value);
8025
70
                break;
8026
70
            }
8027
24
            buf_ptr = buf;
8028
61
        } else if (type == 'x') {
8029
47
            if (!snmp_hex_to_binary(&buf, &buf_len, &value_len, 1, value)) {
8030
38
                result = SNMPERR_VALUE;
8031
38
                snmp_set_detail(value);
8032
38
                break;
8033
38
            }
8034
9
            buf_ptr = buf;
8035
14
        } else if (type == 's') {
8036
14
            buf_ptr = (const u_char *)value;
8037
14
            value_len = strlen(value);
8038
14
        }
8039
47
#ifndef NETSNMP_DISABLE_MIB_LOADING
8040
47
        if (!_check_range(tp, value_len, &result, "Bad string length"))
8041
0
            break;
8042
47
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8043
47
        snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
8044
47
                              buf_ptr, value_len);
8045
47
        break;
8046
8047
17
    case 'n':
8048
17
        snmp_pdu_add_variable(pdu, name, name_length, ASN_NULL, NULL, 0);
8049
17
        break;
8050
8051
264
    case 'b':
8052
264
#ifndef NETSNMP_DISABLE_MIB_LOADING
8053
264
        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
264
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8059
264
        tint = 0;
8060
264
        buf_len = 256;
8061
264
        buf = calloc(1, buf_len);
8062
264
        if (buf == NULL) {
8063
0
            result = SNMPERR_MALLOC;
8064
0
            break;
8065
0
        }
8066
8067
264
#ifndef NETSNMP_DISABLE_MIB_LOADING
8068
264
        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
264
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8074
264
        if (tint > NETSNMP_MAX_BITS_OCTETS) {
8075
0
            result = SNMPERR_RANGE;
8076
0
            snmp_set_detail(value);
8077
0
            goto err;
8078
0
        }
8079
264
        if (!_bits_buf_grow(&buf, &buf_len, tint)) {
8080
0
            result = SNMPERR_MALLOC;
8081
0
            goto err;
8082
0
        }
8083
8084
264
  vp = strdup(value);
8085
264
        if (!vp)
8086
0
            goto value_error;
8087
8088
555
  for (cp = strtok_r(vp, " ,\t", &st); cp; cp = strtok_r(NULL, " ,\t", &st)) {
8089
460
            int             ix, bit;
8090
8091
460
            ltmp = strtoul(cp, &ecp, 0);
8092
460
            if (ltmp < 0) {
8093
71
                result = SNMPERR_VALUE;
8094
71
                snmp_set_detail(cp);
8095
71
                goto err;
8096
71
            }
8097
389
            if (*ecp != 0) {
8098
25
#ifndef NETSNMP_DISABLE_MIB_LOADING
8099
25
                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
25
                if (ep != NULL) {
8105
0
                    ltmp = ep->value;
8106
25
                } else {
8107
25
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8108
25
                    result = SNMPERR_RANGE;   /* ?? or SNMPERR_VALUE; */
8109
25
                    snmp_set_detail(cp);
8110
25
                    goto err;
8111
25
#ifndef NETSNMP_DISABLE_MIB_LOADING
8112
25
                }
8113
25
#endif /* NETSNMP_DISABLE_MIB_LOADING */
8114
25
            }
8115
8116
364
            if (ltmp < 0 || ltmp / 8 >= NETSNMP_MAX_BITS_OCTETS) {
8117
73
                result = SNMPERR_RANGE;
8118
73
                snmp_set_detail(cp);
8119
73
                goto err;
8120
73
            }
8121
291
            ix = ltmp / 8;
8122
291
            if (ix >= (int) tint) {
8123
213
                tint = ix + 1;
8124
213
            }
8125
291
            if (!_bits_buf_grow(&buf, &buf_len, ix + 1)) {
8126
0
                result = SNMPERR_MALLOC;
8127
0
                goto err;
8128
0
            }
8129
291
            bit = 0x80 >> ltmp % 8;
8130
291
            buf[ix] |= bit;
8131
      
8132
291
        }
8133
95
  SNMP_FREE(vp);
8134
95
        snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
8135
95
                              buf, tint);
8136
95
        break;
8137
8138
0
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
8139
50
    case 'U':
8140
50
        if (read64(&c64tmp, value))
8141
46
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_U64,
8142
46
                                  &c64tmp, sizeof(c64tmp));
8143
4
        else
8144
4
            goto value_error;
8145
46
        break;
8146
8147
150
    case 'I':
8148
150
        if (read64(&c64tmp, value))
8149
119
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_I64,
8150
119
                                  &c64tmp, sizeof(c64tmp));
8151
31
        else
8152
31
            goto value_error;
8153
119
        break;
8154
8155
119
    case 'F':
8156
108
        if (sscanf(value, "%f", &ftmp) == 1)
8157
40
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_FLOAT,
8158
40
                                  &ftmp, sizeof(ftmp));
8159
68
        else
8160
68
            goto value_error;
8161
40
        break;
8162
8163
149
    case 'D':
8164
149
        if (sscanf(value, "%lf", &dtmp) == 1)
8165
78
            snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_DOUBLE,
8166
78
                                  &dtmp, sizeof(dtmp));
8167
71
        else
8168
71
            goto value_error;
8169
78
        break;
8170
78
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
8171
8172
2.90k
    default:
8173
2.90k
        result = SNMPERR_VAR_TYPE;
8174
2.90k
  buf = calloc(1, 4);
8175
2.90k
  if (buf != NULL) {
8176
2.90k
      snprintf((char *)buf, 4, "\"%c\"", type);
8177
2.90k
      snmp_set_detail((char *)buf);
8178
2.90k
  }
8179
2.90k
        break;
8180
5.30k
    }
8181
8182
4.71k
    SNMP_FREE(buf);
8183
4.71k
    SET_SNMP_ERROR(result);
8184
4.71k
    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
421
value_error:
8254
421
    result = SNMPERR_VALUE;
8255
421
    snmp_set_detail(value);
8256
8257
590
err:
8258
590
    free(buf);
8259
590
    free(vp);
8260
8261
590
out:
8262
590
    SET_SNMP_ERROR(result);
8263
590
    return result;
8264
590
}
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
87.8k
{
8274
87.8k
    struct session_list *slp;
8275
8276
87.8k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
8277
137k
    for (slp = Sessions; slp; slp = slp->next) {
8278
112k
        if (slp->session == session) {
8279
63.0k
            break;
8280
63.0k
        }
8281
112k
    }
8282
87.8k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
8283
8284
87.8k
    if (slp == NULL) {
8285
24.7k
        snmp_errno = SNMPERR_BAD_SESSION;       /*MTCRITICAL_RESOURCE */
8286
24.7k
        return (NULL);
8287
24.7k
    }
8288
63.0k
    return slp;
8289
87.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
10.7k
{
8298
10.7k
    if (slp == NULL)
8299
0
        return (NULL);
8300
10.7k
    return (slp->session);
8301
10.7k
}
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
3.58k
{
8315
3.58k
    struct session_list *slp;
8316
8317
3.58k
    snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
8318
3.58k
    for (slp = Sessions; slp; slp = slp->next) {
8319
3.58k
        if (slp == sessp) {
8320
3.58k
            break;
8321
3.58k
        }
8322
3.58k
    }
8323
3.58k
    snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
8324
8325
3.58k
    return (netsnmp_session *)slp;
8326
3.58k
}
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
144k
{
8395
144k
    oid            *returnOid;
8396
144k
    if (objToCopy != NULL && objToCopyLen != 0) {
8397
144k
        returnOid = (oid *) malloc(objToCopyLen * sizeof(oid));
8398
144k
        if (returnOid) {
8399
144k
            memcpy(returnOid, objToCopy, objToCopyLen * sizeof(oid));
8400
144k
        }
8401
144k
    } else
8402
0
        returnOid = NULL;
8403
144k
    return returnOid;
8404
144k
}
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
80.0k
{
8415
80.0k
    if (which >= 0 && which < NETSNMP_STAT_MAX_STATS) {
8416
80.0k
        statistics[which]++;
8417
80.0k
        return statistics[which];
8418
80.0k
    }
8419
0
    return 0;
8420
80.0k
}
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
11
{
8435
11
    if (which >= 0 && which < NETSNMP_STAT_MAX_STATS)
8436
11
        return statistics[which];
8437
0
    return 0;
8438
11
}
8439
8440
void
8441
snmp_init_statistics(void)
8442
3.65k
{
8443
3.65k
    memset(statistics, 0, sizeof(statistics));
8444
3.65k
}
8445
#endif /* NETSNMP_FEATURE_REMOVE_STATISTICS */
8446
/**  @} */