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