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