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