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