Fixed MacAddress toString function for different formats; Introduced even more MacAdd...
[public/netxms.git] / include / nms_util.h
CommitLineData
cc022855 1/*
7ac71e60 2** NetXMS - Network Management System
7768852d 3** Copyright (C) 2003-2016 Victor Kirhenshtein
e9246d26
VK
4**
5** This program is free software; you can redistribute it and/or modify
68f384ea
VK
6** it under the terms of the GNU Lesser General Public License as published
7** by the Free Software Foundation; either version 3 of the License, or
e9246d26
VK
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**
68f384ea 15** You should have received a copy of the GNU Lesser General Public License
e9246d26
VK
16** along with this program; if not, write to the Free Software
17** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18**
fb7ce4b9 19** File: nms_util.h
e9246d26
VK
20**
21**/
22
23#ifndef _nms_util_h_
24#define _nms_util_h_
25
64584976
VK
26#ifdef _WIN32
27#ifdef LIBNETXMS_EXPORTS
28#define LIBNETXMS_EXPORTABLE __declspec(dllexport)
29#else
30#define LIBNETXMS_EXPORTABLE __declspec(dllimport)
31#endif
32#else /* _WIN32 */
33#define LIBNETXMS_EXPORTABLE
34#endif
35
e9246d26
VK
36#include <nms_common.h>
37#include <nms_cscp.h>
953dfe76 38#include <nms_threads.h>
64584976 39#include <time.h>
e9ef47dd 40#include <jansson.h>
e9246d26 41
bbaae283
VK
42// JSON_EMBED was added in jansson 2.10 - ignore it for older version
43#ifndef JSON_EMBED
44#define JSON_EMBED 0
45#endif
46
1668f7ed
VK
47#if HAVE_POLL_H
48#include <poll.h>
49#endif
50
6d8aee95
VK
51#if HAVE_BYTESWAP_H
52#include <byteswap.h>
53#endif
54
92502d5f
VK
55#include <base64.h>
56
4b47d7d7
VK
57/*** Byte swapping ***/
58#if WORDS_BIGENDIAN
59#define htonq(x) (x)
60#define ntohq(x) (x)
61#define htond(x) (x)
62#define ntohd(x) (x)
c62d158b 63#define SwapUCS2String(x)
4b47d7d7 64#else
c62d158b 65#if HAVE_HTONLL
4b47d7d7
VK
66#define htonq(x) htonll(x)
67#else
c62d158b 68#define htonq(x) bswap_64(x)
4b47d7d7 69#endif
c62d158b 70#if HAVE_NTOHLL
4b47d7d7
VK
71#define ntohq(x) ntohll(x)
72#else
c62d158b 73#define ntohq(x) bswap_64(x)
4b47d7d7 74#endif
c62d158b
VK
75#define htond(x) bswap_double(x)
76#define ntohd(x) bswap_double(x)
669fcb92 77#define SwapUCS2String(x) bswap_array_16((UINT16 *)(x), -1)
4b47d7d7 78#endif
6d8aee95 79
4b47d7d7 80#ifdef __cplusplus
c62d158b
VK
81
82#if !(HAVE_DECL_BSWAP_16)
83inline UINT16 bswap_16(UINT16 val)
84{
85 return (val >> 8) | ((val << 8) & 0xFF00);
86}
4b47d7d7
VK
87#endif
88
c62d158b
VK
89#if !(HAVE_DECL_BSWAP_32)
90inline UINT32 bswap_32(UINT32 val)
91{
92 UINT32 result;
93 BYTE *sptr = (BYTE *)&val;
3c15eedb 94 BYTE *dptr = (BYTE *)&result + 3;
c62d158b
VK
95 for(int i = 0; i < 4; i++, sptr++, dptr--)
96 *dptr = *sptr;
97 return result;
98}
4b47d7d7 99#endif
c62d158b
VK
100
101#if !(HAVE_DECL_BSWAP_64)
102inline UINT64 bswap_64(UINT64 val)
103{
104 UINT64 result;
105 BYTE *sptr = (BYTE *)&val;
106 BYTE *dptr = (BYTE *)&result + 7;
107 for(int i = 0; i < 8; i++, sptr++, dptr--)
108 *dptr = *sptr;
109 return result;
110}
4b47d7d7 111#endif
6d8aee95 112
c62d158b
VK
113inline double bswap_double(double val)
114{
115 double result;
116 BYTE *sptr = (BYTE *)&val;
117 BYTE *dptr = (BYTE *)&result + 7;
118 for(int i = 0; i < 8; i++, sptr++, dptr--)
119 *dptr = *sptr;
120 return result;
4b47d7d7 121}
c62d158b 122
96772780
VK
123#else
124
125#if !(HAVE_DECL_BSWAP_16)
126UINT16 LIBNETXMS_EXPORTABLE __bswap_16(UINT16 val);
127#define bswap_16 __bswap_16
128#endif
129
130#if !(HAVE_DECL_BSWAP_32)
131UINT32 LIBNETXMS_EXPORTABLE __bswap_32(UINT32 val);
132#define bswap_32 __bswap_32
133#endif
134
135#if !(HAVE_DECL_BSWAP_64)
136UINT64 LIBNETXMS_EXPORTABLE __bswap_64(UINT64 val);
137#define bswap_64 __bswap_64
138#endif
139
140#endif
141
142#ifdef __cplusplus
143extern "C" {
144#endif
c62d158b
VK
145void LIBNETXMS_EXPORTABLE bswap_array_16(UINT16 *v, int len);
146void LIBNETXMS_EXPORTABLE bswap_array_32(UINT32 *v, int len);
96772780
VK
147#ifdef __cplusplus
148}
4b47d7d7
VK
149#endif
150
151
152/*** Serial communications ***/
6d8aee95
VK
153#ifdef _WIN32
154
155#define FLOW_NONE 0
156#define FLOW_SOFTWARE 1
157#define FLOW_HARDWARE 2
158
159#else /* _WIN32 */
160
70fed300
AK
161#ifdef HAVE_TERMIOS_H
162# include <termios.h>
163#else
164# error termios.h not found
165#endif
166
6d8aee95
VK
167#endif /* _WIN32 */
168
e2e66145
VK
169/**
170 * Return codes for IcmpPing()
171 */
66c04cc7
VK
172#define ICMP_SUCCESS 0
173#define ICMP_UNREACHEABLE 1
174#define ICMP_TIMEOUT 2
175#define ICMP_RAW_SOCK_FAILED 3
5418d4bb 176#define ICMP_API_ERROR 4
66c04cc7 177
e2e66145
VK
178/**
179 * Token types for configuration loader
180 */
4826c8a5
VK
181#define CT_LONG 0
182#define CT_STRING 1
183#define CT_STRING_LIST 2
184#define CT_END_OF_LIST 3
185#define CT_BOOLEAN 4
186#define CT_WORD 5
fc935a60 187#define CT_IGNORE 6
dda7c270 188#define CT_MB_STRING 7
e95680e5 189#define CT_BOOLEAN64 8
12f43871
VK
190#define CT_SIZE_BYTES 9 /* 64 bit integer, automatically converts K, M, G, T suffixes using 1024 as base) */
191#define CT_SIZE_UNITS 10 /* 64 bit integer, automatically converts K, M, G, T suffixes using 1000 as base) */
4826c8a5 192
e2e66145
VK
193/**
194 * Uninitialized value for override indicator
195 */
196#define NXCONFIG_UNINITIALIZED_VALUE (-1)
197
605fc935
VK
198/**
199 * Return codes for NxLoadConfig()
200 */
4826c8a5
VK
201#define NXCFG_ERR_OK 0
202#define NXCFG_ERR_NOFILE 1
203#define NXCFG_ERR_SYNTAX 2
204
605fc935
VK
205/**
206 * nxlog_open() flags
207 */
4e0e77e6
VK
208#define NXLOG_USE_SYSLOG ((UINT32)0x00000001)
209#define NXLOG_PRINT_TO_STDOUT ((UINT32)0x00000002)
210#define NXLOG_BACKGROUND_WRITER ((UINT32)0x00000004)
70be5423 211#define NXLOG_DEBUG_MODE ((UINT32)0x00000008)
4e0e77e6 212#define NXLOG_IS_OPEN ((UINT32)0x80000000)
9f2902ac 213
605fc935
VK
214/**
215 * nxlog rotation policy
216 */
5945d50a
VK
217#define NXLOG_ROTATION_DISABLED 0
218#define NXLOG_ROTATION_DAILY 1
219#define NXLOG_ROTATION_BY_SIZE 2
220
7768852d
VK
221/**
222 * Custom wcslen()
223 */
224#if !HAVE_WCSLEN
225
226#ifdef __cplusplus
227extern "C" {
228#endif
229size_t LIBNETXMS_EXPORTABLE wcslen(const WCHAR *s);
230#ifdef __cplusplus
231}
232#endif
233
234#endif
235
236/**
237 * Custom wcsncpy()
238 */
239#if !HAVE_WCSNCPY
240
241#ifdef __cplusplus
242extern "C" {
243#endif
244WCHAR LIBNETXMS_EXPORTABLE *wcsncpy(WCHAR *dest, const WCHAR *src, size_t n);
245#ifdef __cplusplus
246}
247#endif
248
249#endif
250
605fc935
VK
251/**
252 * _tcsdup() replacement
253 */
8ff13508
VK
254#if defined(_WIN32) && defined(USE_WIN32_HEAP)
255#ifdef __cplusplus
256extern "C" {
257#endif
fd72502a 258char LIBNETXMS_EXPORTABLE *nx_strdup(const char *src);
8ff13508
VK
259WCHAR LIBNETXMS_EXPORTABLE *nx_wcsdup(const WCHAR *src);
260#ifdef __cplusplus
261}
262#endif
263#endif
264
f4d2c9ba
VK
265/**
266 * Custom wcsdup
267 */
7768852d 268#if !HAVE_WCSDUP
fd72502a 269
f4d2c9ba
VK
270#ifdef __cplusplus
271extern "C" {
272#endif
7768852d 273WCHAR LIBNETXMS_EXPORTABLE *wcsdup(const WCHAR *src);
f4d2c9ba
VK
274#ifdef __cplusplus
275}
276#endif
fd72502a
VK
277
278#elif defined(_AIX)
279
280// Some AIX versions have broken wcsdup() so we use internal implementation
281#ifdef __cplusplus
282extern "C" {
283#endif
7768852d 284WCHAR LIBNETXMS_EXPORTABLE *nx_wcsdup(const WCHAR *src);
fd72502a
VK
285#ifdef __cplusplus
286}
287#endif
288
289#define wcsdup nx_wcsdup
290
f4d2c9ba
VK
291#endif
292
c012b7b7
VK
293#ifdef __cplusplus
294
c83f6449
VK
295/**
296 * Extended tcsdup: returns NULL if NULL pointer passed
297 */
298inline TCHAR *_tcsdup_ex(const TCHAR *s)
299{
300 return (s != NULL) ? _tcsdup(s) : NULL;
301}
302
c012b7b7
VK
303#endif
304
7768852d
VK
305/******* UNICODE related conversion and helper functions *******/
306
d65c16a8
VK
307#ifdef __cplusplus
308extern "C" {
309#endif
7768852d
VK
310
311// Basic string functions
312#ifdef UNICODE_UCS2
313
314#define ucs2_strlen wcslen
315#define ucs2_strncpy wcsncpy
316#define ucs2_strdup wcsdup
317
318size_t LIBNETXMS_EXPORTABLE ucs4_strlen(const UCS4CHAR *s);
319UCS4CHAR LIBNETXMS_EXPORTABLE *ucs4_strncpy(UCS4CHAR *dest, const UCS2CHAR *src, size_t n);
320UCS4CHAR LIBNETXMS_EXPORTABLE *ucs4_strdup(const UCS4CHAR *src);
321
322#else
323
324size_t LIBNETXMS_EXPORTABLE ucs2_strlen(const UCS2CHAR *s);
325UCS2CHAR LIBNETXMS_EXPORTABLE *ucs2_strncpy(UCS2CHAR *dest, const UCS2CHAR *src, size_t n);
326UCS2CHAR LIBNETXMS_EXPORTABLE *ucs2_strdup(const UCS2CHAR *src);
327
328#define ucs4_strlen wcslen
329#define ucs4_strncpy wcsncpy
330#define ucs4_strdup wcsdup
331
332#endif
333
334// Character conversion functions
335int LIBNETXMS_EXPORTABLE ucs2_to_ucs4(const UCS2CHAR *src, int srcLen, UCS4CHAR *dst, int dstLen);
336#if defined(_WIN32) || defined(UNICODE_UCS2)
337#define ucs2_to_utf8(wstr, wlen, mstr, mlen) WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, mstr, mlen, NULL, NULL)
338#define ucs2_to_mb(wstr, wlen, mstr, mlen) WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR, wstr, wlen, mstr, mlen, NULL, NULL)
339#else
340int LIBNETXMS_EXPORTABLE ucs2_to_utf8(const UCS2CHAR *src, int srcLen, char *dst, int dstLen);
341int LIBNETXMS_EXPORTABLE ucs2_to_mb(const UCS2CHAR *src, int srcLen, char *dst, int dstLen);
342#endif
343
344int LIBNETXMS_EXPORTABLE ucs4_to_ucs2(const UCS4CHAR *src, int srcLen, UCS2CHAR *dst, int dstLen);
345#ifdef UNICODE_UCS4
346#define ucs4_to_utf8(wstr, wlen, mstr, mlen) WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, mstr, mlen, NULL, NULL)
347#define ucs4_to_mb(wstr, wlen, mstr, mlen) WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR, wstr, wlen, mstr, mlen, NULL, NULL)
348#else
349int LIBNETXMS_EXPORTABLE ucs4_to_utf8(const UCS4CHAR *src, int srcLen, char *dst, int dstLen);
350int LIBNETXMS_EXPORTABLE ucs4_to_mb(const UCS4CHAR *src, int srcLen, char *dst, int dstLen);
351#endif
352
353#ifdef UNICODE_UCS4
354#define utf8_to_ucs4(mstr, mlen, wstr, wlen) MultiByteToWideChar(CP_UTF8, 0, mstr, mlen, wstr, wlen)
355#else
356int LIBNETXMS_EXPORTABLE utf8_to_ucs4(const char *src, int srcLen, UCS4CHAR *dst, int dstLen);
357#endif
358#if defined(_WIN32) || defined(UNICODE_UCS2)
359#define utf8_to_ucs2(mstr, mlen, wstr, wlen) MultiByteToWideChar(CP_UTF8, 0, mstr, mlen, wstr, wlen)
360#else
361int LIBNETXMS_EXPORTABLE utf8_to_ucs2(const char *src, int srcLen, UCS2CHAR *dst, int dstLen);
362#endif
363int LIBNETXMS_EXPORTABLE utf8_to_mb(const char *src, int srcLen, char *dst, int dstLen);
364
365#ifdef UNICODE_UCS4
366#define mb_to_ucs4(mstr, mlen, wstr, wlen) MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, mstr, mlen, wstr, wlen)
367#else
368int LIBNETXMS_EXPORTABLE mb_to_ucs4(const char *src, int srcLen, UCS4CHAR *dst, int dstLen);
369#endif
370#if defined(_WIN32) || defined(UNICODE_UCS2)
371#define mb_to_ucs2(mstr, mlen, wstr, wlen) MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, mstr, mlen, wstr, wlen)
372#else
373int LIBNETXMS_EXPORTABLE mb_to_ucs2(const char *src, int srcLen, UCS2CHAR *dst, int dstLen);
374#endif
375int LIBNETXMS_EXPORTABLE mb_to_utf8(const char *src, int srcLen, char *dst, int dstLen);
376
377// Conversion helpers
378WCHAR LIBNETXMS_EXPORTABLE *WideStringFromMBString(const char *src);
379WCHAR LIBNETXMS_EXPORTABLE *WideStringFromMBStringSysLocale(const char *src);
380WCHAR LIBNETXMS_EXPORTABLE *WideStringFromUTF8String(const char *src);
381char LIBNETXMS_EXPORTABLE *MBStringFromWideString(const WCHAR *src);
382char LIBNETXMS_EXPORTABLE *MBStringFromWideStringSysLocale(const WCHAR *src);
f25381f3 383char LIBNETXMS_EXPORTABLE *MBStringFromUTF8String(const char *src);
7768852d 384char LIBNETXMS_EXPORTABLE *UTF8StringFromWideString(const WCHAR *src);
f25381f3 385char LIBNETXMS_EXPORTABLE *UTF8StringFromMBString(const char *src);
7768852d
VK
386UCS2CHAR LIBNETXMS_EXPORTABLE *UCS2StringFromUCS4String(const UCS4CHAR *src);
387UCS4CHAR LIBNETXMS_EXPORTABLE *UCS4StringFromUCS2String(const UCS2CHAR *src);
388
389#ifdef UNICODE_UCS2
390#define UCS2StringFromMBString WideStringFromMBString
391#define MBStringFromUCS2String MBStringFromWideString
392#define UCS2StringFromUTF8String WideStringFromUTF8String
393#define UTF8StringFromUCS2String UTF8StringFromWideString
394#else
395UCS2CHAR LIBNETXMS_EXPORTABLE *UCS2StringFromMBString(const char *src);
396char LIBNETXMS_EXPORTABLE *MBStringFromUCS2String(const UCS2CHAR *src);
397UCS2CHAR LIBNETXMS_EXPORTABLE *UCS2StringFromUTF8String(const char *src);
398char LIBNETXMS_EXPORTABLE *UTF8StringFromUCS2String(const UCS2CHAR *src);
399#endif
400
401#ifdef UNICODE_UCS4
402#define UCS4StringFromMBString WideStringFromMBString
403#define MBStringFromUCS4String MBStringFromWideString
404#else
405UCS4CHAR LIBNETXMS_EXPORTABLE *UCS4StringFromMBString(const char *src);
406char LIBNETXMS_EXPORTABLE *MBStringFromUCS4String(const UCS4CHAR *src);
d65c16a8
VK
407#endif
408
f38a7636 409#ifdef UNICODE
7fcdcb0c 410#define UTF8StringFromTString(s) UTF8StringFromWideString(s)
f38a7636 411#else
7fcdcb0c 412#define UTF8StringFromTString(s) UTF8StringFromMBString(s)
f38a7636
AK
413#endif
414
7768852d
VK
415#ifdef __cplusplus
416}
417#endif
418
419/******* end of UNICODE related conversion and helper functions *******/
420
820fd491 421
605fc935
VK
422/**
423 * Class for serial communications
424 */
b160350d
VK
425#ifdef __cplusplus
426
427#ifndef _WIN32
428enum
429{
430 NOPARITY,
431 ODDPARITY,
432 EVENPARITY,
433 ONESTOPBIT,
434 TWOSTOPBITS
435};
436
70fed300
AK
437enum
438{
439 FLOW_NONE,
440 FLOW_HARDWARE,
441 FLOW_SOFTWARE
442};
443
b160350d
VK
444#ifndef INVALID_HANDLE_VALUE
445#define INVALID_HANDLE_VALUE (-1)
446#endif
447#endif /* _WIN32 */
448
449class LIBNETXMS_EXPORTABLE Serial
450{
b160350d
VK
451private:
452 TCHAR *m_pszPort;
453 int m_nTimeout;
454 int m_nSpeed;
455 int m_nDataBits;
456 int m_nStopBits;
457 int m_nParity;
70fed300 458 int m_nFlowControl;
96784db1
VK
459 int m_writeBlockSize;
460 int m_writeDelay;
b160350d
VK
461
462#ifndef _WIN32
463 int m_hPort;
70fed300 464 struct termios m_originalSettings;
b160350d
VK
465#else
466 HANDLE m_hPort;
467#endif
b160350d 468
96784db1
VK
469 bool writeBlock(const char *data, int length);
470
826fcc1f
VK
471public:
472 Serial();
473 ~Serial();
474
475 bool open(const TCHAR *pszPort);
476 void close();
477 void setTimeout(int nTimeout);
478 int read(char *pBuff, int nSize); /* waits up to timeout and do single read */
479 int readAll(char *pBuff, int nSize); /* read until timeout or out of space */
c3f71625 480 int readToMark(char *buff, int size, const char **marks, char **occurence);
96784db1 481 bool write(const char *buffer, int length);
826fcc1f
VK
482 void flush();
483 bool set(int nSpeed, int nDataBits, int nParity, int nStopBits, int nFlowControl = FLOW_NONE);
96784db1
VK
484 void setWriteBlockSize(int bs) { m_writeBlockSize = bs; }
485 void setWriteDelay(int delay) { m_writeDelay = delay; }
826fcc1f
VK
486 bool restart();
487};
ff214673 488
3f088d52
VK
489/**
490 * Pair class (stores pair of items)
491 */
492template <typename T1, typename T2> class Pair
493{
494private:
495 T1 value1;
496 T2 value2;
497
498public:
499 Pair() { }
500 Pair(const T1& v1, const T2& v2)
501 {
502 value1 = v1;
503 value2 = v2;
504 }
505 Pair(const Pair<T1, T2>& src)
506 {
507 value1 = src.value1;
508 value2 = src.value2;
509 }
510
511 Pair<T1, T2>& operator=(const Pair<T1, T2> &src)
512 {
513 return Pair<T1, T2>(src.value1, src.value2);
514 }
515
516 const T1& first() const { return value1; }
517 const T2& second() const { return value2; }
518};
519
3fe40613
VK
520/**
521 * Dynamic string class
522 */
8bad8476
VK
523class LIBNETXMS_EXPORTABLE String
524{
525protected:
4e0e77e6
VK
526 TCHAR *m_buffer;
527 size_t m_length;
528 size_t m_allocated;
dcc7a2b0 529 size_t m_allocationStep;
8bad8476
VK
530
531public:
c577e360
VK
532 static const int npos;
533
8bad8476 534 String();
f3cdd1c5 535 String(const TCHAR *init);
643c9dcb 536 String(const String &src);
8bad8476
VK
537 ~String();
538
4e0e77e6
VK
539 TCHAR *getBuffer() { return m_buffer; }
540 void setBuffer(TCHAR *buffer);
8bad8476 541
dcc7a2b0
VK
542 size_t getAllocationStep() { return m_allocationStep; }
543 void setAllocationStep(size_t step) { m_allocationStep = step; }
4e0e77e6 544
3f088d52
VK
545 String& operator =(const TCHAR *str);
546 String& operator =(const String &src);
547 String& operator +=(const TCHAR *str);
548 String& operator +=(const String &str);
18a7c1e9
VK
549 String operator +(const String &right) const;
550 String operator +(const TCHAR *right) const;
5508ef9f 551 operator const TCHAR*() const { return CHECK_NULL_EX(m_buffer); }
8bad8476 552
3f088d52
VK
553 bool operator ==(const String &s) const { return equals(s); }
554 bool operator !=(const String &s) const { return !equals(s); }
555
08b214c6
VK
556 char *getUTF8String();
557
4e0e77e6
VK
558 void append(const TCHAR *str) { if (str != NULL) append(str, _tcslen(str)); }
559 void append(const TCHAR *str, size_t len);
f98a8402 560 void append(const TCHAR c) { append(&c, 1); }
5f648670
VK
561 void append(INT32 n);
562 void append(UINT32 n);
563 void append(INT64 n);
564 void append(UINT64 n);
4e0e77e6
VK
565
566 void appendPreallocated(TCHAR *str) { if (str != NULL) { append(str); free(str); } }
567
568 void appendMBString(const char *str, size_t len, int nCodePage);
569 void appendWideString(const WCHAR *str, size_t len);
c577e360 570
4e0e77e6
VK
571 void appendFormattedString(const TCHAR *format, ...);
572 void appendFormattedStringV(const TCHAR *format, va_list args);
ff175e91 573
4e0e77e6 574 void clear();
c577e360 575
4e0e77e6
VK
576 size_t length() const { return m_length; }
577 bool isEmpty() const { return m_length == 0; }
c577e360 578
3f088d52 579 bool equals(const String& s) const;
18a7c1e9
VK
580 bool equals(const TCHAR *s) const;
581 bool startsWith(const String& s) const;
582 bool startsWith(const TCHAR *s) const;
583 bool endsWith(const String& s) const;
584 bool endsWith(const TCHAR *s) const;
3f088d52 585
7ac965a4 586 wchar_t charAt(size_t pos) const { return (pos < m_length) ? m_buffer[pos] : 0; }
807a4c40 587
3f088d52
VK
588 String substring(size_t start, int len) const;
589 TCHAR *substring(size_t start, int len, TCHAR *buffer) const;
c3c060b8 590 String left(size_t len) const { return substring(0, (int)len); }
ed4e267e 591 String right(size_t len) const { return substring((m_length > len) ? m_length - len : 0, (int)len); }
3f088d52 592
18a7c1e9
VK
593 StringList *split(const TCHAR *separator) const;
594
3f088d52 595 int find(const TCHAR *str, size_t start = 0) const;
1e1450ef 596
6bcafa2d
VK
597 void escapeCharacter(int ch, int esc);
598 void replace(const TCHAR *pszSrc, const TCHAR *pszDst);
0bbab9d3
VK
599 void trim();
600 void shrink(int chars = 1);
c577e360
VK
601};
602
df26f039
VK
603/**
604 * Abstract iterator class (to be implemented by actual iterable class)
605 */
606class LIBNETXMS_EXPORTABLE AbstractIterator
607{
608public:
c5e1f0bb
VK
609 virtual ~AbstractIterator();
610
df26f039
VK
611 virtual bool hasNext() = 0;
612 virtual void *next() = 0;
e0f7dbec 613 virtual void remove() = 0;
df26f039
VK
614};
615
616/**
617 * Iterator class (public interface for iteration)
618 */
619template <class T> class Iterator
620{
621private:
622 AbstractIterator *m_worker;
623
624public:
625 Iterator(AbstractIterator *worker) { m_worker = worker; }
626 ~Iterator() { delete m_worker; }
627
628 bool hasNext() { return m_worker->hasNext(); }
629 T *next() { return (T *)m_worker->next(); }
e0f7dbec 630 void remove() { m_worker->remove(); }
df26f039
VK
631};
632
400e55c4 633/**
f9861ff9
VK
634 * Dynamic array class
635 */
636class LIBNETXMS_EXPORTABLE Array
637{
638private:
639 int m_size;
640 int m_allocated;
641 int m_grow;
642 size_t m_elementSize;
643 void **m_data;
644 bool m_objectOwner;
645
646 void internalRemove(int index, bool allowDestruction);
647 void destroyObject(void *object) { if (object != NULL) m_objectDestructor(object); }
648
649protected:
650 bool m_storePointers;
651 void (*m_objectDestructor)(void *);
652
653 Array(void *data, int initial, int grow, size_t elementSize);
9f24dfe8
EJ
654 Array(const Array *src);
655
dcc7a2b0 656 void *__getBuffer() const { return m_data; }
f9861ff9
VK
657
658public:
659 Array(int initial = 0, int grow = 16, bool owner = false);
660 virtual ~Array();
661
662 int add(void *element);
dcc7a2b0
VK
663 void *get(int index) const { return ((index >= 0) && (index < m_size)) ? (m_storePointers ? m_data[index] : (void *)((char *)m_data + index * m_elementSize)): NULL; }
664 int indexOf(void *element) const;
f9861ff9
VK
665 void set(int index, void *element);
666 void replace(int index, void *element);
3f088d52 667 void insert(int index, void *element);
f9861ff9
VK
668 void remove(int index) { internalRemove(index, true); }
669 void remove(void *element) { internalRemove(indexOf(element), true); }
670 void unlink(int index) { internalRemove(index, false); }
671 void unlink(void *element) { internalRemove(indexOf(element), false); }
672 void clear();
673 void sort(int (*cb)(const void *, const void *));
dcc7a2b0 674 void *find(const void *key, int (*cb)(const void *, const void *)) const;
f9861ff9 675
dcc7a2b0 676 int size() const { return m_size; }
18a7c1e9 677 bool isEmpty() const { return m_size == 0; }
f9861ff9
VK
678
679 void setOwner(bool owner) { m_objectOwner = owner; }
dcc7a2b0 680 bool isOwner() const { return m_objectOwner; }
f9861ff9
VK
681};
682
df26f039
VK
683/**
684 * Array iterator class
685 */
686class LIBNETXMS_EXPORTABLE ArrayIterator : public AbstractIterator
687{
688private:
e0f7dbec 689 Array *m_array;
df26f039
VK
690 int m_pos;
691
692public:
e0f7dbec 693 ArrayIterator(Array *array);
df26f039
VK
694
695 virtual bool hasNext();
696 virtual void *next();
e0f7dbec 697 virtual void remove();
df26f039
VK
698};
699
f9861ff9
VK
700/**
701 * Template class for dynamic array which holds objects
702 */
703template <class T> class ObjectArray : public Array
704{
705private:
706 static void destructor(void *object) { delete (T*)object; }
707
708public:
709 ObjectArray(int initial = 0, int grow = 16, bool owner = false) : Array(initial, grow, owner) { m_objectDestructor = destructor; }
710 virtual ~ObjectArray() { }
711
712 int add(T *object) { return Array::add((void *)object); }
dcc7a2b0 713 T *get(int index) const { return (T*)Array::get(index); }
18a7c1e9
VK
714 T *first() const { return get(0); }
715 T *last() const { return get(size() - 1); }
dcc7a2b0 716 int indexOf(T *object) const { return Array::indexOf((void *)object); }
dfed892b 717 bool contains(T *object) const { return indexOf(object) >= 0; }
f9861ff9
VK
718 void set(int index, T *object) { Array::set(index, (void *)object); }
719 void replace(int index, T *object) { Array::replace(index, (void *)object); }
3f088d52 720 void insert(int index, T *object) { Array::insert(index, (void *)object); }
f9861ff9
VK
721 void remove(int index) { Array::remove(index); }
722 void remove(T *object) { Array::remove((void *)object); }
723 void unlink(int index) { Array::unlink(index); }
724 void unlink(T *object) { Array::unlink((void *)object); }
df26f039 725
fa01c3b6
VK
726 void sort(int (*cb)(const T **, const T **)) { Array::sort((int (*)(const void *, const void *))cb); }
727 T *find(const T *key, int (*cb)(const T **, const T **)) const
728 {
729 T **result = (T **)Array::find(&key, (int (*)(const void *, const void *))cb);
730 return (result != NULL) ? *result : NULL;
731 }
732
e0f7dbec 733 Iterator<T> *iterator() { return new Iterator<T>(new ArrayIterator(this)); }
f9861ff9
VK
734};
735
9c144154
VK
736/**
737 * Template class for dynamic array which holds references to objects with inaccessible destructors
738 */
739template <class T> class ObjectRefArray : public Array
740{
741private:
742 static void destructor(void *object) { }
743
744public:
745 ObjectRefArray(int initial = 0, int grow = 16) : Array(initial, grow, false) { m_objectDestructor = destructor; }
746 virtual ~ObjectRefArray() { }
747
748 int add(T *object) { return Array::add((void *)object); }
749 T *get(int index) const { return (T*)Array::get(index); }
750 int indexOf(T *object) const { return Array::indexOf((void *)object); }
751 bool contains(T *object) const { return indexOf(object) >= 0; }
752 void set(int index, T *object) { Array::set(index, (void *)object); }
753 void replace(int index, T *object) { Array::replace(index, (void *)object); }
754 void remove(int index) { Array::remove(index); }
755 void remove(T *object) { Array::remove((void *)object); }
756 void unlink(int index) { Array::unlink(index); }
757 void unlink(T *object) { Array::unlink((void *)object); }
758
759 Iterator<T> *iterator() { return new Iterator<T>(new ArrayIterator(this)); }
760};
761
f9861ff9
VK
762/**
763 * Template class for dynamic array which holds scalar values
764 */
765template <class T> class IntegerArray : public Array
766{
767private:
768 static void destructor(void *element) { }
769
770public:
771 IntegerArray(int initial = 0, int grow = 16) : Array(NULL, initial, grow, sizeof(T)) { m_objectDestructor = destructor; m_storePointers = (sizeof(T) == sizeof(void *)); }
9f24dfe8 772 IntegerArray(const IntegerArray<T> *src) : Array(src) { }
f9861ff9
VK
773 virtual ~IntegerArray() { }
774
775 int add(T value) { return Array::add(m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
e5390fb5 776 T get(int index) const { if (m_storePointers) return CAST_FROM_POINTER(Array::get(index), T); T *p = (T*)Array::get(index); return (p != NULL) ? *p : 0; }
dcc7a2b0 777 int indexOf(T value) const { return Array::indexOf(m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
dfed892b 778 bool contains(T value) const { return indexOf(value) >= 0; }
f9861ff9
VK
779 void set(int index, T value) { Array::set(index, m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
780 void replace(int index, T value) { Array::replace(index, m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
781
dcc7a2b0 782 T *getBuffer() const { return (T*)__getBuffer(); }
e9ef47dd 783
6336bba3 784 json_t *toJson() const { json_t *a = json_array(); for(int i = 0; i < size(); i++) json_array_append_new(a, json_integer(get(i))); return a; }
f9861ff9
VK
785};
786
787/**
788 * Auxilliary class to hold dynamically allocated array of structures
789 */
790template <class T> class StructArray : public Array
791{
792private:
793 static void destructor(void *element) { }
794
795public:
796 StructArray(int initial = 0, int grow = 16) : Array(NULL, initial, grow, sizeof(T)) { m_objectDestructor = destructor; }
797 StructArray(T *data, int size) : Array(data, size, 16, sizeof(T)) { m_objectDestructor = destructor; }
9f24dfe8 798 StructArray(const StructArray<T> *src) : Array(src) { }
f9861ff9
VK
799 virtual ~StructArray() { }
800
801 int add(T *element) { return Array::add((void *)element); }
dcc7a2b0
VK
802 T *get(int index) const { return (T*)Array::get(index); }
803 int indexOf(T *element) const { return Array::indexOf((void *)element); }
dfed892b 804 bool contains(T *element) const { return indexOf(element) >= 0; }
f9861ff9
VK
805 void set(int index, T *element) { Array::set(index, (void *)element); }
806 void replace(int index, T *element) { Array::replace(index, (void *)element); }
807 void remove(int index) { Array::remove(index); }
808 void remove(T *element) { Array::remove((void *)element); }
809 void unlink(int index) { Array::unlink(index); }
810 void unlink(T *element) { Array::unlink((void *)element); }
811
dcc7a2b0 812 T *getBuffer() const { return (T*)__getBuffer(); }
f9861ff9
VK
813};
814
815/**
816 * Entry of string map (internal)
400e55c4
VK
817 */
818struct StringMapEntry;
819
f9861ff9
VK
820/**
821 * Key/value pair
822 */
823struct KeyValuePair
824{
825 const TCHAR *key;
826 const void *value;
827};
828
3fe40613
VK
829/**
830 * String maps base class
831 */
832class LIBNETXMS_EXPORTABLE StringMapBase
c577e360
VK
833{
834protected:
400e55c4 835 StringMapEntry *m_data;
3fe40613 836 bool m_objectOwner;
55bdca5a 837 bool m_ignoreCase;
3fe40613 838 void (*m_objectDestructor)(void *);
c577e360 839
6e14de7c 840 StringMapEntry *find(const TCHAR *key) const;
3fe40613 841 void setObject(TCHAR *key, void *value, bool keyPreAlloc);
6e14de7c 842 void *getObject(const TCHAR *key) const;
3fe40613 843 void destroyObject(void *object) { if (object != NULL) m_objectDestructor(object); }
c577e360
VK
844
845public:
3fe40613
VK
846 StringMapBase(bool objectOwner);
847 virtual ~StringMapBase();
848
55bdca5a 849 void setOwner(bool owner) { m_objectOwner = owner; }
91a581c5 850 void setIgnoreCase(bool ignore);
55bdca5a 851
3fe40613
VK
852 void remove(const TCHAR *key);
853 void clear();
c07cf3be 854 void filterElements(bool (*filter)(const TCHAR *, const void *, void *), void *userData);
3fe40613 855
6e14de7c
VK
856 int size() const;
857 bool contains(const TCHAR *key) const { return find(key) != NULL; }
400e55c4 858
6e14de7c
VK
859 EnumerationCallbackResult forEach(EnumerationCallbackResult (*cb)(const TCHAR *, const void *, void *), void *userData) const;
860 const void *findElement(bool (*comparator)(const TCHAR *, const void *, void *), void *userData) const;
f9861ff9 861
6e14de7c
VK
862 StructArray<KeyValuePair> *toArray() const;
863 StringList *keys() const;
3fe40613
VK
864};
865
400e55c4
VK
866/**
867 * NXCP message class
868 */
b368969c 869class NXCPMessage;
400e55c4 870
3fe40613
VK
871/**
872 * String map class
873 */
874class LIBNETXMS_EXPORTABLE StringMap : public StringMapBase
875{
876public:
877 StringMap() : StringMapBase(true) { }
fb986055 878 StringMap(const StringMap &src);
3fe40613 879 virtual ~StringMap();
c577e360 880
fb986055 881 StringMap& operator =(const StringMap &src);
40b7416c 882
3fe40613
VK
883 void set(const TCHAR *key, const TCHAR *value) { setObject((TCHAR *)key, _tcsdup(value), false); }
884 void setPreallocated(TCHAR *key, TCHAR *value) { setObject(key, value, true); }
967893bb 885 void set(const TCHAR *key, UINT32 value);
5ad2167d 886
dedeffb3 887 void addAll(const StringMap *src);
a6312bd6 888
6e14de7c 889 const TCHAR *get(const TCHAR *key) const { return (const TCHAR *)getObject(key); }
7ec22f81
VK
890 INT32 getInt32(const TCHAR *key, INT32 defaultValue) const;
891 UINT32 getUInt32(const TCHAR *key, UINT32 defaultValue) const;
892 INT64 getInt64(const TCHAR *key, INT64 defaultValue) const;
893 UINT64 getUInt64(const TCHAR *key, UINT64 defaultValue) const;
894 double getDouble(const TCHAR *key, double defaultValue) const;
6e14de7c 895 bool getBoolean(const TCHAR *key, bool defaultValue) const;
5ad2167d 896
6e14de7c 897 void fillMessage(NXCPMessage *msg, UINT32 sizeFieldId, UINT32 baseFieldId) const;
ca0a165b 898 void loadMessage(const NXCPMessage *msg, UINT32 sizeFieldId, UINT32 baseFieldId);
6336bba3 899
88e14cac 900 json_t *toJson() const;
8bad8476
VK
901};
902
3fe40613
VK
903/**
904 * String map template for holding objects as values
905 */
906template <class T> class StringObjectMap : public StringMapBase
907{
908private:
909 static void destructor(void *object) { delete (T*)object; }
6173bea8 910
3fe40613
VK
911public:
912 StringObjectMap(bool objectOwner) : StringMapBase(objectOwner) { m_objectDestructor = destructor; }
913
914 void set(const TCHAR *key, T *object) { setObject((TCHAR *)key, (void *)object, false); }
b7c8729b 915 void setPreallocated(TCHAR *key, T *object) { setObject((TCHAR *)key, (void *)object, true); }
6e14de7c 916 T *get(const TCHAR *key) const { return (T*)getObject(key); }
3fe40613 917};
6173bea8 918
3fe40613
VK
919/**
920 * String list class
921 */
6173bea8
VK
922class LIBNETXMS_EXPORTABLE StringList
923{
924private:
925 int m_count;
926 int m_allocated;
927 TCHAR **m_values;
928
929public:
930 StringList();
01116597 931 StringList(const StringList *src);
22ee6d97 932 StringList(const TCHAR *src, const TCHAR *separator);
6173bea8
VK
933 ~StringList();
934
935 void add(const TCHAR *value);
936 void addPreallocated(TCHAR *value);
967893bb
VK
937 void add(INT32 value);
938 void add(UINT32 value);
6173bea8 939 void add(INT64 value);
967893bb 940 void add(UINT64 value);
6173bea8 941 void add(double value);
24dc5346 942 void replace(int index, const TCHAR *value);
b0353a33
VK
943 void addOrReplace(int index, const TCHAR *value);
944 void addOrReplacePreallocated(int index, TCHAR *value);
e2dc0372
VK
945#ifdef UNICODE
946 void addMBString(const char *value) { addPreallocated(WideStringFromMBString(value)); }
947#else
948 void addMBString(const char *value) { add(value); }
949#endif
a31a2d32
VK
950 void addAll(const StringList *src);
951 void merge(const StringList *src, bool matchCase);
952 void splitAndAdd(const TCHAR *src, const TCHAR *separator);
953 void remove(int index);
6173bea8 954 void clear();
a31a2d32
VK
955
956 void sort(bool ascending = true, bool caseSensitive = false);
957
01116597 958 int size() const { return m_count; }
18a7c1e9 959 bool isEmpty() const { return m_count == 0; }
01116597
VK
960 const TCHAR *get(int index) const { return ((index >=0) && (index < m_count)) ? m_values[index] : NULL; }
961 int indexOf(const TCHAR *value) const;
e2845745 962 bool contains(const TCHAR *value) const { return indexOf(value) != -1; }
01116597 963 int indexOfIgnoreCase(const TCHAR *value) const;
e2845745 964 bool containsIgnoreCase(const TCHAR *value) const { return indexOfIgnoreCase(value) != -1; }
7d25a5c5 965 TCHAR *join(const TCHAR *separator);
a31a2d32 966
6fbaa926 967 void fillMessage(NXCPMessage *msg, UINT32 baseId, UINT32 countId);
a31a2d32 968 json_t *toJson() const;
6173bea8
VK
969};
970
a58501c0
VK
971/**
972 * Entry of string set
973 */
974struct StringSetEntry;
975
f3603b79
VK
976/**
977 * NXCP message
978 */
b368969c 979class NXCPMessage;
f3603b79 980
8100b554
VK
981/**
982 * String set
983 */
984class StringSet;
985
986/**
987 * String set iterator
988 */
989class LIBNETXMS_EXPORTABLE StringSetIterator : public AbstractIterator
990{
991private:
992 StringSet *m_stringSet;
993 StringSetEntry *m_curr;
994 StringSetEntry *m_next;
995
996public:
997 StringSetIterator(StringSet *stringSet);
998
999 virtual bool hasNext();
1000 virtual void *next();
1001 virtual void remove();
1002};
1003
a58501c0
VK
1004/**
1005 * String set class
1006 */
1007class LIBNETXMS_EXPORTABLE StringSet
1008{
8100b554
VK
1009 friend class StringSetIterator;
1010
a58501c0
VK
1011private:
1012 StringSetEntry *m_data;
1013
1014public:
1015 StringSet();
1016 ~StringSet();
1017
1018 void add(const TCHAR *str);
f3603b79 1019 void addPreallocated(TCHAR *str);
a58501c0
VK
1020 void remove(const TCHAR *str);
1021 void clear();
1022
8100b554
VK
1023 int size() const;
1024 bool contains(const TCHAR *str) const;
1025 bool equals(const StringSet *s) const;
a58501c0 1026
fa493140 1027 void addAll(StringSet *src);
f3603b79 1028 void addAll(TCHAR **strings, int count);
d45f9179 1029 void splitAndAdd(const TCHAR *src, const TCHAR *separator);
d6c4cdc1 1030 void addAllPreallocated(TCHAR **strings, int count);
f3603b79 1031
8100b554
VK
1032 void forEach(bool (*cb)(const TCHAR *, void *), void *userData) const;
1033
1034 void fillMessage(NXCPMessage *msg, UINT32 baseId, UINT32 countId) const;
1035 void addAllFromMessage(const NXCPMessage *msg, UINT32 baseId, UINT32 countId, bool clearBeforeAdd, bool toUppercase);
c262bc08 1036
d45f9179 1037 String join(const TCHAR *separator);
8100b554
VK
1038
1039 Iterator<const TCHAR> *iterator() { return new Iterator<const TCHAR>(new StringSetIterator(this)); }
a58501c0
VK
1040};
1041
296ae03d
VK
1042/**
1043 * Opaque hash map entry structure
1044 */
1045struct HashMapEntry;
1046
1047/**
1048 * Hash map base class (for fixed size non-pointer keys)
1049 */
1050class LIBNETXMS_EXPORTABLE HashMapBase
1051{
df26f039
VK
1052 friend class HashMapIterator;
1053
296ae03d
VK
1054private:
1055 HashMapEntry *m_data;
1056 bool m_objectOwner;
1057 unsigned int m_keylen;
1058
df26f039 1059 HashMapEntry *find(const void *key) const;
296ae03d
VK
1060 void destroyObject(void *object) { if (object != NULL) m_objectDestructor(object); }
1061
1062protected:
1063 void (*m_objectDestructor)(void *);
1064
1065 HashMapBase(bool objectOwner, unsigned int keylen);
1066
df26f039 1067 void *_get(const void *key) const;
296ae03d
VK
1068 void _set(const void *key, void *value);
1069 void _remove(const void *key);
1070
df26f039 1071 bool _contains(const void *key) const { return find(key) != NULL; }
296ae03d
VK
1072
1073public:
1074 virtual ~HashMapBase();
1075
1076 void setOwner(bool owner) { m_objectOwner = owner; }
1077 void clear();
1078
df26f039
VK
1079 int size() const;
1080
1081 EnumerationCallbackResult forEach(EnumerationCallbackResult (*cb)(const void *, const void *, void *), void *userData) const;
1082 const void *findElement(bool (*comparator)(const void *, const void *, void *), void *userData) const;
1083};
296ae03d 1084
df26f039
VK
1085/**
1086 * Hash map iterator
1087 */
1088class LIBNETXMS_EXPORTABLE HashMapIterator : public AbstractIterator
1089{
1090private:
1091 HashMapBase *m_hashMap;
1092 HashMapEntry *m_curr;
1093 HashMapEntry *m_next;
1094
1095public:
1096 HashMapIterator(HashMapBase *hashMap);
1097
1098 virtual bool hasNext();
1099 virtual void *next();
e0f7dbec 1100 virtual void remove();
296ae03d
VK
1101};
1102
1103/**
1104 * Hash map template for holding objects as values
1105 */
1106template <class K, class V> class HashMap : public HashMapBase
1107{
1108private:
1109 static void destructor(void *object) { delete (V*)object; }
1110
1111public:
1112 HashMap(bool objectOwner = false) : HashMapBase(objectOwner, sizeof(K)) { m_objectDestructor = destructor; }
1113
1114 V *get(const K& key) { return (V*)_get(&key); }
1115 void set(const K& key, V *value) { _set(&key, (void *)value); }
1116 void remove(const K& key) { _remove(&key); }
1117 bool contains(const K& key) { return _contains(&key); }
df26f039
VK
1118
1119 Iterator<V> *iterator() { return new Iterator<V>(new HashMapIterator(this)); }
296ae03d
VK
1120};
1121
50963ced
VK
1122/**
1123 * Hash map template for holding reference counting objects as values
1124 */
1125template <class K, class V> class RefCountHashMap : public HashMapBase
1126{
1127private:
87c91211 1128 static void destructor(void *object) { if (object != NULL) ((V*)object)->decRefCount(); }
50963ced
VK
1129
1130public:
1131 RefCountHashMap(bool objectOwner = false) : HashMapBase(objectOwner, sizeof(K)) { m_objectDestructor = destructor; }
1132
87c91211
VK
1133 V *get(const K& key) { V *v = (V*)_get(&key); if (v != NULL) v->incRefCount(); return v; }
1134 void set(const K& key, V *value) { if (value != NULL) value->incRefCount(); _set(&key, (void *)value); }
50963ced
VK
1135 void remove(const K& key) { _remove(&key); }
1136 bool contains(const K& key) { return _contains(&key); }
1137
1138 Iterator<V> *iterator() { return new Iterator<V>(new HashMapIterator(this)); }
1139};
1140
3dc1af83
VK
1141/**
1142 * Ring buffer
1143 */
1144class LIBNETXMS_EXPORTABLE RingBuffer
1145{
1146private:
1147 BYTE *m_data;
1148 size_t m_size;
1149 size_t m_allocated;
1150 size_t m_allocationStep;
1151 size_t m_readPos;
1152 size_t m_writePos;
1153
1154public:
1155 RingBuffer(size_t initial = 8192, size_t allocationStep = 8192);
1156 ~RingBuffer();
1157
1158 void write(const BYTE *data, size_t dataSize);
1159 size_t read(BYTE *buffer, size_t bufferSize);
1160
1161 size_t size() const { return m_size; }
b0039c52 1162 bool isEmpty() const { return m_size == 0; }
3dc1af83
VK
1163};
1164
57f34c0a
VK
1165/**
1166 * Byte stream
1167 */
1168class LIBNETXMS_EXPORTABLE ByteStream
1169{
1170private:
1171 BYTE *m_data;
1172 size_t m_size;
1173 size_t m_allocated;
1174 size_t m_pos;
3cf3dedd 1175 size_t m_allocationStep;
57f34c0a
VK
1176
1177public:
1178 ByteStream(size_t initial = 8192);
1179 ByteStream(const void *data, size_t size);
1180 virtual ~ByteStream();
1181
4b47d7d7
VK
1182 static ByteStream *load(const TCHAR *file);
1183
1184 void seek(size_t pos) { if (pos <= m_size) m_pos = pos; }
57f34c0a
VK
1185 size_t pos() { return m_pos; }
1186 size_t size() { return m_size; }
1187 bool eos() { return m_pos == m_size; }
1188
3cf3dedd
VK
1189 void setAllocationStep(size_t s) { m_allocationStep = s; }
1190
1191 const BYTE *buffer(size_t *size) { *size = m_size; return m_data; }
57f34c0a 1192
4b47d7d7 1193 void write(const void *data, size_t size);
57f34c0a
VK
1194 void write(char c) { write(&c, 1); }
1195 void write(BYTE b) { write(&b, 1); }
1196 void write(INT16 n) { UINT16 x = htons((UINT16)n); write(&x, 2); }
1197 void write(UINT16 n) { UINT16 x = htons(n); write(&x, 2); }
1198 void write(INT32 n) { UINT32 x = htonl((UINT32)n); write(&x, 4); }
1199 void write(UINT32 n) { UINT32 x = htonl(n); write(&x, 4); }
4b47d7d7
VK
1200 void write(INT64 n) { UINT64 x = htonq((UINT64)n); write(&x, 8); }
1201 void write(UINT64 n) { UINT64 x = htonq(n); write(&x, 8); }
1202 void write(double n) { double x = htond(n); write(&x, 8); }
1203 void writeString(const TCHAR *s);
57f34c0a 1204
4b47d7d7 1205 size_t read(void *buffer, size_t count);
57f34c0a
VK
1206 char readChar() { return !eos() ? (char)m_data[m_pos++] : 0; }
1207 BYTE readByte() { return !eos() ? m_data[m_pos++] : 0; }
1208 INT16 readInt16();
1209 UINT16 readUInt16();
1210 INT32 readInt32();
1211 UINT32 readUInt32();
4b47d7d7
VK
1212 INT64 readInt64();
1213 UINT64 readUInt64();
1214 double readDouble();
1215 TCHAR *readString();
1216
1217 bool save(int f);
57f34c0a
VK
1218};
1219
25fe6265
VK
1220/**
1221 * Auxilliary class for objects which counts references and
1222 * destroys itself wheren reference count falls to 0
1223 */
7f632dfe
VK
1224class LIBNETXMS_EXPORTABLE RefCountObject
1225{
1226private:
7785322f 1227 VolatileCounter m_refCount;
7f632dfe 1228
7dd6369a
VK
1229protected:
1230 virtual ~RefCountObject();
1231
7f632dfe 1232public:
7785322f
VK
1233 RefCountObject()
1234 {
1235 m_refCount = 1;
1236 }
1237
1238 void incRefCount()
1239 {
1240 InterlockedIncrement(&m_refCount);
1241 }
1242
1243 void decRefCount()
1244 {
1245 if (InterlockedDecrement(&m_refCount) == 0)
1246 delete this;
1247 }
7f632dfe
VK
1248};
1249
b368969c 1250class NXCPMessage;
967893bb
VK
1251
1252/**
1253 * Table column definition
1254 */
1255class LIBNETXMS_EXPORTABLE TableColumnDefinition
1256{
1257private:
1258 TCHAR *m_name;
1259 TCHAR *m_displayName;
1260 INT32 m_dataType;
1261 bool m_instanceColumn;
1262
1263public:
1264 TableColumnDefinition(const TCHAR *name, const TCHAR *displayName, INT32 dataType, bool isInstance);
b368969c 1265 TableColumnDefinition(NXCPMessage *msg, UINT32 baseId);
967893bb
VK
1266 TableColumnDefinition(TableColumnDefinition *src);
1267 ~TableColumnDefinition();
1268
b368969c 1269 void fillMessage(NXCPMessage *msg, UINT32 baseId);
967893bb
VK
1270
1271 const TCHAR *getName() { return m_name; }
1272 const TCHAR *getDisplayName() { return m_displayName; }
1273 INT32 getDataType() { return m_dataType; }
1274 bool isInstanceColumn() { return m_instanceColumn; }
1275
1276 void setDataType(INT32 type) { m_dataType = type; }
1277 void setInstanceColumn(bool isInstance) { m_instanceColumn = isInstance; }
a0ddfb29 1278 void setDisplayName(const TCHAR *name) { safe_free(m_displayName); m_displayName = _tcsdup(CHECK_NULL_EX(name)); }
967893bb
VK
1279};
1280
d6bbfa4e
VK
1281/**
1282 * Table cell
1283 */
1284class TableCell
1285{
1286private:
1287 TCHAR *m_value;
1288 int m_status;
43666be9 1289 UINT32 m_objectId;
d6bbfa4e
VK
1290
1291public:
43666be9
VK
1292 TableCell() { m_value = NULL; m_status = -1; m_objectId = 0; }
1293 TableCell(const TCHAR *value) { m_value = _tcsdup_ex(value); m_status = -1; m_objectId = 0; }
1294 TableCell(const TCHAR *value, int status) { m_value = _tcsdup_ex(value); m_status = status; m_objectId = 0; }
1295 TableCell(TableCell *src) { m_value = _tcsdup_ex(src->m_value); m_status = src->m_status; m_objectId = src->m_objectId; }
d6bbfa4e
VK
1296 ~TableCell() { safe_free(m_value); }
1297
43666be9
VK
1298 void set(const TCHAR *value, int status, UINT32 objectId) { safe_free(m_value); m_value = _tcsdup_ex(value); m_status = status; m_objectId = objectId; }
1299 void setPreallocated(TCHAR *value, int status, UINT32 objectId) { safe_free(m_value); m_value = value; m_status = status; m_objectId = objectId; }
d6bbfa4e
VK
1300
1301 const TCHAR *getValue() { return m_value; }
c83f6449 1302 void setValue(const TCHAR *value) { safe_free(m_value); m_value = _tcsdup_ex(value); }
e40e0fdc 1303 void setPreallocatedValue(TCHAR *value) { free(m_value); m_value = value; }
d6bbfa4e
VK
1304
1305 int getStatus() { return m_status; }
1306 void setStatus(int status) { m_status = status; }
43666be9
VK
1307
1308 int getObjectId() { return m_objectId; }
1309 void setObjectId(UINT32 id) { m_objectId = id; }
d6bbfa4e
VK
1310};
1311
1312/**
1313 * Table row
1314 */
1315class TableRow
1316{
1317private:
1318 ObjectArray<TableCell> *m_cells;
1319 UINT32 m_objectId;
bac74bf7 1320
d6bbfa4e
VK
1321public:
1322 TableRow(int columnCount);
1323 TableRow(TableRow *src);
1324 ~TableRow() { delete m_cells; }
1325
1326 void addColumn() { m_cells->add(new TableCell); }
1327 void deleteColumn(int index) { m_cells->remove(index); }
bac74bf7 1328
43666be9
VK
1329 void set(int index, const TCHAR *value, int status, UINT32 objectId) { TableCell *c = m_cells->get(index); if (c != NULL) c->set(value, status, objectId); }
1330 void setPreallocated(int index, TCHAR *value, int status, UINT32 objectId) { TableCell *c = m_cells->get(index); if (c != NULL) c->setPreallocated(value, status, objectId); }
d6bbfa4e
VK
1331
1332 void setValue(int index, const TCHAR *value) { TableCell *c = m_cells->get(index); if (c != NULL) c->setValue(value); }
e40e0fdc 1333 void setPreallocatedValue(int index, TCHAR *value) { TableCell *c = m_cells->get(index); if (c != NULL) c->setPreallocatedValue(value); else free(value); }
d6bbfa4e
VK
1334
1335 void setStatus(int index, int status) { TableCell *c = m_cells->get(index); if (c != NULL) c->setStatus(status); }
1336
1337 const TCHAR *getValue(int index) { TableCell *c = m_cells->get(index); return (c != NULL) ? c->getValue() : NULL; }
1338 int getStatus(int index) { TableCell *c = m_cells->get(index); return (c != NULL) ? c->getStatus() : -1; }
1339
1340 UINT32 getObjectId() { return m_objectId; }
1341 void setObjectId(UINT32 id) { m_objectId = id; }
43666be9
VK
1342
1343 UINT32 getCellObjectId(int index) { TableCell *c = m_cells->get(index); return (c != NULL) ? c->getObjectId() : 0; }
1344 void setCellObjectId(int index, UINT32 id) { TableCell *c = m_cells->get(index); if (c != NULL) c->setObjectId(id); }
d6bbfa4e
VK
1345};
1346
967893bb
VK
1347/**
1348 * Class for table data storage
1349 */
a0ddfb29 1350class LIBNETXMS_EXPORTABLE Table : public RefCountObject
967893bb
VK
1351{
1352private:
d6bbfa4e 1353 ObjectArray<TableRow> *m_data;
967893bb
VK
1354 ObjectArray<TableColumnDefinition> *m_columns;
1355 TCHAR *m_title;
1356 int m_source;
d6bbfa4e 1357 bool m_extendedFormat;
967893bb 1358
b368969c 1359 void createFromMessage(NXCPMessage *msg);
967893bb 1360 void destroy();
63ff3c9d 1361 bool parseXML(const char *xml);
967893bb
VK
1362
1363public:
1364 Table();
a0ddfb29 1365 Table(Table *src);
b368969c 1366 Table(NXCPMessage *msg);
b549a0f8 1367 virtual ~Table();
967893bb 1368
b368969c
VK
1369 int fillMessage(NXCPMessage &msg, int offset, int rowLimit);
1370 void updateFromMessage(NXCPMessage *msg);
967893bb 1371
a0ddfb29
VK
1372 void addAll(Table *src);
1373 void copyRow(Table *src, int row);
967893bb 1374
d6bbfa4e
VK
1375 int getNumRows() { return m_data->size(); }
1376 int getNumColumns() { return m_columns->size(); }
967893bb
VK
1377 const TCHAR *getTitle() { return CHECK_NULL_EX(m_title); }
1378 int getSource() { return m_source; }
1379
d6bbfa4e
VK
1380 bool isExtendedFormat() { return m_extendedFormat; }
1381 void setExtendedFormat(bool ext) { m_extendedFormat = ext; }
1382
967893bb
VK
1383 const TCHAR *getColumnName(int col) { return ((col >= 0) && (col < m_columns->size())) ? m_columns->get(col)->getName() : NULL; }
1384 INT32 getColumnDataType(int col) { return ((col >= 0) && (col < m_columns->size())) ? m_columns->get(col)->getDataType() : 0; }
1385 int getColumnIndex(const TCHAR *name);
1386 ObjectArray<TableColumnDefinition> *getColumnDefinitions() { return m_columns; }
1387
c83f6449 1388 void setTitle(const TCHAR *title) { safe_free(m_title); m_title = _tcsdup_ex(title); }
967893bb 1389 void setSource(int source) { m_source = source; }
8dba1eac 1390 int addColumn(const TCHAR *name, INT32 dataType = 0, const TCHAR *displayName = NULL, bool isInstance = false);
967893bb
VK
1391 void setColumnDataType(int col, INT32 dataType) { if ((col >= 0) && (col < m_columns->size())) m_columns->get(col)->setDataType(dataType); }
1392 int addRow();
1393
25076d53
VK
1394 void deleteRow(int row);
1395 void deleteColumn(int col);
1396
967893bb
VK
1397 void setAt(int nRow, int nCol, INT32 nData);
1398 void setAt(int nRow, int nCol, UINT32 dwData);
1399 void setAt(int nRow, int nCol, double dData);
1400 void setAt(int nRow, int nCol, INT64 nData);
1401 void setAt(int nRow, int nCol, UINT64 qwData);
1402 void setAt(int nRow, int nCol, const TCHAR *pszData);
1403 void setPreallocatedAt(int nRow, int nCol, TCHAR *pszData);
1404
d6bbfa4e
VK
1405 void set(int nCol, INT32 nData) { setAt(getNumRows() - 1, nCol, nData); }
1406 void set(int nCol, UINT32 dwData) { setAt(getNumRows() - 1, nCol, dwData); }
1407 void set(int nCol, double dData) { setAt(getNumRows() - 1, nCol, dData); }
1408 void set(int nCol, INT64 nData) { setAt(getNumRows() - 1, nCol, nData); }
1409 void set(int nCol, UINT64 qwData) { setAt(getNumRows() - 1, nCol, qwData); }
d65c16a8
VK
1410 void set(int nCol, const TCHAR *data) { setAt(getNumRows() - 1, nCol, data); }
1411#ifdef UNICODE
1412 void set(int nCol, const char *data) { setPreallocatedAt(getNumRows() - 1, nCol, WideStringFromMBString(data)); }
1413#else
1414 void set(int nCol, const WCHAR *data) { setPreallocatedAt(getNumRows() - 1, nCol, MBStringFromWideString(data)); }
1415#endif
1416 void setPreallocated(int nCol, TCHAR *data) { setPreallocatedAt(getNumRows() - 1, nCol, data); }
d6bbfa4e
VK
1417
1418 void setStatusAt(int row, int col, int status);
1419 void setStatus(int col, int status) { setStatusAt(getNumRows() - 1, col, status); }
967893bb 1420
816a25f5 1421 const TCHAR *getAsString(int nRow, int nCol, const TCHAR *defaultValue = NULL);
967893bb
VK
1422 INT32 getAsInt(int nRow, int nCol);
1423 UINT32 getAsUInt(int nRow, int nCol);
1424 INT64 getAsInt64(int nRow, int nCol);
1425 UINT64 getAsUInt64(int nRow, int nCol);
1426 double getAsDouble(int nRow, int nCol);
22aaa779 1427
d6bbfa4e
VK
1428 int getStatus(int nRow, int nCol);
1429
22aaa779 1430 void buildInstanceString(int row, TCHAR *buffer, size_t bufLen);
a0ddfb29 1431 int findRowByInstance(const TCHAR *instance);
d6bbfa4e
VK
1432
1433 UINT32 getObjectId(int row) { TableRow *r = m_data->get(row); return (r != NULL) ? r->getObjectId() : 0; }
1434 void setObjectId(int row, UINT32 id) { TableRow *r = m_data->get(row); if (r != NULL) r->setObjectId(id); }
a3d3f9d5 1435
43666be9
VK
1436 void setCellObjectIdAt(int row, int col, UINT32 objectId);
1437 void setCellObjectId(int col, UINT32 objectId) { setCellObjectIdAt(getNumRows() - 1, col, objectId); }
1438 UINT32 getCellObjectId(int row, int col) { TableRow *r = m_data->get(row); return (r != NULL) ? r->getCellObjectId(col) : 0; }
1439
63ff3c9d
VK
1440 static Table *createFromXML(const char *xml);
1441 TCHAR *createXML();
f1b8f11c
VK
1442
1443 static Table *createFromPackedXML(const char *packedXml);
1444 char *createPackedXML();
967893bb
VK
1445};
1446
a31a2d32
VK
1447/**
1448 * Create JSON string with null check
1449 */
1450inline json_t *json_string_a(const char *s)
1451{
1452 return (s != NULL) ? json_string(s) : json_null();
1453}
1454
88e14cac
VK
1455/**
1456 * Create JSON string from wide character string
1457 */
1458inline json_t *json_string_w(const WCHAR *s)
1459{
1460 if (s == NULL)
1461 return json_null();
1462 char *us = UTF8StringFromWideString(s);
1463 json_t *js = json_string(us);
1464 free(us);
1465 return js;
1466}
1467
820fd491
VK
1468#ifdef UNICODE
1469#define json_string_t json_string_w
1470#else
a31a2d32 1471#define json_string_t json_string_a
820fd491
VK
1472#endif
1473
1474/**
1475 * Create JSON array from integer array
1476 */
c3c060b8 1477template<typename T> json_t *json_integer_array(const T *values, size_t size)
820fd491
VK
1478{
1479 json_t *a = json_array();
1480 for(size_t i = 0; i < size; i++)
1481 json_array_append_new(a, json_integer(values[i]));
1482 return a;
1483}
1484
1485/**
1486 * Serialize ObjectArray as JSON
1487 */
1488template<typename T> json_t *json_object_array(ObjectArray<T> *a)
1489{
1490 json_t *root = json_array();
a31a2d32
VK
1491 if (a != NULL)
1492 {
1493 for(int i = 0; i < a->size(); i++)
1494 {
1495 T *e = a->get(i);
1496 if (e != NULL)
1497 json_array_append_new(root, e->toJson());
1498 }
1499 }
820fd491
VK
1500 return root;
1501}
1502
c11eee9b
VK
1503/**
1504 * sockaddr buffer
1505 */
1506union SockAddrBuffer
1507{
1508 struct sockaddr_in sa4;
1509#ifdef WITH_IPV6
1510 struct sockaddr_in6 sa6;
1511#endif
1512};
1513
1514/**
1515 * sockaddr length calculation
1516 */
abac7ffe 1517#undef SA_LEN
c11eee9b
VK
1518#ifdef WITH_IPV6
1519#define SA_LEN(sa) (((sa)->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))
1520#else
1521#define SA_LEN(sa) sizeof(struct sockaddr_in)
1522#endif
1523
5f6e8d09
VK
1524/**
1525 * Get port number from SockAddrBuffer
1526 */
1527#ifdef WITH_IPV6
1528#define SA_PORT(sa) ((((struct sockaddr *)sa)->sa_family == AF_INET) ? ((struct sockaddr_in *)sa)->sin_port : ((struct sockaddr_in6 *)sa)->sin6_port)
1529#else
1530#define SA_PORT(sa) (((struct sockaddr_in *)sa)->sin_port)
1531#endif
1532
30592fa6
VK
1533/**
1534 * Compare addresses in sockaddr
1535 */
1536inline bool SocketAddressEquals(struct sockaddr *a1, struct sockaddr *a2)
1537{
1538 if (a1->sa_family != a2->sa_family)
1539 return false;
1540 if (a1->sa_family == AF_INET)
1541 return ((struct sockaddr_in *)a1)->sin_addr.s_addr == ((struct sockaddr_in *)a2)->sin_addr.s_addr;
1542#ifdef WITH_IPV6
1543 if (a1->sa_family == AF_INET6)
1544 return !memcmp(((struct sockaddr_in6 *)a1)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)a2)->sin6_addr.s6_addr, 16);
1545#endif
1546 return false;
1547}
1548
ce9e00cc
VK
1549enum MacAddressNotation
1550{
1551 MAC_ADDR_FLAT_STRING = 0,
1552 MAC_ADDR_COLON_SEPARATED = 1,
1553 MAC_ADDR_BYTEPAIR_COLON_SEPARATED = 2,
1554 MAC_ADDR_HYPHEN_SEPARATED = 3,
1555 MAC_ADDR_DOT_SEPARATED = 4,
1556 MAC_ADDR_BYTEPAIR_DOT_SEPARATED = 5
1557};
1558
1559/**
1560 * MAC address
1561 */
1562class LIBNETXMS_EXPORTABLE MacAddress
1563{
1564private:
1565 BYTE m_value[16];
1566 size_t m_length;
1567
1568 TCHAR *toStringInternal(TCHAR *buffer, const TCHAR separator, bool bytePair = false) const;
709cd5a4 1569 TCHAR *toStringInternal3(TCHAR *buffer, const TCHAR separator) const;
ce9e00cc
VK
1570
1571public:
1572 MacAddress() { m_length = 0; memset(m_value, 0, 16); }
1573 MacAddress(const BYTE *value, size_t length) { m_length = min(length, 16); memcpy(m_value, value, m_length); }
1574 MacAddress(const MacAddress& src) { memcpy(m_value, src.m_value, src.m_length); m_length = src.m_length; }
1575
1576 static MacAddress parse(const char *str);
e590796d 1577 static MacAddress parse(const WCHAR *str);
ce9e00cc
VK
1578
1579 const BYTE *value() const { return m_value; }
1580 size_t length() const { return m_length; }
1581
1582 bool isMulticast() const;
1583 bool isBroadcast() const;
1584 bool equals(const MacAddress &a) const;
1585
1586 TCHAR *toString(TCHAR *buffer, MacAddressNotation notation = MAC_ADDR_COLON_SEPARATED) const;
1587 String toString(MacAddressNotation notation = MAC_ADDR_COLON_SEPARATED) const;
1588};
1589
9319c166
VK
1590/**
1591 * IP address
1592 */
1593class LIBNETXMS_EXPORTABLE InetAddress
1594{
9319c166 1595private:
8c75ad41
VK
1596 short m_maskBits;
1597 short m_family;
1598 union
1599 {
1600 UINT32 v4;
1601 BYTE v6[16];
1602 } m_addr;
9319c166
VK
1603
1604public:
8c75ad41
VK
1605 InetAddress();
1606 InetAddress(UINT32 addr);
c75e9ee4 1607 InetAddress(UINT32 addr, UINT32 mask);
4203dcb5 1608 InetAddress(const BYTE *addr, int maskBits = 128);
9319c166 1609
8c75ad41
VK
1610 bool isAnyLocal() const;
1611 bool isLoopback() const;
1612 bool isMulticast() const;
1613 bool isBroadcast() const;
4203dcb5 1614 bool isLinkLocal() const;
8c75ad41 1615 bool isValid() const { return m_family != AF_UNSPEC; }
4203dcb5 1616 bool isValidUnicast() const { return isValid() && !isAnyLocal() && !isLoopback() && !isMulticast() && !isBroadcast() && !isLinkLocal(); }
9319c166 1617
8c75ad41 1618 int getFamily() const { return m_family; }
c7853753
VK
1619 UINT32 getAddressV4() const { return (m_family == AF_INET) ? m_addr.v4 : 0; }
1620 const BYTE *getAddressV6() const { return (m_family == AF_INET6) ? m_addr.v6 : (const BYTE *)"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; }
9319c166 1621
8c75ad41 1622 bool contain(const InetAddress &a) const;
43709a0c 1623 bool sameSubnet(const InetAddress &a) const;
8c75ad41
VK
1624 bool equals(const InetAddress &a) const;
1625 int compareTo(const InetAddress &a) const;
9319c166 1626
8c75ad41
VK
1627 void setMaskBits(int m) { m_maskBits = m; }
1628 int getMaskBits() const { return m_maskBits; }
c75e9ee4 1629 int getHostBits() const { return (m_family == AF_INET) ? (32 - m_maskBits) : (128 - m_maskBits); }
9319c166 1630
463b1d34 1631 InetAddress getSubnetAddress() const;
ba889094 1632 InetAddress getSubnetBroadcast() const;
463b1d34 1633 bool isSubnetBroadcast(int maskBits) const;
ffabd7f8 1634
8c75ad41
VK
1635 String toString() const;
1636 TCHAR *toString(TCHAR *buffer) const;
af4a09df
VK
1637#ifdef UNICODE
1638 char *toStringA(char *buffer) const;
1639#else
1640 char *toStringA(char *buffer) const { return toString(buffer); }
1641#endif
9319c166 1642
e9ef47dd
VK
1643 json_t *toJson() const;
1644
43709a0c 1645 BYTE *buildHashKey(BYTE *key) const;
f3b94fc5 1646
43709a0c
VK
1647 TCHAR *getHostByAddr(TCHAR *buffer, size_t buflen) const;
1648
1649 struct sockaddr *fillSockAddr(SockAddrBuffer *buffer, UINT16 port = 0) const;
c11eee9b 1650
c7853753
VK
1651 static InetAddress resolveHostName(const WCHAR *hostname, int af = AF_INET);
1652 static InetAddress resolveHostName(const char *hostname, int af = AF_INET);
f3b94fc5
VK
1653 static InetAddress parse(const WCHAR *str);
1654 static InetAddress parse(const char *str);
8c75ad41 1655 static InetAddress createFromSockaddr(struct sockaddr *s);
dcc7a2b0
VK
1656
1657 static const InetAddress INVALID;
48313f37 1658 static const InetAddress LOOPBACK;
dcc7a2b0
VK
1659};
1660
1661/**
1662 * IP address list
1663 */
1664class LIBNETXMS_EXPORTABLE InetAddressList
1665{
1666private:
1667 ObjectArray<InetAddress> *m_list;
1668
1669 int indexOf(const InetAddress& addr) const;
1670
1671public:
1672 InetAddressList();
1673 ~InetAddressList();
1674
1675 void add(const InetAddress& addr);
c30c0c0f
VK
1676 void add(const InetAddressList& addrList);
1677 void replace(const InetAddress& addr);
dcc7a2b0 1678 void remove(const InetAddress& addr);
c30c0c0f 1679 void clear() { m_list->clear(); }
4203dcb5 1680 const InetAddress& get(int index) const { const InetAddress *a = m_list->get(index); return (a != NULL) ? *a : InetAddress::INVALID; }
dcc7a2b0
VK
1681
1682 int size() const { return m_list->size(); }
1683 bool hasAddress(const InetAddress& addr) const { return indexOf(addr) != -1; }
4203dcb5 1684 const InetAddress& findAddress(const InetAddress& addr) const { int idx = indexOf(addr); return (idx != -1) ? *m_list->get(idx) : InetAddress::INVALID; }
c34b611c 1685 const InetAddress& findSameSubnetAddress(const InetAddress& addr) const;
dcc7a2b0 1686 const InetAddress& getFirstUnicastAddress() const;
c34b611c
VK
1687 const InetAddress& getFirstUnicastAddressV4() const;
1688 bool hasValidUnicastAddress() const { return getFirstUnicastAddress().isValid(); }
c30c0c0f 1689 bool isLoopbackOnly() const;
dcc7a2b0
VK
1690
1691 const ObjectArray<InetAddress> *getList() const { return m_list; }
40c8f341
VK
1692
1693 void fillMessage(NXCPMessage *msg, UINT32 sizeFieldId, UINT32 baseFieldId) const;
820fd491
VK
1694
1695 json_t *toJson() const { return json_object_array(m_list); }
9319c166
VK
1696};
1697
25fe6265
VK
1698/**
1699 * Network connection
1700 */
58ee2f43
VK
1701class LIBNETXMS_EXPORTABLE SocketConnection
1702{
1703protected:
1704 SOCKET m_socket;
1705 char m_data[4096];
1706 int m_dataPos;
1707
1708public:
1709 SocketConnection();
1710 virtual ~SocketConnection();
1711
967893bb 1712 bool connectTCP(const TCHAR *hostName, WORD port, UINT32 timeout);
b4cf3199 1713 bool connectTCP(const InetAddress& ip, WORD port, UINT32 timeout);
58ee2f43
VK
1714 void disconnect();
1715
967893bb
VK
1716 bool canRead(UINT32 timeout);
1717 virtual int read(char *pBuff, int nSize, UINT32 timeout = INFINITE);
58ee2f43 1718 bool waitForText(const char *text, int timeout);
cc022855 1719
58ee2f43 1720 int write(const char *pBuff, int nSize);
1671f85d
VK
1721 bool writeLine(const char *line);
1722
967893bb 1723 static SocketConnection *createTCPConnection(const TCHAR *hostName, WORD port, UINT32 timeout);
58ee2f43
VK
1724};
1725
030a0779
VK
1726/**
1727 * Telnet connection - handles all telnet negotiation
1728 */
def5b792
AK
1729class LIBNETXMS_EXPORTABLE TelnetConnection : public SocketConnection
1730{
030a0779 1731protected:
967893bb 1732 bool connectTCP(const TCHAR *hostName, WORD port, UINT32 timeout);
b4cf3199 1733 bool connectTCP(const InetAddress& ip, WORD port, UINT32 timeout);
030a0779 1734
def5b792 1735public:
967893bb 1736 static TelnetConnection *createConnection(const TCHAR *hostName, WORD port, UINT32 timeout);
d4e9d325 1737
967893bb 1738 bool connect(const TCHAR *hostName, WORD port, UINT32 timeout);
b4cf3199 1739 bool connect(const InetAddress& ip, WORD port, UINT32 timeout);
967893bb
VK
1740 virtual int read(char *pBuff, int nSize, UINT32 timeout = INFINITE);
1741 int readLine(char *buffer, int size, UINT32 timeout = INFINITE);
def5b792
AK
1742};
1743
56fa1092
VK
1744/**
1745 * Postal address representation
1746 */
1747class LIBNETXMS_EXPORTABLE PostalAddress
1748{
1749private:
1750 TCHAR *m_country;
1751 TCHAR *m_city;
1752 TCHAR *m_streetAddress;
1753 TCHAR *m_postcode;
1754
1755public:
1756 PostalAddress();
1757 PostalAddress(const TCHAR *country, const TCHAR *city, const TCHAR *streetAddress, const TCHAR *postcode);
1758 ~PostalAddress();
1759
63e99e56
VK
1760 const TCHAR *getCountry() const { return CHECK_NULL_EX(m_country); }
1761 const TCHAR *getCity() const { return CHECK_NULL_EX(m_city); }
1762 const TCHAR *getStreetAddress() const { return CHECK_NULL_EX(m_streetAddress); }
1763 const TCHAR *getPostCode() const { return CHECK_NULL_EX(m_postcode); }
56fa1092 1764
6336bba3
VK
1765 json_t *toJson() const;
1766
cbc8c849
VK
1767 void setCountry(const TCHAR *country) { free(m_country); m_country = _tcsdup_ex(country); }
1768 void setCity(const TCHAR *city) { free(m_city); m_city = _tcsdup_ex(city); }
1769 void setStreetAddress(const TCHAR *streetAddress) { free(m_streetAddress); m_streetAddress = _tcsdup_ex(streetAddress); }
1770 void setPostCode(const TCHAR *postcode) { free(m_postcode); m_postcode = _tcsdup_ex(postcode); }
56fa1092
VK
1771};
1772
1668f7ed
VK
1773/**
1774 * Max number of polled sockets
1775 */
1776#define SOCKET_POLLER_MAX_SOCKETS 16
1777
1778/**
1779 * Socket poller
1780 */
1781class LIBNETXMS_EXPORTABLE SocketPoller
1782{
1783private:
1784 bool m_write;
1785 int m_count;
94f7aa43 1786#if HAVE_POLL
1668f7ed
VK
1787 struct pollfd m_sockets[SOCKET_POLLER_MAX_SOCKETS];
1788#else
1789 fd_set m_sockets;
4c5e8456 1790#ifndef _WIN32
1668f7ed
VK
1791 SOCKET m_maxfd;
1792#endif
4c5e8456 1793#endif
1668f7ed
VK
1794
1795public:
1796 SocketPoller(bool write = false);
1797 ~SocketPoller();
1798
1799 bool add(SOCKET s);
1800 int poll(UINT32 timeout);
1801 bool isSet(SOCKET s);
4c5e8456 1802 void reset();
1668f7ed
VK
1803};
1804
eae56922
VK
1805/**
1806 * Abstract communication channel
1807 */
1808class LIBNETXMS_EXPORTABLE AbstractCommChannel : public RefCountObject
1809{
1810protected:
1811 virtual ~AbstractCommChannel();
1812
1813public:
1814 AbstractCommChannel();
1815
1816 virtual int send(const void *data, size_t size, MUTEX mutex = INVALID_MUTEX_HANDLE) = 0;
1817 virtual int recv(void *buffer, size_t size, UINT32 timeout = INFINITE) = 0;
1818 virtual int poll(UINT32 timeout, bool write = false) = 0;
1819 virtual int shutdown() = 0;
1820 virtual void close() = 0;
1821};
1822
1823/**
1824 * Socket communication channel
1825 */
1826class LIBNETXMS_EXPORTABLE SocketCommChannel : public AbstractCommChannel
1827{
1828private:
1829 SOCKET m_socket;
1830 bool m_owner;
1831
1832protected:
1833 virtual ~SocketCommChannel();
1834
1835public:
1836 SocketCommChannel(SOCKET socket, bool owner = true);
1837
1838 virtual int send(const void *data, size_t size, MUTEX mutex = INVALID_MUTEX_HANDLE);
1839 virtual int recv(void *buffer, size_t size, UINT32 timeout = INFINITE);
1840 virtual int poll(UINT32 timeout, bool write = false);
1841 virtual int shutdown();
1842 virtual void close();
1843};
1844
b160350d
VK
1845#endif /* __cplusplus */
1846
030a0779
VK
1847/**
1848 * Configuration item template for configuration loader
1849 */
4826c8a5
VK
1850typedef struct
1851{
e2e66145
VK
1852 TCHAR token[64];
1853 BYTE type;
1854 BYTE separator; // Separator character for lists
1855 WORD listElements; // Number of list elements, should be set to 0 before calling NxLoadConfig()
e95680e5 1856 UINT64 bufferSize; // Buffer size for strings or flag to be set for CT_BOOLEAN
e2e66145
VK
1857 UINT32 bufferPos; // Should be set to 0
1858 void *buffer;
1859 void *overrideIndicator;
4826c8a5 1860} NX_CFG_TEMPLATE;
dcb44c9a 1861
030a0779
VK
1862/**
1863 * Code translation structure
1864 */
1b56f3c5 1865typedef struct __CODE_TO_TEXT
bc858635
VK
1866{
1867 int code;
1868 const TCHAR *text;
1869} CODE_TO_TEXT;
1870
e2e66145
VK
1871/**
1872 * getopt() prototype if needed
1873 */
df9812a9 1874#if USE_BUNDLED_GETOPT
99e50bb7 1875#include <netxms_getopt.h>
3046f9a4
VK
1876#endif
1877
3d1cb7d6
VK
1878//
1879// Structures for opendir() / readdir() / closedir()
1880//
1881
1882#ifdef _WIN32
1883
1a459ba3
VK
1884#define DT_UNKNOWN 0
1885#define DT_REG 1
1886#define DT_DIR 2
1887
7f9e0c00 1888typedef struct dirent
3d1cb7d6
VK
1889{
1890 long d_ino; /* inode number (not used by MS-DOS) */
1a459ba3 1891 unsigned char d_type; /* file type */
3d1cb7d6 1892 int d_namlen; /* Name length */
1f704f19 1893 char d_name[MAX_PATH]; /* file name */
3d1cb7d6
VK
1894} _DIRECT;
1895
1896typedef struct _dir_struc
1897{
1f704f19
VK
1898 HANDLE handle;
1899 struct dirent dirstr; /* Directory structure to return */
3d1cb7d6
VK
1900} DIR;
1901
5ea2db30
VK
1902#ifdef UNICODE
1903
1904typedef struct dirent_w
1905{
1906 long d_ino; /* inode number (not used by MS-DOS) */
1a459ba3 1907 unsigned char d_type; /* file type */
5ea2db30 1908 int d_namlen; /* Name length */
1f704f19 1909 WCHAR d_name[MAX_PATH]; /* file name */
5ea2db30
VK
1910} _DIRECTW;
1911
1912typedef struct _dir_struc_w
1913{
1f704f19 1914 HANDLE handle;
5ea2db30
VK
1915 struct dirent_w dirstr; /* Directory structure to return */
1916} DIRW;
1917
1918#define _TDIR DIRW
1919#define _TDIRECT _DIRECTW
1920#define _tdirent dirent_w
1921
1922#else
1923
1924#define _TDIR DIR
1925#define _TDIRECT _DIRECT
1926#define _tdirent dirent
1927
37d62364
AK
1928#endif
1929
76b1d3d8
VK
1930#else /* not _WIN32 */
1931
1932typedef struct dirent_w
1933{
1934 long d_ino; /* inode number */
5f77533a
VK
1935#if HAVE_DIRENT_D_TYPE
1936 unsigned char d_type; /* file type */
1937#endif
76b1d3d8
VK
1938 WCHAR d_name[257]; /* file name */
1939} _DIRECTW;
1940
1941typedef struct _dir_struc_w
1942{
1943 DIR *dir; /* Original non-unicode structure */
1944 struct dirent_w dirstr; /* Directory structure to return */
1945} DIRW;
1946
3d1cb7d6
VK
1947#endif /* _WIN32 */
1948
1949
e9246d26
VK
1950//
1951// Functions
1952//
1953
c81979bc 1954#ifdef __cplusplus
18c575eb 1955
2e590d1a
VK
1956inline TCHAR *nx_strncpy(TCHAR *pszDest, const TCHAR *pszSrc, size_t nLen)
1957{
64a055a2 1958#if defined(_WIN32) && (_MSC_VER >= 1400) && !defined(__clang__)
2e590d1a 1959 _tcsncpy_s(pszDest, nLen, pszSrc, _TRUNCATE);
912b994d 1960#else
2e590d1a
VK
1961 _tcsncpy(pszDest, pszSrc, nLen - 1);
1962 pszDest[nLen - 1] = 0;
912b994d 1963#endif
2e590d1a
VK
1964 return pszDest;
1965}
f3387429
VK
1966
1967#ifdef UNICODE
2e590d1a
VK
1968inline char *nx_strncpy_mb(char *pszDest, const char *pszSrc, size_t nLen)
1969{
64a055a2 1970#if defined(_WIN32) && (_MSC_VER >= 1400) && !defined(__clang__)
2e590d1a 1971 strncpy_s(pszDest, nLen, pszSrc, _TRUNCATE);
f3387429 1972#else
2e590d1a
VK
1973 strncpy(pszDest, pszSrc, nLen - 1);
1974 pszDest[nLen - 1] = 0;
c81979bc 1975#endif
2e590d1a
VK
1976 return pszDest;
1977}
c81979bc 1978#else
f3387429 1979#define nx_strncpy_mb nx_strncpy
7b8b337e
VK
1980#endif
1981
967893bb 1982int LIBNETXMS_EXPORTABLE ConnectEx(SOCKET s, struct sockaddr *addr, int len, UINT32 timeout);
5e60b759
VK
1983int LIBNETXMS_EXPORTABLE SendEx(SOCKET hSocket, const void *data, size_t len, int flags, MUTEX mutex);
1984int LIBNETXMS_EXPORTABLE RecvEx(SOCKET hSocket, void *data, size_t len, int flags, UINT32 timeout);
18c575eb
VK
1985bool LIBNETXMS_EXPORTABLE RecvAll(SOCKET s, void *buffer, size_t size, UINT32 timeout);
1986
b42c9187
VK
1987SOCKET LIBNETXMS_EXPORTABLE ConnectToHost(const InetAddress& addr, UINT16 port, UINT32 timeout);
1988
b0608204 1989#endif /* __cplusplus */
c81979bc 1990
b50f1100 1991#ifdef __cplusplus
e9246d26
VK
1992extern "C"
1993{
b50f1100 1994#endif
735bac5c 1995
d37e7f10 1996void LIBNETXMS_EXPORTABLE InitNetXMSProcess(bool commandLineTool);
fe8ea784 1997
7768852d 1998#ifndef _WIN32
8b86c5dc 1999#if defined(UNICODE_UCS2) || defined(UNICODE_UCS4)
735bac5c
VK
2000void LIBNETXMS_EXPORTABLE __wcsupr(WCHAR *in);
2001#define wcsupr __wcsupr
cc022855 2002#endif
735bac5c
VK
2003void LIBNETXMS_EXPORTABLE __strupr(char *in);
2004#define strupr __strupr
7768852d 2005#endif /* _WIN32 */
cc022855 2006
735bac5c 2007void LIBNETXMS_EXPORTABLE QSortEx(void *base, size_t nmemb, size_t size, void *arg,
b8a8d064
VK
2008 int (*compare)(const void *, const void *, void *));
2009
735bac5c 2010INT64 LIBNETXMS_EXPORTABLE GetCurrentTimeMs();
d35ed0aa 2011
735bac5c
VK
2012UINT64 LIBNETXMS_EXPORTABLE FileSizeW(const WCHAR *pszFileName);
2013UINT64 LIBNETXMS_EXPORTABLE FileSizeA(const char *pszFileName);
d35ed0aa
VK
2014#ifdef UNICODE
2015#define FileSize FileSizeW
2016#else
2017#define FileSize FileSizeA
2018#endif
670c7f3d 2019
735bac5c
VK
2020int LIBNETXMS_EXPORTABLE BitsInMask(UINT32 dwMask);
2021TCHAR LIBNETXMS_EXPORTABLE *IpToStr(UINT32 dwAddr, TCHAR *szBuffer);
e0f99bf0 2022#ifdef UNICODE
735bac5c 2023char LIBNETXMS_EXPORTABLE *IpToStrA(UINT32 dwAddr, char *szBuffer);
17b35ccc
VK
2024#else
2025#define IpToStrA IpToStr
e0f99bf0 2026#endif
8c75ad41 2027TCHAR LIBNETXMS_EXPORTABLE *Ip6ToStr(const BYTE *addr, TCHAR *buffer);
af4a09df
VK
2028#ifdef UNICODE
2029char LIBNETXMS_EXPORTABLE *Ip6ToStrA(const BYTE *addr, char *buffer);
2030#else
2031#define Ip6ToStrA Ip6ToStr
2032#endif
735bac5c 2033TCHAR LIBNETXMS_EXPORTABLE *SockaddrToStr(struct sockaddr *addr, TCHAR *buffer);
60557d06 2034
735bac5c
VK
2035void LIBNETXMS_EXPORTABLE *nx_memdup(const void *data, size_t size);
2036void LIBNETXMS_EXPORTABLE nx_memswap(void *block1, void *block2, size_t size);
31521248 2037
73a67950
VK
2038WCHAR LIBNETXMS_EXPORTABLE *BinToStrW(const void *data, size_t size, WCHAR *str);
2039char LIBNETXMS_EXPORTABLE *BinToStrA(const void *data, size_t size, char *str);
d7970ee7
VK
2040#ifdef UNICODE
2041#define BinToStr BinToStrW
2042#else
2043#define BinToStr BinToStrA
2044#endif
2045
735bac5c
VK
2046size_t LIBNETXMS_EXPORTABLE StrToBinW(const WCHAR *pStr, BYTE *data, size_t size);
2047size_t LIBNETXMS_EXPORTABLE StrToBinA(const char *pStr, BYTE *data, size_t size);
52db3ed1
VK
2048#ifdef UNICODE
2049#define StrToBin StrToBinW
2050#else
2051#define StrToBin StrToBinA
2052#endif
cc022855 2053
735bac5c 2054TCHAR LIBNETXMS_EXPORTABLE *MACToStr(const BYTE *data, TCHAR *pStr);
b50f1100 2055
735bac5c
VK
2056void LIBNETXMS_EXPORTABLE StrStripA(char *pszStr);
2057void LIBNETXMS_EXPORTABLE StrStripW(WCHAR *pszStr);
b07c50cc
VK
2058#ifdef UNICODE
2059#define StrStrip StrStripW
2060#else
2061#define StrStrip StrStripA
2062#endif
2063
735bac5c
VK
2064const char LIBNETXMS_EXPORTABLE *ExtractWordA(const char *line, char *buffer);
2065const WCHAR LIBNETXMS_EXPORTABLE *ExtractWordW(const WCHAR *line, WCHAR *buffer);
ada97259
VK
2066#ifdef UNICODE
2067#define ExtractWord ExtractWordW
2068#else
2069#define ExtractWord ExtractWordA
2070#endif
2071
735bac5c
VK
2072int LIBNETXMS_EXPORTABLE NumCharsA(const char *pszStr, char ch);
2073int LIBNETXMS_EXPORTABLE NumCharsW(const WCHAR *pszStr, WCHAR ch);
3583a400
VK
2074#ifdef UNICODE
2075#define NumChars NumCharsW
2076#else
2077#define NumChars NumCharsA
2078#endif
ada97259 2079
735bac5c
VK
2080void LIBNETXMS_EXPORTABLE RemoveTrailingCRLFA(char *str);
2081void LIBNETXMS_EXPORTABLE RemoveTrailingCRLFW(WCHAR *str);
35f836fe
VK
2082#ifdef UNICODE
2083#define RemoveTrailingCRLF RemoveTrailingCRLFW
2084#else
2085#define RemoveTrailingCRLF RemoveTrailingCRLFA
cafe592d
VK
2086#endif
2087
e5f88e5a
VK
2088bool LIBNETXMS_EXPORTABLE RegexpMatchA(const char *str, const char *expr, bool matchCase);
2089bool LIBNETXMS_EXPORTABLE RegexpMatchW(const WCHAR *str, const WCHAR *expr, bool matchCase);
cafe592d
VK
2090#ifdef UNICODE
2091#define RegexpMatch RegexpMatchW
2092#else
2093#define RegexpMatch RegexpMatchA
35f836fe
VK
2094#endif
2095
735bac5c 2096const TCHAR LIBNETXMS_EXPORTABLE *ExpandFileName(const TCHAR *name, TCHAR *buffer, size_t bufSize, bool allowShellCommand);
d77c193c 2097BOOL LIBNETXMS_EXPORTABLE CreateFolder(const TCHAR *directory);
7b45b90d 2098bool LIBNETXMS_EXPORTABLE SetLastModificationTime(TCHAR *fileName, time_t lastModDate);
818f8c94 2099TCHAR LIBNETXMS_EXPORTABLE *Trim(TCHAR *str);
735bac5c
VK
2100bool LIBNETXMS_EXPORTABLE MatchString(const TCHAR *pattern, const TCHAR *str, bool matchCase);
2101TCHAR LIBNETXMS_EXPORTABLE **SplitString(const TCHAR *source, TCHAR sep, int *numStrings);
0a145c10 2102int LIBNETXMS_EXPORTABLE GetLastMonthDay(struct tm *currTime);
0a145c10 2103bool LIBNETXMS_EXPORTABLE MatchScheduleElement(TCHAR *pszPattern, int nValue, int maxValue, struct tm *localTime, time_t currTime);
073283c5 2104bool LIBNETXMS_EXPORTABLE MatchSchedule(const TCHAR *schedule, struct tm *currTime, time_t now);
ada97259 2105
f7794b68 2106#ifdef __cplusplus
735bac5c 2107BOOL LIBNETXMS_EXPORTABLE IsValidObjectName(const TCHAR *pszName, BOOL bExtendedChars = FALSE);
f7794b68 2108#endif
735bac5c
VK
2109BOOL LIBNETXMS_EXPORTABLE IsValidScriptName(const TCHAR *pszName);
2110/* deprecated */ void LIBNETXMS_EXPORTABLE TranslateStr(TCHAR *pszString, const TCHAR *pszSubStr, const TCHAR *pszReplace);
2111const TCHAR LIBNETXMS_EXPORTABLE *GetCleanFileName(const TCHAR *pszFileName);
2112void LIBNETXMS_EXPORTABLE GetOSVersionString(TCHAR *pszBuffer, int nBufSize);
2113BYTE LIBNETXMS_EXPORTABLE *LoadFile(const TCHAR *pszFileName, UINT32 *pdwFileSize);
08b214c6 2114#ifdef UNICODE
735bac5c 2115BYTE LIBNETXMS_EXPORTABLE *LoadFileA(const char *pszFileName, UINT32 *pdwFileSize);
08b214c6
VK
2116#else
2117#define LoadFileA LoadFile
2118#endif
2119
735bac5c 2120UINT32 LIBNETXMS_EXPORTABLE CalculateCRC32(const unsigned char *data, UINT32 size, UINT32 dwCRC);
1e019efa
VK
2121BOOL LIBNETXMS_EXPORTABLE CalculateFileCRC32(const TCHAR *pszFileName, UINT32 *pResult);
2122
2123typedef unsigned char MD5_STATE[128];
2124
2125void LIBNETXMS_EXPORTABLE CalculateMD5Hash(const BYTE *data, size_t nbytes, BYTE *hash);
2126void LIBNETXMS_EXPORTABLE MD5HashForPattern(const BYTE *data, size_t patternSize, size_t fullSize, BYTE *hash);
735bac5c 2127BOOL LIBNETXMS_EXPORTABLE CalculateFileMD5Hash(const TCHAR *pszFileName, BYTE *pHash);
1e019efa
VK
2128void LIBNETXMS_EXPORTABLE MD5Init(MD5_STATE *state);
2129void LIBNETXMS_EXPORTABLE MD5Update(MD5_STATE *state, const BYTE *data, size_t size);
2130void LIBNETXMS_EXPORTABLE MD5Finish(MD5_STATE *state, BYTE *hash);
2131
2132typedef unsigned char SHA1_STATE[128];
2133
2134void LIBNETXMS_EXPORTABLE CalculateSHA1Hash(const BYTE *data, size_t nbytes, BYTE *hash);
2135void LIBNETXMS_EXPORTABLE SHA1HashForPattern(const BYTE *data, size_t patternSize, size_t fullSize, BYTE *hash);
735bac5c 2136BOOL LIBNETXMS_EXPORTABLE CalculateFileSHA1Hash(const TCHAR *pszFileName, BYTE *pHash);
1e019efa
VK
2137void LIBNETXMS_EXPORTABLE SHA1Init(SHA1_STATE *state);
2138void LIBNETXMS_EXPORTABLE SHA1Update(SHA1_STATE *state, const BYTE *data, size_t size);
2139void LIBNETXMS_EXPORTABLE SHA1Finish(SHA1_STATE *state, BYTE *hash);
2140
2141void LIBNETXMS_EXPORTABLE CalculateSHA256Hash(const BYTE *data, size_t len, BYTE *hash);
66c04cc7 2142
981d246a
VK
2143void LIBNETXMS_EXPORTABLE GenerateRandomBytes(BYTE *buffer, size_t size);
2144
7f9ff8a5
VK
2145void LIBNETXMS_EXPORTABLE LogOpenSSLErrorStack(int level);
2146
735bac5c
VK
2147void LIBNETXMS_EXPORTABLE ICEEncryptData(const BYTE *in, int inLen, BYTE *out, const BYTE *key);
2148void LIBNETXMS_EXPORTABLE ICEDecryptData(const BYTE *in, int inLen, BYTE *out, const BYTE *key);
4e2debcc 2149
11f1babb
VK
2150bool LIBNETXMS_EXPORTABLE DecryptPasswordW(const WCHAR *login, const WCHAR *encryptedPasswd, WCHAR *decryptedPasswd, size_t bufferLenght);
2151bool LIBNETXMS_EXPORTABLE DecryptPasswordA(const char *login, const char *encryptedPasswd, char *decryptedPasswd, size_t bufferLenght);
2152#ifdef UNICODE
2153#define DecryptPassword DecryptPasswordW
2154#else
2155#define DecryptPassword DecryptPasswordA
2156#endif
6b1282e7 2157
735bac5c 2158int LIBNETXMS_EXPORTABLE NxDCIDataTypeFromText(const TCHAR *pszText);
aa13cfd9 2159
735bac5c
VK
2160HMODULE LIBNETXMS_EXPORTABLE DLOpen(const TCHAR *pszLibName, TCHAR *pszErrorText);
2161void LIBNETXMS_EXPORTABLE DLClose(HMODULE hModule);
2162void LIBNETXMS_EXPORTABLE *DLGetSymbolAddr(HMODULE hModule, const char *pszSymbol, TCHAR *pszErrorText);
aa13cfd9 2163
735bac5c
VK
2164bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueW(const WCHAR *optString, const WCHAR *option, WCHAR *buffer, int bufSize);
2165bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsBoolW(const WCHAR *optString, const WCHAR *option, bool defVal);
2166long LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsIntW(const WCHAR *optString, const WCHAR *option, long defVal);
289d126b 2167
735bac5c
VK
2168bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueA(const char *optString, const char *option, char *buffer, int bufSize);
2169bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsBoolA(const char *optString, const char *option, bool defVal);
2170long LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsIntA(const char *optString, const char *option, long defVal);
289d126b
VK
2171
2172#ifdef UNICODE
2173#define ExtractNamedOptionValue ExtractNamedOptionValueW
2174#define ExtractNamedOptionValueAsBool ExtractNamedOptionValueAsBoolW
2175#define ExtractNamedOptionValueAsInt ExtractNamedOptionValueAsIntW
2176#else
2177#define ExtractNamedOptionValue ExtractNamedOptionValueA
2178#define ExtractNamedOptionValueAsBool ExtractNamedOptionValueAsBoolA
2179#define ExtractNamedOptionValueAsInt ExtractNamedOptionValueAsIntA
2180#endif
ae9cddaf 2181
bc858635 2182#ifdef __cplusplus
20d885d8 2183const TCHAR LIBNETXMS_EXPORTABLE *CodeToText(int code, CODE_TO_TEXT *translator, const TCHAR *defaultText = _T("Unknown"));
bc858635 2184#else
20d885d8
VK
2185const TCHAR LIBNETXMS_EXPORTABLE *CodeToText(int code, CODE_TO_TEXT *translator, const TCHAR *defaultText);
2186#endif
2187#ifdef __cplusplus
2188int LIBNETXMS_EXPORTABLE CodeFromText(const TCHAR *text, CODE_TO_TEXT *translator, int defaultCode = -1);
2189#else
2190int LIBNETXMS_EXPORTABLE CodeFromText(const TCHAR *text, CODE_TO_TEXT *translator, int defaultCode);
bc858635
VK
2191#endif
2192
aa13cfd9 2193#ifdef _WIN32
735bac5c
VK
2194TCHAR LIBNETXMS_EXPORTABLE *GetSystemErrorText(UINT32 dwError, TCHAR *pszBuffer, size_t iBufSize);
2195BOOL LIBNETXMS_EXPORTABLE GetWindowsVersionString(TCHAR *versionString, int strSize);
2196INT64 LIBNETXMS_EXPORTABLE GetProcessRSS();
aa13cfd9 2197#endif
696fc54f 2198
ee3d42df
VK
2199TCHAR LIBNETXMS_EXPORTABLE *GetLastSocketErrorText(TCHAR *buffer, size_t size);
2200
de4c0511
VK
2201#if !HAVE_DAEMON || !HAVE_DECL_DAEMON
2202int LIBNETXMS_EXPORTABLE __daemon(int nochdir, int noclose);
2203#define daemon __daemon
696fc54f 2204#endif
4332e9d8 2205
735bac5c 2206UINT32 LIBNETXMS_EXPORTABLE inet_addr_w(const WCHAR *pszAddr);
268774a0 2207
4332e9d8 2208#ifndef _WIN32
7768852d
VK
2209
2210bool LIBNETXMS_EXPORTABLE SetDefaultCodepage(const char *cp);
735bac5c
VK
2211int LIBNETXMS_EXPORTABLE WideCharToMultiByte(int iCodePage, UINT32 dwFlags, const WCHAR *pWideCharStr,
2212 int cchWideChar, char *pByteStr, int cchByteChar,
2213 char *pDefaultChar, BOOL *pbUsedDefChar);
2214int LIBNETXMS_EXPORTABLE MultiByteToWideChar(int iCodePage, UINT32 dwFlags, const char *pByteStr,
2215 int cchByteChar, WCHAR *pWideCharStr,
2216 int cchWideChar);
04dbaf62 2217
c6d5c1b0 2218#ifdef UNICODE
735bac5c
VK
2219int LIBNETXMS_EXPORTABLE nx_wprintf(const WCHAR *format, ...);
2220int LIBNETXMS_EXPORTABLE nx_fwprintf(FILE *fp, const WCHAR *format, ...);
2221int LIBNETXMS_EXPORTABLE nx_swprintf(WCHAR *buffer, size_t size, const WCHAR *format, ...);
2222int LIBNETXMS_EXPORTABLE nx_vwprintf(const WCHAR *format, va_list args);
2223int LIBNETXMS_EXPORTABLE nx_vfwprintf(FILE *fp, const WCHAR *format, va_list args);
2224int LIBNETXMS_EXPORTABLE nx_vswprintf(WCHAR *buffer, size_t size, const WCHAR *format, va_list args);
04dbaf62 2225
735bac5c
VK
2226int LIBNETXMS_EXPORTABLE nx_wscanf(const WCHAR *format, ...);
2227int LIBNETXMS_EXPORTABLE nx_fwscanf(FILE *fp, const WCHAR *format, ...);
2228int LIBNETXMS_EXPORTABLE nx_swscanf(const WCHAR *str, const WCHAR *format, ...);
2229int LIBNETXMS_EXPORTABLE nx_vwscanf(const WCHAR *format, va_list args);
2230int LIBNETXMS_EXPORTABLE nx_vfwscanf(FILE *fp, const WCHAR *format, va_list args);
2231int LIBNETXMS_EXPORTABLE nx_vswscanf(const WCHAR *str, const WCHAR *format, va_list args);
c6d5c1b0 2232#endif
25575d38 2233
3e39fcde 2234#endif /* _WIN32 */
8b86c5dc 2235
3d1058ed 2236#ifdef _WITH_ENCRYPTION
735bac5c 2237WCHAR LIBNETXMS_EXPORTABLE *ERR_error_string_W(int nError, WCHAR *pwszBuffer);
3d1058ed
VK
2238#endif
2239
842c22f4 2240#if !defined(_WIN32) && !HAVE_WSTAT
735bac5c 2241int wstat(const WCHAR *_path, struct stat *_sbuf);
842c22f4
AK
2242#endif
2243
ef856d02 2244#if defined(UNICODE) && !defined(_WIN32)
d9b66a56 2245
f3387429 2246#if !HAVE_WPOPEN
735bac5c 2247FILE LIBNETXMS_EXPORTABLE *wpopen(const WCHAR *_command, const WCHAR *_type);
f3387429 2248#endif
8b86c5dc 2249#if !HAVE_WFOPEN
735bac5c 2250FILE LIBNETXMS_EXPORTABLE *wfopen(const WCHAR *_name, const WCHAR *_type);
8b86c5dc 2251#endif
8c2489aa 2252#if HAVE_FOPEN64 && !HAVE_WFOPEN64
735bac5c 2253FILE LIBNETXMS_EXPORTABLE *wfopen64(const WCHAR *_name, const WCHAR *_type);
8c2489aa 2254#endif
8b86c5dc 2255#if !HAVE_WOPEN
735bac5c 2256int LIBNETXMS_EXPORTABLE wopen(const WCHAR *, int, ...);
b50f1100 2257#endif
f3387429 2258#if !HAVE_WCHMOD
735bac5c 2259int LIBNETXMS_EXPORTABLE wchmod(const WCHAR *_name, int mode);
f3387429 2260#endif
b07c50cc 2261#if !HAVE_WCHDIR
735bac5c 2262int wchdir(const WCHAR *_path);
b07c50cc
VK
2263#endif
2264#if !HAVE_WMKDIR
735bac5c 2265int wmkdir(const WCHAR *_path, int mode);
b07c50cc 2266#endif
7b45b90d 2267#if !HAVE_WUTIME
2268int wutime(const WCHAR *_path, struct utimbuf *buf);
2269#endif
b07c50cc 2270#if !HAVE_WRMDIR
735bac5c 2271int wrmdir(const WCHAR *_path);
b07c50cc 2272#endif
ccc34207 2273#if !HAVE_WRENAME
735bac5c 2274int wrename(const WCHAR *_oldpath, const WCHAR *_newpath);
ccc34207
VK
2275#endif
2276#if !HAVE_WUNLINK
735bac5c 2277int wunlink(const WCHAR *_path);
ccc34207 2278#endif
b07c50cc 2279#if !HAVE_WREMOVE
735bac5c 2280int wremove(const WCHAR *_path);
b07c50cc
VK
2281#endif
2282#if !HAVE_WSYSTEM
735bac5c 2283int wsystem(const WCHAR *_cmd);
b07c50cc 2284#endif
dda7c270 2285#if !HAVE_WMKSTEMP
735bac5c 2286int wmkstemp(WCHAR *_template);
dda7c270 2287#endif
b07c50cc 2288#if !HAVE_WACCESS
735bac5c 2289int waccess(const WCHAR *_path, int mode);
b07c50cc 2290#endif
273da39a 2291#if !HAVE_WGETENV
735bac5c 2292WCHAR *wgetenv(const WCHAR *_string);
273da39a 2293#endif
f3387429 2294#if !HAVE_WCTIME
735bac5c 2295WCHAR *wctime(const time_t *timep);
f3387429 2296#endif
0186b5da 2297#if !HAVE_PUTWS
735bac5c 2298int putws(const WCHAR *s);
0186b5da 2299#endif
9757ca46 2300#if !HAVE_WCSERROR && (HAVE_STRERROR || HAVE_DECL_STRERROR)
735bac5c 2301WCHAR *wcserror(int errnum);
d49d7500
VK
2302#endif
2303#if !HAVE_WCSERROR_R && HAVE_STRERROR_R
b0823d06 2304#if HAVE_POSIX_STRERROR_R
735bac5c 2305int wcserror_r(int errnum, WCHAR *strerrbuf, size_t buflen);
b0823d06 2306#else
735bac5c 2307WCHAR *wcserror_r(int errnum, WCHAR *strerrbuf, size_t buflen);
d49d7500 2308#endif
b0823d06 2309#endif
e05f8aaf 2310
ef856d02 2311#endif /* UNICODE && !_WIN32*/
e05f8aaf 2312
8b86c5dc 2313#if !HAVE_STRTOLL
735bac5c 2314INT64 LIBNETXMS_EXPORTABLE strtoll(const char *nptr, char **endptr, int base);
8b86c5dc
VK
2315#endif
2316#if !HAVE_STRTOULL
735bac5c 2317UINT64 LIBNETXMS_EXPORTABLE strtoull(const char *nptr, char **endptr, int base);
8b86c5dc 2318#endif
e05f8aaf
VK
2319
2320#if !HAVE_WCSTOLL
735bac5c 2321INT64 LIBNETXMS_EXPORTABLE wcstoll(const WCHAR *nptr, WCHAR **endptr, int base);
e05f8aaf
VK
2322#endif
2323#if !HAVE_WCSTOULL
735bac5c 2324UINT64 LIBNETXMS_EXPORTABLE wcstoull(const WCHAR *nptr, WCHAR **endptr, int base);
e05f8aaf 2325#endif
b50f1100 2326
3b3ee220
VK
2327#if !HAVE_STRLWR && !defined(_WIN32)
2328char LIBNETXMS_EXPORTABLE *strlwr(char *str);
2329#endif
2330
2f56be29 2331#if !HAVE_WCSLWR && !defined(_WIN32)
735bac5c 2332WCHAR LIBNETXMS_EXPORTABLE *wcslwr(WCHAR *str);
fdf1ed50
VK
2333#endif
2334
4d978b4a 2335#if !HAVE_WCSCASECMP && !defined(_WIN32)
735bac5c 2336int LIBNETXMS_EXPORTABLE wcscasecmp(const wchar_t *s1, const wchar_t *s2);
4d978b4a
VK
2337#endif
2338
f4d2c9ba 2339#if !HAVE_WCSNCASECMP && !defined(_WIN32)
735bac5c 2340int LIBNETXMS_EXPORTABLE wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n);
f4d2c9ba
VK
2341#endif
2342
75b4d48e
VK
2343#if !defined(_WIN32) && (!HAVE_WCSFTIME || !WORKING_WCSFTIME)
2344size_t LIBNETXMS_EXPORTABLE nx_wcsftime(WCHAR *buffer, size_t bufsize, const WCHAR *format, const struct tm *t);
2345#undef wcsftime
2346#define wcsftime nx_wcsftime
2347#endif
2348
9138dfe2
VK
2349#ifndef _WIN32
2350
2351#if HAVE_ITOA && !HAVE__ITOA
2352#define _itoa itoa
2353#undef HAVE__ITOA
2354#define HAVE__ITOA 1
2355#endif
2356#if !HAVE__ITOA && !defined(_WIN32)
2357char LIBNETXMS_EXPORTABLE *_itoa(int value, char *str, int base);
2358#endif
2359
2360#if HAVE_ITOW && !HAVE__ITOW
2361#define _itow itow
2362#undef HAVE__ITOW
2363#define HAVE__ITOW 1
2364#endif
2365#if !HAVE__ITOW && !defined(_WIN32)
2366WCHAR LIBNETXMS_EXPORTABLE *_itow(int value, WCHAR *str, int base);
2367#endif
2368
2369#endif /* _WIN32 */
2370
3d1cb7d6 2371#ifdef _WIN32
5ea2db30 2372#ifdef UNICODE
1f704f19
VK
2373DIRW LIBNETXMS_EXPORTABLE *wopendir(const WCHAR *path);
2374struct dirent_w LIBNETXMS_EXPORTABLE *wreaddir(DIRW *p);
2375int LIBNETXMS_EXPORTABLE wclosedir(DIRW *p);
5ea2db30
VK
2376
2377#define _topendir wopendir
2378#define _treaddir wreaddir
2379#define _tclosedir wclosedir
2380#else
2381#define _topendir opendir
2382#define _treaddir readdir
2383#define _tclosedir closedir
2384#endif
2385
1f704f19
VK
2386DIR LIBNETXMS_EXPORTABLE *opendir(const char *path);
2387struct dirent LIBNETXMS_EXPORTABLE *readdir(DIR *p);
2388int LIBNETXMS_EXPORTABLE closedir(DIR *p);
5ea2db30 2389
76b1d3d8
VK
2390#else /* not _WIN32 */
2391
735bac5c
VK
2392DIRW LIBNETXMS_EXPORTABLE *wopendir(const WCHAR *filename);
2393struct dirent_w LIBNETXMS_EXPORTABLE *wreaddir(DIRW *dirp);
2394int LIBNETXMS_EXPORTABLE wclosedir(DIRW *dirp);
76b1d3d8 2395
37d62364 2396#endif
3d1cb7d6 2397
7f9e0c00 2398#if defined(_WIN32) || !(HAVE_SCANDIR)
735bac5c
VK
2399int LIBNETXMS_EXPORTABLE scandir(const char *dir, struct dirent ***namelist,
2400 int (*select)(const struct dirent *),
2401 int (*compar)(const struct dirent **, const struct dirent **));
2402int LIBNETXMS_EXPORTABLE alphasort(const struct dirent **a, const struct dirent **b);
7f9e0c00
VK
2403#endif
2404
3bf0df9f
VK
2405TCHAR LIBNETXMS_EXPORTABLE *safe_fgetts(TCHAR *buffer, int len, FILE *f);
2406
2df047f4 2407bool LIBNETXMS_EXPORTABLE nxlog_open(const TCHAR *logName, UINT32 flags, const TCHAR *msgModule,
90a9e65e
VK
2408 unsigned int msgCount, const TCHAR **messages,
2409 DWORD debugMsg, DWORD genericMsg);
2410void LIBNETXMS_EXPORTABLE nxlog_close();
9f2902ac 2411void LIBNETXMS_EXPORTABLE nxlog_write(DWORD msg, WORD wType, const char *format, ...);
90a9e65e 2412void LIBNETXMS_EXPORTABLE nxlog_write_generic(WORD type, const TCHAR *format, ...);
2df047f4
VK
2413void LIBNETXMS_EXPORTABLE nxlog_debug(int level, const TCHAR *format, ...);
2414void LIBNETXMS_EXPORTABLE nxlog_debug2(int level, const TCHAR *format, va_list args);
458b5d2b 2415bool LIBNETXMS_EXPORTABLE nxlog_set_rotation_policy(int rotationMode, UINT64 maxLogSize, int historySize, const TCHAR *dailySuffix);
2df047f4
VK
2416bool LIBNETXMS_EXPORTABLE nxlog_rotate();
2417void LIBNETXMS_EXPORTABLE nxlog_set_debug_level(int level);
2418int LIBNETXMS_EXPORTABLE nxlog_get_debug_level();
7c587518
VK
2419
2420typedef void (*NxLogDebugWriter)(const TCHAR *);
2421void LIBNETXMS_EXPORTABLE nxlog_set_debug_writer(NxLogDebugWriter writer);
9113e749
VK
2422
2423typedef void (*NxLogConsoleWriter)(const TCHAR *, ...);
2424void LIBNETXMS_EXPORTABLE nxlog_set_console_writer(NxLogConsoleWriter writer);
f669df41
VK
2425
2426void LIBNETXMS_EXPORTABLE WriteToTerminal(const TCHAR *text);
6e383343
VK
2427void LIBNETXMS_EXPORTABLE WriteToTerminalEx(const TCHAR *format, ...)
2428#if !defined(UNICODE) && (defined(__GNUC__) || defined(__clang__))
2429 __attribute__ ((format(printf, 1, 2)))
2430#endif
2431;
9f2902ac 2432
4a64a795
VK
2433bool LIBNETXMS_EXPORTABLE ReadPassword(const TCHAR *prompt, TCHAR *buffer, size_t bufferSize);
2434
37a7a862
VK
2435#ifdef _WIN32
2436int LIBNETXMS_EXPORTABLE mkstemp(char *tmpl);
2437int LIBNETXMS_EXPORTABLE wmkstemp(WCHAR *tmpl);
2438#ifdef UNICODE
2439#define _tmkstemp wmkstemp
2440#else
2441#define _tmkstemp mkstemp
2442#endif
2443#endif
2444
9b13553b
VK
2445#ifndef _WIN32
2446int strcat_s(char *dst, size_t dstSize, const char *src);
2447int wcscat_s(WCHAR *dst, size_t dstSize, const WCHAR *src);
2448#endif
2449
c57d020a
VK
2450#if !HAVE_STRPTIME
2451char LIBNETXMS_EXPORTABLE *strptime(const char *buf, const char *fmt, struct tm *_tm);
2452#endif
2453
2454#if !HAVE_TIMEGM
2455time_t LIBNETXMS_EXPORTABLE timegm(struct tm *_tm);
2456#endif
2457
6f95ef89
VK
2458#if !HAVE_INET_PTON
2459int LIBNETXMS_EXPORTABLE nx_inet_pton(int af, const char *src, void *dst);
2460#define inet_pton nx_inet_pton
2461#endif
2462
b06ae508 2463int LIBNETXMS_EXPORTABLE GetSleepTime(int hour, int minute, int second);
b60584cf
VK
2464time_t LIBNETXMS_EXPORTABLE ParseDateTimeA(const char *text, time_t defaultValue);
2465time_t LIBNETXMS_EXPORTABLE ParseDateTimeW(const WCHAR *text, time_t defaultValue);
2466
2467#ifdef UNICODE
2468#define ParseDateTime ParseDateTimeW
2469#else
2470#define ParseDateTime ParseDateTimeA
2471#endif
b06ae508 2472
b50f1100 2473#ifdef __cplusplus
e9246d26 2474}
b50f1100 2475#endif
e9246d26 2476
a7ff20a5
VK
2477
2478//
b06ae508 2479// C++ only functions
a7ff20a5
VK
2480//
2481
2482#ifdef __cplusplus
2483
a97f02e1
VK
2484enum nxDirectoryType
2485{
2486 nxDirBin = 0,
2487 nxDirData = 1,
2488 nxDirEtc = 2,
1039d7ee
VK
2489 nxDirLib = 3,
2490 nxDirShare = 4
a97f02e1
VK
2491};
2492
5962498b
VK
2493TCHAR LIBNETXMS_EXPORTABLE *GetHeapInfo();
2494
a97f02e1
VK
2495void LIBNETXMS_EXPORTABLE GetNetXMSDirectory(nxDirectoryType type, TCHAR *dir);
2496
43709a0c
VK
2497UINT32 LIBNETXMS_EXPORTABLE IcmpPing(const InetAddress& addr, int iNumRetries, UINT32 dwTimeout, UINT32 *pdwRTT, UINT32 dwPacketSize);
2498
240816b0
VK
2499TCHAR LIBNETXMS_EXPORTABLE *EscapeStringForXML(const TCHAR *str, int length);
2500String LIBNETXMS_EXPORTABLE EscapeStringForXML2(const TCHAR *str, int length = -1);
53c96e2d
VK
2501const char LIBNETXMS_EXPORTABLE *XMLGetAttr(const char **attrs, const char *name);
2502int LIBNETXMS_EXPORTABLE XMLGetAttrInt(const char **attrs, const char *name, int defVal);
967893bb 2503UINT32 LIBNETXMS_EXPORTABLE XMLGetAttrUINT32(const char **attrs, const char *name, UINT32 defVal);
53c96e2d
VK
2504bool LIBNETXMS_EXPORTABLE XMLGetAttrBoolean(const char **attrs, const char *name, bool defVal);
2505
0356b995 2506String LIBNETXMS_EXPORTABLE EscapeStringForJSON(const TCHAR *s);
1d919454 2507String LIBNETXMS_EXPORTABLE EscapeStringForAgent(const TCHAR *s);
0356b995 2508
e9bf9011
VK
2509StringList LIBNETXMS_EXPORTABLE *ParseCommandLine(const TCHAR *cmdline);
2510
53c96e2d 2511#if !defined(_WIN32) && !defined(_NETWARE) && defined(NMS_THREADS_H_INCLUDED)
d37e7f10 2512void LIBNETXMS_EXPORTABLE BlockAllSignals(bool processWide, bool allowInterrupt);
9113e749 2513void LIBNETXMS_EXPORTABLE StartMainLoop(ThreadFunction pfSignalHandler, ThreadFunction pfMain);
53c96e2d
VK
2514#endif
2515
18a7c1e9
VK
2516String LIBNETXMS_EXPORTABLE GenerateLineDiff(const String& left, const String& right);
2517
a7ff20a5
VK
2518#endif
2519
e9246d26 2520#endif /* _nms_util_h_ */