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