1 /*
2 ** Zabbix
3 ** Copyright (C) 2001-2021 Zabbix SIA
4 **
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ** GNU General Public License for more details.
14 **
15 ** You should have received a copy of the GNU General Public License
16 ** along with this program; if not, write to the Free Software
17 ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 **/
19
20 #include "checks_snmp.h"
21
22 #ifdef HAVE_NETSNMP
23
24 #define SNMP_NO_DEBUGGING /* disabling debugging messages from Net-SNMP library */
25 #include <net-snmp/net-snmp-config.h>
26 #include <net-snmp/net-snmp-includes.h>
27
28 #include "comms.h"
29 #include "zbxalgo.h"
30 #include "zbxjson.h"
31
32 /*
33 * SNMP Dynamic Index Cache
34 * ========================
35 *
36 * Description
37 * -----------
38 *
39 * Zabbix caches the whole index table for the particular OID separately based on:
40 * * IP address;
41 * * port;
42 * * community string (SNMPv2c);
43 * * context, security name (SNMPv3).
44 *
45 * Zabbix revalidates each index before using it to get a value and rebuilds the index cache for the OID if the
46 * index is invalid.
47 *
48 * Example
49 * -------
50 *
51 * OID for getting memory usage of process by PID (index):
52 * HOST-RESOURCES-MIB::hrSWRunPerfMem:<PID>
53 *
54 * OID for getting PID (index) by process name (value):
55 * HOST-RESOURCES-MIB::hrSWRunPath:<PID> <NAME>
56 *
57 * SNMP OID as configured in Zabbix to get memory usage of "snmpd" process:
58 * HOST-RESOURCES-MIB::hrSWRunPerfMem["index","HOST-RESOURCES-MIB::hrSWRunPath","snmpd"]
59 *
60 * 1. Zabbix walks hrSWRunPath table and caches all <PID> and <NAME> pairs of particular SNMP agent/user.
61 * 2. Before each GET request Zabbix revalidates the cached <PID> by getting its <NAME> from hrSWRunPath table.
62 * 3. If the names match then Zabbix uses the cached <PID> in the GET request for the hrSWRunPerfMem.
63 * Otherwise Zabbix rebuilds the hrSWRunPath cache for the particular agent/user (see 1.).
64 *
65 * Implementation
66 * --------------
67 *
68 * The cache is implemented using hash tables. In ERD:
69 * zbx_snmpidx_main_key_t -------------------------------------------0< zbx_snmpidx_mapping_t
70 * (OID, host, <v2c: community|v3: (context, security name)>) (index, value)
71 */
72
73 /******************************************************************************
74 * *
75 * This is zbx_snmp_walk() callback function prototype. *
76 * *
77 * Parameters: arg - [IN] an user argument passed to zbx_snmp_walk() *
78 * function *
79 * oid - [IN] the OID the walk function is looking for *
80 * index - [IN] the index of found OID *
81 * value - [IN] the OID value *
82 * *
83 ******************************************************************************/
84 typedef void (zbx_snmp_walk_cb_func)(void *arg, const char *oid, const char *index, const char *value);
85
86 typedef struct
87 {
88 char *addr;
89 unsigned short port;
90 char *oid;
91 char *community_context; /* community (SNMPv1 or v2c) or contextName (SNMPv3) */
92 char *security_name; /* only SNMPv3, empty string in case of other versions */
93 zbx_hashset_t *mappings;
94 }
95 zbx_snmpidx_main_key_t;
96
97 typedef struct
98 {
99 char *value;
100 char *index;
101 }
102 zbx_snmpidx_mapping_t;
103
104 static zbx_hashset_t snmpidx; /* Dynamic Index Cache */
105
__snmpidx_main_key_hash(const void * data)106 static zbx_hash_t __snmpidx_main_key_hash(const void *data)
107 {
108 const zbx_snmpidx_main_key_t *main_key = (const zbx_snmpidx_main_key_t *)data;
109
110 zbx_hash_t hash;
111
112 hash = ZBX_DEFAULT_STRING_HASH_FUNC(main_key->addr);
113 hash = ZBX_DEFAULT_STRING_HASH_ALGO(&main_key->port, sizeof(main_key->port), hash);
114 hash = ZBX_DEFAULT_STRING_HASH_ALGO(main_key->oid, strlen(main_key->oid), hash);
115 hash = ZBX_DEFAULT_STRING_HASH_ALGO(main_key->community_context, strlen(main_key->community_context), hash);
116 hash = ZBX_DEFAULT_STRING_HASH_ALGO(main_key->security_name, strlen(main_key->security_name), hash);
117
118 return hash;
119 }
120
__snmpidx_main_key_compare(const void * d1,const void * d2)121 static int __snmpidx_main_key_compare(const void *d1, const void *d2)
122 {
123 const zbx_snmpidx_main_key_t *main_key1 = (const zbx_snmpidx_main_key_t *)d1;
124 const zbx_snmpidx_main_key_t *main_key2 = (const zbx_snmpidx_main_key_t *)d2;
125
126 int ret;
127
128 if (0 != (ret = strcmp(main_key1->addr, main_key2->addr)))
129 return ret;
130
131 ZBX_RETURN_IF_NOT_EQUAL(main_key1->port, main_key2->port);
132
133 if (0 != (ret = strcmp(main_key1->community_context, main_key2->community_context)))
134 return ret;
135
136 if (0 != (ret = strcmp(main_key1->security_name, main_key2->security_name)))
137 return ret;
138
139 return strcmp(main_key1->oid, main_key2->oid);
140 }
141
__snmpidx_main_key_clean(void * data)142 static void __snmpidx_main_key_clean(void *data)
143 {
144 zbx_snmpidx_main_key_t *main_key = (zbx_snmpidx_main_key_t *)data;
145
146 zbx_free(main_key->addr);
147 zbx_free(main_key->oid);
148 zbx_free(main_key->community_context);
149 zbx_free(main_key->security_name);
150 zbx_hashset_destroy(main_key->mappings);
151 zbx_free(main_key->mappings);
152 }
153
__snmpidx_mapping_hash(const void * data)154 static zbx_hash_t __snmpidx_mapping_hash(const void *data)
155 {
156 const zbx_snmpidx_mapping_t *mapping = (const zbx_snmpidx_mapping_t *)data;
157
158 return ZBX_DEFAULT_STRING_HASH_FUNC(mapping->value);
159 }
160
__snmpidx_mapping_compare(const void * d1,const void * d2)161 static int __snmpidx_mapping_compare(const void *d1, const void *d2)
162 {
163 const zbx_snmpidx_mapping_t *mapping1 = (const zbx_snmpidx_mapping_t *)d1;
164 const zbx_snmpidx_mapping_t *mapping2 = (const zbx_snmpidx_mapping_t *)d2;
165
166 return strcmp(mapping1->value, mapping2->value);
167 }
168
__snmpidx_mapping_clean(void * data)169 static void __snmpidx_mapping_clean(void *data)
170 {
171 zbx_snmpidx_mapping_t *mapping = (zbx_snmpidx_mapping_t *)data;
172
173 zbx_free(mapping->value);
174 zbx_free(mapping->index);
175 }
176
get_item_community_context(const DC_ITEM * item)177 static char *get_item_community_context(const DC_ITEM *item)
178 {
179 if (ITEM_TYPE_SNMPv1 == item->type || ITEM_TYPE_SNMPv2c == item->type)
180 return item->snmp_community;
181 else if (ITEM_TYPE_SNMPv3 == item->type)
182 return item->snmpv3_contextname;
183
184 THIS_SHOULD_NEVER_HAPPEN;
185 exit(EXIT_FAILURE);
186 }
187
get_item_security_name(const DC_ITEM * item)188 static char *get_item_security_name(const DC_ITEM *item)
189 {
190 if (ITEM_TYPE_SNMPv3 == item->type)
191 return item->snmpv3_securityname;
192
193 return "";
194 }
195
196 /******************************************************************************
197 * *
198 * Function: cache_get_snmp_index *
199 * *
200 * Purpose: retrieve index that matches value from the relevant index cache *
201 * *
202 * Parameters: item - [IN] configuration of Zabbix item, contains *
203 * IP address, port, community string, context, *
204 * security name *
205 * oid - [IN] OID of the table which contains the indexes *
206 * value - [IN] value for which to look up the index *
207 * idx - [IN/OUT] destination pointer for the *
208 * heap-(re)allocated index *
209 * idx_alloc - [IN/OUT] size of the (re)allocated index *
210 * *
211 * Return value: FAIL - dynamic index cache is empty or cache does not *
212 * contain index matching the value *
213 * SUCCEED - idx contains the found index, *
214 * idx_alloc contains the current size of the *
215 * heap-(re)allocated idx *
216 * *
217 ******************************************************************************/
cache_get_snmp_index(const DC_ITEM * item,const char * oid,const char * value,char ** idx,size_t * idx_alloc)218 static int cache_get_snmp_index(const DC_ITEM *item, const char *oid, const char *value, char **idx, size_t *idx_alloc)
219 {
220 const char *__function_name = "cache_get_snmp_index";
221
222 int ret = FAIL;
223 zbx_snmpidx_main_key_t *main_key, main_key_local;
224 zbx_snmpidx_mapping_t *mapping;
225 size_t idx_offset = 0;
226
227 zabbix_log(LOG_LEVEL_DEBUG, "In %s() oid:'%s' value:'%s'", __function_name, oid, value);
228
229 if (NULL == snmpidx.slots)
230 goto end;
231
232 main_key_local.addr = item->interface.addr;
233 main_key_local.port = item->interface.port;
234 main_key_local.oid = (char *)oid;
235
236 main_key_local.community_context = get_item_community_context(item);
237 main_key_local.security_name = get_item_security_name(item);
238
239 if (NULL == (main_key = zbx_hashset_search(&snmpidx, &main_key_local)))
240 goto end;
241
242 if (NULL == (mapping = zbx_hashset_search(main_key->mappings, &value)))
243 goto end;
244
245 zbx_strcpy_alloc(idx, idx_alloc, &idx_offset, mapping->index);
246 ret = SUCCEED;
247 end:
248 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s idx:'%s'", __function_name, zbx_result_string(ret),
249 SUCCEED == ret ? *idx : "");
250
251 return ret;
252 }
253
254 /******************************************************************************
255 * *
256 * Function: cache_put_snmp_index *
257 * *
258 * Purpose: store the index-value pair in the relevant index cache *
259 * *
260 * Parameters: item - [IN] configuration of Zabbix item, contains *
261 * IP address, port, community string, context, *
262 * security name *
263 * oid - [IN] OID of the table which contains the indexes *
264 * index - [IN] index part of the index-value pair *
265 * value - [IN] value part of the index-value pair *
266 * *
267 ******************************************************************************/
cache_put_snmp_index(const DC_ITEM * item,const char * oid,const char * index,const char * value)268 static void cache_put_snmp_index(const DC_ITEM *item, const char *oid, const char *index, const char *value)
269 {
270 const char *__function_name = "cache_put_snmp_index";
271
272 zbx_snmpidx_main_key_t *main_key, main_key_local;
273 zbx_snmpidx_mapping_t *mapping, mapping_local;
274
275 zabbix_log(LOG_LEVEL_DEBUG, "In %s() oid:'%s' index:'%s' value:'%s'", __function_name, oid, index, value);
276
277 if (NULL == snmpidx.slots)
278 {
279 zbx_hashset_create_ext(&snmpidx, 100,
280 __snmpidx_main_key_hash, __snmpidx_main_key_compare, __snmpidx_main_key_clean,
281 ZBX_DEFAULT_MEM_MALLOC_FUNC, ZBX_DEFAULT_MEM_REALLOC_FUNC, ZBX_DEFAULT_MEM_FREE_FUNC);
282 }
283
284 main_key_local.addr = item->interface.addr;
285 main_key_local.port = item->interface.port;
286 main_key_local.oid = (char *)oid;
287
288 main_key_local.community_context = get_item_community_context(item);
289 main_key_local.security_name = get_item_security_name(item);
290
291 if (NULL == (main_key = zbx_hashset_search(&snmpidx, &main_key_local)))
292 {
293 main_key_local.addr = zbx_strdup(NULL, item->interface.addr);
294 main_key_local.oid = zbx_strdup(NULL, oid);
295
296 main_key_local.community_context = zbx_strdup(NULL, get_item_community_context(item));
297 main_key_local.security_name = zbx_strdup(NULL, get_item_security_name(item));
298
299 main_key_local.mappings = zbx_malloc(NULL, sizeof(zbx_hashset_t));
300 zbx_hashset_create_ext(main_key_local.mappings, 100,
301 __snmpidx_mapping_hash, __snmpidx_mapping_compare, __snmpidx_mapping_clean,
302 ZBX_DEFAULT_MEM_MALLOC_FUNC, ZBX_DEFAULT_MEM_REALLOC_FUNC, ZBX_DEFAULT_MEM_FREE_FUNC);
303
304 main_key = zbx_hashset_insert(&snmpidx, &main_key_local, sizeof(main_key_local));
305 }
306
307 if (NULL == (mapping = zbx_hashset_search(main_key->mappings, &value)))
308 {
309 mapping_local.value = zbx_strdup(NULL, value);
310 mapping_local.index = zbx_strdup(NULL, index);
311
312 zbx_hashset_insert(main_key->mappings, &mapping_local, sizeof(mapping_local));
313 }
314 else if (0 != strcmp(mapping->index, index))
315 {
316 zbx_free(mapping->index);
317 mapping->index = zbx_strdup(NULL, index);
318 }
319
320 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
321 }
322
323 /******************************************************************************
324 * *
325 * Function: cache_del_snmp_index_subtree *
326 * *
327 * Purpose: delete index-value mappings from the specified index cache *
328 * *
329 * Parameters: item - [IN] configuration of Zabbix item, contains *
330 * IP address, port, community string, context, *
331 * security name *
332 * oid - [IN] OID of the table which contains the indexes *
333 * *
334 * Comments: does nothing if the index cache is empty or if it does not *
335 * contain the cache for the specified OID *
336 * *
337 ******************************************************************************/
cache_del_snmp_index_subtree(const DC_ITEM * item,const char * oid)338 static void cache_del_snmp_index_subtree(const DC_ITEM *item, const char *oid)
339 {
340 const char *__function_name = "cache_del_snmp_index_subtree";
341
342 zbx_snmpidx_main_key_t *main_key, main_key_local;
343
344 zabbix_log(LOG_LEVEL_DEBUG, "In %s() oid:'%s'", __function_name, oid);
345
346 if (NULL == snmpidx.slots)
347 goto end;
348
349 main_key_local.addr = item->interface.addr;
350 main_key_local.port = item->interface.port;
351 main_key_local.oid = (char *)oid;
352
353 main_key_local.community_context = get_item_community_context(item);
354 main_key_local.security_name = get_item_security_name(item);
355
356 if (NULL == (main_key = zbx_hashset_search(&snmpidx, &main_key_local)))
357 goto end;
358
359 zbx_hashset_clear(main_key->mappings);
360 end:
361 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
362 }
363
zbx_get_snmp_type_error(u_char type)364 static char *zbx_get_snmp_type_error(u_char type)
365 {
366 switch (type)
367 {
368 case SNMP_NOSUCHOBJECT:
369 return zbx_strdup(NULL, "No Such Object available on this agent at this OID");
370 case SNMP_NOSUCHINSTANCE:
371 return zbx_strdup(NULL, "No Such Instance currently exists at this OID");
372 case SNMP_ENDOFMIBVIEW:
373 return zbx_strdup(NULL, "No more variables left in this MIB View"
374 " (it is past the end of the MIB tree)");
375 default:
376 return zbx_dsprintf(NULL, "Value has unknown type 0x%02X", (unsigned int)type);
377 }
378 }
379
zbx_get_snmp_response_error(const struct snmp_session * ss,const DC_INTERFACE * interface,int status,const struct snmp_pdu * response,char * error,size_t max_error_len)380 static int zbx_get_snmp_response_error(const struct snmp_session *ss, const DC_INTERFACE *interface, int status,
381 const struct snmp_pdu *response, char *error, size_t max_error_len)
382 {
383 int ret;
384
385 if (STAT_SUCCESS == status)
386 {
387 zbx_snprintf(error, max_error_len, "SNMP error: %s", snmp_errstring(response->errstat));
388 ret = NOTSUPPORTED;
389 }
390 else if (STAT_ERROR == status)
391 {
392 zbx_snprintf(error, max_error_len, "Cannot connect to \"%s:%hu\": %s.",
393 interface->addr, interface->port, snmp_api_errstring(ss->s_snmp_errno));
394
395 switch (ss->s_snmp_errno)
396 {
397 case SNMPERR_UNKNOWN_USER_NAME:
398 case SNMPERR_UNSUPPORTED_SEC_LEVEL:
399 case SNMPERR_AUTHENTICATION_FAILURE:
400 ret = NOTSUPPORTED;
401 break;
402 default:
403 ret = NETWORK_ERROR;
404 }
405 }
406 else if (STAT_TIMEOUT == status)
407 {
408 zbx_snprintf(error, max_error_len, "Timeout while connecting to \"%s:%hu\".",
409 interface->addr, interface->port);
410 ret = NETWORK_ERROR;
411 }
412 else
413 {
414 zbx_snprintf(error, max_error_len, "SNMP error: [%d]", status);
415 ret = NOTSUPPORTED;
416 }
417
418 return ret;
419 }
420
zbx_snmp_open_session(const DC_ITEM * item,char * error,size_t max_error_len)421 static struct snmp_session *zbx_snmp_open_session(const DC_ITEM *item, char *error, size_t max_error_len)
422 {
423 const char *__function_name = "zbx_snmp_open_session";
424 struct snmp_session session, *ss = NULL;
425 char addr[128];
426 #ifdef HAVE_IPV6
427 int family;
428 #endif
429
430 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
431
432 snmp_sess_init(&session);
433
434 /* Allow using sub-OIDs higher than MAX_INT, like in 'snmpwalk -Ir'. */
435 /* Disables the validation of varbind values against the MIB definition for the relevant OID. */
436 if (SNMPERR_SUCCESS != netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE, 1))
437 {
438 /* This error is not fatal and should never happen (see netsnmp_ds_set_boolean() implementation). */
439 /* Only items with sub-OIDs higher than MAX_INT will be unsupported. */
440 zabbix_log(LOG_LEVEL_WARNING, "cannot set \"DontCheckRange\" option for Net-SNMP");
441 }
442
443 switch (item->type)
444 {
445 case ITEM_TYPE_SNMPv1:
446 session.version = SNMP_VERSION_1;
447 break;
448 case ITEM_TYPE_SNMPv2c:
449 session.version = SNMP_VERSION_2c;
450 break;
451 case ITEM_TYPE_SNMPv3:
452 session.version = SNMP_VERSION_3;
453 break;
454 default:
455 THIS_SHOULD_NEVER_HAPPEN;
456 break;
457 }
458
459 session.timeout = CONFIG_TIMEOUT * 1000 * 1000; /* timeout of one attempt in microseconds */
460 /* (net-snmp default = 1 second) */
461
462 #ifdef HAVE_IPV6
463 if (SUCCEED != get_address_family(item->interface.addr, &family, error, max_error_len))
464 goto end;
465
466 if (PF_INET == family)
467 {
468 zbx_snprintf(addr, sizeof(addr), "%s:%hu", item->interface.addr, item->interface.port);
469 }
470 else
471 {
472 if (item->interface.useip)
473 zbx_snprintf(addr, sizeof(addr), "udp6:[%s]:%hu", item->interface.addr, item->interface.port);
474 else
475 zbx_snprintf(addr, sizeof(addr), "udp6:%s:%hu", item->interface.addr, item->interface.port);
476 }
477 #else
478 zbx_snprintf(addr, sizeof(addr), "%s:%hu", item->interface.addr, item->interface.port);
479 #endif
480 session.peername = addr;
481
482 if (SNMP_VERSION_1 == session.version || SNMP_VERSION_2c == session.version)
483 {
484 session.community = (u_char *)item->snmp_community;
485 session.community_len = strlen((void *)session.community);
486 zabbix_log(LOG_LEVEL_DEBUG, "SNMP [%s@%s]", session.community, session.peername);
487 }
488 else if (SNMP_VERSION_3 == session.version)
489 {
490 /* set the SNMPv3 user name */
491 session.securityName = item->snmpv3_securityname;
492 session.securityNameLen = strlen(session.securityName);
493
494 /* set the SNMPv3 context if specified */
495 if ('\0' != *item->snmpv3_contextname)
496 {
497 session.contextName = item->snmpv3_contextname;
498 session.contextNameLen = strlen(session.contextName);
499 }
500
501 /* set the security level to authenticated, but not encrypted */
502 switch (item->snmpv3_securitylevel)
503 {
504 case ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV:
505 session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
506 break;
507 case ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV:
508 session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
509
510 switch (item->snmpv3_authprotocol)
511 {
512 case ITEM_SNMPV3_AUTHPROTOCOL_MD5:
513 /* set the authentication protocol to MD5 */
514 session.securityAuthProto = usmHMACMD5AuthProtocol;
515 session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
516 break;
517 case ITEM_SNMPV3_AUTHPROTOCOL_SHA:
518 /* set the authentication protocol to SHA */
519 session.securityAuthProto = usmHMACSHA1AuthProtocol;
520 session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
521 break;
522 default:
523 zbx_snprintf(error, max_error_len,
524 "Unsupported authentication protocol [%d]",
525 item->snmpv3_authprotocol);
526 goto end;
527 }
528
529 session.securityAuthKeyLen = USM_AUTH_KU_LEN;
530
531 if (SNMPERR_SUCCESS != generate_Ku(session.securityAuthProto,
532 session.securityAuthProtoLen, (u_char *)item->snmpv3_authpassphrase,
533 strlen(item->snmpv3_authpassphrase), session.securityAuthKey,
534 &session.securityAuthKeyLen))
535 {
536 zbx_strlcpy(error, "Error generating Ku from authentication pass phrase",
537 max_error_len);
538 goto end;
539 }
540 break;
541 case ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV:
542 session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
543
544 switch (item->snmpv3_authprotocol)
545 {
546 case ITEM_SNMPV3_AUTHPROTOCOL_MD5:
547 /* set the authentication protocol to MD5 */
548 session.securityAuthProto = usmHMACMD5AuthProtocol;
549 session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
550 break;
551 case ITEM_SNMPV3_AUTHPROTOCOL_SHA:
552 /* set the authentication protocol to SHA */
553 session.securityAuthProto = usmHMACSHA1AuthProtocol;
554 session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
555 break;
556 default:
557 zbx_snprintf(error, max_error_len,
558 "Unsupported authentication protocol [%d]",
559 item->snmpv3_authprotocol);
560 goto end;
561 }
562
563 session.securityAuthKeyLen = USM_AUTH_KU_LEN;
564
565 if (SNMPERR_SUCCESS != generate_Ku(session.securityAuthProto,
566 session.securityAuthProtoLen, (u_char *)item->snmpv3_authpassphrase,
567 strlen(item->snmpv3_authpassphrase), session.securityAuthKey,
568 &session.securityAuthKeyLen))
569 {
570 zbx_strlcpy(error, "Error generating Ku from authentication pass phrase",
571 max_error_len);
572 goto end;
573 }
574
575 switch (item->snmpv3_privprotocol)
576 {
577 case ITEM_SNMPV3_PRIVPROTOCOL_DES:
578 /* set the privacy protocol to DES */
579 session.securityPrivProto = usmDESPrivProtocol;
580 session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
581 break;
582 case ITEM_SNMPV3_PRIVPROTOCOL_AES:
583 /* set the privacy protocol to AES */
584 session.securityPrivProto = usmAESPrivProtocol;
585 session.securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
586 break;
587 default:
588 zbx_snprintf(error, max_error_len,
589 "Unsupported privacy protocol [%d]",
590 item->snmpv3_privprotocol);
591 goto end;
592 }
593
594 session.securityPrivKeyLen = USM_PRIV_KU_LEN;
595
596 if (SNMPERR_SUCCESS != generate_Ku(session.securityAuthProto,
597 session.securityAuthProtoLen, (u_char *)item->snmpv3_privpassphrase,
598 strlen(item->snmpv3_privpassphrase), session.securityPrivKey,
599 &session.securityPrivKeyLen))
600 {
601 zbx_strlcpy(error, "Error generating Ku from privacy pass phrase",
602 max_error_len);
603 goto end;
604 }
605 break;
606 }
607
608 zabbix_log(LOG_LEVEL_DEBUG, "SNMPv3 [%s@%s]", session.securityName, session.peername);
609 }
610
611 #ifdef HAVE_NETSNMP_SESSION_LOCALNAME
612 if (NULL != CONFIG_SOURCE_IP)
613 {
614 /* In some cases specifying just local host (without local port) is not enough. We do */
615 /* not care about the port number though so we let the OS select one by specifying 0. */
616 /* See marc.info/?l=net-snmp-bugs&m=115624676507760 for details. */
617
618 static char localname[64];
619
620 zbx_snprintf(localname, sizeof(localname), "%s:0", CONFIG_SOURCE_IP);
621 session.localname = localname;
622 }
623 #endif
624
625 SOCK_STARTUP;
626
627 if (NULL == (ss = snmp_open(&session)))
628 {
629 SOCK_CLEANUP;
630
631 zbx_strlcpy(error, "Cannot open SNMP session", max_error_len);
632 }
633 end:
634 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
635
636 return ss;
637 }
638
zbx_snmp_close_session(struct snmp_session * session)639 static void zbx_snmp_close_session(struct snmp_session *session)
640 {
641 const char *__function_name = "zbx_snmp_close_session";
642
643 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
644
645 snmp_close(session);
646 SOCK_CLEANUP;
647
648 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
649 }
650
zbx_snmp_get_octet_string(const struct variable_list * var)651 static char *zbx_snmp_get_octet_string(const struct variable_list *var)
652 {
653 const char *__function_name = "zbx_snmp_get_octet_string";
654
655 const char *hint;
656 char buffer[MAX_STRING_LEN];
657 char *strval_dyn = NULL;
658 struct tree *subtree;
659
660 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
661
662 /* find the subtree to get display hint */
663 subtree = get_tree(var->name, var->name_length, get_tree_head());
664 hint = (NULL != subtree ? subtree->hint : NULL);
665
666 /* we will decide if we want the value from var->val or what snprint_value() returned later */
667 if (-1 == snprint_value(buffer, sizeof(buffer), var->name, var->name_length, var))
668 goto end;
669
670 zabbix_log(LOG_LEVEL_DEBUG, "%s() full value:'%s' hint:'%s'", __function_name, buffer, ZBX_NULL2STR(hint));
671
672 if (0 == strncmp(buffer, "Hex-STRING: ", 12))
673 {
674 strval_dyn = zbx_strdup(strval_dyn, buffer + 12);
675 }
676 else if (NULL != hint && 0 == strncmp(buffer, "STRING: ", 8))
677 {
678 strval_dyn = zbx_strdup(strval_dyn, buffer + 8);
679 }
680 else if (0 == strncmp(buffer, "OID: ", 5))
681 {
682 strval_dyn = zbx_strdup(strval_dyn, buffer + 5);
683 }
684 else if (0 == strncmp(buffer, "BITS: ", 6))
685 {
686 strval_dyn = zbx_strdup(strval_dyn, buffer + 6);
687 }
688 else
689 {
690 /* snprint_value() escapes hintless ASCII strings, so */
691 /* we are copying the raw unescaped value in this case */
692
693 strval_dyn = zbx_malloc(strval_dyn, var->val_len + 1);
694 memcpy(strval_dyn, var->val.string, var->val_len);
695 strval_dyn[var->val_len] = '\0';
696 }
697
698 end:
699 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():'%s'", __function_name, ZBX_NULL2STR(strval_dyn));
700
701 return strval_dyn;
702 }
703
zbx_snmp_set_result(const struct variable_list * var,unsigned char value_type,unsigned char data_type,AGENT_RESULT * result)704 static int zbx_snmp_set_result(const struct variable_list *var, unsigned char value_type, unsigned char data_type,
705 AGENT_RESULT *result)
706 {
707 const char *__function_name = "zbx_snmp_set_result";
708 char *strval_dyn;
709 int ret = SUCCEED;
710
711 zabbix_log(LOG_LEVEL_DEBUG, "In %s() type:%d value_type:%d data_type:%d", __function_name,
712 (int)var->type, (int)value_type, (int)data_type);
713
714 if (ASN_OCTET_STR == var->type || ASN_OBJECT_ID == var->type)
715 {
716 if (NULL == (strval_dyn = zbx_snmp_get_octet_string(var)))
717 {
718 SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot receive string value: out of memory."));
719 ret = NOTSUPPORTED;
720 }
721 else
722 {
723 if (SUCCEED != set_result_type(result, value_type, data_type, strval_dyn))
724 ret = NOTSUPPORTED;
725
726 zbx_free(strval_dyn);
727 }
728 }
729 #ifdef OPAQUE_SPECIAL_TYPES
730 else if (ASN_UINTEGER == var->type || ASN_COUNTER == var->type || ASN_OPAQUE_U64 == var->type ||
731 ASN_TIMETICKS == var->type || ASN_GAUGE == var->type)
732 #else
733 else if (ASN_UINTEGER == var->type || ASN_COUNTER == var->type ||
734 ASN_TIMETICKS == var->type || ASN_GAUGE == var->type)
735 #endif
736 {
737 SET_UI64_RESULT(result, (unsigned long)*var->val.integer);
738 }
739 #ifdef OPAQUE_SPECIAL_TYPES
740 else if (ASN_COUNTER64 == var->type || ASN_OPAQUE_COUNTER64 == var->type)
741 #else
742 else if (ASN_COUNTER64 == var->type)
743 #endif
744 {
745 SET_UI64_RESULT(result, (((zbx_uint64_t)var->val.counter64->high) << 32) +
746 (zbx_uint64_t)var->val.counter64->low);
747 }
748 #ifdef OPAQUE_SPECIAL_TYPES
749 else if (ASN_INTEGER == var->type || ASN_OPAQUE_I64 == var->type)
750 #else
751 else if (ASN_INTEGER == var->type)
752 #endif
753 {
754 char buffer[12];
755
756 zbx_snprintf(buffer, sizeof(buffer), "%d", *var->val.integer);
757
758 if (SUCCEED != set_result_type(result, value_type, data_type, buffer))
759 ret = NOTSUPPORTED;
760 }
761 #ifdef OPAQUE_SPECIAL_TYPES
762 else if (ASN_OPAQUE_FLOAT == var->type)
763 {
764 SET_DBL_RESULT(result, *var->val.floatVal);
765 }
766 else if (ASN_OPAQUE_DOUBLE == var->type)
767 {
768 SET_DBL_RESULT(result, *var->val.doubleVal);
769 }
770 #endif
771 else if (ASN_IPADDRESS == var->type)
772 {
773 SET_STR_RESULT(result, zbx_dsprintf(NULL, "%u.%u.%u.%u",
774 (unsigned int)var->val.string[0],
775 (unsigned int)var->val.string[1],
776 (unsigned int)var->val.string[2],
777 (unsigned int)var->val.string[3]));
778 }
779 else
780 {
781 SET_MSG_RESULT(result, zbx_get_snmp_type_error(var->type));
782 ret = NOTSUPPORTED;
783 }
784
785 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
786
787 return ret;
788 }
789
zbx_snmp_dump_oid(char * buffer,size_t buffer_len,const oid * objid,size_t objid_len)790 static void zbx_snmp_dump_oid(char *buffer, size_t buffer_len, const oid *objid, size_t objid_len)
791 {
792 size_t i, offset = 0;
793
794 *buffer = '\0';
795
796 for (i = 0; i < objid_len; i++)
797 offset += zbx_snprintf(buffer + offset, buffer_len - offset, ".%lu", (unsigned long)objid[i]);
798 }
799
800 #define ZBX_OID_INDEX_STRING 0
801 #define ZBX_OID_INDEX_NUMERIC 1
802
zbx_snmp_print_oid(char * buffer,size_t buffer_len,const oid * objid,size_t objid_len,int format)803 static int zbx_snmp_print_oid(char *buffer, size_t buffer_len, const oid *objid, size_t objid_len, int format)
804 {
805 if (SNMPERR_SUCCESS != netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS,
806 format))
807 {
808 zabbix_log(LOG_LEVEL_WARNING, "cannot set \"dontBreakdownOids\" option to %d for Net-SNMP", format);
809 return -1;
810 }
811
812 return snprint_objid(buffer, buffer_len, objid, objid_len);
813 }
814
zbx_snmp_choose_index(char * buffer,size_t buffer_len,const oid * objid,size_t objid_len,size_t root_string_len,size_t root_numeric_len)815 static int zbx_snmp_choose_index(char *buffer, size_t buffer_len, const oid *objid, size_t objid_len,
816 size_t root_string_len, size_t root_numeric_len)
817 {
818 const char *__function_name = "zbx_snmp_choose_index";
819
820 oid parsed_oid[MAX_OID_LEN];
821 size_t parsed_oid_len = MAX_OID_LEN;
822 char printed_oid[MAX_STRING_LEN];
823
824 /**************************************************************************************************************/
825 /* */
826 /* When we are providing a value for {#SNMPINDEX}, we would like to provide a pretty value. This is only a */
827 /* concern for OIDs with string indices. For instance, suppose we are walking the following OID: */
828 /* */
829 /* SNMP-VIEW-BASED-ACM-MIB::vacmGroupName */
830 /* */
831 /* Suppose also that we are currently looking at this OID: */
832 /* */
833 /* SNMP-VIEW-BASED-ACM-MIB::vacmGroupName.3."authOnlyUser" */
834 /* */
835 /* Then, we would like to provide {#SNMPINDEX} with this value: */
836 /* */
837 /* 3."authOnlyUser" */
838 /* */
839 /* An alternative approach would be to provide {#SNMPINDEX} with numeric value. While it is equivalent to the */
840 /* string representation above, the string representation is more readable and thus more useful to users: */
841 /* */
842 /* 3.12.97.117.116.104.79.110.108.121.85.115.101.114 */
843 /* */
844 /* Here, 12 is the length of "authOnlyUser" and the rest is the string encoding using ASCII characters. */
845 /* */
846 /* There are two problems with always providing {#SNMPINDEX} that has an index representation as a string. */
847 /* */
848 /* The first problem is indices of type InetAddress. The Net-SNMP library has code for pretty-printing IP */
849 /* addresses, but no way to parse them back. As an example, consider the following OID: */
850 /* */
851 /* .1.3.6.1.2.1.4.34.1.4.1.4.192.168.3.255 */
852 /* */
853 /* Its pretty representation is like this: */
854 /* */
855 /* IP-MIB::ipAddressType.ipv4."192.168.3.255" */
856 /* */
857 /* However, when trying to parse it, it turns into this OID: */
858 /* */
859 /* .1.3.6.1.2.1.4.34.1.4.1.13.49.57.50.46.49.54.56.46.51.46.50.53.53 */
860 /* */
861 /* Apparently, this is different than the original. */
862 /* */
863 /* The second problem is indices of type OCTET STRING, which might contain unprintable characters: */
864 /* */
865 /* 1.3.6.1.2.1.17.4.3.1.1.0.0.240.122.113.21 */
866 /* */
867 /* Its pretty representation is like this (note the single quotes which stand for a fixed-length string): */
868 /* */
869 /* BRIDGE-MIB::dot1dTpFdbAddress.'...zq.' */
870 /* */
871 /* Here, '...zq.' stands for 0.0.240.122.113.21, where only 'z' (122) and 'q' (113) are printable. */
872 /* */
873 /* Apparently, this cannot be turned back into the numeric representation. */
874 /* */
875 /* So what we try to do is first print it pretty. If there is no string-looking index, return it as output. */
876 /* If there is such an index, we check that it can be parsed and that the result is the same as the original. */
877 /* */
878 /**************************************************************************************************************/
879
880 if (-1 == zbx_snmp_print_oid(printed_oid, sizeof(printed_oid), objid, objid_len, ZBX_OID_INDEX_STRING))
881 {
882 zabbix_log(LOG_LEVEL_DEBUG, "%s(): cannot print OID with string indices", __function_name);
883 goto numeric;
884 }
885
886 if (NULL == strchr(printed_oid, '"') && NULL == strchr(printed_oid, '\''))
887 {
888 zbx_strlcpy(buffer, printed_oid + root_string_len + 1, buffer_len);
889 return SUCCEED;
890 }
891
892 if (NULL == snmp_parse_oid(printed_oid, parsed_oid, &parsed_oid_len))
893 {
894 zabbix_log(LOG_LEVEL_DEBUG, "%s(): cannot parse OID '%s'", __function_name, printed_oid);
895 goto numeric;
896 }
897
898 if (parsed_oid_len == objid_len && 0 == memcmp(parsed_oid, objid, parsed_oid_len * sizeof(oid)))
899 {
900 zbx_strlcpy(buffer, printed_oid + root_string_len + 1, buffer_len);
901 return SUCCEED;
902 }
903 numeric:
904 if (-1 == zbx_snmp_print_oid(printed_oid, sizeof(printed_oid), objid, objid_len, ZBX_OID_INDEX_NUMERIC))
905 {
906 zabbix_log(LOG_LEVEL_DEBUG, "%s(): cannot print OID with numeric indices", __function_name);
907 return FAIL;
908 }
909
910 zbx_strlcpy(buffer, printed_oid + root_numeric_len + 1, buffer_len);
911 return SUCCEED;
912 }
913
914 /******************************************************************************
915 * *
916 * Functions for detecting looping in SNMP OID sequence using hashset *
917 * *
918 * Once there is a possibility of looping we start putting OIDs into hashset. *
919 * We do it until a duplicate OID shows up or ZBX_OIDS_MAX_NUM OIDs have been *
920 * collected. *
921 * *
922 * The hashset key is array of elements of type 'oid'. Element 0 holds the *
923 * number of OID components (sub-OIDs), element 1 and so on - OID components *
924 * themselves. *
925 * *
926 * OIDs may contain up to 128 sub-OIDs, so 1 byte is sufficient to keep the *
927 * number of them. On the other hand, sub-OIDs are of type 'oid' which can be *
928 * defined in NetSNMP as 'uint8_t' or 'u_long'. Sub-OIDs are compared as *
929 * numbers, so some platforms may require they to be properly aligned in *
930 * memory. To ensure proper alignment we keep number of elements in element 0 *
931 * instead of using a separate structure element for it. *
932 * *
933 ******************************************************************************/
934
__oids_seen_key_hash(const void * data)935 static zbx_hash_t __oids_seen_key_hash(const void *data)
936 {
937 const oid *key = (const oid *)data;
938
939 return ZBX_DEFAULT_HASH_ALGO(key, (key[0] + 1) * sizeof(oid), ZBX_DEFAULT_HASH_SEED);
940 }
941
__oids_seen_key_compare(const void * d1,const void * d2)942 static int __oids_seen_key_compare(const void *d1, const void *d2)
943 {
944 const oid *k1 = (const oid *)d1;
945 const oid *k2 = (const oid *)d2;
946
947 if (d1 == d2)
948 return 0;
949
950 return snmp_oid_compare(k1 + 1, k1[0], k2 + 1, k2[0]);
951 }
952
zbx_detect_loop_init(zbx_hashset_t * hs)953 static void zbx_detect_loop_init(zbx_hashset_t *hs)
954 {
955 #define ZBX_OIDS_SEEN_INIT_SIZE 500 /* minimum initial number of slots in hashset */
956
957 zbx_hashset_create(hs, ZBX_OIDS_SEEN_INIT_SIZE, __oids_seen_key_hash, __oids_seen_key_compare);
958
959 #undef ZBX_OIDS_SEEN_INIT_SIZE
960 }
961
zbx_oid_is_new(zbx_hashset_t * hs,size_t root_len,const oid * p_oid,size_t oid_len)962 static int zbx_oid_is_new(zbx_hashset_t *hs, size_t root_len, const oid *p_oid, size_t oid_len)
963 {
964 #define ZBX_OIDS_MAX_NUM 1000000 /* max number of OIDs to store for checking duplicates */
965
966 const oid *var_oid; /* points to the first element in the variable part */
967 size_t var_len; /* number of elements in the variable part */
968 oid oid_k[MAX_OID_LEN + 1]; /* array for constructing a hashset key */
969
970 /* OIDs share a common initial part. Save space by storing only the variable part. */
971
972 var_oid = p_oid + root_len;
973 var_len = oid_len - root_len;
974
975 if (ZBX_OIDS_MAX_NUM == hs->num_data)
976 return FAIL;
977
978 oid_k[0] = var_len;
979 memcpy(oid_k + 1, var_oid, var_len * sizeof(oid));
980
981 if (NULL != zbx_hashset_search(hs, oid_k))
982 return FAIL; /* OID already seen */
983
984 if (NULL != zbx_hashset_insert(hs, oid_k, (var_len + 1) * sizeof(oid)))
985 return SUCCEED; /* new OID */
986
987 THIS_SHOULD_NEVER_HAPPEN;
988 return FAIL; /* hashset fail */
989
990 #undef ZBX_OIDS_MAX_NUM
991 }
992
993 /******************************************************************************
994 * *
995 * Function: zbx_snmp_walk *
996 * *
997 * Purpose: retrieve information by walking an OID tree *
998 * *
999 * Parameters: ss - [IN] SNMP session handle *
1000 * item - [IN] configuration of Zabbix item *
1001 * OID - [IN] OID of table with values of interest *
1002 * error - [OUT] a buffer to store error message *
1003 * max_error_len - [IN] maximum error message length *
1004 * max_succeed - [OUT] value of "max_repetitions" that succeeded*
1005 * min_fail - [OUT] value of "max_repetitions" that failed *
1006 * max_vars - [IN] suggested value of "max_repetitions" *
1007 * bulk - [IN] whether GetBulkRequest-PDU should be used *
1008 * walk_cb_func - [IN] callback function to process discovered *
1009 * OIDs and their values *
1010 * walk_cb_arg - [IN] argument to pass to the callback function *
1011 * *
1012 * Return value: NOTSUPPORTED - OID does not exist, any other critical error *
1013 * NETWORK_ERROR - recoverable network error *
1014 * CONFIG_ERROR - item configuration error *
1015 * SUCCEED - if function successfully completed *
1016 * *
1017 * Author: Alexander Vladishev, Aleksandrs Saveljevs *
1018 * *
1019 ******************************************************************************/
zbx_snmp_walk(struct snmp_session * ss,const DC_ITEM * item,const char * OID,char * error,size_t max_error_len,int * max_succeed,int * min_fail,int max_vars,int bulk,zbx_snmp_walk_cb_func walk_cb_func,void * walk_cb_arg)1020 static int zbx_snmp_walk(struct snmp_session *ss, const DC_ITEM *item, const char *OID, char *error,
1021 size_t max_error_len, int *max_succeed, int *min_fail, int max_vars, int bulk,
1022 zbx_snmp_walk_cb_func walk_cb_func, void *walk_cb_arg)
1023 {
1024 const char *__function_name = "zbx_snmp_walk";
1025
1026 struct snmp_pdu *pdu, *response;
1027 oid anOID[MAX_OID_LEN], rootOID[MAX_OID_LEN];
1028 size_t anOID_len = MAX_OID_LEN, rootOID_len = MAX_OID_LEN, root_string_len, root_numeric_len;
1029 char snmp_oid[MAX_STRING_LEN];
1030 struct variable_list *var;
1031 int status, level, running, num_vars, check_oid_increase = 1, ret = SUCCEED;
1032 AGENT_RESULT snmp_result;
1033 zbx_hashset_t oids_seen;
1034
1035 zabbix_log(LOG_LEVEL_DEBUG, "In %s() type:%d oid:'%s' bulk:%d", __function_name, (int)item->type, OID, bulk);
1036
1037 if (ITEM_TYPE_SNMPv1 == item->type) /* GetBulkRequest-PDU available since SNMPv2 */
1038 bulk = SNMP_BULK_DISABLED;
1039
1040 /* create OID from string */
1041 if (NULL == snmp_parse_oid(OID, rootOID, &rootOID_len))
1042 {
1043 zbx_snprintf(error, max_error_len, "snmp_parse_oid(): cannot parse OID \"%s\".", OID);
1044 ret = CONFIG_ERROR;
1045 goto out;
1046 }
1047
1048 if (-1 == zbx_snmp_print_oid(snmp_oid, sizeof(snmp_oid), rootOID, rootOID_len, ZBX_OID_INDEX_STRING))
1049 {
1050 zbx_snprintf(error, max_error_len, "zbx_snmp_print_oid(): cannot print OID \"%s\" with string indices.",
1051 OID);
1052 ret = CONFIG_ERROR;
1053 goto out;
1054 }
1055
1056 root_string_len = strlen(snmp_oid);
1057
1058 if (-1 == zbx_snmp_print_oid(snmp_oid, sizeof(snmp_oid), rootOID, rootOID_len, ZBX_OID_INDEX_NUMERIC))
1059 {
1060 zbx_snprintf(error, max_error_len, "zbx_snmp_print_oid(): cannot print OID \"%s\""
1061 " with numeric indices.", OID);
1062 ret = CONFIG_ERROR;
1063 goto out;
1064 }
1065
1066 root_numeric_len = strlen(snmp_oid);
1067
1068 /* copy rootOID to anOID */
1069 memcpy(anOID, rootOID, rootOID_len * sizeof(oid));
1070 anOID_len = rootOID_len;
1071
1072 /* initialize variables */
1073 level = 0;
1074 running = 1;
1075
1076 while (1 == running)
1077 {
1078 /* create PDU */
1079 if (NULL == (pdu = snmp_pdu_create(SNMP_BULK_ENABLED == bulk ? SNMP_MSG_GETBULK : SNMP_MSG_GETNEXT)))
1080 {
1081 zbx_strlcpy(error, "snmp_pdu_create(): cannot create PDU object.", max_error_len);
1082 ret = CONFIG_ERROR;
1083 break;
1084 }
1085
1086 if (NULL == snmp_add_null_var(pdu, anOID, anOID_len)) /* add OID as variable to PDU */
1087 {
1088 zbx_strlcpy(error, "snmp_add_null_var(): cannot add null variable.", max_error_len);
1089 ret = CONFIG_ERROR;
1090 snmp_free_pdu(pdu);
1091 break;
1092 }
1093
1094 if (SNMP_BULK_ENABLED == bulk)
1095 {
1096 pdu->non_repeaters = 0;
1097 pdu->max_repetitions = max_vars;
1098 }
1099
1100 ss->retries = (0 == bulk || (1 == max_vars && 0 == level) ? 1 : 0);
1101
1102 /* communicate with agent */
1103 status = snmp_synch_response(ss, pdu, &response);
1104
1105 zabbix_log(LOG_LEVEL_DEBUG, "%s() snmp_synch_response() status:%d s_snmp_errno:%d errstat:%ld"
1106 " max_vars:%d", __function_name, status, ss->s_snmp_errno,
1107 NULL == response ? (long)-1 : response->errstat, max_vars);
1108
1109 if (1 < max_vars &&
1110 ((STAT_SUCCESS == status && SNMP_ERR_TOOBIG == response->errstat) || STAT_TIMEOUT == status))
1111 {
1112 /* The logic of iteratively reducing request size here is the same as in function */
1113 /* zbx_snmp_get_values(). Please refer to the description there for explanation. */
1114
1115 if (*min_fail > max_vars)
1116 *min_fail = max_vars;
1117
1118 if (0 == level)
1119 {
1120 max_vars /= 2;
1121 }
1122 else if (1 == level)
1123 {
1124 max_vars = 1;
1125 }
1126
1127 level++;
1128
1129 goto next;
1130 }
1131 else if (STAT_SUCCESS != status || SNMP_ERR_NOERROR != response->errstat)
1132 {
1133 ret = zbx_get_snmp_response_error(ss, &item->interface, status, response, error, max_error_len);
1134 running = 0;
1135 goto next;
1136 }
1137
1138 /* process response */
1139 for (num_vars = 0, var = response->variables; NULL != var; num_vars++, var = var->next_variable)
1140 {
1141 /* verify if we are in the same subtree */
1142 if (SNMP_ENDOFMIBVIEW == var->type || var->name_length < rootOID_len ||
1143 0 != memcmp(rootOID, var->name, rootOID_len * sizeof(oid)))
1144 {
1145 /* reached the end or past this subtree */
1146 running = 0;
1147 break;
1148 }
1149 else if (SNMP_NOSUCHOBJECT != var->type && SNMP_NOSUCHINSTANCE != var->type)
1150 {
1151 /* not an exception value */
1152
1153 if (1 == check_oid_increase) /* typical case */
1154 {
1155 int res;
1156
1157 /* normally devices return OIDs in increasing order, */
1158 /* snmp_oid_compare() will return -1 in this case */
1159
1160 if (-1 != (res = snmp_oid_compare(anOID, anOID_len, var->name,
1161 var->name_length)))
1162 {
1163 if (0 == res) /* got the same OID */
1164 {
1165 zbx_strlcpy(error, "OID not changing.", max_error_len);
1166 ret = NOTSUPPORTED;
1167 running = 0;
1168 break;
1169 }
1170 else /* 1 == res */
1171 {
1172 /* OID decreased. Disable further checks of increasing */
1173 /* and set up a protection against endless looping. */
1174
1175 check_oid_increase = 0;
1176 zbx_detect_loop_init(&oids_seen);
1177 }
1178 }
1179 }
1180
1181 if (0 == check_oid_increase && FAIL == zbx_oid_is_new(&oids_seen, rootOID_len,
1182 var->name, var->name_length))
1183 {
1184 zbx_strlcpy(error, "OID loop detected or too many OIDs.", max_error_len);
1185 ret = NOTSUPPORTED;
1186 running = 0;
1187 break;
1188 }
1189
1190 if (SUCCEED != zbx_snmp_choose_index(snmp_oid, sizeof(snmp_oid), var->name,
1191 var->name_length, root_string_len, root_numeric_len))
1192 {
1193 zbx_snprintf(error, max_error_len, "zbx_snmp_choose_index():"
1194 " cannot choose appropriate index while walking for"
1195 " OID \"%s\".", OID);
1196 ret = NOTSUPPORTED;
1197 running = 0;
1198 break;
1199 }
1200
1201 init_result(&snmp_result);
1202
1203 if (SUCCEED == zbx_snmp_set_result(var, ITEM_VALUE_TYPE_STR, 0, &snmp_result) &&
1204 NULL != GET_STR_RESULT(&snmp_result))
1205 {
1206 walk_cb_func(walk_cb_arg, OID, snmp_oid, snmp_result.str);
1207 }
1208 else
1209 {
1210 char **msg;
1211
1212 msg = GET_MSG_RESULT(&snmp_result);
1213
1214 zabbix_log(LOG_LEVEL_DEBUG, "cannot get index '%s' string value: %s",
1215 snmp_oid, NULL != msg && NULL != *msg ? *msg : "(null)");
1216 }
1217
1218 free_result(&snmp_result);
1219
1220 /* go to next variable */
1221 memcpy((char *)anOID, (char *)var->name, var->name_length * sizeof(oid));
1222 anOID_len = var->name_length;
1223 }
1224 else
1225 {
1226 /* an exception value, so stop */
1227 char *errmsg;
1228
1229 errmsg = zbx_get_snmp_type_error(var->type);
1230 zbx_strlcpy(error, errmsg, max_error_len);
1231 zbx_free(errmsg);
1232 ret = NOTSUPPORTED;
1233 running = 0;
1234 break;
1235 }
1236 }
1237
1238 if (*max_succeed < num_vars)
1239 *max_succeed = num_vars;
1240 next:
1241 if (NULL != response)
1242 snmp_free_pdu(response);
1243 }
1244
1245 if (0 == check_oid_increase)
1246 zbx_hashset_destroy(&oids_seen);
1247 out:
1248 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
1249
1250 return ret;
1251 }
1252
zbx_snmp_get_values(struct snmp_session * ss,const DC_ITEM * items,char oids[][ITEM_SNMP_OID_LEN_MAX],AGENT_RESULT * results,int * errcodes,unsigned char * query_and_ignore_type,int num,int level,char * error,size_t max_error_len,int * max_succeed,int * min_fail)1253 static int zbx_snmp_get_values(struct snmp_session *ss, const DC_ITEM *items, char oids[][ITEM_SNMP_OID_LEN_MAX],
1254 AGENT_RESULT *results, int *errcodes, unsigned char *query_and_ignore_type, int num, int level,
1255 char *error, size_t max_error_len, int *max_succeed, int *min_fail)
1256 {
1257 const char *__function_name = "zbx_snmp_get_values";
1258
1259 int i, j, status, ret = SUCCEED;
1260 int mapping[MAX_SNMP_ITEMS], mapping_num = 0;
1261 oid parsed_oids[MAX_SNMP_ITEMS][MAX_OID_LEN];
1262 size_t parsed_oid_lens[MAX_SNMP_ITEMS];
1263 struct snmp_pdu *pdu, *response;
1264 struct variable_list *var;
1265
1266 zabbix_log(LOG_LEVEL_DEBUG, "In %s() num:%d level:%d", __function_name, num, level);
1267
1268 if (NULL == (pdu = snmp_pdu_create(SNMP_MSG_GET)))
1269 {
1270 zbx_strlcpy(error, "snmp_pdu_create(): cannot create PDU object.", max_error_len);
1271 ret = CONFIG_ERROR;
1272 goto out;
1273 }
1274
1275 for (i = 0; i < num; i++)
1276 {
1277 if (SUCCEED != errcodes[i])
1278 continue;
1279
1280 if (NULL != query_and_ignore_type && 0 == query_and_ignore_type[i])
1281 continue;
1282
1283 parsed_oid_lens[i] = MAX_OID_LEN;
1284
1285 if (NULL == snmp_parse_oid(oids[i], parsed_oids[i], &parsed_oid_lens[i]))
1286 {
1287 SET_MSG_RESULT(&results[i], zbx_dsprintf(NULL, "snmp_parse_oid(): cannot parse OID \"%s\".",
1288 oids[i]));
1289 errcodes[i] = CONFIG_ERROR;
1290 continue;
1291 }
1292
1293 if (NULL == snmp_add_null_var(pdu, parsed_oids[i], parsed_oid_lens[i]))
1294 {
1295 SET_MSG_RESULT(&results[i], zbx_strdup(NULL, "snmp_add_null_var(): cannot add null variable."));
1296 errcodes[i] = CONFIG_ERROR;
1297 continue;
1298 }
1299
1300 mapping[mapping_num++] = i;
1301 }
1302
1303 if (0 == mapping_num)
1304 {
1305 snmp_free_pdu(pdu);
1306 goto out;
1307 }
1308
1309 ss->retries = (1 == mapping_num && 0 == level ? 1 : 0);
1310 retry:
1311 status = snmp_synch_response(ss, pdu, &response);
1312
1313 zabbix_log(LOG_LEVEL_DEBUG, "%s() snmp_synch_response() status:%d s_snmp_errno:%d errstat:%ld mapping_num:%d",
1314 __function_name, status, ss->s_snmp_errno, NULL == response ? (long)-1 : response->errstat,
1315 mapping_num);
1316
1317 if (STAT_SUCCESS == status && SNMP_ERR_NOERROR == response->errstat)
1318 {
1319 for (i = 0, var = response->variables;; i++, var = var->next_variable)
1320 {
1321 /* check that response variable binding matches the request variable binding */
1322
1323 if (i == mapping_num)
1324 {
1325 if (NULL != var)
1326 {
1327 zabbix_log(LOG_LEVEL_WARNING, "SNMP response from host \"%s\" contains"
1328 " too many variable bindings", items[0].host.host);
1329
1330 if (1 != mapping_num) /* give device a chance to handle a smaller request */
1331 goto halve;
1332
1333 zbx_strlcpy(error, "Invalid SNMP response: too many variable bindings.",
1334 max_error_len);
1335
1336 ret = NOTSUPPORTED;
1337 }
1338
1339 break;
1340 }
1341
1342 if (NULL == var)
1343 {
1344 zabbix_log(LOG_LEVEL_WARNING, "SNMP response from host \"%s\" contains"
1345 " too few variable bindings", items[0].host.host);
1346
1347 if (1 != mapping_num) /* give device a chance to handle a smaller request */
1348 goto halve;
1349
1350 zbx_strlcpy(error, "Invalid SNMP response: too few variable bindings.", max_error_len);
1351
1352 ret = NOTSUPPORTED;
1353 break;
1354 }
1355
1356 j = mapping[i];
1357
1358 if (parsed_oid_lens[j] != var->name_length ||
1359 0 != memcmp(parsed_oids[j], var->name, parsed_oid_lens[j] * sizeof(oid)))
1360 {
1361 char sent_oid[ITEM_SNMP_OID_LEN_MAX], received_oid[ITEM_SNMP_OID_LEN_MAX];
1362
1363 zbx_snmp_dump_oid(sent_oid, sizeof(sent_oid), parsed_oids[j], parsed_oid_lens[j]);
1364 zbx_snmp_dump_oid(received_oid, sizeof(received_oid), var->name, var->name_length);
1365
1366 if (1 != mapping_num)
1367 {
1368 zabbix_log(LOG_LEVEL_WARNING, "SNMP response from host \"%s\" contains"
1369 " variable bindings that do not match the request:"
1370 " sent \"%s\", received \"%s\"",
1371 items[0].host.host, sent_oid, received_oid);
1372
1373 goto halve; /* give device a chance to handle a smaller request */
1374 }
1375 else
1376 {
1377 zabbix_log(LOG_LEVEL_DEBUG, "SNMP response from host \"%s\" contains"
1378 " variable bindings that do not match the request:"
1379 " sent \"%s\", received \"%s\"",
1380 items[0].host.host, sent_oid, received_oid);
1381 }
1382 }
1383
1384 /* process received data */
1385
1386 if (NULL != query_and_ignore_type && 1 == query_and_ignore_type[j])
1387 {
1388 (void)zbx_snmp_set_result(var, ITEM_VALUE_TYPE_STR, 0, &results[j]);
1389 }
1390 else
1391 {
1392 errcodes[j] = zbx_snmp_set_result(var, items[j].value_type, items[j].data_type,
1393 &results[j]);
1394 }
1395 }
1396
1397 if (SUCCEED == ret)
1398 {
1399 if (*max_succeed < mapping_num)
1400 *max_succeed = mapping_num;
1401 }
1402 else if (1 < mapping_num)
1403 {
1404 if (*min_fail > mapping_num)
1405 *min_fail = mapping_num;
1406 }
1407 }
1408 else if (STAT_SUCCESS == status && SNMP_ERR_NOSUCHNAME == response->errstat && 0 != response->errindex)
1409 {
1410 /* If a request PDU contains a bad variable, the specified behavior is different between SNMPv1 and */
1411 /* later versions. In SNMPv1, the whole PDU is rejected and "response->errindex" is set to indicate */
1412 /* the bad variable. In SNMPv2 and later, the SNMP agent processes the PDU by filling values for the */
1413 /* known variables and marking unknown variables individually in the variable binding list. However, */
1414 /* SNMPv2 allows SNMPv1 behavior, too. So regardless of the SNMP version used, if we get this error, */
1415 /* then we fix the PDU by removing the bad variable and retry the request. */
1416
1417 i = response->errindex - 1;
1418
1419 if (0 > i || i >= mapping_num)
1420 {
1421 zabbix_log(LOG_LEVEL_WARNING, "SNMP response from host \"%s\" contains"
1422 " an out of bounds error index: %ld", items[0].host.host, response->errindex);
1423
1424 zbx_strlcpy(error, "Invalid SNMP response: error index out of bounds.", max_error_len);
1425
1426 ret = NOTSUPPORTED;
1427 goto exit;
1428 }
1429
1430 j = mapping[i];
1431
1432 zabbix_log(LOG_LEVEL_DEBUG, "%s() snmp_synch_response() errindex:%ld oid:'%s'", __function_name,
1433 response->errindex, oids[j]);
1434
1435 if (NULL == query_and_ignore_type || 0 == query_and_ignore_type[j])
1436 {
1437 errcodes[j] = zbx_get_snmp_response_error(ss, &items[0].interface, status, response, error,
1438 max_error_len);
1439 SET_MSG_RESULT(&results[j], zbx_strdup(NULL, error));
1440 *error = '\0';
1441 }
1442
1443 if (1 < mapping_num)
1444 {
1445 if (NULL != (pdu = snmp_fix_pdu(response, SNMP_MSG_GET)))
1446 {
1447 memmove(mapping + i, mapping + i + 1, sizeof(int) * (mapping_num - i - 1));
1448 mapping_num--;
1449
1450 snmp_free_pdu(response);
1451 goto retry;
1452 }
1453 else
1454 {
1455 zbx_strlcpy(error, "snmp_fix_pdu(): cannot fix PDU object.", max_error_len);
1456 ret = NOTSUPPORTED;
1457 }
1458 }
1459 }
1460 else if (1 < mapping_num &&
1461 ((STAT_SUCCESS == status && SNMP_ERR_TOOBIG == response->errstat) || STAT_TIMEOUT == status ||
1462 (STAT_ERROR == status && SNMPERR_TOO_LONG == ss->s_snmp_errno)))
1463 {
1464 /* Since we are trying to obtain multiple values from the SNMP agent, the response that it has to */
1465 /* generate might be too big. It seems to be required by the SNMP standard that in such cases the */
1466 /* error status should be set to "tooBig(1)". However, some devices simply do not respond to such */
1467 /* queries and we get a timeout. Moreover, some devices exhibit both behaviors - they either send */
1468 /* "tooBig(1)" or do not respond at all. So what we do is halve the number of variables to query - */
1469 /* it should work in the vast majority of cases, because, since we are now querying "num" values, */
1470 /* we know that querying "num/2" values succeeded previously. The case where it can still fail due */
1471 /* to exceeded maximum response size is if we are now querying values that are unusually large. So */
1472 /* if querying with half the number of the last values does not work either, we resort to querying */
1473 /* values one by one, and the next time configuration cache gives us items to query, it will give */
1474 /* us less. */
1475
1476 /* The explanation above is for the first two conditions. The third condition comes from SNMPv3, */
1477 /* where the size of the request that we are trying to send exceeds device's "msgMaxSize" limit. */
1478 halve:
1479 if (*min_fail > mapping_num)
1480 *min_fail = mapping_num;
1481
1482 if (0 == level)
1483 {
1484 /* halve the number of items */
1485
1486 int base;
1487
1488 ret = zbx_snmp_get_values(ss, items, oids, results, errcodes, query_and_ignore_type, num / 2,
1489 level + 1, error, max_error_len, max_succeed, min_fail);
1490
1491 if (SUCCEED != ret)
1492 goto exit;
1493
1494 base = num / 2;
1495
1496 ret = zbx_snmp_get_values(ss, items + base, oids + base, results + base, errcodes + base,
1497 NULL == query_and_ignore_type ? NULL : query_and_ignore_type + base, num - base,
1498 level + 1, error, max_error_len, max_succeed, min_fail);
1499 }
1500 else if (1 == level)
1501 {
1502 /* resort to querying items one by one */
1503
1504 for (i = 0; i < num; i++)
1505 {
1506 if (SUCCEED != errcodes[i])
1507 continue;
1508
1509 ret = zbx_snmp_get_values(ss, items + i, oids + i, results + i, errcodes + i,
1510 NULL == query_and_ignore_type ? NULL : query_and_ignore_type + i, 1,
1511 level + 1, error, max_error_len, max_succeed, min_fail);
1512
1513 if (SUCCEED != ret)
1514 goto exit;
1515 }
1516 }
1517 }
1518 else
1519 ret = zbx_get_snmp_response_error(ss, &items[0].interface, status, response, error, max_error_len);
1520 exit:
1521 if (NULL != response)
1522 snmp_free_pdu(response);
1523 out:
1524 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
1525
1526 return ret;
1527 }
1528
1529 /******************************************************************************
1530 * *
1531 * Function: zbx_snmp_translate *
1532 * *
1533 * Purpose: translate well-known object identifiers into numeric form *
1534 * *
1535 * Author: Alexei Vladishev *
1536 * *
1537 ******************************************************************************/
zbx_snmp_translate(char * oid_translated,const char * oid,size_t max_oid_len)1538 static void zbx_snmp_translate(char *oid_translated, const char *oid, size_t max_oid_len)
1539 {
1540 const char *__function_name = "zbx_snmp_translate";
1541
1542 typedef struct
1543 {
1544 const size_t sz;
1545 const char *mib;
1546 const char *replace;
1547 }
1548 zbx_mib_norm_t;
1549
1550 #define LEN_STR(x) ZBX_CONST_STRLEN(x), x
1551 static zbx_mib_norm_t mibs[] =
1552 {
1553 /* the most popular items first */
1554 {LEN_STR("ifDescr"), ".1.3.6.1.2.1.2.2.1.2"},
1555 {LEN_STR("ifInOctets"), ".1.3.6.1.2.1.2.2.1.10"},
1556 {LEN_STR("ifOutOctets"), ".1.3.6.1.2.1.2.2.1.16"},
1557 {LEN_STR("ifAdminStatus"), ".1.3.6.1.2.1.2.2.1.7"},
1558 {LEN_STR("ifOperStatus"), ".1.3.6.1.2.1.2.2.1.8"},
1559 {LEN_STR("ifIndex"), ".1.3.6.1.2.1.2.2.1.1"},
1560 {LEN_STR("ifType"), ".1.3.6.1.2.1.2.2.1.3"},
1561 {LEN_STR("ifMtu"), ".1.3.6.1.2.1.2.2.1.4"},
1562 {LEN_STR("ifSpeed"), ".1.3.6.1.2.1.2.2.1.5"},
1563 {LEN_STR("ifPhysAddress"), ".1.3.6.1.2.1.2.2.1.6"},
1564 {LEN_STR("ifInUcastPkts"), ".1.3.6.1.2.1.2.2.1.11"},
1565 {LEN_STR("ifInNUcastPkts"), ".1.3.6.1.2.1.2.2.1.12"},
1566 {LEN_STR("ifInDiscards"), ".1.3.6.1.2.1.2.2.1.13"},
1567 {LEN_STR("ifInErrors"), ".1.3.6.1.2.1.2.2.1.14"},
1568 {LEN_STR("ifInUnknownProtos"), ".1.3.6.1.2.1.2.2.1.15"},
1569 {LEN_STR("ifOutUcastPkts"), ".1.3.6.1.2.1.2.2.1.17"},
1570 {LEN_STR("ifOutNUcastPkts"), ".1.3.6.1.2.1.2.2.1.18"},
1571 {LEN_STR("ifOutDiscards"), ".1.3.6.1.2.1.2.2.1.19"},
1572 {LEN_STR("ifOutErrors"), ".1.3.6.1.2.1.2.2.1.20"},
1573 {LEN_STR("ifOutQLen"), ".1.3.6.1.2.1.2.2.1.21"},
1574 {0}
1575 };
1576 #undef LEN_STR
1577
1578 int found = 0, i;
1579
1580 zabbix_log(LOG_LEVEL_DEBUG, "In %s() oid:'%s'", __function_name, oid);
1581
1582 for (i = 0; 0 != mibs[i].sz; i++)
1583 {
1584 if (0 == strncmp(mibs[i].mib, oid, mibs[i].sz))
1585 {
1586 found = 1;
1587 zbx_snprintf(oid_translated, max_oid_len, "%s%s", mibs[i].replace, oid + mibs[i].sz);
1588 break;
1589 }
1590 }
1591
1592 if (0 == found)
1593 zbx_strlcpy(oid_translated, oid, max_oid_len);
1594
1595 zabbix_log(LOG_LEVEL_DEBUG, "End of %s() oid_translated:'%s'", __function_name, oid_translated);
1596 }
1597
1598 /* discovered SNMP object, identified by its index */
1599 typedef struct
1600 {
1601 /* object index returned by zbx_snmp_walk */
1602 char *index;
1603
1604 /* an array of OID values stored in the same order as defined in OID key */
1605 char **values;
1606 }
1607 zbx_snmp_dobject_t;
1608
1609 /* helper data structure used by snmp discovery */
1610 typedef struct
1611 {
1612 /* the index of OID being currently processed (walked) */
1613 int num;
1614
1615 /* the discovered SNMP objects */
1616 zbx_hashset_t objects;
1617
1618 /* the index (order) of discovered SNMP objects */
1619 zbx_vector_ptr_t index;
1620
1621 /* request data structure used to parse discovery OID key */
1622 AGENT_REQUEST request;
1623 }
1624 zbx_snmp_ddata_t;
1625
1626 /* discovery objects hashset support */
zbx_snmp_dobject_hash(const void * data)1627 static zbx_hash_t zbx_snmp_dobject_hash(const void *data)
1628 {
1629 const char *index = *(const char **)data;
1630
1631 return ZBX_DEFAULT_STRING_HASH_ALGO(index, strlen(index), ZBX_DEFAULT_HASH_SEED);
1632 }
1633
zbx_snmp_dobject_compare(const void * d1,const void * d2)1634 static int zbx_snmp_dobject_compare(const void *d1, const void *d2)
1635 {
1636 const char *i1 = *(const char **)d1;
1637 const char *i2 = *(const char **)d2;
1638
1639 return strcmp(i1, i2);
1640 }
1641
1642 /******************************************************************************
1643 * *
1644 * Function: zbx_snmp_ddata_init *
1645 * *
1646 * Purpose: initializes snmp discovery data object *
1647 * *
1648 * Parameters: data - [IN] snmp discovery data object *
1649 * key - [IN] discovery OID key *
1650 * error - [OUT] a buffer to store error message *
1651 * max_error_len - [IN] maximum error message length *
1652 * *
1653 * Return value: CONFIG_ERROR - OID key configuration error *
1654 * SUCCEED - if function successfully completed *
1655 * *
1656 ******************************************************************************/
zbx_snmp_ddata_init(zbx_snmp_ddata_t * data,const char * key,char * error,size_t max_error_len)1657 static int zbx_snmp_ddata_init(zbx_snmp_ddata_t *data, const char *key, char *error, size_t max_error_len)
1658 {
1659 int i, j, ret = CONFIG_ERROR;
1660
1661 init_request(&data->request);
1662
1663 if (SUCCEED != parse_item_key(key, &data->request))
1664 {
1665 zbx_strlcpy(error, "Invalid SNMP OID: cannot parse expression.", max_error_len);
1666 goto out;
1667 }
1668
1669 if (0 == data->request.nparam || 0 != (data->request.nparam & 1))
1670 {
1671 zbx_strlcpy(error, "Invalid SNMP OID: pairs of macro and OID are expected.", max_error_len);
1672 goto out;
1673 }
1674
1675 for (i = 0; i < data->request.nparam; i += 2)
1676 {
1677 if (SUCCEED != is_discovery_macro(data->request.params[i]))
1678 {
1679 zbx_snprintf(error, max_error_len, "Invalid SNMP OID: macro \"%s\" is invalid",
1680 data->request.params[i]);
1681 goto out;
1682 }
1683
1684 if (0 == strcmp(data->request.params[i], "{#SNMPINDEX}"))
1685 {
1686 zbx_strlcpy(error, "Invalid SNMP OID: macro \"{#SNMPINDEX}\" is not allowed.", max_error_len);
1687 goto out;
1688 }
1689 }
1690
1691 for (i = 2; i < data->request.nparam; i += 2)
1692 {
1693 for (j = 0; j < i; j += 2)
1694 {
1695 if (0 == strcmp(data->request.params[i], data->request.params[j]))
1696 {
1697 zbx_strlcpy(error, "Invalid SNMP OID: unique macros are expected.", max_error_len);
1698 goto out;
1699 }
1700 }
1701 }
1702
1703 zbx_hashset_create(&data->objects, 10, zbx_snmp_dobject_hash, zbx_snmp_dobject_compare);
1704 zbx_vector_ptr_create(&data->index);
1705
1706 ret = SUCCEED;
1707 out:
1708 if (SUCCEED != ret)
1709 free_request(&data->request);
1710
1711 return ret;
1712 }
1713
1714 /******************************************************************************
1715 * *
1716 * Function: zbx_snmp_ddata_clean *
1717 * *
1718 * Purpose: releases data allocated by snmp discovery *
1719 * *
1720 * Parameters: data - [IN] snmp discovery data object *
1721 * *
1722 ******************************************************************************/
zbx_snmp_ddata_clean(zbx_snmp_ddata_t * data)1723 static void zbx_snmp_ddata_clean(zbx_snmp_ddata_t *data)
1724 {
1725 int i;
1726 zbx_hashset_iter_t iter;
1727 zbx_snmp_dobject_t *obj;
1728
1729 zbx_vector_ptr_destroy(&data->index);
1730
1731 zbx_hashset_iter_reset(&data->objects, &iter);
1732 while (NULL != (obj = zbx_hashset_iter_next(&iter)))
1733 {
1734 for (i = 0; i < data->request.nparam / 2; i++)
1735 zbx_free(obj->values[i]);
1736
1737 zbx_free(obj->index);
1738 zbx_free(obj->values);
1739 }
1740
1741 zbx_hashset_destroy(&data->objects);
1742
1743 free_request(&data->request);
1744 }
1745
zbx_snmp_walk_discovery_cb(void * arg,const char * OID,const char * index,const char * value)1746 static void zbx_snmp_walk_discovery_cb(void *arg, const char *OID, const char *index, const char *value)
1747 {
1748 zbx_snmp_ddata_t *data = (zbx_snmp_ddata_t *)arg;
1749 zbx_snmp_dobject_t *obj;
1750
1751 if (NULL == (obj = zbx_hashset_search(&data->objects, &index)))
1752 {
1753 zbx_snmp_dobject_t new_obj;
1754
1755 new_obj.index = zbx_strdup(NULL, index);
1756 new_obj.values = (char **)zbx_malloc(NULL, sizeof(char *) * data->request.nparam / 2);
1757 memset(new_obj.values, 0, sizeof(char *) * data->request.nparam / 2);
1758
1759 obj = zbx_hashset_insert(&data->objects, &new_obj, sizeof(new_obj));
1760 zbx_vector_ptr_append(&data->index, obj);
1761 }
1762
1763 obj->values[data->num] = zbx_strdup(NULL, value);
1764 }
1765
zbx_snmp_process_discovery(struct snmp_session * ss,const DC_ITEM * item,AGENT_RESULT * result,int * errcode,char * error,size_t max_error_len,int * max_succeed,int * min_fail,int max_vars,int bulk)1766 static int zbx_snmp_process_discovery(struct snmp_session *ss, const DC_ITEM *item, AGENT_RESULT *result,
1767 int *errcode, char *error, size_t max_error_len, int *max_succeed, int *min_fail, int max_vars,
1768 int bulk)
1769 {
1770 const char *__function_name = "zbx_snmp_process_discovery";
1771
1772 int i, j, ret;
1773 char oid_translated[ITEM_SNMP_OID_LEN_MAX];
1774 struct zbx_json js;
1775 zbx_snmp_ddata_t data;
1776 zbx_snmp_dobject_t *obj;
1777
1778 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
1779
1780 if (SUCCEED != (ret = zbx_snmp_ddata_init(&data, item->snmp_oid, error, max_error_len)))
1781 goto out;
1782
1783 for (data.num = 0; data.num < data.request.nparam / 2; data.num++)
1784 {
1785 zbx_snmp_translate(oid_translated, data.request.params[data.num * 2 + 1], sizeof(oid_translated));
1786
1787 if (SUCCEED != (ret = zbx_snmp_walk(ss, item, oid_translated, error, max_error_len,
1788 max_succeed, min_fail, max_vars, bulk, zbx_snmp_walk_discovery_cb, (void *)&data)))
1789 {
1790 goto clean;
1791 }
1792 }
1793
1794 zbx_json_init(&js, ZBX_JSON_STAT_BUF_LEN);
1795 zbx_json_addarray(&js, ZBX_PROTO_TAG_DATA);
1796
1797 for (i = 0; i < data.index.values_num; i++)
1798 {
1799 obj = (zbx_snmp_dobject_t *)data.index.values[i];
1800
1801 zbx_json_addobject(&js, NULL);
1802 zbx_json_addstring(&js, "{#SNMPINDEX}", obj->index, ZBX_JSON_TYPE_STRING);
1803
1804 for (j = 0; j < data.request.nparam / 2; j++)
1805 {
1806 if (NULL == obj->values[j])
1807 continue;
1808
1809 zbx_json_addstring(&js, data.request.params[j * 2], obj->values[j], ZBX_JSON_TYPE_STRING);
1810 }
1811 zbx_json_close(&js);
1812 }
1813
1814 zbx_json_close(&js);
1815
1816 SET_TEXT_RESULT(result, zbx_strdup(NULL, js.buffer));
1817
1818 zbx_json_free(&js);
1819 clean:
1820 zbx_snmp_ddata_clean(&data);
1821 out:
1822 if (SUCCEED != (*errcode = ret))
1823 SET_MSG_RESULT(result, zbx_strdup(NULL, error));
1824
1825 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
1826
1827 return ret;
1828 }
1829
zbx_snmp_walk_cache_cb(void * arg,const char * oid,const char * index,const char * value)1830 static void zbx_snmp_walk_cache_cb(void *arg, const char *oid, const char *index, const char *value)
1831 {
1832 cache_put_snmp_index((const DC_ITEM *)arg, oid, index, value);
1833 }
1834
zbx_snmp_process_dynamic(struct snmp_session * ss,const DC_ITEM * items,AGENT_RESULT * results,int * errcodes,int num,char * error,size_t max_error_len,int * max_succeed,int * min_fail,int bulk)1835 static int zbx_snmp_process_dynamic(struct snmp_session *ss, const DC_ITEM *items, AGENT_RESULT *results,
1836 int *errcodes, int num, char *error, size_t max_error_len, int *max_succeed, int *min_fail, int bulk)
1837 {
1838 const char *__function_name = "zbx_snmp_process_dynamic";
1839
1840 int i, j, k, ret;
1841 int to_walk[MAX_SNMP_ITEMS], to_walk_num = 0;
1842 int to_verify[MAX_SNMP_ITEMS], to_verify_num = 0;
1843 char to_verify_oids[MAX_SNMP_ITEMS][ITEM_SNMP_OID_LEN_MAX];
1844 unsigned char query_and_ignore_type[MAX_SNMP_ITEMS];
1845 char index_oids[MAX_SNMP_ITEMS][ITEM_SNMP_OID_LEN_MAX];
1846 char index_values[MAX_SNMP_ITEMS][ITEM_SNMP_OID_LEN_MAX];
1847 char oids_translated[MAX_SNMP_ITEMS][ITEM_SNMP_OID_LEN_MAX];
1848 char *idx = NULL, *pl;
1849 size_t idx_alloc = 32;
1850
1851 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
1852
1853 idx = zbx_malloc(idx, idx_alloc);
1854
1855 /* perform initial item validation */
1856
1857 for (i = 0; i < num; i++)
1858 {
1859 char method[8];
1860
1861 if (SUCCEED != errcodes[i])
1862 continue;
1863
1864 if (3 != num_key_param(items[i].snmp_oid))
1865 {
1866 SET_MSG_RESULT(&results[i], zbx_dsprintf(NULL, "OID \"%s\" contains unsupported parameters.",
1867 items[i].snmp_oid));
1868 errcodes[i] = CONFIG_ERROR;
1869 continue;
1870 }
1871
1872 get_key_param(items[i].snmp_oid, 1, method, sizeof(method));
1873 get_key_param(items[i].snmp_oid, 2, index_oids[i], sizeof(index_oids[i]));
1874 get_key_param(items[i].snmp_oid, 3, index_values[i], sizeof(index_values[i]));
1875
1876 if (0 != strcmp("index", method))
1877 {
1878 SET_MSG_RESULT(&results[i], zbx_dsprintf(NULL, "Unsupported method \"%s\" in the OID \"%s\".",
1879 method, items[i].snmp_oid));
1880 errcodes[i] = CONFIG_ERROR;
1881 continue;
1882 }
1883
1884 zbx_snmp_translate(oids_translated[i], index_oids[i], sizeof(oids_translated[i]));
1885
1886 if (SUCCEED == cache_get_snmp_index(&items[i], oids_translated[i], index_values[i], &idx, &idx_alloc))
1887 {
1888 zbx_snprintf(to_verify_oids[i], sizeof(to_verify_oids[i]), "%s.%s", oids_translated[i], idx);
1889
1890 to_verify[to_verify_num++] = i;
1891 query_and_ignore_type[i] = 1;
1892 }
1893 else
1894 {
1895 to_walk[to_walk_num++] = i;
1896 query_and_ignore_type[i] = 0;
1897 }
1898 }
1899
1900 /* verify that cached indices are still valid */
1901
1902 if (0 != to_verify_num)
1903 {
1904 ret = zbx_snmp_get_values(ss, items, to_verify_oids, results, errcodes, query_and_ignore_type, num, 0,
1905 error, max_error_len, max_succeed, min_fail);
1906
1907 if (SUCCEED != ret && NOTSUPPORTED != ret)
1908 goto exit;
1909
1910 for (i = 0; i < to_verify_num; i++)
1911 {
1912 j = to_verify[i];
1913
1914 if (SUCCEED != errcodes[j])
1915 continue;
1916
1917 if (NULL == GET_STR_RESULT(&results[j]) || 0 != strcmp(results[j].str, index_values[j]))
1918 {
1919 to_walk[to_walk_num++] = j;
1920 }
1921 else
1922 {
1923 /* ready to construct the final OID with index */
1924
1925 size_t len;
1926
1927 len = strlen(oids_translated[j]);
1928
1929 pl = strchr(items[j].snmp_oid, '[');
1930
1931 *pl = '\0';
1932 zbx_snmp_translate(oids_translated[j], items[j].snmp_oid, sizeof(oids_translated[j]));
1933 *pl = '[';
1934
1935 zbx_strlcat(oids_translated[j], to_verify_oids[j] + len, sizeof(oids_translated[j]));
1936 }
1937
1938 free_result(&results[j]);
1939 }
1940 }
1941
1942 /* walk OID trees to build index cache for cache misses */
1943
1944 if (0 != to_walk_num)
1945 {
1946 for (i = 0; i < to_walk_num; i++)
1947 {
1948 int errcode;
1949
1950 j = to_walk[i];
1951
1952 /* see whether this OID tree was already walked for another item */
1953
1954 for (k = 0; k < i; k++)
1955 {
1956 if (0 == strcmp(oids_translated[to_walk[k]], oids_translated[j]))
1957 break;
1958 }
1959
1960 if (k != i)
1961 continue;
1962
1963 /* walk */
1964
1965 cache_del_snmp_index_subtree(&items[j], oids_translated[j]);
1966
1967 errcode = zbx_snmp_walk(ss, &items[j], oids_translated[j], error, max_error_len, max_succeed,
1968 min_fail, num, bulk, zbx_snmp_walk_cache_cb, (void *)&items[j]);
1969
1970 if (NETWORK_ERROR == errcode)
1971 {
1972 /* consider a network error as relating to all items passed to */
1973 /* this function, including those we did not just try to walk for */
1974
1975 ret = NETWORK_ERROR;
1976 goto exit;
1977 }
1978
1979 if (CONFIG_ERROR == errcode || NOTSUPPORTED == errcode)
1980 {
1981 /* consider a configuration or "not supported" error as */
1982 /* relating only to the items we have just tried to walk for */
1983
1984 for (k = i; k < to_walk_num; k++)
1985 {
1986 if (0 == strcmp(oids_translated[to_walk[k]], oids_translated[j]))
1987 {
1988 SET_MSG_RESULT(&results[to_walk[k]], zbx_strdup(NULL, error));
1989 errcodes[to_walk[k]] = errcode;
1990 }
1991 }
1992 }
1993 }
1994
1995 for (i = 0; i < to_walk_num; i++)
1996 {
1997 j = to_walk[i];
1998
1999 if (SUCCEED != errcodes[j])
2000 continue;
2001
2002 if (SUCCEED == cache_get_snmp_index(&items[j], oids_translated[j], index_values[j], &idx,
2003 &idx_alloc))
2004 {
2005 /* ready to construct the final OID with index */
2006
2007 pl = strchr(items[j].snmp_oid, '[');
2008
2009 *pl = '\0';
2010 zbx_snmp_translate(oids_translated[j], items[j].snmp_oid, sizeof(oids_translated[j]));
2011 *pl = '[';
2012
2013 zbx_strlcat(oids_translated[j], ".", sizeof(oids_translated[j]));
2014 zbx_strlcat(oids_translated[j], idx, sizeof(oids_translated[j]));
2015 }
2016 else
2017 {
2018 SET_MSG_RESULT(&results[j], zbx_dsprintf(NULL,
2019 "Cannot find index of \"%s\" in \"%s\".",
2020 index_values[j], index_oids[j]));
2021 errcodes[j] = NOTSUPPORTED;
2022 }
2023 }
2024 }
2025
2026 /* query values based on the indices verified and/or determined above */
2027
2028 ret = zbx_snmp_get_values(ss, items, oids_translated, results, errcodes, NULL, num, 0, error, max_error_len,
2029 max_succeed, min_fail);
2030 exit:
2031 zbx_free(idx);
2032
2033 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
2034
2035 return ret;
2036 }
2037
zbx_snmp_process_standard(struct snmp_session * ss,const DC_ITEM * items,AGENT_RESULT * results,int * errcodes,int num,char * error,size_t max_error_len,int * max_succeed,int * min_fail)2038 static int zbx_snmp_process_standard(struct snmp_session *ss, const DC_ITEM *items, AGENT_RESULT *results,
2039 int *errcodes, int num, char *error, size_t max_error_len, int *max_succeed, int *min_fail)
2040 {
2041 const char *__function_name = "zbx_snmp_process_standard";
2042
2043 int i, ret;
2044 char oids_translated[MAX_SNMP_ITEMS][ITEM_SNMP_OID_LEN_MAX];
2045
2046 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
2047
2048 for (i = 0; i < num; i++)
2049 {
2050 if (SUCCEED != errcodes[i])
2051 continue;
2052
2053 if (0 != num_key_param(items[i].snmp_oid))
2054 {
2055 SET_MSG_RESULT(&results[i], zbx_dsprintf(NULL, "OID \"%s\" contains unsupported parameters.",
2056 items[i].snmp_oid));
2057 errcodes[i] = CONFIG_ERROR;
2058 continue;
2059 }
2060
2061 zbx_snmp_translate(oids_translated[i], items[i].snmp_oid, sizeof(oids_translated[i]));
2062 }
2063
2064 ret = zbx_snmp_get_values(ss, items, oids_translated, results, errcodes, NULL, num, 0, error, max_error_len,
2065 max_succeed, min_fail);
2066
2067 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
2068
2069 return ret;
2070 }
2071
get_value_snmp(const DC_ITEM * item,AGENT_RESULT * result)2072 int get_value_snmp(const DC_ITEM *item, AGENT_RESULT *result)
2073 {
2074 int errcode = SUCCEED;
2075
2076 get_values_snmp(item, result, &errcode, 1);
2077
2078 return errcode;
2079 }
2080
get_values_snmp(const DC_ITEM * items,AGENT_RESULT * results,int * errcodes,int num)2081 void get_values_snmp(const DC_ITEM *items, AGENT_RESULT *results, int *errcodes, int num)
2082 {
2083 const char *__function_name = "get_values_snmp";
2084
2085 struct snmp_session *ss;
2086 char error[MAX_STRING_LEN];
2087 int i, j, err = SUCCEED, max_succeed = 0, min_fail = MAX_SNMP_ITEMS + 1,
2088 bulk = SNMP_BULK_ENABLED;
2089
2090 zabbix_log(LOG_LEVEL_DEBUG, "In %s() host:'%s' addr:'%s' num:%d",
2091 __function_name, items[0].host.host, items[0].interface.addr, num);
2092
2093 for (j = 0; j < num; j++) /* locate first supported item to use as a reference */
2094 {
2095 if (SUCCEED == errcodes[j])
2096 break;
2097 }
2098
2099 if (j == num) /* all items already NOTSUPPORTED (with invalid key, port or SNMP parameters) */
2100 goto out;
2101
2102 if (NULL == (ss = zbx_snmp_open_session(&items[j], error, sizeof(error))))
2103 {
2104 err = NETWORK_ERROR;
2105 goto exit;
2106 }
2107
2108 if (0 != (ZBX_FLAG_DISCOVERY_RULE & items[j].flags) || 0 == strncmp(items[j].snmp_oid, "discovery[", 10))
2109 {
2110 int max_vars;
2111
2112 max_vars = DCconfig_get_suggested_snmp_vars(items[j].interface.interfaceid, &bulk);
2113
2114 err = zbx_snmp_process_discovery(ss, &items[j], &results[j], &errcodes[j], error, sizeof(error),
2115 &max_succeed, &min_fail, max_vars, bulk);
2116 }
2117 else if (NULL != strchr(items[j].snmp_oid, '['))
2118 {
2119 (void)DCconfig_get_suggested_snmp_vars(items[j].interface.interfaceid, &bulk);
2120
2121 err = zbx_snmp_process_dynamic(ss, items + j, results + j, errcodes + j, num - j, error, sizeof(error),
2122 &max_succeed, &min_fail, bulk);
2123 }
2124 else
2125 {
2126 err = zbx_snmp_process_standard(ss, items + j, results + j, errcodes + j, num - j, error, sizeof(error),
2127 &max_succeed, &min_fail);
2128 }
2129
2130 zbx_snmp_close_session(ss);
2131 exit:
2132 if (SUCCEED != err)
2133 {
2134 zabbix_log(LOG_LEVEL_DEBUG, "getting SNMP values failed: %s", error);
2135
2136 for (i = j; i < num; i++)
2137 {
2138 if (SUCCEED != errcodes[i])
2139 continue;
2140
2141 SET_MSG_RESULT(&results[i], zbx_strdup(NULL, error));
2142 errcodes[i] = err;
2143 }
2144 }
2145 else if (SNMP_BULK_ENABLED == bulk && (0 != max_succeed || MAX_SNMP_ITEMS + 1 != min_fail))
2146 {
2147 DCconfig_update_interface_snmp_stats(items[j].interface.interfaceid, max_succeed, min_fail);
2148 }
2149 out:
2150 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
2151 }
2152
zbx_init_snmp(void)2153 void zbx_init_snmp(void)
2154 {
2155 sigset_t mask, orig_mask;
2156
2157 sigemptyset(&mask);
2158 sigaddset(&mask, SIGTERM);
2159 sigprocmask(SIG_BLOCK, &mask, &orig_mask);
2160
2161 init_snmp(progname);
2162
2163 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
2164 }
2165
2166 #endif /* HAVE_NETSNMP */
2167