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