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