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