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