util/helper.c File Reference

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <time.h>
#include "helper.h"
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <pthread.h>
#include <wchar.h>

Include dependency graph for helper.c:

Go to the source code of this file.

Defines

#define MICRO_SECS_PER_SECOND   1000000
#define NANO_SECS_PER_SECOND   MICRO_SECS_PER_SECOND * 1000
#define ESC   "\033[0m";
#define BOLD   "\033[1m"
#define RED_BLACK   "\033[31;40m"
#define GREEN_BLACK   "\033[32;40m"
#define YELLOW_BLACK   "\033[33;40m"
#define BLUE_BLACK   "\033[34;40m"
#define PINK_BLACK   "\033[35;40m"
#define LTGREEN_BLACK   "\033[36;40m"
#define WHITE_BLACK   "\033[37;40m"
#define WHITE_RED   "\033[37;41m"
#define BLACK_RED   "\033[30;41m"
#define BLACK_GREEN   "\033[40;42m"
#define BLACK_PINK   "\033[40;45m"
#define BLACK_LTGREEN   "\033[40;46m"
#define XMLBLASTER_SLEEP_FALLBACK   0
#define XMLBLASTER_SLEEP_NANO   0

Functions

static int vsnprintf0 (char *s, size_t size, char *format, va_list ap)
char * getStackTrace (int maxNumOfLines)
 Add for GCC compilation: "-rdynamic -export-dynamic -D_ENABLE_STACK_TRACE_".
void sleepMillis (long millisecs)
 Sleep for given milliseconds, on none real time systems expect ~ 10 millisecs tolerance.
int64_t getTimestamp ()
 Create a timestamp in nano seconds elapsed since 1970-01-01.
char ** convertWcsArgv (wchar_t **argv_wcs, int argc)
 Converts the given wide char pwcs to multibyte argv.
void freeArgv (char **argv, int argc)
 Frees the allocated argv from convertWcsArgv().
int getAbsoluteTime (long relativeTimeFromNow, struct timespec *abstime)
 Fills the given abstime with absolute time, using the given timeout relativeTimeFromNow in milliseconds On Linux < 2.5.64 does not support high resolution timers clock_gettime(), but patches are available at http://sourceforge.net/projects/high-res-timers.
char * strcpyAlloc (char *src)
 Allocates the string with malloc for you.
char * strcatAlloc (char **dest, char *src)
 Same as strcat but reallocs the 'dest' string.
char * strcpyRealloc (char **dest, char *src)
 Same as strcpyAlloc but if the given *dest != NULL this old allocation is freed first.
char * strFromBlobAlloc (char *blob, size_t len)
 Allocates the string with malloc for you, it is always ended with 0.
void xb_strerror (char *errnoStr, size_t sizeInBytes, int errnum)
 Convert the errnum to a human readable errnoStr.
char * strncpy0 (char *to, char *from, size_t maxLen)
 Guarantees a 0 terminated string.
char * strncat0 (char *to, char *from, size_t max)
 Guarantees a 0 terminated string.
int snprintf0 (char *buffer, size_t sizeOfBuffer, char *format,...)
 Microsoft introduces the vsnprintf_s().
void trim (char *s)
 strip leading and trailing spaces of the given string
void trimStart (char *s)
 strip leading spaces of the given string
void trimEnd (char *s)
 strip trailing spaces of the given string
char * toReadableDump (char *data, size_t len)
 Converts the given binary data to a more readable string, the zero bytes are replaced by '*'.
long get_pthread_id (pthread_t t)
 Cast the thread identifier to an long value.
void getCurrentTimeStr (char *timeStr, int bufSize)
 Get a human readable time string for logging.
void xmlBlasterDefaultLogging (void *logUserP, XMLBLASTER_LOG_LEVEL currLevel, XMLBLASTER_LOG_LEVEL level, char *location, char *fmt,...)
 Default logging output is handled by this method: All logging is appended a time, the loglevel and the location string.
XMLBLASTER_LOG_LEVEL parseLogLevel (char *logLevelStr)
 Parses the given string and returns the enum for it.
char * getLogLevelStr (XMLBLASTER_LOG_LEVEL logLevel)
 
Returns:
A human readable log level, e.g.

int doLog (XMLBLASTER_LOG_LEVEL currLevel, XMLBLASTER_LOG_LEVEL level)
 Check if logging is necessary.
void embedException (ExceptionStruct *exception, char *newErrorCode, char *newMessage, ExceptionStruct *embed)
 Embed the given 'embed' into exception->message.
void initializeExceptionStruct (ExceptionStruct *exception)
 Should be called on any ExceptionStruct before using it.
char * getExceptionStr (char *out, int outSize, ExceptionStruct *exception)
 Convenience function which returns a formatted exception string.
char * int64ToStr (char *buf, int64_t val)
 Convert a 64 bit integer to a string.
int strToInt64 (int64_t *val, char *str)
 Convert a string to a 64 bit integer.
int strToLong (long *val, char *str)
int strToInt (int *val, char *str)
int strToULong (unsigned long *val, char *str)
BlobHolderblobcpyAlloc (BlobHolder *blob, char *data, size_t dataLen)
 Allocates the string with malloc for you.
BlobHolderfreeBlobHolderContent (BlobHolder *blob)
 free()'s the data in the given blob, does not free the blob itself.
char * blobDump (BlobHolder *blob)
 Converts the given binary data to a more readable string, the zero bytes are replaced by '*'.
void freeBlobDump (char *blobDump)

Variables

static char * LOG_TEXT [] = { "NOLOG", "ERROR", "WARN", "INFO", "CALL", "TIME", "TRACE", "DUMP", "PLAIN" }
static int numLOG_TEXT = 9
static char * LOG_TEXT_ESCAPE []


Define Documentation

#define BLACK_GREEN   "\033[40;42m"

Definition at line 70 of file helper.c.

#define BLACK_LTGREEN   "\033[40;46m"

Definition at line 72 of file helper.c.

#define BLACK_PINK   "\033[40;45m"

Definition at line 71 of file helper.c.

#define BLACK_RED   "\033[30;41m"

Definition at line 69 of file helper.c.

#define BLUE_BLACK   "\033[34;40m"

Definition at line 63 of file helper.c.

#define BOLD   "\033[1m"

Definition at line 58 of file helper.c.

#define ESC   "\033[0m";

Definition at line 57 of file helper.c.

#define GREEN_BLACK   "\033[32;40m"

Definition at line 61 of file helper.c.

#define LTGREEN_BLACK   "\033[36;40m"

Definition at line 65 of file helper.c.

#define MICRO_SECS_PER_SECOND   1000000

Definition at line 51 of file helper.c.

#define NANO_SECS_PER_SECOND   MICRO_SECS_PER_SECOND * 1000

Definition at line 52 of file helper.c.

Referenced by getAbsoluteTime(), and getTimestamp().

#define PINK_BLACK   "\033[35;40m"

Definition at line 64 of file helper.c.

#define RED_BLACK   "\033[31;40m"

Definition at line 60 of file helper.c.

#define WHITE_BLACK   "\033[37;40m"

Definition at line 66 of file helper.c.

#define WHITE_RED   "\033[37;41m"

Definition at line 68 of file helper.c.

#define XMLBLASTER_SLEEP_FALLBACK   0

Definition at line 141 of file helper.c.

#define XMLBLASTER_SLEEP_NANO   0

Definition at line 144 of file helper.c.

#define YELLOW_BLACK   "\033[33;40m"

Definition at line 62 of file helper.c.


Function Documentation

BlobHolder* blobcpyAlloc ( BlobHolder blob,
char *  data,
size_t  dataLen 
)

Allocates the string with malloc for you.

You need to free it with free()

Parameters:
blob If null it is malloc()'d for you, else the given blob is used to be filled.
Returns:
The given blob (or a new malloc()'d if blob was NULL), the data is 0 terminated. We return NULL on out of memory.

Definition at line 945 of file helper.c.

References BlobHolder::data, and BlobHolder::dataLen.

Referenced by responseEvent(), and sendData().

char* blobDump ( BlobHolder blob  ) 

Converts the given binary data to a more readable string, the zero bytes are replaced by '*'.

Parameters:
blob The binary data
Returns:
readable is returned, it must be free()'d

Definition at line 984 of file helper.c.

References BlobHolder::data, BlobHolder::dataLen, and toReadableDump().

Referenced by sendData().

Here is the call graph for this function:

char** convertWcsArgv ( wchar_t **  argv_wcs,
int  argc 
)

Converts the given wide char pwcs to multibyte argv.

Call freeWcsArgv() to free the memory again.

Parameters:
pwcs In parameter: Wide char command line arguments
argc The number of strings in pwcs
Returns:
argv Is allocated with malloc and holds all given pwcs strings

Definition at line 224 of file helper.c.

References argv.

int doLog ( XMLBLASTER_LOG_LEVEL  currLevel,
XMLBLASTER_LOG_LEVEL  level 
)

Check if logging is necessary.

Parameters:
currLevel The actual log level of the client
level The level of this log entry
Returns:
true If logging is desired

Definition at line 811 of file helper.c.

void embedException ( ExceptionStruct exception,
char *  newErrorCode,
char *  newMessage,
ExceptionStruct embed 
)

Embed the given 'embed' into exception->message.

embed and exception may point on the same instance

Parameters:
embed An original exception to embed, can be empty in which case it is ignored
exception Contains the new exception with embedded old exception errorCode/message

Definition at line 822 of file helper.c.

References ExceptionStruct::errorCode, EXCEPTIONSTRUCT_ERRORCODE_LEN, EXCEPTIONSTRUCT_MESSAGE_LEN, getExceptionStr(), ExceptionStruct::message, SNPRINTF, and strncpy0().

Referenced by createQueue(), and xmlBlasterInitQueue().

Here is the call graph for this function:

void freeArgv ( char **  argv,
int  argc 
)

Frees the allocated argv from convertWcsArgv().

Parameters:
argv The main(argv)
argc The number of strings in argv

Definition at line 249 of file helper.c.

Referenced by main().

void freeBlobDump ( char *  blobDump  ) 

Definition at line 989 of file helper.c.

Referenced by sendData().

BlobHolder* freeBlobHolderContent ( BlobHolder blob  ) 

free()'s the data in the given blob, does not free the blob itself.

Parameters:
blob if NULL we return NULL
Returns:
The given blob

Definition at line 967 of file helper.c.

References BlobHolder::data, and BlobHolder::dataLen.

Referenced by handleMessage(), postSendEvent(), sendData(), xmlBlasterConnect(), xmlBlasterDisconnect(), xmlBlasterErase(), xmlBlasterGet(), xmlBlasterPing(), xmlBlasterPublish(), xmlBlasterSubscribe(), and xmlBlasterUnSubscribe().

long get_pthread_id ( pthread_t  t  ) 

Cast the thread identifier to an long value.

Parameters:
t The pthread_t type
Returns:
A uniquue long, usually the pointer address

Definition at line 648 of file helper.c.

Referenced by freeXmlBlasterAccessUnparsed(), interceptUpdate(), runUpdate(), and xmlBlasterDefaultLogging().

int getAbsoluteTime ( long  relativeTimeFromNow,
struct timespec *  abstime 
)

Fills the given abstime with absolute time, using the given timeout relativeTimeFromNow in milliseconds On Linux < 2.5.64 does not support high resolution timers clock_gettime(), but patches are available at http://sourceforge.net/projects/high-res-timers.

Parameters:
relativeTimeFromNow the relative time from now in milliseconds
abstime 
Returns:
true If implemented

Definition at line 266 of file helper.c.

References NANO_SECS_PER_SECOND.

Referenced by getTimestamp(), and postSendEvent().

void getCurrentTimeStr ( char *  timeStr,
int  bufSize 
)

Get a human readable time string for logging.

Parameters:
timeStr out parameter, e.g. "2006-11-14 12:34:46"
bufSize The size of timeStr

Definition at line 663 of file helper.c.

References snprintf0(), and strncpy0().

Referenced by xmlBlasterDefaultLogging().

Here is the call graph for this function:

char* getExceptionStr ( char *  out,
int  outSize,
ExceptionStruct exception 
)

Convenience function which returns a formatted exception string.

 
Parameters:
out The string where the exception is written into, you should allocate at least EXCEPTIONSTRUCT_ERRORCODE_LEN + EXCEPTIONSTRUCT_MESSAGE_LEN + 64 bytes for it
outSize The max size of 'out'
exception The exception to dump
Returns:
out

Definition at line 861 of file helper.c.

References ExceptionStruct::errorCode, ExceptionStruct::message, and SNPRINTF.

Referenced by destroy(), and embedException().

char* getLogLevelStr ( XMLBLASTER_LOG_LEVEL  logLevel  ) 

Returns:
A human readable log level, e.g.

"ERROR"

Definition at line 800 of file helper.c.

References LOG_TEXT.

Referenced by getXmlBlasterAccessUnparsed(), and myLogger().

char* getStackTrace ( int  maxNumOfLines  ) 

Add for GCC compilation: "-rdynamic -export-dynamic -D_ENABLE_STACK_TRACE_".

Returns:
The stack trace, you need to free() it. Returns NULL if out of memory.

Definition at line 94 of file helper.c.

References strcatAlloc(), and strcpyAlloc().

Referenced by checkArgs(), freeXmlBlasterAccessUnparsed(), and xmlBlasterDefaultLogging().

Here is the call graph for this function:

int64_t getTimestamp ( void   ) 

Create a timestamp in nano seconds elapsed since 1970-01-01.

The timestamp is guaranteed to be ascending and unique.

Definition at line 199 of file helper.c.

References getAbsoluteTime(), and NANO_SECS_PER_SECOND.

Referenced by myUpdate().

Here is the call graph for this function:

void initializeExceptionStruct ( ExceptionStruct exception  ) 

Should be called on any ExceptionStruct before using it.

Nulls all fields

Definition at line 843 of file helper.c.

References ExceptionStruct::errorCode, ExceptionStruct::message, and ExceptionStruct::remote.

Referenced by checkArgs().

char* int64ToStr ( char *  buf,
int64_t  val 
)

Convert a 64 bit integer to a string.

This helper concentrates this conversion to one place to simplify porting to compilers with no int64_t = long long support

Parameters:
buf You need to pass this buffer with at least INT64_STRLEN_MAX=22 bytes of size
Returns:
buf

< Size of a max int64_t dumped to a string including an optional LL and termination '': LLONG_MAX from limits.h 9223372036854775807LL

Definition at line 874 of file helper.c.

References INT64_STRLEN_MAX, PRINTF_PREFIX_INT64_T, and snprintf0().

Referenced by fillCache(), parseQueueEntryArr(), persistentQueuePeekWithSamePriority(), persistentQueuePut(), persistentQueueRandomRemove(), queueEntryToXml(), test_overflow(), and test_queue().

Here is the call graph for this function:

XMLBLASTER_LOG_LEVEL parseLogLevel ( char *  logLevelStr  ) 

Parses the given string and returns the enum for it.

If logLevelStr is NULL or empty or unknown we return the default log level.

Parameters:
logLevelStr The level e.g. "WARN" or "warn" or "2"
Returns:
The enum, e.g. XMLBLASTER_LOG_WARN

Definition at line 776 of file helper.c.

References LOG_TEXT, numLOG_TEXT, strToInt(), and XMLBLASTER_LOG_WARN.

Referenced by getCallbackServerUnparsed(), getXmlBlasterAccessUnparsed(), and getXmlBlasterConnectionUnparsed().

Here is the call graph for this function:

void sleepMillis ( long  millisecs  ) 

Sleep for given milliseconds, on none real time systems expect ~ 10 millisecs tolerance.

Definition at line 150 of file helper.c.

Referenced by compilePreparedQuery(), freeXmlBlasterAccessUnparsed(), getResultRows(), main(), and myUpdate().

int snprintf0 ( char *  buffer,
size_t  sizeOfBuffer,
char *  format,
  ... 
)

Microsoft introduces the vsnprintf_s().

Definition at line 524 of file helper.c.

References vsnprintf0().

Referenced by encodeMsgUnitArr(), encodeSocketMessage(), getCurrentTimeStr(), int64ToStr(), parseSocketData(), xb_strerror(), and xmlBlasterConnect().

Here is the call graph for this function:

char* strcatAlloc ( char **  dest,
char *  src 
)

Same as strcat but reallocs the 'dest' string.

Returns:
The allocated string (*dest) or NULL if out of memory

Definition at line 379 of file helper.c.

References strncat0().

Referenced by getStackTrace(), and messageUnitToXmlLimited().

Here is the call graph for this function:

char* strcpyAlloc ( char *  src  ) 

Allocates the string with malloc for you.

You need to free it with free()

Parameters:
src The text to copy
Returns:
The allocated string or NULL if out of memory

Definition at line 363 of file helper.c.

References strncpy0().

Referenced by convert(), getCallbackServerUnparsed(), getStackTrace(), getXmlBlasterAccessUnparsedUnmanaged(), getXmlBlasterAccessUnparsedUnmanagedCE(), interceptUpdate(), main(), messageUnitToXmlLimited(), myUpdate(), parseMsgUnitArr(), parseQosArr(), sendResponse(), strcpyRealloc(), xmlBlasterConnect(), xmlBlasterUnmanagedCEErase(), xmlBlasterUnmanagedCEGet(), xmlBlasterUnmanagedCEUnSubscribe(), xmlBlasterUnmanagedCEVersion(), xmlBlasterUnmanagedErase(), xmlBlasterUnmanagedGet(), and xmlBlasterUnmanagedUnSubscribe().

Here is the call graph for this function:

char* strcpyRealloc ( char **  dest,
char *  src 
)

Same as strcpyAlloc but if the given *dest != NULL this old allocation is freed first.

Returns:
*dest The allocated string filled with 'src', you need to free() it when not needed anymore.

Definition at line 396 of file helper.c.

References strcpyAlloc().

Referenced by createCallbackServer(), and useThisSocket().

Here is the call graph for this function:

char* strFromBlobAlloc ( char *  blob,
size_t  len 
)

Allocates the string with malloc for you, it is always ended with 0.

NOTE: If your given blob or len is 0 an empty string of size 1 is returned

Returns:
The string, never null. You need to free it with free()

Definition at line 410 of file helper.c.

Referenced by interceptUpdate(), main(), messageUnitToXmlLimited(), queueEntryToXml(), test_queue(), xmlBlasterConnect(), xmlBlasterPing(), xmlBlasterPublish(), xmlBlasterSubscribe(), and xmlBlasterUnmanagedGet().

char* strncat0 ( char *  to,
char *  from,
size_t  max 
)

Guarantees a 0 terminated string.

Parameters:
to The destination string must be big enough
from The source to be appended
max Number of characters to append, max-1 will be ended by 0
Returns:
The destination string 'to'

Definition at line 491 of file helper.c.

Referenced by strcatAlloc(), xmlBlasterConnect(), and xmlBlasterConnectionUnparsedUsage().

char* strncpy0 ( char *  to,
char *  from,
size_t  maxLen 
)

Guarantees a 0 terminated string.

Parameters:
to The destination string must be big enough
from The source to be copied
maxLen (maxLen-1) of 'to' will be filled with a 0, so effectively only maxLen-1 from 'from' are copied.
Returns:
The destination string 'to'

Definition at line 461 of file helper.c.

Referenced by checkArgs(), compilePreparedQuery(), convertToXmlBlasterException(), destroy(), embedException(), execSilent(), getCurrentTimeStr(), handleMessage(), initConnection(), initialize(), interceptUpdate(), messageUnitToXmlLimited(), mutexUnlock(), myUpdate(), parseCacheInfo(), parseMsgUnitArr(), parseQueueEntryArr(), parseSocketData(), persistentQueueDestroy(), persistentQueueInitialize(), persistentQueuePeekWithSamePriority(), persistentQueuePut(), postSendEvent(), preSendEvent(), sendData(), strcpyAlloc(), test_illegal(), test_overflow(), test_queue(), xb_strerror(), xmlBlasterConnect(), xmlBlasterConnectionUnparsedUsage(), xmlBlasterErase(), xmlBlasterGet(), xmlBlasterInitQueue(), xmlBlasterSubscribe(), and xmlBlasterUnSubscribe().

int strToInt ( int *  val,
char *  str 
)

Definition at line 915 of file helper.c.

References strToInt64().

Referenced by parseLogLevel().

Here is the call graph for this function:

int strToInt64 ( int64_t *  val,
char *  str 
)

Convert a string to a 64 bit integer.

This helper concentrates this conversion to one place to simplify porting to compilers with no long long support

Parameters:
val Your long long which is filled from str
str The string to convert, for example "123450000LL"
Returns:
true on success

Definition at line 891 of file helper.c.

References PRINTF_PREFIX_INT64_T.

Referenced by getInt64(), parseCacheInfo(), parseQueueEntryArr(), strToInt(), and strToLong().

int strToLong ( long *  val,
char *  str 
)

Definition at line 903 of file helper.c.

References strToInt64().

Referenced by getLong().

Here is the call graph for this function:

int strToULong ( unsigned long *  val,
char *  str 
)

Definition at line 927 of file helper.c.

Referenced by parseMsgUnitArr(), and parseSocketData().

char* toReadableDump ( char *  data,
size_t  len 
)

Converts the given binary data to a more readable string, the zero bytes are replaced by '*'.

Parameters:
data The data to convert
len The length of the binary data
Returns:
readable is returned, it must be free()'d. If allocation fails NULL is returned

Definition at line 623 of file helper.c.

Referenced by blobDump(), encodeSocketMessage(), and parseSocketData().

void trim ( char *  s  ) 

strip leading and trailing spaces of the given string

Definition at line 540 of file helper.c.

Referenced by convertToXmlBlasterException(), parseMsgUnitArr(), and parseSocketData().

void trimEnd ( char *  s  ) 

strip trailing spaces of the given string

Definition at line 604 of file helper.c.

void trimStart ( char *  s  ) 

strip leading spaces of the given string

Definition at line 576 of file helper.c.

int vsnprintf0 ( char *  s,
size_t  size,
char *  format,
va_list  ap 
) [static]

Definition at line 506 of file helper.c.

Referenced by snprintf0(), and xmlBlasterDefaultLogging().

void xb_strerror ( char *  errnoStr,
size_t  sizeInBytes,
int  errnum 
)

Convert the errnum to a human readable errnoStr.

Parameters:
errnoStr Out parameter holding the string
sizeInBytes Size of the buffer
errnum The error number (errno)

Definition at line 437 of file helper.c.

References snprintf0(), and strncpy0().

Referenced by initConnection().

Here is the call graph for this function:

void xmlBlasterDefaultLogging ( void *  logUserP,
XMLBLASTER_LOG_LEVEL  currLevel,
XMLBLASTER_LOG_LEVEL  level,
char *  location,
char *  fmt,
  ... 
)

Default logging output is handled by this method: All logging is appended a time, the loglevel and the location string.

The logging output is to console.

If you have your own logging device you need to implement this method yourself and register it with

 xa->log = myXmlBlasterLoggingHandler;
 
Parameters:
logUserP User specific location bounced back
currLevel The actual log level of the client
level The level of this log entry
location A string describing the code place
fmt The formatting string
... Other variables to log, corresponds to 'fmt'

Definition at line 710 of file helper.c.

References get_pthread_id(), getCurrentTimeStr(), getStackTrace(), LOG_TEXT, LOG_TEXT_ESCAPE, vsnprintf0(), and XMLBLASTER_LOG_ERROR.

Referenced by getCallbackServerUnparsed(), getXmlBlasterAccessUnparsed(), and getXmlBlasterConnectionUnparsed().

Here is the call graph for this function:


Variable Documentation

char* LOG_TEXT[] = { "NOLOG", "ERROR", "WARN", "INFO", "CALL", "TIME", "TRACE", "DUMP", "PLAIN" } [static]

Definition at line 54 of file helper.c.

Referenced by getLogLevelStr(), parseLogLevel(), and xmlBlasterDefaultLogging().

char* LOG_TEXT_ESCAPE[] [static]

Initial value:

 {
       "NOLOG",
        "\033[31;40mERROR\033[0m",
        "\033[33;40mWARN\033[0m",
        "\033[32;40mINFO\033[0m",
        "\033[34;40mCALL\033[0m",
        "\033[36;40mTIME\033[0m",
        "\033[37;40mTRACE\033[0m",
        "\033[35;40mDUMP\033[0m",
        "\033[37;40mPLAIN\033[0m"
        }

Definition at line 75 of file helper.c.

Referenced by xmlBlasterDefaultLogging().

int numLOG_TEXT = 9 [static]

Definition at line 55 of file helper.c.

Referenced by parseLogLevel().