atomic functions moved into separete header; added atomic function InterlockedExchang...
[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, int len) const;
619 TCHAR *substring(size_t start, int len, TCHAR *buffer) const;
620 String left(size_t len) const { return substring(0, (int)len); }
621 String right(size_t len) const { return substring((m_length > len) ? m_length - len : 0, (int)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(int chars = 1);
631 };
632
633 /**
634 * Abstract iterator class (to be implemented by actual iterable class)
635 */
636 class LIBNETXMS_EXPORTABLE AbstractIterator
637 {
638 public:
639 virtual ~AbstractIterator();
640
641 virtual bool hasNext() = 0;
642 virtual void *next() = 0;
643 virtual void remove() = 0;
644 };
645
646 /**
647 * Iterator class (public interface for iteration)
648 */
649 template <class T> class Iterator
650 {
651 private:
652 AbstractIterator *m_worker;
653
654 public:
655 Iterator(AbstractIterator *worker) { m_worker = worker; }
656 ~Iterator() { delete m_worker; }
657
658 bool hasNext() { return m_worker->hasNext(); }
659 T *next() { return (T *)m_worker->next(); }
660 void remove() { m_worker->remove(); }
661 };
662
663 /**
664 * Dynamic array class
665 */
666 class LIBNETXMS_EXPORTABLE Array
667 {
668 private:
669 int m_size;
670 int m_allocated;
671 int m_grow;
672 size_t m_elementSize;
673 void **m_data;
674 bool m_objectOwner;
675
676 void internalRemove(int index, bool allowDestruction);
677 void destroyObject(void *object) { if (object != NULL) m_objectDestructor(object); }
678
679 protected:
680 bool m_storePointers;
681 void (*m_objectDestructor)(void *);
682
683 Array(void *data, int initial, int grow, size_t elementSize);
684 Array(const Array *src);
685
686 void *__getBuffer() const { return m_data; }
687
688 public:
689 Array(int initial = 0, int grow = 16, bool owner = false);
690 virtual ~Array();
691
692 int add(void *element);
693 void *get(int index) const { return ((index >= 0) && (index < m_size)) ? (m_storePointers ? m_data[index] : (void *)((char *)m_data + index * m_elementSize)): NULL; }
694 int indexOf(void *element) const;
695 void set(int index, void *element);
696 void replace(int index, void *element);
697 void insert(int index, void *element);
698 void remove(int index) { internalRemove(index, true); }
699 void remove(void *element) { internalRemove(indexOf(element), true); }
700 void unlink(int index) { internalRemove(index, false); }
701 void unlink(void *element) { internalRemove(indexOf(element), false); }
702 void clear();
703 void sort(int (*cb)(const void *, const void *));
704 void *find(const void *key, int (*cb)(const void *, const void *)) const;
705
706 int size() const { return m_size; }
707 bool isEmpty() const { return m_size == 0; }
708
709 void setOwner(bool owner) { m_objectOwner = owner; }
710 bool isOwner() const { return m_objectOwner; }
711 };
712
713 /**
714 * Array iterator class
715 */
716 class LIBNETXMS_EXPORTABLE ArrayIterator : public AbstractIterator
717 {
718 private:
719 Array *m_array;
720 int m_pos;
721
722 public:
723 ArrayIterator(Array *array);
724
725 virtual bool hasNext();
726 virtual void *next();
727 virtual void remove();
728 };
729
730 /**
731 * Template class for dynamic array which holds objects
732 */
733 template <class T> class ObjectArray : public Array
734 {
735 private:
736 static void destructor(void *object) { delete (T*)object; }
737
738 public:
739 ObjectArray(int initial = 0, int grow = 16, bool owner = false) : Array(initial, grow, owner) { m_objectDestructor = destructor; }
740 virtual ~ObjectArray() { }
741
742 int add(T *object) { return Array::add((void *)object); }
743 T *get(int index) const { return (T*)Array::get(index); }
744 T *first() const { return get(0); }
745 T *last() const { return get(size() - 1); }
746 int indexOf(T *object) const { return Array::indexOf((void *)object); }
747 bool contains(T *object) const { return indexOf(object) >= 0; }
748 void set(int index, T *object) { Array::set(index, (void *)object); }
749 void replace(int index, T *object) { Array::replace(index, (void *)object); }
750 void insert(int index, T *object) { Array::insert(index, (void *)object); }
751 void remove(int index) { Array::remove(index); }
752 void remove(T *object) { Array::remove((void *)object); }
753 void unlink(int index) { Array::unlink(index); }
754 void unlink(T *object) { Array::unlink((void *)object); }
755
756 void sort(int (*cb)(const T **, const T **)) { Array::sort((int (*)(const void *, const void *))cb); }
757 T *find(const T *key, int (*cb)(const T **, const T **)) const
758 {
759 T **result = (T **)Array::find(&key, (int (*)(const void *, const void *))cb);
760 return (result != NULL) ? *result : NULL;
761 }
762
763 Iterator<T> *iterator() { return new Iterator<T>(new ArrayIterator(this)); }
764 };
765
766 /**
767 * Template class for dynamic array which holds references to objects with inaccessible destructors
768 */
769 template <class T> class ObjectRefArray : public Array
770 {
771 private:
772 static void destructor(void *object) { }
773
774 public:
775 ObjectRefArray(int initial = 0, int grow = 16) : Array(initial, grow, false) { m_objectDestructor = destructor; }
776 virtual ~ObjectRefArray() { }
777
778 int add(T *object) { return Array::add((void *)object); }
779 T *get(int index) const { return (T*)Array::get(index); }
780 int indexOf(T *object) const { return Array::indexOf((void *)object); }
781 bool contains(T *object) const { return indexOf(object) >= 0; }
782 void set(int index, T *object) { Array::set(index, (void *)object); }
783 void replace(int index, T *object) { Array::replace(index, (void *)object); }
784 void remove(int index) { Array::remove(index); }
785 void remove(T *object) { Array::remove((void *)object); }
786 void unlink(int index) { Array::unlink(index); }
787 void unlink(T *object) { Array::unlink((void *)object); }
788
789 Iterator<T> *iterator() { return new Iterator<T>(new ArrayIterator(this)); }
790 };
791
792 /**
793 * Template class for dynamic array which holds scalar values
794 */
795 template <class T> class IntegerArray : public Array
796 {
797 private:
798 static void destructor(void *element) { }
799
800 public:
801 IntegerArray(int initial = 0, int grow = 16) : Array(NULL, initial, grow, sizeof(T)) { m_objectDestructor = destructor; m_storePointers = (sizeof(T) == sizeof(void *)); }
802 IntegerArray(const IntegerArray<T> *src) : Array(src) { }
803 virtual ~IntegerArray() { }
804
805 int add(T value) { return Array::add(m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
806 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; }
807 int indexOf(T value) const { return Array::indexOf(m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
808 bool contains(T value) const { return indexOf(value) >= 0; }
809 void set(int index, T value) { Array::set(index, m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
810 void replace(int index, T value) { Array::replace(index, m_storePointers ? CAST_TO_POINTER(value, void *) : &value); }
811
812 T *getBuffer() const { return (T*)__getBuffer(); }
813
814 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; }
815 };
816
817 /**
818 * Auxilliary class to hold dynamically allocated array of structures
819 */
820 template <class T> class StructArray : public Array
821 {
822 private:
823 static void destructor(void *element) { }
824
825 public:
826 StructArray(int initial = 0, int grow = 16) : Array(NULL, initial, grow, sizeof(T)) { m_objectDestructor = destructor; }
827 StructArray(T *data, int size) : Array(data, size, 16, sizeof(T)) { m_objectDestructor = destructor; }
828 StructArray(const StructArray<T> *src) : Array(src) { }
829 virtual ~StructArray() { }
830
831 int add(T *element) { return Array::add((void *)element); }
832 T *get(int index) const { return (T*)Array::get(index); }
833 int indexOf(T *element) const { return Array::indexOf((void *)element); }
834 bool contains(T *element) const { return indexOf(element) >= 0; }
835 void set(int index, T *element) { Array::set(index, (void *)element); }
836 void replace(int index, T *element) { Array::replace(index, (void *)element); }
837 void remove(int index) { Array::remove(index); }
838 void remove(T *element) { Array::remove((void *)element); }
839 void unlink(int index) { Array::unlink(index); }
840 void unlink(T *element) { Array::unlink((void *)element); }
841
842 T *getBuffer() const { return (T*)__getBuffer(); }
843 };
844
845 /**
846 * Entry of string map (internal)
847 */
848 struct StringMapEntry;
849
850 /**
851 * Key/value pair
852 */
853 struct KeyValuePair
854 {
855 const TCHAR *key;
856 const void *value;
857 };
858
859 /**
860 * String maps base class
861 */
862 class LIBNETXMS_EXPORTABLE StringMapBase
863 {
864 protected:
865 StringMapEntry *m_data;
866 bool m_objectOwner;
867 bool m_ignoreCase;
868 void (*m_objectDestructor)(void *);
869
870 StringMapEntry *find(const TCHAR *key) const;
871 void setObject(TCHAR *key, void *value, bool keyPreAlloc);
872 void *getObject(const TCHAR *key) const;
873 void destroyObject(void *object) { if (object != NULL) m_objectDestructor(object); }
874
875 public:
876 StringMapBase(bool objectOwner);
877 virtual ~StringMapBase();
878
879 void setOwner(bool owner) { m_objectOwner = owner; }
880 void setIgnoreCase(bool ignore);
881
882 void remove(const TCHAR *key);
883 void clear();
884 void filterElements(bool (*filter)(const TCHAR *, const void *, void *), void *userData);
885
886 int size() const;
887 bool contains(const TCHAR *key) const { return find(key) != NULL; }
888
889 EnumerationCallbackResult forEach(EnumerationCallbackResult (*cb)(const TCHAR *, const void *, void *), void *userData) const;
890 const void *findElement(bool (*comparator)(const TCHAR *, const void *, void *), void *userData) const;
891
892 StructArray<KeyValuePair> *toArray() const;
893 StringList *keys() const;
894 };
895
896 /**
897 * NXCP message class
898 */
899 class NXCPMessage;
900
901 /**
902 * String map class
903 */
904 class LIBNETXMS_EXPORTABLE StringMap : public StringMapBase
905 {
906 public:
907 StringMap() : StringMapBase(true) { }
908 StringMap(const StringMap &src);
909 virtual ~StringMap();
910
911 StringMap& operator =(const StringMap &src);
912
913 void set(const TCHAR *key, const TCHAR *value) { setObject((TCHAR *)key, _tcsdup(value), false); }
914 void setPreallocated(TCHAR *key, TCHAR *value) { setObject(key, value, true); }
915 void set(const TCHAR *key, UINT32 value);
916
917 void addAll(const StringMap *src);
918
919 const TCHAR *get(const TCHAR *key) const { return (const TCHAR *)getObject(key); }
920 INT32 getInt32(const TCHAR *key, INT32 defaultValue) const;
921 UINT32 getUInt32(const TCHAR *key, UINT32 defaultValue) const;
922 INT64 getInt64(const TCHAR *key, INT64 defaultValue) const;
923 UINT64 getUInt64(const TCHAR *key, UINT64 defaultValue) const;
924 double getDouble(const TCHAR *key, double defaultValue) const;
925 bool getBoolean(const TCHAR *key, bool defaultValue) const;
926
927 void fillMessage(NXCPMessage *msg, UINT32 sizeFieldId, UINT32 baseFieldId) const;
928 void loadMessage(const NXCPMessage *msg, UINT32 sizeFieldId, UINT32 baseFieldId);
929
930 json_t *toJson() const;
931 };
932
933 /**
934 * String map template for holding objects as values
935 */
936 template <class T> class StringObjectMap : public StringMapBase
937 {
938 private:
939 static void destructor(void *object) { delete (T*)object; }
940
941 public:
942 StringObjectMap(bool objectOwner) : StringMapBase(objectOwner) { m_objectDestructor = destructor; }
943
944 void set(const TCHAR *key, T *object) { setObject((TCHAR *)key, (void *)object, false); }
945 void setPreallocated(TCHAR *key, T *object) { setObject((TCHAR *)key, (void *)object, true); }
946 T *get(const TCHAR *key) const { return (T*)getObject(key); }
947 };
948
949 /**
950 * String list class
951 */
952 class LIBNETXMS_EXPORTABLE StringList
953 {
954 private:
955 int m_count;
956 int m_allocated;
957 TCHAR **m_values;
958
959 public:
960 StringList();
961 StringList(const StringList *src);
962 StringList(const TCHAR *src, const TCHAR *separator);
963 ~StringList();
964
965 void add(const TCHAR *value);
966 void addPreallocated(TCHAR *value);
967 void add(INT32 value);
968 void add(UINT32 value);
969 void add(INT64 value);
970 void add(UINT64 value);
971 void add(double value);
972 void replace(int index, const TCHAR *value);
973 void addOrReplace(int index, const TCHAR *value);
974 void addOrReplacePreallocated(int index, TCHAR *value);
975 #ifdef UNICODE
976 void addMBString(const char *value) { addPreallocated(WideStringFromMBString(value)); }
977 #else
978 void addMBString(const char *value) { add(value); }
979 #endif
980 void addAll(const StringList *src);
981 void merge(const StringList *src, bool matchCase);
982 void splitAndAdd(const TCHAR *src, const TCHAR *separator);
983 void remove(int index);
984 void clear();
985
986 void sort(bool ascending = true, bool caseSensitive = false);
987
988 int size() const { return m_count; }
989 bool isEmpty() const { return m_count == 0; }
990 const TCHAR *get(int index) const { return ((index >=0) && (index < m_count)) ? m_values[index] : NULL; }
991 int indexOf(const TCHAR *value) const;
992 bool contains(const TCHAR *value) const { return indexOf(value) != -1; }
993 int indexOfIgnoreCase(const TCHAR *value) const;
994 bool containsIgnoreCase(const TCHAR *value) const { return indexOfIgnoreCase(value) != -1; }
995 TCHAR *join(const TCHAR *separator);
996
997 void fillMessage(NXCPMessage *msg, UINT32 baseId, UINT32 countId);
998 json_t *toJson() const;
999 };
1000
1001 /**
1002 * Entry of string set
1003 */
1004 struct StringSetEntry;
1005
1006 /**
1007 * NXCP message
1008 */
1009 class NXCPMessage;
1010
1011 /**
1012 * String set
1013 */
1014 class StringSet;
1015
1016 /**
1017 * String set iterator
1018 */
1019 class LIBNETXMS_EXPORTABLE StringSetIterator : public AbstractIterator
1020 {
1021 private:
1022 StringSet *m_stringSet;
1023 StringSetEntry *m_curr;
1024 StringSetEntry *m_next;
1025
1026 public:
1027 StringSetIterator(StringSet *stringSet);
1028
1029 virtual bool hasNext();
1030 virtual void *next();
1031 virtual void remove();
1032 };
1033
1034 /**
1035 * String set class
1036 */
1037 class LIBNETXMS_EXPORTABLE StringSet
1038 {
1039 friend class StringSetIterator;
1040
1041 private:
1042 StringSetEntry *m_data;
1043
1044 public:
1045 StringSet();
1046 ~StringSet();
1047
1048 void add(const TCHAR *str);
1049 void addPreallocated(TCHAR *str);
1050 void remove(const TCHAR *str);
1051 void clear();
1052
1053 int size() const;
1054 bool contains(const TCHAR *str) const;
1055 bool equals(const StringSet *s) const;
1056
1057 void addAll(StringSet *src);
1058 void addAll(TCHAR **strings, int count);
1059 void splitAndAdd(const TCHAR *src, const TCHAR *separator);
1060 void addAllPreallocated(TCHAR **strings, int count);
1061
1062 void forEach(bool (*cb)(const TCHAR *, void *), void *userData) const;
1063
1064 void fillMessage(NXCPMessage *msg, UINT32 baseId, UINT32 countId) const;
1065 void addAllFromMessage(const NXCPMessage *msg, UINT32 baseId, UINT32 countId, bool clearBeforeAdd, bool toUppercase);
1066
1067 String join(const TCHAR *separator);
1068
1069 Iterator<const TCHAR> *iterator() { return new Iterator<const TCHAR>(new StringSetIterator(this)); }
1070 };
1071
1072 /**
1073 * Opaque hash map entry structure
1074 */
1075 struct HashMapEntry;
1076
1077 /**
1078 * Hash map base class (for fixed size non-pointer keys)
1079 */
1080 class LIBNETXMS_EXPORTABLE HashMapBase
1081 {
1082 friend class HashMapIterator;
1083
1084 private:
1085 HashMapEntry *m_data;
1086 bool m_objectOwner;
1087 unsigned int m_keylen;
1088
1089 HashMapEntry *find(const void *key) const;
1090 void destroyObject(void *object) { if (object != NULL) m_objectDestructor(object); }
1091
1092 protected:
1093 void (*m_objectDestructor)(void *);
1094
1095 HashMapBase(bool objectOwner, unsigned int keylen);
1096
1097 void *_get(const void *key) const;
1098 void _set(const void *key, void *value);
1099 void _remove(const void *key);
1100
1101 bool _contains(const void *key) const { return find(key) != NULL; }
1102
1103 public:
1104 virtual ~HashMapBase();
1105
1106 void setOwner(bool owner) { m_objectOwner = owner; }
1107 void clear();
1108
1109 int size() const;
1110
1111 EnumerationCallbackResult forEach(EnumerationCallbackResult (*cb)(const void *, const void *, void *), void *userData) const;
1112 const void *findElement(bool (*comparator)(const void *, const void *, void *), void *userData) const;
1113 };
1114
1115 /**
1116 * Hash map iterator
1117 */
1118 class LIBNETXMS_EXPORTABLE HashMapIterator : public AbstractIterator
1119 {
1120 private:
1121 HashMapBase *m_hashMap;
1122 HashMapEntry *m_curr;
1123 HashMapEntry *m_next;
1124
1125 public:
1126 HashMapIterator(HashMapBase *hashMap);
1127
1128 virtual bool hasNext();
1129 virtual void *next();
1130 virtual void remove();
1131 };
1132
1133 /**
1134 * Hash map template for holding objects as values
1135 */
1136 template <class K, class V> class HashMap : public HashMapBase
1137 {
1138 private:
1139 static void destructor(void *object) { delete (V*)object; }
1140
1141 public:
1142 HashMap(bool objectOwner = false) : HashMapBase(objectOwner, sizeof(K)) { m_objectDestructor = destructor; }
1143
1144 V *get(const K& key) { return (V*)_get(&key); }
1145 void set(const K& key, V *value) { _set(&key, (void *)value); }
1146 void remove(const K& key) { _remove(&key); }
1147 bool contains(const K& key) { return _contains(&key); }
1148
1149 Iterator<V> *iterator() { return new Iterator<V>(new HashMapIterator(this)); }
1150 };
1151
1152 /**
1153 * Hash map template for holding reference counting objects as values
1154 */
1155 template <class K, class V> class RefCountHashMap : public HashMapBase
1156 {
1157 private:
1158 static void destructor(void *object) { if (object != NULL) ((V*)object)->decRefCount(); }
1159
1160 public:
1161 RefCountHashMap(bool objectOwner = false) : HashMapBase(objectOwner, sizeof(K)) { m_objectDestructor = destructor; }
1162
1163 V *get(const K& key) { V *v = (V*)_get(&key); if (v != NULL) v->incRefCount(); return v; }
1164 V *peek(const K& key) { return (V*)_get(&key); }
1165 void set(const K& key, V *value) { if (value != NULL) value->incRefCount(); _set(&key, (void *)value); }
1166 void remove(const K& key) { _remove(&key); }
1167 bool contains(const K& key) { return _contains(&key); }
1168
1169 Iterator<V> *iterator() { return new Iterator<V>(new HashMapIterator(this)); }
1170 };
1171
1172 /**
1173 * Ring buffer
1174 */
1175 class LIBNETXMS_EXPORTABLE RingBuffer
1176 {
1177 private:
1178 BYTE *m_data;
1179 size_t m_size;
1180 size_t m_allocated;
1181 size_t m_allocationStep;
1182 size_t m_readPos;
1183 size_t m_writePos;
1184
1185 public:
1186 RingBuffer(size_t initial = 8192, size_t allocationStep = 8192);
1187 ~RingBuffer();
1188
1189 void write(const BYTE *data, size_t dataSize);
1190 size_t read(BYTE *buffer, size_t bufferSize);
1191
1192 size_t size() const { return m_size; }
1193 bool isEmpty() const { return m_size == 0; }
1194 };
1195
1196 /**
1197 * Byte stream
1198 */
1199 class LIBNETXMS_EXPORTABLE ByteStream
1200 {
1201 private:
1202 BYTE *m_data;
1203 size_t m_size;
1204 size_t m_allocated;
1205 size_t m_pos;
1206 size_t m_allocationStep;
1207
1208 public:
1209 ByteStream(size_t initial = 8192);
1210 ByteStream(const void *data, size_t size);
1211 virtual ~ByteStream();
1212
1213 static ByteStream *load(const TCHAR *file);
1214
1215 void seek(size_t pos) { if (pos <= m_size) m_pos = pos; }
1216 size_t pos() { return m_pos; }
1217 size_t size() { return m_size; }
1218 bool eos() { return m_pos == m_size; }
1219
1220 void setAllocationStep(size_t s) { m_allocationStep = s; }
1221
1222 const BYTE *buffer(size_t *size) { *size = m_size; return m_data; }
1223
1224 void write(const void *data, size_t size);
1225 void write(char c) { write(&c, 1); }
1226 void write(BYTE b) { write(&b, 1); }
1227 void write(INT16 n) { UINT16 x = htons((UINT16)n); write(&x, 2); }
1228 void write(UINT16 n) { UINT16 x = htons(n); write(&x, 2); }
1229 void write(INT32 n) { UINT32 x = htonl((UINT32)n); write(&x, 4); }
1230 void write(UINT32 n) { UINT32 x = htonl(n); write(&x, 4); }
1231 void write(INT64 n) { UINT64 x = htonq((UINT64)n); write(&x, 8); }
1232 void write(UINT64 n) { UINT64 x = htonq(n); write(&x, 8); }
1233 void write(double n) { double x = htond(n); write(&x, 8); }
1234 void writeString(const TCHAR *s);
1235
1236 size_t read(void *buffer, size_t count);
1237 char readChar() { return !eos() ? (char)m_data[m_pos++] : 0; }
1238 BYTE readByte() { return !eos() ? m_data[m_pos++] : 0; }
1239 INT16 readInt16();
1240 UINT16 readUInt16();
1241 INT32 readInt32();
1242 UINT32 readUInt32();
1243 INT64 readInt64();
1244 UINT64 readUInt64();
1245 double readDouble();
1246 TCHAR *readString();
1247
1248 bool save(int f);
1249 };
1250
1251 /**
1252 * Auxilliary class for objects which counts references and
1253 * destroys itself wheren reference count falls to 0
1254 */
1255 class LIBNETXMS_EXPORTABLE RefCountObject
1256 {
1257 private:
1258 VolatileCounter m_refCount;
1259
1260 protected:
1261 virtual ~RefCountObject();
1262
1263 public:
1264 RefCountObject()
1265 {
1266 m_refCount = 1;
1267 }
1268
1269 void incRefCount()
1270 {
1271 InterlockedIncrement(&m_refCount);
1272 }
1273
1274 void decRefCount()
1275 {
1276 if (InterlockedDecrement(&m_refCount) == 0)
1277 delete this;
1278 }
1279 };
1280
1281 class NXCPMessage;
1282
1283 /**
1284 * Table column definition
1285 */
1286 class LIBNETXMS_EXPORTABLE TableColumnDefinition
1287 {
1288 private:
1289 TCHAR *m_name;
1290 TCHAR *m_displayName;
1291 INT32 m_dataType;
1292 bool m_instanceColumn;
1293
1294 public:
1295 TableColumnDefinition(const TCHAR *name, const TCHAR *displayName, INT32 dataType, bool isInstance);
1296 TableColumnDefinition(const NXCPMessage *msg, UINT32 baseId);
1297 TableColumnDefinition(const TableColumnDefinition *src);
1298 ~TableColumnDefinition();
1299
1300 void fillMessage(NXCPMessage *msg, UINT32 baseId) const;
1301
1302 const TCHAR *getName() const { return m_name; }
1303 const TCHAR *getDisplayName() const { return m_displayName; }
1304 INT32 getDataType() const { return m_dataType; }
1305 bool isInstanceColumn() const { return m_instanceColumn; }
1306
1307 void setDataType(INT32 type) { m_dataType = type; }
1308 void setInstanceColumn(bool isInstance) { m_instanceColumn = isInstance; }
1309 void setDisplayName(const TCHAR *name) { safe_free(m_displayName); m_displayName = _tcsdup(CHECK_NULL_EX(name)); }
1310 };
1311
1312 /**
1313 * Table cell
1314 */
1315 class TableCell
1316 {
1317 private:
1318 TCHAR *m_value;
1319 int m_status;
1320 UINT32 m_objectId;
1321
1322 public:
1323 TableCell() { m_value = NULL; m_status = -1; m_objectId = 0; }
1324 TableCell(const TCHAR *value) { m_value = _tcsdup_ex(value); m_status = -1; m_objectId = 0; }
1325 TableCell(const TCHAR *value, int status) { m_value = _tcsdup_ex(value); m_status = status; m_objectId = 0; }
1326 TableCell(TableCell *src) { m_value = _tcsdup_ex(src->m_value); m_status = src->m_status; m_objectId = src->m_objectId; }
1327 ~TableCell() { safe_free(m_value); }
1328
1329 void set(const TCHAR *value, int status, UINT32 objectId) { safe_free(m_value); m_value = _tcsdup_ex(value); m_status = status; m_objectId = objectId; }
1330 void setPreallocated(TCHAR *value, int status, UINT32 objectId) { safe_free(m_value); m_value = value; m_status = status; m_objectId = objectId; }
1331
1332 const TCHAR *getValue() const { return m_value; }
1333 void setValue(const TCHAR *value) { safe_free(m_value); m_value = _tcsdup_ex(value); }
1334 void setPreallocatedValue(TCHAR *value) { free(m_value); m_value = value; }
1335
1336 int getStatus() const { return m_status; }
1337 void setStatus(int status) { m_status = status; }
1338
1339 int getObjectId() const { return m_objectId; }
1340 void setObjectId(UINT32 id) { m_objectId = id; }
1341 };
1342
1343 /**
1344 * Table row
1345 */
1346 class TableRow
1347 {
1348 private:
1349 ObjectArray<TableCell> *m_cells;
1350 UINT32 m_objectId;
1351 int m_baseRow;
1352
1353 public:
1354 TableRow(int columnCount);
1355 TableRow(TableRow *src);
1356 ~TableRow() { delete m_cells; }
1357
1358 void addColumn() { m_cells->add(new TableCell); }
1359 void deleteColumn(int index) { m_cells->remove(index); }
1360
1361 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); }
1362 void setPreallocated(int index, TCHAR *value, int status, UINT32 objectId) { TableCell *c = m_cells->get(index); if (c != NULL) c->setPreallocated(value, status, objectId); }
1363
1364 void setValue(int index, const TCHAR *value) { TableCell *c = m_cells->get(index); if (c != NULL) c->setValue(value); }
1365 void setPreallocatedValue(int index, TCHAR *value) { TableCell *c = m_cells->get(index); if (c != NULL) c->setPreallocatedValue(value); else free(value); }
1366
1367 void setStatus(int index, int status) { TableCell *c = m_cells->get(index); if (c != NULL) c->setStatus(status); }
1368
1369 const TCHAR *getValue(int index) const { const TableCell *c = m_cells->get(index); return (c != NULL) ? c->getValue() : NULL; }
1370 int getStatus(int index) const { const TableCell *c = m_cells->get(index); return (c != NULL) ? c->getStatus() : -1; }
1371
1372 UINT32 getObjectId() const { return m_objectId; }
1373 void setObjectId(UINT32 id) { m_objectId = id; }
1374
1375 int getBaseRow() const { return m_baseRow; }
1376 void setBaseRow(int baseRow) { m_baseRow = baseRow; }
1377
1378 UINT32 getCellObjectId(int index) const { const TableCell *c = m_cells->get(index); return (c != NULL) ? c->getObjectId() : 0; }
1379 void setCellObjectId(int index, UINT32 id) { TableCell *c = m_cells->get(index); if (c != NULL) c->setObjectId(id); }
1380 };
1381
1382 /**
1383 * Class for table data storage
1384 */
1385 class LIBNETXMS_EXPORTABLE Table : public RefCountObject
1386 {
1387 private:
1388 ObjectArray<TableRow> *m_data;
1389 ObjectArray<TableColumnDefinition> *m_columns;
1390 TCHAR *m_title;
1391 int m_source;
1392 bool m_extendedFormat;
1393
1394 void createFromMessage(NXCPMessage *msg);
1395 void destroy();
1396 bool parseXML(const char *xml);
1397
1398 public:
1399 Table();
1400 Table(Table *src);
1401 Table(NXCPMessage *msg);
1402 virtual ~Table();
1403
1404 int fillMessage(NXCPMessage &msg, int offset, int rowLimit);
1405 void updateFromMessage(NXCPMessage *msg);
1406
1407 void addAll(Table *src);
1408 void copyRow(Table *src, int row);
1409
1410 int getNumRows() { return m_data->size(); }
1411 int getNumColumns() const { return m_columns->size(); }
1412 const TCHAR *getTitle() { return CHECK_NULL_EX(m_title); }
1413 int getSource() { return m_source; }
1414
1415 bool isExtendedFormat() { return m_extendedFormat; }
1416 void setExtendedFormat(bool ext) { m_extendedFormat = ext; }
1417
1418 const TCHAR *getColumnName(int col) const { return ((col >= 0) && (col < m_columns->size())) ? m_columns->get(col)->getName() : NULL; }
1419 INT32 getColumnDataType(int col) const { return ((col >= 0) && (col < m_columns->size())) ? m_columns->get(col)->getDataType() : 0; }
1420 const TableColumnDefinition *getColumnDefinition(int col) const { return m_columns->get(col); }
1421 int getColumnIndex(const TCHAR *name) const;
1422 ObjectArray<TableColumnDefinition> *getColumnDefinitions() { return m_columns; }
1423
1424 void setTitle(const TCHAR *title) { safe_free(m_title); m_title = _tcsdup_ex(title); }
1425 void setSource(int source) { m_source = source; }
1426 int addColumn(const TCHAR *name, INT32 dataType = 0, const TCHAR *displayName = NULL, bool isInstance = false);
1427 int addColumn(const TableColumnDefinition *d);
1428 void setColumnDataType(int col, INT32 dataType) { if ((col >= 0) && (col < m_columns->size())) m_columns->get(col)->setDataType(dataType); }
1429 int addRow();
1430
1431 void deleteRow(int row);
1432 void deleteColumn(int col);
1433
1434 void setAt(int nRow, int nCol, INT32 nData);
1435 void setAt(int nRow, int nCol, UINT32 dwData);
1436 void setAt(int nRow, int nCol, double dData);
1437 void setAt(int nRow, int nCol, INT64 nData);
1438 void setAt(int nRow, int nCol, UINT64 qwData);
1439 void setAt(int nRow, int nCol, const TCHAR *pszData);
1440 void setPreallocatedAt(int nRow, int nCol, TCHAR *pszData);
1441
1442 void set(int nCol, INT32 nData) { setAt(getNumRows() - 1, nCol, nData); }
1443 void set(int nCol, UINT32 dwData) { setAt(getNumRows() - 1, nCol, dwData); }
1444 void set(int nCol, double dData) { setAt(getNumRows() - 1, nCol, dData); }
1445 void set(int nCol, INT64 nData) { setAt(getNumRows() - 1, nCol, nData); }
1446 void set(int nCol, UINT64 qwData) { setAt(getNumRows() - 1, nCol, qwData); }
1447 void set(int nCol, const TCHAR *data) { setAt(getNumRows() - 1, nCol, data); }
1448 #ifdef UNICODE
1449 void set(int nCol, const char *data) { setPreallocatedAt(getNumRows() - 1, nCol, WideStringFromMBString(data)); }
1450 #else
1451 void set(int nCol, const WCHAR *data) { setPreallocatedAt(getNumRows() - 1, nCol, MBStringFromWideString(data)); }
1452 #endif
1453 void setPreallocated(int nCol, TCHAR *data) { setPreallocatedAt(getNumRows() - 1, nCol, data); }
1454
1455 void setStatusAt(int row, int col, int status);
1456 void setStatus(int col, int status) { setStatusAt(getNumRows() - 1, col, status); }
1457
1458 const TCHAR *getAsString(int nRow, int nCol, const TCHAR *defaultValue = NULL);
1459 INT32 getAsInt(int nRow, int nCol);
1460 UINT32 getAsUInt(int nRow, int nCol);
1461 INT64 getAsInt64(int nRow, int nCol);
1462 UINT64 getAsUInt64(int nRow, int nCol);
1463 double getAsDouble(int nRow, int nCol);
1464
1465 int getStatus(int nRow, int nCol);
1466
1467 void buildInstanceString(int row, TCHAR *buffer, size_t bufLen);
1468 int findRowByInstance(const TCHAR *instance);
1469
1470 UINT32 getObjectId(int row) const { const TableRow *r = m_data->get(row); return (r != NULL) ? r->getObjectId() : 0; }
1471 void setObjectIdAt(int row, UINT32 id) { TableRow *r = m_data->get(row); if (r != NULL) r->setObjectId(id); }
1472 void setObjectId(UINT32 id) { setObjectIdAt(getNumRows() - 1, id); }
1473
1474 void setCellObjectIdAt(int row, int col, UINT32 objectId);
1475 void setCellObjectId(int col, UINT32 objectId) { setCellObjectIdAt(getNumRows() - 1, col, objectId); }
1476 UINT32 getCellObjectId(int row, int col) const { const TableRow *r = m_data->get(row); return (r != NULL) ? r->getCellObjectId(col) : 0; }
1477
1478 void setBaseRowAt(int row, int baseRow);
1479 void setBaseRow(int baseRow) { setBaseRowAt(getNumRows() - 1, baseRow); }
1480 int getBaseRow(int row) const { const TableRow *r = m_data->get(row); return (r != NULL) ? r->getBaseRow() : 0; }
1481
1482 static Table *createFromXML(const char *xml);
1483 TCHAR *createXML();
1484
1485 static Table *createFromPackedXML(const char *packedXml);
1486 char *createPackedXML();
1487 };
1488
1489 /**
1490 * Create JSON string with null check
1491 */
1492 inline json_t *json_string_a(const char *s)
1493 {
1494 return (s != NULL) ? json_string(s) : json_null();
1495 }
1496
1497 /**
1498 * Create JSON string from wide character string
1499 */
1500 inline json_t *json_string_w(const WCHAR *s)
1501 {
1502 if (s == NULL)
1503 return json_null();
1504 char *us = UTF8StringFromWideString(s);
1505 json_t *js = json_string(us);
1506 free(us);
1507 return js;
1508 }
1509
1510 #ifdef UNICODE
1511 #define json_string_t json_string_w
1512 #else
1513 #define json_string_t json_string_a
1514 #endif
1515
1516 /**
1517 * Create JSON array from integer array
1518 */
1519 template<typename T> json_t *json_integer_array(const T *values, size_t size)
1520 {
1521 json_t *a = json_array();
1522 for(size_t i = 0; i < size; i++)
1523 json_array_append_new(a, json_integer(values[i]));
1524 return a;
1525 }
1526
1527 /**
1528 * Serialize ObjectArray as JSON
1529 */
1530 template<typename T> json_t *json_object_array(ObjectArray<T> *a)
1531 {
1532 json_t *root = json_array();
1533 if (a != NULL)
1534 {
1535 for(int i = 0; i < a->size(); i++)
1536 {
1537 T *e = a->get(i);
1538 if (e != NULL)
1539 json_array_append_new(root, e->toJson());
1540 }
1541 }
1542 return root;
1543 }
1544
1545 /**
1546 * sockaddr buffer
1547 */
1548 union SockAddrBuffer
1549 {
1550 struct sockaddr_in sa4;
1551 #ifdef WITH_IPV6
1552 struct sockaddr_in6 sa6;
1553 #endif
1554 };
1555
1556 /**
1557 * sockaddr length calculation
1558 */
1559 #undef SA_LEN
1560 #ifdef WITH_IPV6
1561 #define SA_LEN(sa) (((sa)->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))
1562 #else
1563 #define SA_LEN(sa) sizeof(struct sockaddr_in)
1564 #endif
1565
1566 /**
1567 * Get port number from SockAddrBuffer
1568 */
1569 #ifdef WITH_IPV6
1570 #define SA_PORT(sa) ((((struct sockaddr *)sa)->sa_family == AF_INET) ? ((struct sockaddr_in *)sa)->sin_port : ((struct sockaddr_in6 *)sa)->sin6_port)
1571 #else
1572 #define SA_PORT(sa) (((struct sockaddr_in *)sa)->sin_port)
1573 #endif
1574
1575 /**
1576 * Compare addresses in sockaddr
1577 */
1578 inline bool SocketAddressEquals(struct sockaddr *a1, struct sockaddr *a2)
1579 {
1580 if (a1->sa_family != a2->sa_family)
1581 return false;
1582 if (a1->sa_family == AF_INET)
1583 return ((struct sockaddr_in *)a1)->sin_addr.s_addr == ((struct sockaddr_in *)a2)->sin_addr.s_addr;
1584 #ifdef WITH_IPV6
1585 if (a1->sa_family == AF_INET6)
1586 return !memcmp(((struct sockaddr_in6 *)a1)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)a2)->sin6_addr.s6_addr, 16);
1587 #endif
1588 return false;
1589 }
1590
1591 enum MacAddressNotation
1592 {
1593 MAC_ADDR_FLAT_STRING = 0,
1594 MAC_ADDR_COLON_SEPARATED = 1,
1595 MAC_ADDR_BYTEPAIR_COLON_SEPARATED = 2,
1596 MAC_ADDR_HYPHEN_SEPARATED = 3,
1597 MAC_ADDR_DOT_SEPARATED = 4,
1598 MAC_ADDR_BYTEPAIR_DOT_SEPARATED = 5
1599 };
1600
1601 /**
1602 * MAC address
1603 */
1604 class LIBNETXMS_EXPORTABLE MacAddress
1605 {
1606 private:
1607 BYTE m_value[16];
1608 size_t m_length;
1609
1610 TCHAR *toStringInternal(TCHAR *buffer, const TCHAR separator, bool bytePair = false) const;
1611 TCHAR *toStringInternal3(TCHAR *buffer, const TCHAR separator) const;
1612
1613 public:
1614 MacAddress() { m_length = 0; memset(m_value, 0, 16); }
1615 MacAddress(const BYTE *value, size_t length) { m_length = min(length, 16); memcpy(m_value, value, m_length); }
1616 MacAddress(const MacAddress& src) { memcpy(m_value, src.m_value, src.m_length); m_length = src.m_length; }
1617
1618 static MacAddress parse(const char *str);
1619 static MacAddress parse(const WCHAR *str);
1620
1621 const BYTE *value() const { return m_value; }
1622 size_t length() const { return m_length; }
1623
1624 bool isMulticast() const;
1625 bool isBroadcast() const;
1626 bool equals(const MacAddress &a) const;
1627
1628 TCHAR *toString(TCHAR *buffer, MacAddressNotation notation = MAC_ADDR_COLON_SEPARATED) const;
1629 String toString(MacAddressNotation notation = MAC_ADDR_COLON_SEPARATED) const;
1630 };
1631
1632 /**
1633 * IP address
1634 */
1635 class LIBNETXMS_EXPORTABLE InetAddress
1636 {
1637 private:
1638 short m_maskBits;
1639 short m_family;
1640 union
1641 {
1642 UINT32 v4;
1643 BYTE v6[16];
1644 } m_addr;
1645
1646 public:
1647 InetAddress();
1648 InetAddress(UINT32 addr);
1649 InetAddress(UINT32 addr, UINT32 mask);
1650 InetAddress(const BYTE *addr, int maskBits = 128);
1651
1652 bool isAnyLocal() const;
1653 bool isLoopback() const;
1654 bool isMulticast() const;
1655 bool isBroadcast() const;
1656 bool isLinkLocal() const;
1657 bool isValid() const { return m_family != AF_UNSPEC; }
1658 bool isValidUnicast() const { return isValid() && !isAnyLocal() && !isLoopback() && !isMulticast() && !isBroadcast() && !isLinkLocal(); }
1659
1660 int getFamily() const { return m_family; }
1661 UINT32 getAddressV4() const { return (m_family == AF_INET) ? m_addr.v4 : 0; }
1662 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"; }
1663
1664 bool contain(const InetAddress &a) const;
1665 bool sameSubnet(const InetAddress &a) const;
1666 bool equals(const InetAddress &a) const;
1667 int compareTo(const InetAddress &a) const;
1668
1669 void setMaskBits(int m) { m_maskBits = m; }
1670 int getMaskBits() const { return m_maskBits; }
1671 int getHostBits() const { return (m_family == AF_INET) ? (32 - m_maskBits) : (128 - m_maskBits); }
1672
1673 InetAddress getSubnetAddress() const;
1674 InetAddress getSubnetBroadcast() const;
1675 bool isSubnetBroadcast(int maskBits) const;
1676
1677 String toString() const;
1678 TCHAR *toString(TCHAR *buffer) const;
1679 #ifdef UNICODE
1680 char *toStringA(char *buffer) const;
1681 #else
1682 char *toStringA(char *buffer) const { return toString(buffer); }
1683 #endif
1684
1685 json_t *toJson() const;
1686
1687 BYTE *buildHashKey(BYTE *key) const;
1688
1689 TCHAR *getHostByAddr(TCHAR *buffer, size_t buflen) const;
1690
1691 struct sockaddr *fillSockAddr(SockAddrBuffer *buffer, UINT16 port = 0) const;
1692
1693 static InetAddress resolveHostName(const WCHAR *hostname, int af = AF_INET);
1694 static InetAddress resolveHostName(const char *hostname, int af = AF_INET);
1695 static InetAddress parse(const WCHAR *str);
1696 static InetAddress parse(const char *str);
1697 static InetAddress createFromSockaddr(struct sockaddr *s);
1698
1699 static const InetAddress INVALID;
1700 static const InetAddress LOOPBACK;
1701 };
1702
1703 /**
1704 * IP address list
1705 */
1706 class LIBNETXMS_EXPORTABLE InetAddressList
1707 {
1708 private:
1709 ObjectArray<InetAddress> *m_list;
1710
1711 int indexOf(const InetAddress& addr) const;
1712
1713 public:
1714 InetAddressList();
1715 ~InetAddressList();
1716
1717 void add(const InetAddress& addr);
1718 void add(const InetAddressList& addrList);
1719 void replace(const InetAddress& addr);
1720 void remove(const InetAddress& addr);
1721 void clear() { m_list->clear(); }
1722 const InetAddress& get(int index) const { const InetAddress *a = m_list->get(index); return (a != NULL) ? *a : InetAddress::INVALID; }
1723
1724 int size() const { return m_list->size(); }
1725 bool hasAddress(const InetAddress& addr) const { return indexOf(addr) != -1; }
1726 const InetAddress& findAddress(const InetAddress& addr) const { int idx = indexOf(addr); return (idx != -1) ? *m_list->get(idx) : InetAddress::INVALID; }
1727 const InetAddress& findSameSubnetAddress(const InetAddress& addr) const;
1728 const InetAddress& getFirstUnicastAddress() const;
1729 const InetAddress& getFirstUnicastAddressV4() const;
1730 bool hasValidUnicastAddress() const { return getFirstUnicastAddress().isValid(); }
1731 bool isLoopbackOnly() const;
1732
1733 const ObjectArray<InetAddress> *getList() const { return m_list; }
1734
1735 void fillMessage(NXCPMessage *msg, UINT32 sizeFieldId, UINT32 baseFieldId) const;
1736
1737 json_t *toJson() const { return json_object_array(m_list); }
1738 };
1739
1740 /**
1741 * Network connection
1742 */
1743 class LIBNETXMS_EXPORTABLE SocketConnection
1744 {
1745 protected:
1746 SOCKET m_socket;
1747 char m_data[4096];
1748 int m_dataPos;
1749
1750 public:
1751 SocketConnection();
1752 virtual ~SocketConnection();
1753
1754 bool connectTCP(const TCHAR *hostName, WORD port, UINT32 timeout);
1755 bool connectTCP(const InetAddress& ip, WORD port, UINT32 timeout);
1756 void disconnect();
1757
1758 bool canRead(UINT32 timeout);
1759 virtual int read(char *pBuff, int nSize, UINT32 timeout = INFINITE);
1760 bool waitForText(const char *text, int timeout);
1761
1762 int write(const char *pBuff, int nSize);
1763 bool writeLine(const char *line);
1764
1765 static SocketConnection *createTCPConnection(const TCHAR *hostName, WORD port, UINT32 timeout);
1766 };
1767
1768 /**
1769 * Telnet connection - handles all telnet negotiation
1770 */
1771 class LIBNETXMS_EXPORTABLE TelnetConnection : public SocketConnection
1772 {
1773 protected:
1774 bool connectTCP(const TCHAR *hostName, WORD port, UINT32 timeout);
1775 bool connectTCP(const InetAddress& ip, WORD port, UINT32 timeout);
1776
1777 public:
1778 static TelnetConnection *createConnection(const TCHAR *hostName, WORD port, UINT32 timeout);
1779
1780 bool connect(const TCHAR *hostName, WORD port, UINT32 timeout);
1781 bool connect(const InetAddress& ip, WORD port, UINT32 timeout);
1782 virtual int read(char *pBuff, int nSize, UINT32 timeout = INFINITE);
1783 int readLine(char *buffer, int size, UINT32 timeout = INFINITE);
1784 };
1785
1786 /**
1787 * Postal address representation
1788 */
1789 class LIBNETXMS_EXPORTABLE PostalAddress
1790 {
1791 private:
1792 TCHAR *m_country;
1793 TCHAR *m_city;
1794 TCHAR *m_streetAddress;
1795 TCHAR *m_postcode;
1796
1797 public:
1798 PostalAddress();
1799 PostalAddress(const TCHAR *country, const TCHAR *city, const TCHAR *streetAddress, const TCHAR *postcode);
1800 ~PostalAddress();
1801
1802 const TCHAR *getCountry() const { return CHECK_NULL_EX(m_country); }
1803 const TCHAR *getCity() const { return CHECK_NULL_EX(m_city); }
1804 const TCHAR *getStreetAddress() const { return CHECK_NULL_EX(m_streetAddress); }
1805 const TCHAR *getPostCode() const { return CHECK_NULL_EX(m_postcode); }
1806
1807 json_t *toJson() const;
1808
1809 void setCountry(const TCHAR *country) { free(m_country); m_country = _tcsdup_ex(country); }
1810 void setCity(const TCHAR *city) { free(m_city); m_city = _tcsdup_ex(city); }
1811 void setStreetAddress(const TCHAR *streetAddress) { free(m_streetAddress); m_streetAddress = _tcsdup_ex(streetAddress); }
1812 void setPostCode(const TCHAR *postcode) { free(m_postcode); m_postcode = _tcsdup_ex(postcode); }
1813 };
1814
1815 /**
1816 * Max number of polled sockets
1817 */
1818 #define SOCKET_POLLER_MAX_SOCKETS 16
1819
1820 /**
1821 * Socket poller
1822 */
1823 class LIBNETXMS_EXPORTABLE SocketPoller
1824 {
1825 private:
1826 bool m_write;
1827 int m_count;
1828 #if HAVE_POLL
1829 struct pollfd m_sockets[SOCKET_POLLER_MAX_SOCKETS];
1830 #else
1831 fd_set m_sockets;
1832 #ifndef _WIN32
1833 SOCKET m_maxfd;
1834 #endif
1835 #endif
1836
1837 public:
1838 SocketPoller(bool write = false);
1839 ~SocketPoller();
1840
1841 bool add(SOCKET s);
1842 int poll(UINT32 timeout);
1843 bool isSet(SOCKET s);
1844 void reset();
1845 };
1846
1847 /**
1848 * Abstract communication channel
1849 */
1850 class LIBNETXMS_EXPORTABLE AbstractCommChannel : public RefCountObject
1851 {
1852 protected:
1853 virtual ~AbstractCommChannel();
1854
1855 public:
1856 AbstractCommChannel();
1857
1858 virtual int send(const void *data, size_t size, MUTEX mutex = INVALID_MUTEX_HANDLE) = 0;
1859 virtual int recv(void *buffer, size_t size, UINT32 timeout = INFINITE) = 0;
1860 virtual int poll(UINT32 timeout, bool write = false) = 0;
1861 virtual int shutdown() = 0;
1862 virtual void close() = 0;
1863 };
1864
1865 /**
1866 * Socket communication channel
1867 */
1868 class LIBNETXMS_EXPORTABLE SocketCommChannel : public AbstractCommChannel
1869 {
1870 private:
1871 SOCKET m_socket;
1872 bool m_owner;
1873
1874 protected:
1875 virtual ~SocketCommChannel();
1876
1877 public:
1878 SocketCommChannel(SOCKET socket, bool owner = true);
1879
1880 virtual int send(const void *data, size_t size, MUTEX mutex = INVALID_MUTEX_HANDLE);
1881 virtual int recv(void *buffer, size_t size, UINT32 timeout = INFINITE);
1882 virtual int poll(UINT32 timeout, bool write = false);
1883 virtual int shutdown();
1884 virtual void close();
1885 };
1886
1887 #endif /* __cplusplus */
1888
1889 /**
1890 * Configuration item template for configuration loader
1891 */
1892 typedef struct
1893 {
1894 TCHAR token[64];
1895 BYTE type;
1896 BYTE separator; // Separator character for lists
1897 WORD listElements; // Number of list elements, should be set to 0 before calling NxLoadConfig()
1898 UINT64 bufferSize; // Buffer size for strings or flag to be set for CT_BOOLEAN
1899 UINT32 bufferPos; // Should be set to 0
1900 void *buffer;
1901 void *overrideIndicator;
1902 } NX_CFG_TEMPLATE;
1903
1904 /**
1905 * Code translation structure
1906 */
1907 typedef struct __CODE_TO_TEXT
1908 {
1909 int code;
1910 const TCHAR *text;
1911 } CODE_TO_TEXT;
1912
1913 /**
1914 * getopt() prototype if needed
1915 */
1916 #if USE_BUNDLED_GETOPT
1917 #include <netxms_getopt.h>
1918 #endif
1919
1920 //
1921 // Structures for opendir() / readdir() / closedir()
1922 //
1923
1924 #ifdef _WIN32
1925
1926 #define DT_UNKNOWN 0
1927 #define DT_REG 1
1928 #define DT_DIR 2
1929
1930 typedef struct dirent
1931 {
1932 long d_ino; /* inode number (not used by MS-DOS) */
1933 unsigned char d_type; /* file type */
1934 int d_namlen; /* Name length */
1935 char d_name[MAX_PATH]; /* file name */
1936 } _DIRECT;
1937
1938 typedef struct _dir_struc
1939 {
1940 HANDLE handle;
1941 struct dirent dirstr; /* Directory structure to return */
1942 } DIR;
1943
1944 #ifdef UNICODE
1945
1946 typedef struct dirent_w
1947 {
1948 long d_ino; /* inode number (not used by MS-DOS) */
1949 unsigned char d_type; /* file type */
1950 int d_namlen; /* Name length */
1951 WCHAR d_name[MAX_PATH]; /* file name */
1952 } _DIRECTW;
1953
1954 typedef struct _dir_struc_w
1955 {
1956 HANDLE handle;
1957 struct dirent_w dirstr; /* Directory structure to return */
1958 } DIRW;
1959
1960 #define _TDIR DIRW
1961 #define _TDIRECT _DIRECTW
1962 #define _tdirent dirent_w
1963
1964 #else
1965
1966 #define _TDIR DIR
1967 #define _TDIRECT _DIRECT
1968 #define _tdirent dirent
1969
1970 #endif
1971
1972 #else /* not _WIN32 */
1973
1974 typedef struct dirent_w
1975 {
1976 long d_ino; /* inode number */
1977 #if HAVE_DIRENT_D_TYPE
1978 unsigned char d_type; /* file type */
1979 #endif
1980 WCHAR d_name[257]; /* file name */
1981 } _DIRECTW;
1982
1983 typedef struct _dir_struc_w
1984 {
1985 DIR *dir; /* Original non-unicode structure */
1986 struct dirent_w dirstr; /* Directory structure to return */
1987 } DIRW;
1988
1989 #endif /* _WIN32 */
1990
1991
1992 //
1993 // Functions
1994 //
1995
1996 #ifdef __cplusplus
1997
1998 inline TCHAR *nx_strncpy(TCHAR *pszDest, const TCHAR *pszSrc, size_t nLen)
1999 {
2000 #if defined(_WIN32) && (_MSC_VER >= 1400) && !defined(__clang__)
2001 _tcsncpy_s(pszDest, nLen, pszSrc, _TRUNCATE);
2002 #else
2003 _tcsncpy(pszDest, pszSrc, nLen - 1);
2004 pszDest[nLen - 1] = 0;
2005 #endif
2006 return pszDest;
2007 }
2008
2009 #ifdef UNICODE
2010 inline char *nx_strncpy_mb(char *pszDest, const char *pszSrc, size_t nLen)
2011 {
2012 #if defined(_WIN32) && (_MSC_VER >= 1400) && !defined(__clang__)
2013 strncpy_s(pszDest, nLen, pszSrc, _TRUNCATE);
2014 #else
2015 strncpy(pszDest, pszSrc, nLen - 1);
2016 pszDest[nLen - 1] = 0;
2017 #endif
2018 return pszDest;
2019 }
2020 #else
2021 #define nx_strncpy_mb nx_strncpy
2022 #endif
2023
2024 int LIBNETXMS_EXPORTABLE ConnectEx(SOCKET s, struct sockaddr *addr, int len, UINT32 timeout);
2025 int LIBNETXMS_EXPORTABLE SendEx(SOCKET hSocket, const void *data, size_t len, int flags, MUTEX mutex);
2026 int LIBNETXMS_EXPORTABLE RecvEx(SOCKET hSocket, void *data, size_t len, int flags, UINT32 timeout);
2027 bool LIBNETXMS_EXPORTABLE RecvAll(SOCKET s, void *buffer, size_t size, UINT32 timeout);
2028
2029 SOCKET LIBNETXMS_EXPORTABLE ConnectToHost(const InetAddress& addr, UINT16 port, UINT32 timeout);
2030
2031 #endif /* __cplusplus */
2032
2033 #ifdef __cplusplus
2034 extern "C"
2035 {
2036 #endif
2037
2038 void LIBNETXMS_EXPORTABLE InitNetXMSProcess(bool commandLineTool);
2039
2040 #ifndef _WIN32
2041 #if defined(UNICODE_UCS2) || defined(UNICODE_UCS4)
2042 void LIBNETXMS_EXPORTABLE __wcsupr(WCHAR *in);
2043 #define wcsupr __wcsupr
2044 #endif
2045 void LIBNETXMS_EXPORTABLE __strupr(char *in);
2046 #define strupr __strupr
2047 #endif /* _WIN32 */
2048
2049 void LIBNETXMS_EXPORTABLE QSortEx(void *base, size_t nmemb, size_t size, void *arg,
2050 int (*compare)(const void *, const void *, void *));
2051
2052 INT64 LIBNETXMS_EXPORTABLE GetCurrentTimeMs();
2053
2054 UINT64 LIBNETXMS_EXPORTABLE FileSizeW(const WCHAR *pszFileName);
2055 UINT64 LIBNETXMS_EXPORTABLE FileSizeA(const char *pszFileName);
2056 #ifdef UNICODE
2057 #define FileSize FileSizeW
2058 #else
2059 #define FileSize FileSizeA
2060 #endif
2061
2062 int LIBNETXMS_EXPORTABLE BitsInMask(UINT32 dwMask);
2063 TCHAR LIBNETXMS_EXPORTABLE *IpToStr(UINT32 dwAddr, TCHAR *szBuffer);
2064 #ifdef UNICODE
2065 char LIBNETXMS_EXPORTABLE *IpToStrA(UINT32 dwAddr, char *szBuffer);
2066 #else
2067 #define IpToStrA IpToStr
2068 #endif
2069 TCHAR LIBNETXMS_EXPORTABLE *Ip6ToStr(const BYTE *addr, TCHAR *buffer);
2070 #ifdef UNICODE
2071 char LIBNETXMS_EXPORTABLE *Ip6ToStrA(const BYTE *addr, char *buffer);
2072 #else
2073 #define Ip6ToStrA Ip6ToStr
2074 #endif
2075 TCHAR LIBNETXMS_EXPORTABLE *SockaddrToStr(struct sockaddr *addr, TCHAR *buffer);
2076
2077 void LIBNETXMS_EXPORTABLE *nx_memdup(const void *data, size_t size);
2078 void LIBNETXMS_EXPORTABLE nx_memswap(void *block1, void *block2, size_t size);
2079
2080 WCHAR LIBNETXMS_EXPORTABLE *BinToStrW(const void *data, size_t size, WCHAR *str);
2081 char LIBNETXMS_EXPORTABLE *BinToStrA(const void *data, size_t size, char *str);
2082 #ifdef UNICODE
2083 #define BinToStr BinToStrW
2084 #else
2085 #define BinToStr BinToStrA
2086 #endif
2087
2088 size_t LIBNETXMS_EXPORTABLE StrToBinW(const WCHAR *pStr, BYTE *data, size_t size);
2089 size_t LIBNETXMS_EXPORTABLE StrToBinA(const char *pStr, BYTE *data, size_t size);
2090 #ifdef UNICODE
2091 #define StrToBin StrToBinW
2092 #else
2093 #define StrToBin StrToBinA
2094 #endif
2095
2096 TCHAR LIBNETXMS_EXPORTABLE *MACToStr(const BYTE *data, TCHAR *pStr);
2097
2098 void LIBNETXMS_EXPORTABLE StrStripA(char *pszStr);
2099 void LIBNETXMS_EXPORTABLE StrStripW(WCHAR *pszStr);
2100 #ifdef UNICODE
2101 #define StrStrip StrStripW
2102 #else
2103 #define StrStrip StrStripA
2104 #endif
2105
2106 const char LIBNETXMS_EXPORTABLE *ExtractWordA(const char *line, char *buffer);
2107 const WCHAR LIBNETXMS_EXPORTABLE *ExtractWordW(const WCHAR *line, WCHAR *buffer);
2108 #ifdef UNICODE
2109 #define ExtractWord ExtractWordW
2110 #else
2111 #define ExtractWord ExtractWordA
2112 #endif
2113
2114 int LIBNETXMS_EXPORTABLE NumCharsA(const char *pszStr, char ch);
2115 int LIBNETXMS_EXPORTABLE NumCharsW(const WCHAR *pszStr, WCHAR ch);
2116 #ifdef UNICODE
2117 #define NumChars NumCharsW
2118 #else
2119 #define NumChars NumCharsA
2120 #endif
2121
2122 void LIBNETXMS_EXPORTABLE RemoveTrailingCRLFA(char *str);
2123 void LIBNETXMS_EXPORTABLE RemoveTrailingCRLFW(WCHAR *str);
2124 #ifdef UNICODE
2125 #define RemoveTrailingCRLF RemoveTrailingCRLFW
2126 #else
2127 #define RemoveTrailingCRLF RemoveTrailingCRLFA
2128 #endif
2129
2130 bool LIBNETXMS_EXPORTABLE RegexpMatchA(const char *str, const char *expr, bool matchCase);
2131 bool LIBNETXMS_EXPORTABLE RegexpMatchW(const WCHAR *str, const WCHAR *expr, bool matchCase);
2132 #ifdef UNICODE
2133 #define RegexpMatch RegexpMatchW
2134 #else
2135 #define RegexpMatch RegexpMatchA
2136 #endif
2137
2138 const TCHAR LIBNETXMS_EXPORTABLE *ExpandFileName(const TCHAR *name, TCHAR *buffer, size_t bufSize, bool allowShellCommand);
2139 BOOL LIBNETXMS_EXPORTABLE CreateFolder(const TCHAR *directory);
2140 bool LIBNETXMS_EXPORTABLE SetLastModificationTime(TCHAR *fileName, time_t lastModDate);
2141 TCHAR LIBNETXMS_EXPORTABLE *Trim(TCHAR *str);
2142 bool LIBNETXMS_EXPORTABLE MatchString(const TCHAR *pattern, const TCHAR *str, bool matchCase);
2143 TCHAR LIBNETXMS_EXPORTABLE **SplitString(const TCHAR *source, TCHAR sep, int *numStrings);
2144 int LIBNETXMS_EXPORTABLE GetLastMonthDay(struct tm *currTime);
2145 bool LIBNETXMS_EXPORTABLE MatchScheduleElement(TCHAR *pszPattern, int nValue, int maxValue, struct tm *localTime, time_t currTime);
2146 bool LIBNETXMS_EXPORTABLE MatchSchedule(const TCHAR *schedule, struct tm *currTime, time_t now);
2147
2148 #ifdef __cplusplus
2149 BOOL LIBNETXMS_EXPORTABLE IsValidObjectName(const TCHAR *pszName, BOOL bExtendedChars = FALSE);
2150 #endif
2151 BOOL LIBNETXMS_EXPORTABLE IsValidScriptName(const TCHAR *pszName);
2152 /* deprecated */ void LIBNETXMS_EXPORTABLE TranslateStr(TCHAR *pszString, const TCHAR *pszSubStr, const TCHAR *pszReplace);
2153 const TCHAR LIBNETXMS_EXPORTABLE *GetCleanFileName(const TCHAR *pszFileName);
2154 void LIBNETXMS_EXPORTABLE GetOSVersionString(TCHAR *pszBuffer, int nBufSize);
2155 BYTE LIBNETXMS_EXPORTABLE *LoadFile(const TCHAR *pszFileName, UINT32 *pdwFileSize);
2156 #ifdef UNICODE
2157 BYTE LIBNETXMS_EXPORTABLE *LoadFileA(const char *pszFileName, UINT32 *pdwFileSize);
2158 #else
2159 #define LoadFileA LoadFile
2160 #endif
2161
2162 UINT32 LIBNETXMS_EXPORTABLE CalculateCRC32(const unsigned char *data, UINT32 size, UINT32 dwCRC);
2163 BOOL LIBNETXMS_EXPORTABLE CalculateFileCRC32(const TCHAR *pszFileName, UINT32 *pResult);
2164
2165 typedef unsigned char MD5_STATE[128];
2166
2167 void LIBNETXMS_EXPORTABLE CalculateMD5Hash(const BYTE *data, size_t nbytes, BYTE *hash);
2168 void LIBNETXMS_EXPORTABLE MD5HashForPattern(const BYTE *data, size_t patternSize, size_t fullSize, BYTE *hash);
2169 BOOL LIBNETXMS_EXPORTABLE CalculateFileMD5Hash(const TCHAR *pszFileName, BYTE *pHash);
2170 void LIBNETXMS_EXPORTABLE MD5Init(MD5_STATE *state);
2171 void LIBNETXMS_EXPORTABLE MD5Update(MD5_STATE *state, const BYTE *data, size_t size);
2172 void LIBNETXMS_EXPORTABLE MD5Finish(MD5_STATE *state, BYTE *hash);
2173
2174 typedef unsigned char SHA1_STATE[128];
2175
2176 void LIBNETXMS_EXPORTABLE CalculateSHA1Hash(const BYTE *data, size_t nbytes, BYTE *hash);
2177 void LIBNETXMS_EXPORTABLE SHA1HashForPattern(const BYTE *data, size_t patternSize, size_t fullSize, BYTE *hash);
2178 BOOL LIBNETXMS_EXPORTABLE CalculateFileSHA1Hash(const TCHAR *pszFileName, BYTE *pHash);
2179 void LIBNETXMS_EXPORTABLE SHA1Init(SHA1_STATE *state);
2180 void LIBNETXMS_EXPORTABLE SHA1Update(SHA1_STATE *state, const BYTE *data, size_t size);
2181 void LIBNETXMS_EXPORTABLE SHA1Finish(SHA1_STATE *state, BYTE *hash);
2182
2183 void LIBNETXMS_EXPORTABLE CalculateSHA256Hash(const BYTE *data, size_t len, BYTE *hash);
2184
2185 void LIBNETXMS_EXPORTABLE GenerateRandomBytes(BYTE *buffer, size_t size);
2186
2187 void LIBNETXMS_EXPORTABLE LogOpenSSLErrorStack(int level);
2188
2189 void LIBNETXMS_EXPORTABLE ICEEncryptData(const BYTE *in, int inLen, BYTE *out, const BYTE *key);
2190 void LIBNETXMS_EXPORTABLE ICEDecryptData(const BYTE *in, int inLen, BYTE *out, const BYTE *key);
2191
2192 bool LIBNETXMS_EXPORTABLE DecryptPasswordW(const WCHAR *login, const WCHAR *encryptedPasswd, WCHAR *decryptedPasswd, size_t bufferLenght);
2193 bool LIBNETXMS_EXPORTABLE DecryptPasswordA(const char *login, const char *encryptedPasswd, char *decryptedPasswd, size_t bufferLenght);
2194 #ifdef UNICODE
2195 #define DecryptPassword DecryptPasswordW
2196 #else
2197 #define DecryptPassword DecryptPasswordA
2198 #endif
2199
2200 int LIBNETXMS_EXPORTABLE NxDCIDataTypeFromText(const TCHAR *pszText);
2201
2202 HMODULE LIBNETXMS_EXPORTABLE DLOpen(const TCHAR *pszLibName, TCHAR *pszErrorText);
2203 void LIBNETXMS_EXPORTABLE DLClose(HMODULE hModule);
2204 void LIBNETXMS_EXPORTABLE *DLGetSymbolAddr(HMODULE hModule, const char *pszSymbol, TCHAR *pszErrorText);
2205
2206 bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueW(const WCHAR *optString, const WCHAR *option, WCHAR *buffer, int bufSize);
2207 bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsBoolW(const WCHAR *optString, const WCHAR *option, bool defVal);
2208 long LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsIntW(const WCHAR *optString, const WCHAR *option, long defVal);
2209
2210 bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueA(const char *optString, const char *option, char *buffer, int bufSize);
2211 bool LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsBoolA(const char *optString, const char *option, bool defVal);
2212 long LIBNETXMS_EXPORTABLE ExtractNamedOptionValueAsIntA(const char *optString, const char *option, long defVal);
2213
2214 #ifdef UNICODE
2215 #define ExtractNamedOptionValue ExtractNamedOptionValueW
2216 #define ExtractNamedOptionValueAsBool ExtractNamedOptionValueAsBoolW
2217 #define ExtractNamedOptionValueAsInt ExtractNamedOptionValueAsIntW
2218 #else
2219 #define ExtractNamedOptionValue ExtractNamedOptionValueA
2220 #define ExtractNamedOptionValueAsBool ExtractNamedOptionValueAsBoolA
2221 #define ExtractNamedOptionValueAsInt ExtractNamedOptionValueAsIntA
2222 #endif
2223
2224 #ifdef __cplusplus
2225 const TCHAR LIBNETXMS_EXPORTABLE *CodeToText(int code, CODE_TO_TEXT *translator, const TCHAR *defaultText = _T("Unknown"));
2226 #else
2227 const TCHAR LIBNETXMS_EXPORTABLE *CodeToText(int code, CODE_TO_TEXT *translator, const TCHAR *defaultText);
2228 #endif
2229 #ifdef __cplusplus
2230 int LIBNETXMS_EXPORTABLE CodeFromText(const TCHAR *text, CODE_TO_TEXT *translator, int defaultCode = -1);
2231 #else
2232 int LIBNETXMS_EXPORTABLE CodeFromText(const TCHAR *text, CODE_TO_TEXT *translator, int defaultCode);
2233 #endif
2234
2235 #ifdef _WIN32
2236 TCHAR LIBNETXMS_EXPORTABLE *GetSystemErrorText(UINT32 dwError, TCHAR *pszBuffer, size_t iBufSize);
2237 BOOL LIBNETXMS_EXPORTABLE GetWindowsVersionString(TCHAR *versionString, int strSize);
2238 INT64 LIBNETXMS_EXPORTABLE GetProcessRSS();
2239 #endif
2240
2241 TCHAR LIBNETXMS_EXPORTABLE *GetLastSocketErrorText(TCHAR *buffer, size_t size);
2242
2243 TCHAR LIBNETXMS_EXPORTABLE *GetLocalHostName(TCHAR *buffer, size_t size, bool fqdn);
2244
2245 #if !HAVE_DAEMON || !HAVE_DECL_DAEMON
2246 int LIBNETXMS_EXPORTABLE __daemon(int nochdir, int noclose);
2247 #define daemon __daemon
2248 #endif
2249
2250 UINT32 LIBNETXMS_EXPORTABLE inet_addr_w(const WCHAR *pszAddr);
2251
2252 #ifndef _WIN32
2253
2254 bool LIBNETXMS_EXPORTABLE SetDefaultCodepage(const char *cp);
2255 int LIBNETXMS_EXPORTABLE WideCharToMultiByte(int iCodePage, UINT32 dwFlags, const WCHAR *pWideCharStr,
2256 int cchWideChar, char *pByteStr, int cchByteChar,
2257 char *pDefaultChar, BOOL *pbUsedDefChar);
2258 int LIBNETXMS_EXPORTABLE MultiByteToWideChar(int iCodePage, UINT32 dwFlags, const char *pByteStr,
2259 int cchByteChar, WCHAR *pWideCharStr,
2260 int cchWideChar);
2261
2262 #ifdef UNICODE
2263 int LIBNETXMS_EXPORTABLE nx_wprintf(const WCHAR *format, ...);
2264 int LIBNETXMS_EXPORTABLE nx_fwprintf(FILE *fp, const WCHAR *format, ...);
2265 int LIBNETXMS_EXPORTABLE nx_swprintf(WCHAR *buffer, size_t size, const WCHAR *format, ...);
2266 int LIBNETXMS_EXPORTABLE nx_vwprintf(const WCHAR *format, va_list args);
2267 int LIBNETXMS_EXPORTABLE nx_vfwprintf(FILE *fp, const WCHAR *format, va_list args);
2268 int LIBNETXMS_EXPORTABLE nx_vswprintf(WCHAR *buffer, size_t size, const WCHAR *format, va_list args);
2269
2270 int LIBNETXMS_EXPORTABLE nx_wscanf(const WCHAR *format, ...);
2271 int LIBNETXMS_EXPORTABLE nx_fwscanf(FILE *fp, const WCHAR *format, ...);
2272 int LIBNETXMS_EXPORTABLE nx_swscanf(const WCHAR *str, const WCHAR *format, ...);
2273 int LIBNETXMS_EXPORTABLE nx_vwscanf(const WCHAR *format, va_list args);
2274 int LIBNETXMS_EXPORTABLE nx_vfwscanf(FILE *fp, const WCHAR *format, va_list args);
2275 int LIBNETXMS_EXPORTABLE nx_vswscanf(const WCHAR *str, const WCHAR *format, va_list args);
2276 #endif
2277
2278 #endif /* _WIN32 */
2279
2280 #ifdef _WITH_ENCRYPTION
2281 WCHAR LIBNETXMS_EXPORTABLE *ERR_error_string_W(int nError, WCHAR *pwszBuffer);
2282 #endif
2283
2284 #if !defined(_WIN32) && !HAVE_WSTAT
2285 int wstat(const WCHAR *_path, struct stat *_sbuf);
2286 #endif
2287
2288 #if defined(UNICODE) && !defined(_WIN32)
2289
2290 #if !HAVE_WPOPEN
2291 FILE LIBNETXMS_EXPORTABLE *wpopen(const WCHAR *_command, const WCHAR *_type);
2292 #endif
2293 #if !HAVE_WFOPEN
2294 FILE LIBNETXMS_EXPORTABLE *wfopen(const WCHAR *_name, const WCHAR *_type);
2295 #endif
2296 #if HAVE_FOPEN64 && !HAVE_WFOPEN64
2297 FILE LIBNETXMS_EXPORTABLE *wfopen64(const WCHAR *_name, const WCHAR *_type);
2298 #endif
2299 #if !HAVE_WOPEN
2300 int LIBNETXMS_EXPORTABLE wopen(const WCHAR *, int, ...);
2301 #endif
2302 #if !HAVE_WCHMOD
2303 int LIBNETXMS_EXPORTABLE wchmod(const WCHAR *_name, int mode);
2304 #endif
2305 #if !HAVE_WCHDIR
2306 int wchdir(const WCHAR *_path);
2307 #endif
2308 #if !HAVE_WMKDIR
2309 int wmkdir(const WCHAR *_path, int mode);
2310 #endif
2311 #if !HAVE_WUTIME
2312 int wutime(const WCHAR *_path, struct utimbuf *buf);
2313 #endif
2314 #if !HAVE_WRMDIR
2315 int wrmdir(const WCHAR *_path);
2316 #endif
2317 #if !HAVE_WRENAME
2318 int wrename(const WCHAR *_oldpath, const WCHAR *_newpath);
2319 #endif
2320 #if !HAVE_WUNLINK
2321 int wunlink(const WCHAR *_path);
2322 #endif
2323 #if !HAVE_WREMOVE
2324 int wremove(const WCHAR *_path);
2325 #endif
2326 #if !HAVE_WSYSTEM
2327 int wsystem(const WCHAR *_cmd);
2328 #endif
2329 #if !HAVE_WMKSTEMP
2330 int wmkstemp(WCHAR *_template);
2331 #endif
2332 #if !HAVE_WACCESS
2333 int waccess(const WCHAR *_path, int mode);
2334 #endif
2335 #if !HAVE_WGETENV
2336 WCHAR *wgetenv(const WCHAR *_string);
2337 #endif
2338 #if !HAVE_WCTIME
2339 WCHAR *wctime(const time_t *timep);
2340 #endif
2341 #if !HAVE_PUTWS
2342 int putws(const WCHAR *s);
2343 #endif
2344 #if !HAVE_WCSERROR && (HAVE_STRERROR || HAVE_DECL_STRERROR)
2345 WCHAR *wcserror(int errnum);
2346 #endif
2347 #if !HAVE_WCSERROR_R && HAVE_STRERROR_R
2348 #if HAVE_POSIX_STRERROR_R
2349 int wcserror_r(int errnum, WCHAR *strerrbuf, size_t buflen);
2350 #else
2351 WCHAR *wcserror_r(int errnum, WCHAR *strerrbuf, size_t buflen);
2352 #endif
2353 #endif
2354
2355 #endif /* UNICODE && !_WIN32*/
2356
2357 #if !HAVE_STRTOLL
2358 INT64 LIBNETXMS_EXPORTABLE strtoll(const char *nptr, char **endptr, int base);
2359 #endif
2360 #if !HAVE_STRTOULL
2361 UINT64 LIBNETXMS_EXPORTABLE strtoull(const char *nptr, char **endptr, int base);
2362 #endif
2363
2364 #if !HAVE_WCSTOLL
2365 INT64 LIBNETXMS_EXPORTABLE wcstoll(const WCHAR *nptr, WCHAR **endptr, int base);
2366 #endif
2367 #if !HAVE_WCSTOULL
2368 UINT64 LIBNETXMS_EXPORTABLE wcstoull(const WCHAR *nptr, WCHAR **endptr, int base);
2369 #endif
2370
2371 #if !HAVE_STRLWR && !defined(_WIN32)
2372 char LIBNETXMS_EXPORTABLE *strlwr(char *str);
2373 #endif
2374
2375 #if !HAVE_WCSLWR && !defined(_WIN32)
2376 WCHAR LIBNETXMS_EXPORTABLE *wcslwr(WCHAR *str);
2377 #endif
2378
2379 #if !HAVE_WCSCASECMP && !defined(_WIN32)
2380 int LIBNETXMS_EXPORTABLE wcscasecmp(const wchar_t *s1, const wchar_t *s2);
2381 #endif
2382
2383 #if !HAVE_WCSNCASECMP && !defined(_WIN32)
2384 int LIBNETXMS_EXPORTABLE wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n);
2385 #endif
2386
2387 #if !defined(_WIN32) && (!HAVE_WCSFTIME || !WORKING_WCSFTIME)
2388 size_t LIBNETXMS_EXPORTABLE nx_wcsftime(WCHAR *buffer, size_t bufsize, const WCHAR *format, const struct tm *t);
2389 #undef wcsftime
2390 #define wcsftime nx_wcsftime
2391 #endif
2392
2393 #ifndef _WIN32
2394
2395 #if HAVE_ITOA && !HAVE__ITOA
2396 #define _itoa itoa
2397 #undef HAVE__ITOA
2398 #define HAVE__ITOA 1
2399 #endif
2400 #if !HAVE__ITOA && !defined(_WIN32)
2401 char LIBNETXMS_EXPORTABLE *_itoa(int value, char *str, int base);
2402 #endif
2403
2404 #if HAVE_ITOW && !HAVE__ITOW
2405 #define _itow itow
2406 #undef HAVE__ITOW
2407 #define HAVE__ITOW 1
2408 #endif
2409 #if !HAVE__ITOW && !defined(_WIN32)
2410 WCHAR LIBNETXMS_EXPORTABLE *_itow(int value, WCHAR *str, int base);
2411 #endif
2412
2413 #endif /* _WIN32 */
2414
2415 #ifdef _WIN32
2416 #ifdef UNICODE
2417 DIRW LIBNETXMS_EXPORTABLE *wopendir(const WCHAR *path);
2418 struct dirent_w LIBNETXMS_EXPORTABLE *wreaddir(DIRW *p);
2419 int LIBNETXMS_EXPORTABLE wclosedir(DIRW *p);
2420
2421 #define _topendir wopendir
2422 #define _treaddir wreaddir
2423 #define _tclosedir wclosedir
2424 #else
2425 #define _topendir opendir
2426 #define _treaddir readdir
2427 #define _tclosedir closedir
2428 #endif
2429
2430 DIR LIBNETXMS_EXPORTABLE *opendir(const char *path);
2431 struct dirent LIBNETXMS_EXPORTABLE *readdir(DIR *p);
2432 int LIBNETXMS_EXPORTABLE closedir(DIR *p);
2433
2434 #else /* not _WIN32 */
2435
2436 DIRW LIBNETXMS_EXPORTABLE *wopendir(const WCHAR *filename);
2437 struct dirent_w LIBNETXMS_EXPORTABLE *wreaddir(DIRW *dirp);
2438 int LIBNETXMS_EXPORTABLE wclosedir(DIRW *dirp);
2439
2440 #endif
2441
2442 #if defined(_WIN32) || !(HAVE_SCANDIR)
2443 int LIBNETXMS_EXPORTABLE scandir(const char *dir, struct dirent ***namelist,
2444 int (*select)(const struct dirent *),
2445 int (*compar)(const struct dirent **, const struct dirent **));
2446 int LIBNETXMS_EXPORTABLE alphasort(const struct dirent **a, const struct dirent **b);
2447 #endif
2448
2449 TCHAR LIBNETXMS_EXPORTABLE *safe_fgetts(TCHAR *buffer, int len, FILE *f);
2450
2451 bool LIBNETXMS_EXPORTABLE nxlog_open(const TCHAR *logName, UINT32 flags, const TCHAR *msgModule,
2452 unsigned int msgCount, const TCHAR **messages,
2453 DWORD debugMsg, DWORD debugMsgTag, DWORD genericMsg);
2454 void LIBNETXMS_EXPORTABLE nxlog_close();
2455 void LIBNETXMS_EXPORTABLE nxlog_write(DWORD msg, WORD wType, const char *format, ...);
2456 void LIBNETXMS_EXPORTABLE nxlog_write_generic(WORD type, const TCHAR *format, ...);
2457 void LIBNETXMS_EXPORTABLE nxlog_debug(int level, const TCHAR *format, ...);
2458 void LIBNETXMS_EXPORTABLE nxlog_debug_tag(const TCHAR *tag, int level, const TCHAR *format, ...);
2459 void LIBNETXMS_EXPORTABLE nxlog_debug2(int level, const TCHAR *format, va_list args);
2460 bool LIBNETXMS_EXPORTABLE nxlog_set_rotation_policy(int rotationMode, UINT64 maxLogSize, int historySize, const TCHAR *dailySuffix);
2461 bool LIBNETXMS_EXPORTABLE nxlog_rotate();
2462 void LIBNETXMS_EXPORTABLE nxlog_set_debug_level(int level);
2463 void LIBNETXMS_EXPORTABLE nxlog_set_debug_level_tag(const TCHAR *tags, int level);
2464 int LIBNETXMS_EXPORTABLE nxlog_get_debug_level();
2465 int LIBNETXMS_EXPORTABLE nxlog_get_debug_level_tag(const TCHAR *tag);
2466
2467 typedef void (*NxLogDebugWriter)(const TCHAR *, const TCHAR *);
2468 void LIBNETXMS_EXPORTABLE nxlog_set_debug_writer(NxLogDebugWriter writer);
2469
2470 typedef void (*NxLogConsoleWriter)(const TCHAR *, ...);
2471 void LIBNETXMS_EXPORTABLE nxlog_set_console_writer(NxLogConsoleWriter writer);
2472
2473 void LIBNETXMS_EXPORTABLE WriteToTerminal(const TCHAR *text);
2474 void LIBNETXMS_EXPORTABLE WriteToTerminalEx(const TCHAR *format, ...)
2475 #if !defined(UNICODE) && (defined(__GNUC__) || defined(__clang__))
2476 __attribute__ ((format(printf, 1, 2)))
2477 #endif
2478 ;
2479
2480 bool LIBNETXMS_EXPORTABLE ReadPassword(const TCHAR *prompt, TCHAR *buffer, size_t bufferSize);
2481
2482 #ifdef _WIN32
2483 int LIBNETXMS_EXPORTABLE mkstemp(char *tmpl);
2484 int LIBNETXMS_EXPORTABLE wmkstemp(WCHAR *tmpl);
2485 #ifdef UNICODE
2486 #define _tmkstemp wmkstemp
2487 #else
2488 #define _tmkstemp mkstemp
2489 #endif
2490 #endif
2491
2492 #ifndef _WIN32
2493 int strcat_s(char *dst, size_t dstSize, const char *src);
2494 int wcscat_s(WCHAR *dst, size_t dstSize, const WCHAR *src);
2495 #endif
2496
2497 #if !HAVE_STRPTIME
2498 char LIBNETXMS_EXPORTABLE *strptime(const char *buf, const char *fmt, struct tm *_tm);
2499 #endif
2500
2501 #if !HAVE_TIMEGM
2502 time_t LIBNETXMS_EXPORTABLE timegm(struct tm *_tm);
2503 #endif
2504
2505 #if !HAVE_INET_PTON
2506 int LIBNETXMS_EXPORTABLE nx_inet_pton(int af, const char *src, void *dst);
2507 #define inet_pton nx_inet_pton
2508 #endif
2509
2510 int LIBNETXMS_EXPORTABLE GetSleepTime(int hour, int minute, int second);
2511 time_t LIBNETXMS_EXPORTABLE ParseDateTimeA(const char *text, time_t defaultValue);
2512 time_t LIBNETXMS_EXPORTABLE ParseDateTimeW(const WCHAR *text, time_t defaultValue);
2513
2514 #ifdef UNICODE
2515 #define ParseDateTime ParseDateTimeW
2516 #else
2517 #define ParseDateTime ParseDateTimeA
2518 #endif
2519
2520 #ifdef __cplusplus
2521 }
2522 #endif
2523
2524
2525 //
2526 // C++ only functions
2527 //
2528
2529 #ifdef __cplusplus
2530
2531 enum nxDirectoryType
2532 {
2533 nxDirBin = 0,
2534 nxDirData = 1,
2535 nxDirEtc = 2,
2536 nxDirLib = 3,
2537 nxDirShare = 4
2538 };
2539
2540 TCHAR LIBNETXMS_EXPORTABLE *GetHeapInfo();
2541
2542 void LIBNETXMS_EXPORTABLE GetNetXMSDirectory(nxDirectoryType type, TCHAR *dir);
2543
2544 UINT32 LIBNETXMS_EXPORTABLE IcmpPing(const InetAddress& addr, int iNumRetries, UINT32 dwTimeout, UINT32 *pdwRTT, UINT32 dwPacketSize);
2545
2546 TCHAR LIBNETXMS_EXPORTABLE *EscapeStringForXML(const TCHAR *str, int length);
2547 String LIBNETXMS_EXPORTABLE EscapeStringForXML2(const TCHAR *str, int length = -1);
2548 const char LIBNETXMS_EXPORTABLE *XMLGetAttr(const char **attrs, const char *name);
2549 int LIBNETXMS_EXPORTABLE XMLGetAttrInt(const char **attrs, const char *name, int defVal);
2550 UINT32 LIBNETXMS_EXPORTABLE XMLGetAttrUINT32(const char **attrs, const char *name, UINT32 defVal);
2551 bool LIBNETXMS_EXPORTABLE XMLGetAttrBoolean(const char **attrs, const char *name, bool defVal);
2552
2553 String LIBNETXMS_EXPORTABLE EscapeStringForJSON(const TCHAR *s);
2554 String LIBNETXMS_EXPORTABLE EscapeStringForAgent(const TCHAR *s);
2555
2556 StringList LIBNETXMS_EXPORTABLE *ParseCommandLine(const TCHAR *cmdline);
2557
2558 #if !defined(_WIN32) && !defined(_NETWARE) && defined(NMS_THREADS_H_INCLUDED)
2559 void LIBNETXMS_EXPORTABLE BlockAllSignals(bool processWide, bool allowInterrupt);
2560 void LIBNETXMS_EXPORTABLE StartMainLoop(ThreadFunction pfSignalHandler, ThreadFunction pfMain);
2561 #endif
2562
2563 String LIBNETXMS_EXPORTABLE GenerateLineDiff(const String& left, const String& right);
2564
2565 #endif
2566
2567 #endif /* _nms_util_h_ */