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