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