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